feat(mobile-api): event leads API with phone normalisation and team rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
5d768b1566
commit
fe9d9bd38d
12 files changed
+1312
-1
No files matched your search
@@ -69,7 +69,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial
|
||||
- Scope: `solvway-mobile-api/src/**/*Interest*`, `solvway-mobile-api/src/main/java/**/constants/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`.
|
||||
|
||||
- [ ] 3.2 Add the event-leads admin API (design decisions 2–7).
|
||||
- [x] 3.2 Add the event-leads admin API (design decisions 2–7).
|
||||
- Add `com.googlecode.libphonenumber:libphonenumber` (latest 8.x, exact version) to `solvway-mobile-api/pom.xml`.
|
||||
- `AdminEventLeadController` and `AdminEventLeadService` under `/api/admin/event-leads`, all `@AppAuth @AdminModule("BO_EVENT_LEADS")`:
|
||||
- `GET /events`
|
||||
|
||||
@@ -61,6 +61,12 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<!-- Lead capture: mobile numbers normalised to E.164 (add-event-lead-capture). -->
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>libphonenumber</artifactId>
|
||||
<version>8.13.55</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
||||
+5
@@ -40,6 +40,11 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}";
|
||||
public static final String API_REST_COUNTER_INTEREST_SAVE="/counter/interest/save";
|
||||
public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds";
|
||||
public static final String API_REST_COUNTER_LEAD_FIND_MATCHES="/counter/lead/findMatches";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT="/counter/eventLead/findByEvent";
|
||||
|
||||
//Event Product
|
||||
public static final String API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID = "/counter/eventProduct/findByEventUuid/{eventUuid}";
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Event-floor lead capture: events, options, match, capture, listing and edit. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/event-leads")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminEventLeadController {
|
||||
private final AdminEventLeadService adminEventLeadService;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/events")
|
||||
public ResponseEntity<List<Map<String, Object>>> events() {
|
||||
return ResponseEntity.ok(adminEventLeadService.events());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/interest-options")
|
||||
public ResponseEntity<List<Map<String, Object>>> interestOptions() {
|
||||
return ResponseEntity.ok(adminEventLeadService.interestOptions());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/salesperson-options")
|
||||
public ResponseEntity<List<Map<String, Object>>> salespersonOptions(@PathVariable String eventUuid) {
|
||||
return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PostMapping("/{eventUuid}/match")
|
||||
public ResponseEntity<Map<String, Object>> match(@PathVariable String eventUuid, @RequestBody AdminLeadMatchRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.match(eventUuid, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PostMapping("/{eventUuid}")
|
||||
public ResponseEntity<Map<String, Object>> capture(@PathVariable String eventUuid, @RequestBody AdminEventLeadCaptureRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.capture(eventUuid, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/leads")
|
||||
public ResponseEntity<Map<String, Object>> list(@PathVariable String eventUuid,
|
||||
@RequestParam(required = false) Long salespersonId,
|
||||
@RequestParam(required = false) String temperature,
|
||||
@RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) Long interestId,
|
||||
@RequestParam(required = false) String leadType,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(adminEventLeadService.list(eventUuid, salespersonId, temperature, status, interestId, leadType, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/leads/{eventLeadUuid}")
|
||||
public ResponseEntity<Map<String, Object>> get(@PathVariable String eventUuid, @PathVariable String eventLeadUuid) {
|
||||
return ResponseEntity.ok(adminEventLeadService.get(eventUuid, eventLeadUuid));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PutMapping("/{eventUuid}/leads/{eventLeadUuid}")
|
||||
public ResponseEntity<Map<String, Object>> update(@PathVariable String eventUuid, @PathVariable String eventLeadUuid,
|
||||
@RequestBody AdminEventLeadUpdateRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.update(eventUuid, eventLeadUuid, request));
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Step 2 of capture. leadUuid is the picked match as a string, or null for a new person. nextFollowUpDate is YYYY-MM-DD. */
|
||||
public record AdminEventLeadCaptureRequest(String leadUuid, String name, String mobile, String email, String companyName,
|
||||
String jobTitle, Long salespersonId, String temperature, String status,
|
||||
List<Long> interestIds, String nextFollowUpDate, String notes) {}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** An event lead's working fields. nextFollowUpDate is YYYY-MM-DD; null clears it. */
|
||||
public record AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List<Long> interestIds,
|
||||
String nextFollowUpDate, String notes) {}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
/** Step 1 of capture: the mobile and/or email to look up. */
|
||||
public record AdminLeadMatchRequest(String mobile, String email) {}
|
||||
+447
@@ -0,0 +1,447 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Lead capture at events for the admin portal. Validates and normalises at this boundary; services-counter stores.
|
||||
* Company comes from the logged-in admin, never the request. Uuids leave as strings (Snowflake longs).
|
||||
* Never log a lead's name, mobile or email.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@SuppressWarnings("unchecked")
|
||||
public class AdminEventLeadService {
|
||||
private static final Set<String> TEMPERATURES = Set.of("HOT", "WARM", "COLD");
|
||||
private static final Set<String> STATUSES = Set.of("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST");
|
||||
private static final Set<String> LEAD_TYPES = Set.of("NEW", "EXISTING");
|
||||
private static final int EVENT_PAGE = 100;
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private static final ParameterizedTypeReference<AdminEventService.EventPage> PAGE = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Event> EVENT = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
// --- options ---
|
||||
|
||||
/** Enabled events, newest start first. ponytail: one page of 100; add paging when a company has more enabled events. */
|
||||
public List<Map<String, Object>> events() {
|
||||
Map<String, Object> request = Map.of("property", Map.of("name", "", "enabled", "Y"),
|
||||
"pageableRest", Map.of("number", 0, "size", EVENT_PAGE, "sorts", List.of(Map.of("direction", "DESC", "property", "dateStart"))));
|
||||
AdminEventService.EventPage p = restTemplateUtil.postForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE), PAGE, request).getBody();
|
||||
if (p == null || p.content() == null) return List.of();
|
||||
return p.content().stream().map(e -> {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("uuid", String.valueOf(e.getUuid()));
|
||||
m.put("name", e.getName());
|
||||
m.put("location", e.getLocation());
|
||||
m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
|
||||
m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
|
||||
return m;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> interestOptions() {
|
||||
return interests(caller().getCompanyId()).values().stream().filter(i -> Boolean.TRUE.equals(i.get("active"))).toList();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> salespersonOptions(String eventUuid) {
|
||||
Event event = loadEvent(eventUuid);
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Long id : teamIds(event.getUuid())) {
|
||||
Map<String, Object> u = user(id);
|
||||
if (isActiveAdmin(u)) out.add(Map.of("id", id, "name", String.valueOf(u.get("name")), "username", String.valueOf(u.get("username"))));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- capture ---
|
||||
|
||||
public Map<String, Object> match(String eventUuid, AdminLeadMatchRequest r) {
|
||||
User caller = caller();
|
||||
String mobile = mobile(r.mobile());
|
||||
String email = email(r.email());
|
||||
if (mobile == null && email == null) throw required(List.of("mobile", "email"));
|
||||
Event event = loadEvent(eventUuid);
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("mobile", mobile);
|
||||
out.put("email", email);
|
||||
out.put("candidates", findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream().map(m -> {
|
||||
Map<String, Object> c = new LinkedHashMap<>();
|
||||
c.put("leadUuid", str(m.get("leadUuid")));
|
||||
c.put("name", m.get("name"));
|
||||
c.put("mobile", m.get("mobileE164"));
|
||||
c.put("email", m.get("email"));
|
||||
c.put("companyName", m.get("companyName"));
|
||||
c.put("jobTitle", m.get("jobTitle"));
|
||||
c.put("eventLeadUuid", str(m.get("eventLeadUuid")));
|
||||
return c;
|
||||
}).toList());
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> capture(String eventUuid, AdminEventLeadCaptureRequest r) {
|
||||
User caller = caller();
|
||||
String name = trimmed(r.name());
|
||||
String mobile = mobile(r.mobile());
|
||||
String email = email(r.email());
|
||||
List<String> missing = new ArrayList<>();
|
||||
if (name == null) missing.add("name");
|
||||
if (mobile == null && email == null) { missing.add("mobile"); missing.add("email"); }
|
||||
if (!missing.isEmpty()) throw required(missing);
|
||||
maxLength("name", name, 100);
|
||||
maxLength("email", email, 254);
|
||||
String companyName = maxLength("companyName", trimmed(r.companyName()), 150);
|
||||
String jobTitle = maxLength("jobTitle", trimmed(r.jobTitle()), 100);
|
||||
String temperature = oneOf("temperature", r.temperature(), TEMPERATURES);
|
||||
String status = oneOf("status", r.status(), STATUSES);
|
||||
LocalDate followUp = date(r.nextFollowUpDate());
|
||||
Long leadUuid = r.leadUuid() == null ? null : parseOr(r.leadUuid(), () -> error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null));
|
||||
|
||||
Event event = loadEvent(eventUuid);
|
||||
if (event.getEnabled() != GeneralEnum.FlagYesNo.Y) {
|
||||
throw error(HttpStatus.CONFLICT, "This event is disabled and cannot take new leads", "EVENT_DISABLED", null);
|
||||
}
|
||||
if (r.salespersonId() != null) checkOnTeam(event.getUuid(), r.salespersonId());
|
||||
Map<Long, Map<String, Object>> known = interests(caller.getCompanyId());
|
||||
List<Long> interestIds = checkedInterests(known, r.interestIds(), List.of());
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("leadUuid", leadUuid);
|
||||
body.put("name", name);
|
||||
body.put("mobileE164", mobile);
|
||||
body.put("email", email);
|
||||
body.put("companyName", companyName);
|
||||
body.put("jobTitle", jobTitle);
|
||||
body.put("salespersonUserId", r.salespersonId());
|
||||
body.put("temperature", temperature);
|
||||
body.put("status", status);
|
||||
body.put("interestIds", interestIds);
|
||||
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
|
||||
body.put("notes", trimmed(r.notes()));
|
||||
body.put("doneBy", caller.getUsername());
|
||||
try {
|
||||
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_CAPTURE), MAP, body).getBody(),
|
||||
known, new HashMap<>());
|
||||
} catch (HttpClientErrorException.Conflict e) {
|
||||
Object existing = conflictEventLeadUuid(e);
|
||||
if (existing == null) existing = findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream()
|
||||
.filter(m -> Objects.equals(str(m.get("leadUuid")), str(leadUuid))).map(m -> m.get("eventLeadUuid"))
|
||||
.filter(Objects::nonNull).findFirst().orElse(null);
|
||||
CodedResponseStatusException ex = new CodedResponseStatusException(HttpStatus.CONFLICT,
|
||||
"This person is already captured at this event", "ALREADY_CAPTURED");
|
||||
if (existing != null) ex.getBody().setProperty("details", Map.of("eventLeadUuid", str(existing)));
|
||||
throw ex;
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null);
|
||||
}
|
||||
}
|
||||
|
||||
// --- listing and edit ---
|
||||
|
||||
public Map<String, Object> list(String eventUuid, Long salespersonId, String temperature, String status, Long interestId,
|
||||
String leadType, int page, int size) {
|
||||
User caller = caller();
|
||||
Event event = loadEvent(eventUuid);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("salespersonUserId", salespersonId);
|
||||
body.put("temperature", oneOf("temperature", temperature, TEMPERATURES));
|
||||
body.put("status", oneOf("status", status, STATUSES));
|
||||
body.put("interestId", interestId);
|
||||
body.put("leadType", oneOf("leadType", leadType, LEAD_TYPES));
|
||||
body.put("page", Math.max(page, 0));
|
||||
body.put("size", size);
|
||||
Map<String, Object> p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), MAP, body).getBody();
|
||||
List<Map<String, Object>> rows = p == null || p.get("content") == null ? List.of() : (List<Map<String, Object>>) p.get("content");
|
||||
Map<Long, Map<String, Object>> interests = rows.isEmpty() ? Map.of() : interests(caller.getCompanyId());
|
||||
Map<Long, Map<String, Object>> users = new HashMap<>();
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("content", rows.stream().map(row -> view(row, interests, users)).toList());
|
||||
out.put("totalElements", p == null ? 0 : p.get("totalElements"));
|
||||
out.put("totalPages", p == null ? 0 : p.get("totalPages"));
|
||||
out.put("number", p == null ? 0 : p.get("number"));
|
||||
out.put("size", p == null ? size : p.get("size"));
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> get(String eventUuid, String eventLeadUuid) {
|
||||
User caller = caller();
|
||||
return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId());
|
||||
}
|
||||
|
||||
public Map<String, Object> update(String eventUuid, String eventLeadUuid, AdminEventLeadUpdateRequest r) {
|
||||
User caller = caller();
|
||||
String temperature = oneOf("temperature", r.temperature(), TEMPERATURES);
|
||||
String status = oneOf("status", r.status(), STATUSES);
|
||||
LocalDate followUp = date(r.nextFollowUpDate());
|
||||
Map<String, Object> current = stored(caller.getCompanyId(), eventUuid, eventLeadUuid);
|
||||
Long currentSalesperson = current.get("salespersonUserId") == null ? null : ((Number) current.get("salespersonUserId")).longValue();
|
||||
if (r.salespersonId() != null && !r.salespersonId().equals(currentSalesperson)) {
|
||||
checkOnTeam(((Number) current.get("eventUuid")).longValue(), r.salespersonId());
|
||||
}
|
||||
Map<Long, Map<String, Object>> known = interests(caller.getCompanyId());
|
||||
List<Long> interestIds = checkedInterests(known, r.interestIds(), longs(current.get("interestIds")));
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("eventLeadUuid", ((Number) current.get("eventLeadUuid")).longValue());
|
||||
body.put("salespersonUserId", r.salespersonId());
|
||||
body.put("temperature", temperature);
|
||||
body.put("status", status);
|
||||
body.put("interestIds", interestIds);
|
||||
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
|
||||
body.put("notes", trimmed(r.notes()));
|
||||
body.put("doneBy", caller.getUsername());
|
||||
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(),
|
||||
known, new HashMap<>());
|
||||
}
|
||||
|
||||
// --- rules ---
|
||||
|
||||
/** A salesperson newly set must be an active admin on the event's current team. */
|
||||
private void checkOnTeam(long eventUuid, long userId) {
|
||||
if (!teamIds(eventUuid).contains(userId) || !isActiveAdmin(user(userId))) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "The salesperson must be an active member of the event's team", "NOT_ON_TEAM", "salespersonId");
|
||||
}
|
||||
}
|
||||
|
||||
/** Ids must be the company's interests; one newly added must be active, one already on the lead may stay. */
|
||||
private static List<Long> checkedInterests(Map<Long, Map<String, Object>> known, List<Long> requested, List<Long> current) {
|
||||
List<Long> ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList()));
|
||||
for (Long id : ids) {
|
||||
Map<String, Object> interest = known.get(id);
|
||||
if (interest == null) throw error(HttpStatus.BAD_REQUEST, "Unknown interest " + id, "INVALID_VALUE", "interestIds");
|
||||
if (!Boolean.TRUE.equals(interest.get("active")) && !current.contains(id)) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Interest " + interest.get("name") + " is no longer active", "INACTIVE_INTEREST", "interestIds");
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private Map<String, Object> stored(long companyId, String eventUuid, String eventLeadUuid) {
|
||||
Event event = loadEvent(eventUuid);
|
||||
long id = parseOr(eventLeadUuid, AdminEventLeadService::eventLeadNotFound);
|
||||
Map<String, Object> d;
|
||||
try {
|
||||
d = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID), MAP, companyId, id).getBody();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw eventLeadNotFound();
|
||||
}
|
||||
if (d == null || !(d.get("eventUuid") instanceof Number n) || n.longValue() != event.getUuid()) throw eventLeadNotFound();
|
||||
return d;
|
||||
}
|
||||
|
||||
// --- views ---
|
||||
|
||||
private Map<String, Object> view(Map<String, Object> d, long companyId) {
|
||||
return view(d, interests(companyId), new HashMap<>());
|
||||
}
|
||||
|
||||
private Map<String, Object> view(Map<String, Object> d, Map<Long, Map<String, Object>> interests, Map<Long, Map<String, Object>> users) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("eventLeadUuid", str(d.get("eventLeadUuid")));
|
||||
m.put("eventUuid", str(d.get("eventUuid")));
|
||||
m.put("leadUuid", str(d.get("leadUuid")));
|
||||
m.put("name", d.get("name"));
|
||||
m.put("mobile", d.get("mobileE164"));
|
||||
m.put("email", d.get("email"));
|
||||
m.put("companyName", d.get("companyName"));
|
||||
m.put("jobTitle", d.get("jobTitle"));
|
||||
m.put("leadType", d.get("leadType"));
|
||||
Object sp = d.get("salespersonUserId");
|
||||
if (sp instanceof Number n) {
|
||||
Map<String, Object> u = users.computeIfAbsent(n.longValue(), this::user);
|
||||
m.put("salesperson", Map.of("id", n.longValue(), "name", u == null ? String.valueOf(n) : String.valueOf(u.get("name"))));
|
||||
} else {
|
||||
m.put("salesperson", null);
|
||||
}
|
||||
m.put("temperature", d.get("temperature"));
|
||||
m.put("status", d.get("status"));
|
||||
m.put("interests", longs(d.get("interestIds")).stream().map(id -> {
|
||||
Map<String, Object> i = interests.get(id);
|
||||
return Map.<String, Object>of("id", id, "name", i == null ? String.valueOf(id) : i.get("name"),
|
||||
"active", i != null && Boolean.TRUE.equals(i.get("active")));
|
||||
}).toList());
|
||||
m.put("nextFollowUpDate", d.get("nextFollowUpDate"));
|
||||
m.put("notes", d.get("notes"));
|
||||
m.put("capturedAt", d.get("capturedAt"));
|
||||
return m;
|
||||
}
|
||||
|
||||
// --- lookups ---
|
||||
|
||||
private List<Map<String, Object>> findMatches(long companyId, long eventUuid, String mobile, String email) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", companyId);
|
||||
body.put("eventUuid", eventUuid);
|
||||
body.put("mobileE164", mobile);
|
||||
body.put("email", email);
|
||||
List<Map<String, Object>> rows = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_FIND_MATCHES), MAP_LIST, body).getBody();
|
||||
return rows == null ? List.of() : rows;
|
||||
}
|
||||
|
||||
/** id -> {id, name, active}, in the counter's order (sort order, then name). */
|
||||
private Map<Long, Map<String, Object>> interests(long companyId) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId).getBody();
|
||||
Map<Long, Map<String, Object>> out = new LinkedHashMap<>();
|
||||
if (rows != null) for (Map<String, Object> r : rows) {
|
||||
long id = ((Number) r.get("id")).longValue();
|
||||
out.put(id, Map.of("id", id, "name", String.valueOf(r.get("name")), "active", Boolean.TRUE.equals(r.get("active"))));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<Long> teamIds(long eventUuid) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID), MAP_LIST, eventUuid).getBody();
|
||||
return rows == null ? List.of() : rows.stream().map(m -> ((Number) m.get("userId")).longValue()).toList();
|
||||
}
|
||||
|
||||
private Map<String, Object> user(Long id) {
|
||||
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody();
|
||||
}
|
||||
|
||||
private Event loadEvent(String uuid) {
|
||||
long id = parseOr(uuid, AdminEventLeadService::eventNotFound);
|
||||
Event event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
|
||||
if (event == null) throw eventNotFound();
|
||||
return event;
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
|
||||
return caller;
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return restTemplateUtil.getURLforApiService(api);
|
||||
}
|
||||
|
||||
// --- small helpers ---
|
||||
|
||||
private static Object conflictEventLeadUuid(HttpClientErrorException e) {
|
||||
try {
|
||||
return JSON.readValue(e.getResponseBodyAsString(), Map.class).get("eventLeadUuid");
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isActiveAdmin(Map<String, Object> user) {
|
||||
return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled"));
|
||||
}
|
||||
|
||||
private static String mobile(String input) {
|
||||
try {
|
||||
return EventLeadContact.mobile(input);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Enter a valid mobile number", "INVALID_MOBILE", "mobile");
|
||||
}
|
||||
}
|
||||
|
||||
private static String email(String input) {
|
||||
try {
|
||||
return EventLeadContact.email(input);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Enter a valid email address", "INVALID_EMAIL", "email");
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDate date(String input) {
|
||||
if (input == null || input.isBlank()) return null;
|
||||
try {
|
||||
return LocalDate.parse(input.trim());
|
||||
} catch (DateTimeParseException e) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Use a date like 2027-01-20", "INVALID_DATE", "nextFollowUpDate");
|
||||
}
|
||||
}
|
||||
|
||||
private static String oneOf(String field, String value, Set<String> allowed) {
|
||||
if (value == null || value.isBlank()) return null;
|
||||
if (!allowed.contains(value)) throw error(HttpStatus.BAD_REQUEST, "Unknown " + field + " " + value, "INVALID_VALUE", field);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String maxLength(String field, String value, int max) {
|
||||
if (value != null && value.length() > max) throw error(HttpStatus.BAD_REQUEST, field + " is too long", "TOO_LONG", field);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String trimmed(String s) {
|
||||
return s == null || s.isBlank() ? null : s.trim();
|
||||
}
|
||||
|
||||
private static long parseOr(String s, java.util.function.Supplier<CodedResponseStatusException> notFound) {
|
||||
try {
|
||||
return Long.parseLong(s.trim());
|
||||
} catch (RuntimeException e) {
|
||||
throw notFound.get();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Long> longs(Object list) {
|
||||
if (!(list instanceof List<?> l)) return List.of();
|
||||
return l.stream().filter(Number.class::isInstance).map(o -> ((Number) o).longValue()).toList();
|
||||
}
|
||||
|
||||
private static String str(Object o) {
|
||||
return o == null ? null : String.valueOf(o);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException required(List<String> fields) {
|
||||
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: " + String.join(", ", fields), "REQUIRED_FIELD", fields.get(0));
|
||||
e.getBody().setProperty("errors", fields);
|
||||
return e;
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException eventNotFound() {
|
||||
return error(HttpStatus.NOT_FOUND, "Event not found", "EVENT_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException eventLeadNotFound() {
|
||||
return error(HttpStatus.NOT_FOUND, "Event lead not found", "EVENT_LEAD_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) {
|
||||
CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code);
|
||||
if (field != null) e.getBody().setProperty("details", Map.of("field", field));
|
||||
return e;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Normalises a lead's contact values so the same person always has the same value: mobile numbers to E.164
|
||||
* (a number without a country code is Malaysian), emails trimmed and lowercased. Blank input is null;
|
||||
* anything that is not a valid number or email address throws IllegalArgumentException.
|
||||
*/
|
||||
final class EventLeadContact {
|
||||
private static final PhoneNumberUtil PHONES = PhoneNumberUtil.getInstance();
|
||||
private static final Pattern EMAIL = Pattern.compile("[^\\s@]+@[^\\s@]+\\.[^\\s@]+");
|
||||
|
||||
private EventLeadContact() {}
|
||||
|
||||
static String mobile(String input) {
|
||||
if (input == null || input.isBlank()) return null;
|
||||
try {
|
||||
Phonenumber.PhoneNumber number = PHONES.parse(input.trim(), "MY");
|
||||
if (PHONES.isValidNumber(number)) return PHONES.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
} catch (NumberParseException ignored) {
|
||||
// falls through to the refusal below
|
||||
}
|
||||
throw new IllegalArgumentException("not a valid phone number");
|
||||
}
|
||||
|
||||
static String email(String input) {
|
||||
if (input == null || input.isBlank()) return null;
|
||||
String email = input.trim().toLowerCase(Locale.ROOT);
|
||||
if (!EMAIL.matcher(email).matches()) throw new IllegalArgumentException("not an email address");
|
||||
return email;
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminEventLeadControllerTest {
|
||||
|
||||
private static final String EV = "3312726793093644288";
|
||||
private static final String EL = "3312853897594494976";
|
||||
|
||||
@Mock private AdminEventLeadService eventLeads;
|
||||
@InjectMocks private AdminEventLeadController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyHandlerIsAuthenticatedAndGuardedByBoEventLeads() {
|
||||
List<Method> handlers = Arrays.stream(AdminEventLeadController.class.getDeclaredMethods())
|
||||
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
|
||||
assertThat(handlers).hasSize(8);
|
||||
for (Method m : handlers) {
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue();
|
||||
assertThat(Arrays.asList(m.getAnnotation(AdminModule.class).value())).as(m.getName()).containsExactly("BO_EVENT_LEADS");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void optionsEndpoints() throws Exception {
|
||||
when(eventLeads.events()).thenReturn(List.of(Map.of("uuid", EV, "name", "Fair")));
|
||||
mvc.perform(get("/api/admin/event-leads/events")).andExpect(status().isOk())
|
||||
.andExpect(content().json("[{\"uuid\":\"" + EV + "\",\"name\":\"Fair\"}]", true));
|
||||
when(eventLeads.interestOptions()).thenReturn(List.of(Map.of("id", 3, "name", "Cookware", "active", true)));
|
||||
mvc.perform(get("/api/admin/event-leads/interest-options")).andExpect(status().isOk());
|
||||
when(eventLeads.salespersonOptions(EV)).thenReturn(List.of(Map.of("id", 21, "name", "Sales One", "username", "sales1")));
|
||||
mvc.perform(get("/api/admin/event-leads/" + EV + "/salesperson-options")).andExpect(status().isOk())
|
||||
.andExpect(content().json("[{\"id\":21,\"username\":\"sales1\"}]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchAndCaptureBindTheirBodies() throws Exception {
|
||||
when(eventLeads.match(EV, new AdminLeadMatchRequest("0123456789", null))).thenReturn(Map.of("candidates", List.of()));
|
||||
mvc.perform(post("/api/admin/event-leads/" + EV + "/match").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"mobile\":\"0123456789\"}")).andExpect(status().isOk());
|
||||
|
||||
AdminEventLeadCaptureRequest req = new AdminEventLeadCaptureRequest(null, "Aisyah", "0123456789", null, null, null,
|
||||
21L, "HOT", null, List.of(3L), "2027-01-20", null);
|
||||
when(eventLeads.capture(EV, req)).thenReturn(Map.of("eventLeadUuid", EL));
|
||||
mvc.perform(post("/api/admin/event-leads/" + EV).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"Aisyah\",\"mobile\":\"0123456789\",\"salespersonId\":21,\"temperature\":\"HOT\",\"interestIds\":[3],\"nextFollowUpDate\":\"2027-01-20\"}"))
|
||||
.andExpect(status().isOk()).andExpect(content().json("{\"eventLeadUuid\":\"" + EL + "\"}", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPassesFiltersAndPaging() throws Exception {
|
||||
when(eventLeads.list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25)).thenReturn(Map.of("content", List.of(), "totalElements", 0));
|
||||
mvc.perform(get("/api/admin/event-leads/" + EV + "/leads").param("salespersonId", "21").param("temperature", "HOT")
|
||||
.param("status", "OPEN").param("interestId", "3").param("leadType", "NEW").param("page", "1").param("size", "25"))
|
||||
.andExpect(status().isOk());
|
||||
verify(eventLeads).list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25);
|
||||
|
||||
when(eventLeads.list(EV, null, null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of()));
|
||||
mvc.perform(get("/api/admin/event-leads/" + EV + "/leads")).andExpect(status().isOk());
|
||||
verify(eventLeads).list(EV, null, null, null, null, null, 0, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAndUpdateAnEventLead() throws Exception {
|
||||
when(eventLeads.get(EV, EL)).thenReturn(Map.of("eventLeadUuid", EL));
|
||||
mvc.perform(get("/api/admin/event-leads/" + EV + "/leads/" + EL)).andExpect(status().isOk());
|
||||
|
||||
AdminEventLeadUpdateRequest req = new AdminEventLeadUpdateRequest(21L, "COLD", "CONTACTED", List.of(3L), "2027-01-20", "call");
|
||||
when(eventLeads.update(EV, EL, req)).thenReturn(Map.of("eventLeadUuid", EL));
|
||||
mvc.perform(put("/api/admin/event-leads/" + EV + "/leads/" + EL).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"salespersonId\":21,\"temperature\":\"COLD\",\"status\":\"CONTACTED\",\"interestIds\":[3],\"nextFollowUpDate\":\"2027-01-20\",\"notes\":\"call\"}"))
|
||||
.andExpect(status().isOk());
|
||||
verify(eventLeads).update(EV, EL, req);
|
||||
}
|
||||
}
|
||||
+536
@@ -0,0 +1,536 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEventLeadServiceTest {
|
||||
|
||||
private static final String EVENTS = "/counter/event/findByPropertyAndPageable";
|
||||
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
|
||||
private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}";
|
||||
private static final String USER = "/user/findById/{id}";
|
||||
private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final String MATCHES = "/counter/lead/findMatches";
|
||||
private static final String CAPTURE = "/counter/eventLead/capture";
|
||||
private static final String FIND = "/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}";
|
||||
private static final String UPDATE = "/counter/eventLead/update";
|
||||
private static final String SEARCH = "/counter/eventLead/findByEvent";
|
||||
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long EL = 3312853897594494976L;
|
||||
private static final long LEAD = 3312853897040846848L;
|
||||
private static final long COMPANY = 5L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminEventLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEventLeadService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setId(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(COMPANY);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
stubEvent(true);
|
||||
stubTeam(21L, 22L);
|
||||
stubUser(21L, "Sales One", true);
|
||||
stubUser(22L, "Sales Two", true);
|
||||
stubUser(23L, "Sales Three", true);
|
||||
stubInterests(interest(3, "Cookware", true), interest(4, "Kitchen appliances", true), interest(5, "Old", false));
|
||||
when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(detailFrom((Map<String, Object>) i.getArgument(2))));
|
||||
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(detailFrom((Map<String, Object>) i.getArgument(2))));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
// --- stubs ---
|
||||
|
||||
private void stubEvent(boolean enabled) {
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
e.setName("KL Food Fair 2027");
|
||||
e.setLocation("MITEC");
|
||||
e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0));
|
||||
e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
e.setEnabled(enabled ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N);
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
}
|
||||
|
||||
private void stubTeam(long... userIds) {
|
||||
List<Map<String, Object>> rows = new java.util.ArrayList<>();
|
||||
for (long id : userIds) rows.add(Map.of("userId", id));
|
||||
when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(rows));
|
||||
}
|
||||
|
||||
private void stubUser(long id, String name, boolean enabled) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("id", id);
|
||||
u.put("name", name);
|
||||
u.put("username", "u" + id);
|
||||
u.put("type", "A");
|
||||
u.put("enabled", enabled);
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private static Map<String, Object> interest(long id, String name, boolean active) {
|
||||
return Map.of("id", id, "companyId", COMPANY, "name", name, "active", active, "sortOrder", 0);
|
||||
}
|
||||
|
||||
private void stubInterests(Map<String, Object>... rows) {
|
||||
when(rest.getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(COMPANY))).thenReturn(ResponseEntity.ok(List.of(rows)));
|
||||
}
|
||||
|
||||
/** What the counter returns for a capture or update body. */
|
||||
private static Map<String, Object> detailFrom(Map<String, Object> body) {
|
||||
Map<String, Object> d = new LinkedHashMap<>();
|
||||
d.put("eventLeadUuid", EL);
|
||||
d.put("eventUuid", body.getOrDefault("eventUuid", EV));
|
||||
d.put("leadUuid", body.get("leadUuid") == null ? LEAD : body.get("leadUuid"));
|
||||
d.put("name", body.getOrDefault("name", "Aisyah"));
|
||||
d.put("mobileE164", body.get("mobileE164"));
|
||||
d.put("email", body.get("email"));
|
||||
d.put("companyName", body.get("companyName"));
|
||||
d.put("jobTitle", body.get("jobTitle"));
|
||||
d.put("leadType", body.get("leadUuid") == null ? "NEW" : "EXISTING");
|
||||
d.put("salespersonUserId", body.get("salespersonUserId"));
|
||||
d.put("temperature", body.get("temperature"));
|
||||
d.put("status", body.get("status") == null ? "OPEN" : body.get("status"));
|
||||
d.put("nextFollowUpDate", body.get("nextFollowUpDate") == null ? null : body.get("nextFollowUpDate").toString());
|
||||
d.put("notes", body.get("notes"));
|
||||
d.put("capturedAt", "2027-01-15T10:00:00");
|
||||
d.put("interestIds", body.getOrDefault("interestIds", List.of()));
|
||||
return d;
|
||||
}
|
||||
|
||||
private void stubStored(long eventUuid, Long salespersonUserId, List<Long> interestIds) {
|
||||
Map<String, Object> d = new LinkedHashMap<>();
|
||||
d.put("eventLeadUuid", EL);
|
||||
d.put("eventUuid", eventUuid);
|
||||
d.put("leadUuid", LEAD);
|
||||
d.put("name", "Aisyah");
|
||||
d.put("mobileE164", "+60123456789");
|
||||
d.put("leadType", "NEW");
|
||||
d.put("salespersonUserId", salespersonUserId);
|
||||
d.put("status", "OPEN");
|
||||
d.put("interestIds", interestIds);
|
||||
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL))).thenReturn(ResponseEntity.ok(d));
|
||||
}
|
||||
|
||||
private static AdminEventLeadCaptureRequest capture(String leadUuid, String name, String mobile, String email) {
|
||||
return new AdminEventLeadCaptureRequest(leadUuid, name, mobile, email, null, null, null, null, null, List.of(), null, null);
|
||||
}
|
||||
|
||||
private static AdminEventLeadCaptureRequest captureWith(Long salespersonId, String temperature, String status, List<Long> interests, String followUp) {
|
||||
return new AdminEventLeadCaptureRequest(null, "Aisyah", "0123456789", null, null, null, salespersonId, temperature, status, interests, followUp, null);
|
||||
}
|
||||
|
||||
private Map<String, Object> sent(String api) {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) c.getValue();
|
||||
}
|
||||
|
||||
private void assertNothingSent(String api) {
|
||||
verify(rest, never()).postForEntity(eq(api), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
private static void assertCoded(Runnable r, HttpStatus status, String code, String field) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(status);
|
||||
assertThat(e.getCode()).isEqualTo(code);
|
||||
if (field != null) assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", field);
|
||||
});
|
||||
}
|
||||
|
||||
// --- events and options ---
|
||||
|
||||
@Test
|
||||
void eventsAreTheEnabledOnesNewestFirst() {
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
e.setName("KL Food Fair 2027");
|
||||
e.setLocation("MITEC");
|
||||
e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0));
|
||||
e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(e), 1, 1, 0, 100)));
|
||||
|
||||
List<Map<String, Object>> events = service.events();
|
||||
|
||||
assertThat(events).containsExactly(Map.of("uuid", String.valueOf(EV), "name", "KL Food Fair 2027", "location", "MITEC",
|
||||
"startDate", "2027-01-15", "endDate", "2027-01-17"));
|
||||
Map<String, Object> body = sent(EVENTS);
|
||||
assertThat((Map<String, Object>) body.get("property")).containsEntry("enabled", "Y");
|
||||
Map<String, Object> pageable = (Map<String, Object>) body.get("pageableRest");
|
||||
assertThat(pageable).containsEntry("size", 100);
|
||||
assertThat((List<Map<String, Object>>) pageable.get("sorts")).containsExactly(Map.of("direction", "DESC", "property", "dateStart"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventWithEmptyFieldsStillListsWithNulls() {
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(e), 1, 1, 0, 100)));
|
||||
|
||||
Map<String, Object> row = service.events().get(0);
|
||||
|
||||
assertThat(row).containsEntry("uuid", String.valueOf(EV)).containsEntry("name", null)
|
||||
.containsEntry("location", null).containsEntry("startDate", null).containsEntry("endDate", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailLongerThanTheColumnIsTooLong() {
|
||||
String email = "a".repeat(250) + "@x.co";
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", null, email)), HttpStatus.BAD_REQUEST, "TOO_LONG", "email");
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void captureReadsTheInterestListOnce() {
|
||||
service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(3L), null));
|
||||
|
||||
verify(rest, org.mockito.Mockito.times(1)).getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(COMPANY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void interestOptionsAreActiveOnly() {
|
||||
assertThat(service.interestOptions()).extracting(m -> m.get("name")).containsExactly("Cookware", "Kitchen appliances");
|
||||
}
|
||||
|
||||
@Test
|
||||
void salespersonOptionsAreTheActiveTeam() {
|
||||
stubTeam(21L, 22L, 23L);
|
||||
stubUser(23L, "Sales Three", false);
|
||||
|
||||
assertThat(service.salespersonOptions(String.valueOf(EV))).extracting(m -> m.get("id")).containsExactly(21L, 22L);
|
||||
}
|
||||
|
||||
// --- normalisation and validation ---
|
||||
|
||||
@Test
|
||||
void matchNormalisesBothValuesAndReturnsCandidates() {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("leadUuid", LEAD);
|
||||
m.put("name", "Aisyah");
|
||||
m.put("mobileE164", "+60123456789");
|
||||
m.put("email", null);
|
||||
m.put("companyName", "Acme");
|
||||
m.put("jobTitle", null);
|
||||
m.put("eventLeadUuid", EL);
|
||||
when(rest.postForEntity(eq(MATCHES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(m)));
|
||||
|
||||
Map<String, Object> out = service.match(String.valueOf(EV), new AdminLeadMatchRequest("012-345 6789", " Aisyah@Example.COM "));
|
||||
|
||||
assertThat(out).containsEntry("mobile", "+60123456789").containsEntry("email", "aisyah@example.com");
|
||||
assertThat(sent(MATCHES)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV)
|
||||
.containsEntry("mobileE164", "+60123456789").containsEntry("email", "aisyah@example.com");
|
||||
Map<String, Object> candidate = ((List<Map<String, Object>>) out.get("candidates")).get(0);
|
||||
assertThat(candidate).containsEntry("leadUuid", String.valueOf(LEAD)).containsEntry("eventLeadUuid", String.valueOf(EL))
|
||||
.containsEntry("mobile", "+60123456789").containsEntry("companyName", "Acme");
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchWithNeitherValueNamesBothFields() {
|
||||
assertThatThrownBy(() -> service.match(String.valueOf(EV), new AdminLeadMatchRequest(" ", null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD");
|
||||
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("mobile", "email"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void captureNormalisesAndSendsTheCallersCompanyAndUsername() {
|
||||
Map<String, Object> out = service.capture(String.valueOf(EV), capture(null, " Aisyah ", "+60 12-345 6789", " Aisyah@Example.COM "));
|
||||
|
||||
Map<String, Object> body = sent(CAPTURE);
|
||||
assertThat(body).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("name", "Aisyah")
|
||||
.containsEntry("mobileE164", "+60123456789").containsEntry("email", "aisyah@example.com")
|
||||
.containsEntry("doneBy", "sales1").containsEntry("leadUuid", null);
|
||||
assertThat(out).containsEntry("eventLeadUuid", String.valueOf(EL)).containsEntry("leadUuid", String.valueOf(LEAD))
|
||||
.containsEntry("eventUuid", String.valueOf(EV)).containsEntry("leadType", "NEW").containsEntry("mobile", "+60123456789");
|
||||
}
|
||||
|
||||
@Test
|
||||
void neitherMobileNorEmailIsRefusedNamingBoth() {
|
||||
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "", " ")))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD");
|
||||
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("mobile", "email"));
|
||||
});
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingNameAndContactAreAllNamed() {
|
||||
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(null, " ", null, null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e ->
|
||||
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("name", "mobile", "email")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidMobileIsRefusedOnTheMobileField() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "12345", null)), HttpStatus.BAD_REQUEST, "INVALID_MOBILE", "mobile");
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidEmailIsRefusedOnTheEmailField() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", null, "aisyah@")), HttpStatus.BAD_REQUEST, "INVALID_EMAIL", "email");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tooLongValuesAreRefused() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "x".repeat(101), "0123456789", null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "name");
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), new AdminEventLeadCaptureRequest(null, "A", "0123456789", null,
|
||||
"x".repeat(151), null, null, null, null, List.of(), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "companyName");
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), new AdminEventLeadCaptureRequest(null, "A", "0123456789", null,
|
||||
null, "x".repeat(101), null, null, null, List.of(), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "jobTitle");
|
||||
}
|
||||
|
||||
@Test
|
||||
void temperatureStatusAndDateMustBeKnownValues() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, "WARMISH", null, List.of(), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "temperature");
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, "DONE", List.of(), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "status");
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(), "20/01/2027")), HttpStatus.BAD_REQUEST, "INVALID_DATE", "nextFollowUpDate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void workingFieldsAreSentWhenValid() {
|
||||
service.capture(String.valueOf(EV), captureWith(22L, "HOT", "CONTACTED", List.of(3L, 4L), "2027-01-20"));
|
||||
|
||||
assertThat(sent(CAPTURE)).containsEntry("salespersonUserId", 22L).containsEntry("temperature", "HOT")
|
||||
.containsEntry("status", "CONTACTED").containsEntry("interestIds", List.of(3L, 4L))
|
||||
.containsEntry("nextFollowUpDate", "2027-01-20");
|
||||
}
|
||||
|
||||
// --- events open for capture ---
|
||||
|
||||
@Test
|
||||
void disabledEventRefusesCapture() {
|
||||
stubEvent(false);
|
||||
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "0123456789", null)), HttpStatus.CONFLICT, "EVENT_DISABLED", null);
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownEventIsNotFound() {
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(1L))).thenReturn(ResponseEntity.ok().build());
|
||||
|
||||
assertCoded(() -> service.capture("1", capture(null, "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null);
|
||||
assertCoded(() -> service.list("not-a-number", null, null, null, null, null, 0, 20), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
// --- salesperson from the team ---
|
||||
|
||||
@Test
|
||||
void outsiderSalespersonIsRefused() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(23L, null, null, List.of(), null)), HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId");
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deactivatedTeamMemberCannotBeNewlyAssigned() {
|
||||
stubUser(22L, "Sales Two", false);
|
||||
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(22L, null, null, List.of(), null)), HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void salespersonAlreadySetStaysAllowedAfterLeavingTheTeam() {
|
||||
stubStored(EV, 23L, List.of());
|
||||
|
||||
service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(23L, null, "CONTACTED", List.of(), null, null));
|
||||
|
||||
assertThat(sent(UPDATE)).containsEntry("salespersonUserId", 23L).containsEntry("status", "CONTACTED")
|
||||
.containsEntry("companyId", COMPANY).containsEntry("eventLeadUuid", EL).containsEntry("doneBy", "sales1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingToAnOutsiderOnEditIsRefused() {
|
||||
stubStored(EV, 21L, List.of());
|
||||
|
||||
assertCoded(() -> service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(23L, null, "OPEN", List.of(), null, null)),
|
||||
HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId");
|
||||
assertNothingSent(UPDATE);
|
||||
}
|
||||
|
||||
// --- interests ---
|
||||
|
||||
@Test
|
||||
void inactiveInterestCannotBeAddedAtCapture() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(5L), null)), HttpStatus.BAD_REQUEST, "INACTIVE_INTEREST", "interestIds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherCompanysInterestIsRefused() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(99L), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "interestIds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void inactiveInterestAlreadyOnTheLeadIsKeptOnEdit() {
|
||||
stubStored(EV, null, List.of(5L));
|
||||
|
||||
service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(null, null, "CONTACTED", List.of(5L, 3L), null, null));
|
||||
|
||||
assertThat(sent(UPDATE)).containsEntry("interestIds", List.of(5L, 3L));
|
||||
}
|
||||
|
||||
// --- already captured ---
|
||||
|
||||
@Test
|
||||
void alreadyCapturedCarriesTheExistingEventLeadUuid() {
|
||||
byte[] body = ("{\"status\":409,\"detail\":\"ALREADY_CAPTURED\",\"eventLeadUuid\":\"" + EL + "\"}").getBytes(StandardCharsets.UTF_8);
|
||||
when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, body, StandardCharsets.UTF_8));
|
||||
|
||||
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getCode()).isEqualTo("ALREADY_CAPTURED");
|
||||
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("eventLeadUuid", String.valueOf(EL));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyCapturedByARaceFindsTheEventLeadThroughMatching() {
|
||||
when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, "{\"status\":409}".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("leadUuid", LEAD);
|
||||
m.put("eventLeadUuid", EL);
|
||||
when(rest.postForEntity(eq(MATCHES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(m)));
|
||||
|
||||
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e ->
|
||||
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("eventLeadUuid", String.valueOf(EL)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pickedLeadOfAnotherCompanyIsNotFound() {
|
||||
when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", null, null, null));
|
||||
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null);
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture("abc", "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
// --- listing, get, update ---
|
||||
|
||||
@Test
|
||||
void listingSendsFiltersAndNamesSalespeopleAndInterests() {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("eventLeadUuid", EL);
|
||||
row.put("eventUuid", EV);
|
||||
row.put("leadUuid", LEAD);
|
||||
row.put("name", "Aisyah");
|
||||
row.put("mobileE164", "+60123456789");
|
||||
row.put("leadType", "EXISTING");
|
||||
row.put("salespersonUserId", 22L);
|
||||
row.put("temperature", "HOT");
|
||||
row.put("status", "OPEN");
|
||||
row.put("nextFollowUpDate", "2027-01-20");
|
||||
row.put("interestIds", List.of(3, 5));
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(row), "totalElements", 1, "totalPages", 1, "number", 0, "size", 20)));
|
||||
|
||||
Map<String, Object> out = service.list(String.valueOf(EV), 22L, "HOT", "OPEN", 3L, "EXISTING", 0, 20);
|
||||
|
||||
assertThat(sent(SEARCH)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserId", 22L)
|
||||
.containsEntry("temperature", "HOT").containsEntry("status", "OPEN").containsEntry("interestId", 3L)
|
||||
.containsEntry("leadType", "EXISTING").containsEntry("page", 0).containsEntry("size", 20);
|
||||
assertThat(out).containsEntry("totalElements", 1);
|
||||
Map<String, Object> first = ((List<Map<String, Object>>) out.get("content")).get(0);
|
||||
assertThat(first).containsEntry("eventLeadUuid", String.valueOf(EL)).containsEntry("mobile", "+60123456789")
|
||||
.containsEntry("salesperson", Map.of("id", 22L, "name", "Sales Two")).containsEntry("nextFollowUpDate", "2027-01-20");
|
||||
assertThat((List<Map<String, Object>>) first.get("interests")).containsExactly(
|
||||
Map.of("id", 3L, "name", "Cookware", "active", true), Map.of("id", 5L, "name", "Old", "active", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventLeadOfAnotherEventIsNotFound() {
|
||||
stubStored(EV + 1, null, List.of());
|
||||
|
||||
assertCoded(() -> service.get(String.valueOf(EV), String.valueOf(EL)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null);
|
||||
assertCoded(() -> service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(null, null, "OPEN", List.of(), null, null)),
|
||||
HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null);
|
||||
assertNothingSent(UPDATE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownEventLeadIsNotFound() {
|
||||
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL)))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", null, null, null));
|
||||
|
||||
assertCoded(() -> service.get(String.valueOf(EV), String.valueOf(EL)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getShowsSalespersonAndInterestsByName() {
|
||||
stubStored(EV, 21L, List.of(4L));
|
||||
|
||||
Map<String, Object> out = service.get(String.valueOf(EV), String.valueOf(EL));
|
||||
|
||||
assertThat(out).containsEntry("salesperson", Map.of("id", 21L, "name", "Sales One"))
|
||||
.containsEntry("name", "Aisyah").containsEntry("leadType", "NEW");
|
||||
assertThat((List<Map<String, Object>>) out.get("interests")).containsExactly(Map.of("id", 4L, "name", "Kitchen appliances", "active", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWorksALead() {
|
||||
stubStored(EV, null, List.of());
|
||||
|
||||
Map<String, Object> out = service.update(String.valueOf(EV), String.valueOf(EL),
|
||||
new AdminEventLeadUpdateRequest(21L, "HOT", "CONTACTED", List.of(3L), "2027-01-20", " call back "));
|
||||
|
||||
assertThat(sent(UPDATE)).containsEntry("temperature", "HOT").containsEntry("status", "CONTACTED")
|
||||
.containsEntry("nextFollowUpDate", "2027-01-20").containsEntry("notes", "call back").containsEntry("interestIds", List.of(3L));
|
||||
assertThat(out).containsEntry("status", "CONTACTED").containsEntry("temperature", "HOT");
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/** Mobile numbers become E.164 (Malaysia by default) and emails are trimmed and lowercased, so one person is one value. */
|
||||
class EventLeadContactTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"012-345 6789", "0123456789", "+60 12-345 6789", "60123456789", " +60123456789 ", "(012) 345-6789"})
|
||||
void malaysianFormatsAreOneNumber(String input) {
|
||||
assertThat(EventLeadContact.mobile(input)).isEqualTo("+60123456789");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"+65 9123 4567", "+6591234567"})
|
||||
void foreignNumbersKeepTheirCountryCode(String input) {
|
||||
assertThat(EventLeadContact.mobile(input)).isEqualTo("+6591234567");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"12345", "abc", "0123", "+60 1"})
|
||||
void invalidNumbersAreRefused(String input) {
|
||||
assertThatThrownBy(() -> EventLeadContact.mobile(input)).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void blankMobileIsNull(String input) {
|
||||
assertThat(EventLeadContact.mobile(input)).isNull();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {" Aisyah@Example.COM ", "aisyah@example.com", "AISYAH@EXAMPLE.COM"})
|
||||
void emailIsTrimmedAndLowercased(String input) {
|
||||
assertThat(EventLeadContact.email(input)).isEqualTo("aisyah@example.com");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"aisyah", "aisyah@", "@example.com", "a b@example.com", "a@b@example.com", "aisyah@example"})
|
||||
void invalidEmailsAreRefused(String input) {
|
||||
assertThatThrownBy(() -> EventLeadContact.email(input)).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void blankEmailIsNull(String input) {
|
||||
assertThat(EventLeadContact.email(input)).isNull();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user