From fe9d9bd38de056d4aee24d35a6fa6dc6bee9d9fa Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 11:37:27 +0800 Subject: [PATCH] feat(mobile-api): event leads API with phone normalisation and team rule Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-event-lead-capture/tasks.md | 2 +- solvway-mobile-api/pom.xml | 6 + .../api/RestApiCounterServiceConstants.java | 5 + .../admin/AdminEventLeadController.java | 93 +++ .../admin/AdminEventLeadCaptureRequest.java | 8 + .../admin/AdminEventLeadUpdateRequest.java | 7 + .../api/dto/admin/AdminLeadMatchRequest.java | 4 + .../api/service/AdminEventLeadService.java | 447 +++++++++++++++ .../mobile/api/service/EventLeadContact.java | 38 ++ .../admin/AdminEventLeadControllerTest.java | 111 ++++ .../service/AdminEventLeadServiceTest.java | 536 ++++++++++++++++++ .../api/service/EventLeadContactTest.java | 56 ++ 12 files changed, 1312 insertions(+), 1 deletion(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/EventLeadContact.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/EventLeadContactTest.java diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md index 7f23722..2e9b0f3 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -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` diff --git a/solvway-mobile-api/pom.xml b/solvway-mobile-api/pom.xml index 94b06ab..3e451a0 100644 --- a/solvway-mobile-api/pom.xml +++ b/solvway-mobile-api/pom.xml @@ -61,6 +61,12 @@ org.springframework.boot spring-boot-starter-validation + + + com.googlecode.libphonenumber + libphonenumber + 8.13.55 + org.springframework.boot diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index 0fb5b82..af58433 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -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}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java new file mode 100644 index 0000000..6eb3a36 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java @@ -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>> events() { + return ResponseEntity.ok(adminEventLeadService.events()); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @GetMapping("/interest-options") + public ResponseEntity>> interestOptions() { + return ResponseEntity.ok(adminEventLeadService.interestOptions()); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @GetMapping("/{eventUuid}/salesperson-options") + public ResponseEntity>> salespersonOptions(@PathVariable String eventUuid) { + return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid)); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @PostMapping("/{eventUuid}/match") + public ResponseEntity> match(@PathVariable String eventUuid, @RequestBody AdminLeadMatchRequest request) { + return ResponseEntity.ok(adminEventLeadService.match(eventUuid, request)); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @PostMapping("/{eventUuid}") + public ResponseEntity> capture(@PathVariable String eventUuid, @RequestBody AdminEventLeadCaptureRequest request) { + return ResponseEntity.ok(adminEventLeadService.capture(eventUuid, request)); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @GetMapping("/{eventUuid}/leads") + public ResponseEntity> 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> 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> update(@PathVariable String eventUuid, @PathVariable String eventLeadUuid, + @RequestBody AdminEventLeadUpdateRequest request) { + return ResponseEntity.ok(adminEventLeadService.update(eventUuid, eventLeadUuid, request)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java new file mode 100644 index 0000000..b4f3d34 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java @@ -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 interestIds, String nextFollowUpDate, String notes) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java new file mode 100644 index 0000000..42b5a9e --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java @@ -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 interestIds, + String nextFollowUpDate, String notes) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java new file mode 100644 index 0000000..df705df --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java @@ -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) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java new file mode 100644 index 0000000..78df6f5 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -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 TEMPERATURES = Set.of("HOT", "WARM", "COLD"); + private static final Set STATUSES = Set.of("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST"); + private static final Set LEAD_TYPES = Set.of("NEW", "EXISTING"); + private static final int EVENT_PAGE = 100; + private static final ObjectMapper JSON = new ObjectMapper(); + + private static final ParameterizedTypeReference PAGE = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> 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> events() { + Map 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 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> interestOptions() { + return interests(caller().getCompanyId()).values().stream().filter(i -> Boolean.TRUE.equals(i.get("active"))).toList(); + } + + public List> salespersonOptions(String eventUuid) { + Event event = loadEvent(eventUuid); + List> out = new ArrayList<>(); + for (Long id : teamIds(event.getUuid())) { + Map 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 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 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 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 capture(String eventUuid, AdminEventLeadCaptureRequest r) { + User caller = caller(); + String name = trimmed(r.name()); + String mobile = mobile(r.mobile()); + String email = email(r.email()); + List 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> known = interests(caller.getCompanyId()); + List interestIds = checkedInterests(known, r.interestIds(), List.of()); + + Map 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 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 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 p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), MAP, body).getBody(); + List> rows = p == null || p.get("content") == null ? List.of() : (List>) p.get("content"); + Map> interests = rows.isEmpty() ? Map.of() : interests(caller.getCompanyId()); + Map> users = new HashMap<>(); + Map 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 get(String eventUuid, String eventLeadUuid) { + User caller = caller(); + return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId()); + } + + public Map 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 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> known = interests(caller.getCompanyId()); + List interestIds = checkedInterests(known, r.interestIds(), longs(current.get("interestIds"))); + + Map 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 checkedInterests(Map> known, List requested, List current) { + List ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList())); + for (Long id : ids) { + Map 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 stored(long companyId, String eventUuid, String eventLeadUuid) { + Event event = loadEvent(eventUuid); + long id = parseOr(eventLeadUuid, AdminEventLeadService::eventLeadNotFound); + Map 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 view(Map d, long companyId) { + return view(d, interests(companyId), new HashMap<>()); + } + + private Map view(Map d, Map> interests, Map> users) { + Map 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 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 i = interests.get(id); + return Map.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> findMatches(long companyId, long eventUuid, String mobile, String email) { + Map body = new LinkedHashMap<>(); + body.put("companyId", companyId); + body.put("eventUuid", eventUuid); + body.put("mobileE164", mobile); + body.put("email", email); + List> 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> interests(long companyId) { + List> rows = restTemplateUtil.getForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId).getBody(); + Map> out = new LinkedHashMap<>(); + if (rows != null) for (Map 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 teamIds(long eventUuid) { + List> 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 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 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 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 notFound) { + try { + return Long.parseLong(s.trim()); + } catch (RuntimeException e) { + throw notFound.get(); + } + } + + private static List 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 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; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/EventLeadContact.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/EventLeadContact.java new file mode 100644 index 0000000..8a526b8 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/EventLeadContact.java @@ -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; + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java new file mode 100644 index 0000000..02117b8 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java @@ -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 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); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java new file mode 100644 index 0000000..830a191 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java @@ -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 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) i.getArgument(2)))); + when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(detailFrom((Map) 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> 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 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 interest(long id, String name, boolean active) { + return Map.of("id", id, "companyId", COMPANY, "name", name, "active", active, "sortOrder", 0); + } + + private void stubInterests(Map... 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 detailFrom(Map body) { + Map 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 interestIds) { + Map 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 interests, String followUp) { + return new AdminEventLeadCaptureRequest(null, "Aisyah", "0123456789", null, null, null, salespersonId, temperature, status, interests, followUp, null); + } + + private Map sent(String api) { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture()); + return (Map) 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) 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> 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 body = sent(EVENTS); + assertThat((Map) body.get("property")).containsEntry("enabled", "Y"); + Map pageable = (Map) body.get("pageableRest"); + assertThat(pageable).containsEntry("size", 100); + assertThat((List>) 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 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 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 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 candidate = ((List>) 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 out = service.capture(String.valueOf(EV), capture(null, " Aisyah ", "+60 12-345 6789", " Aisyah@Example.COM ")); + + Map 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) 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 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) 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 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 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 first = ((List>) 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>) 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 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>) out.get("interests")).containsExactly(Map.of("id", 4L, "name", "Kitchen appliances", "active", true)); + } + + @Test + void updateWorksALead() { + stubStored(EV, null, List.of()); + + Map 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"); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/EventLeadContactTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/EventLeadContactTest.java new file mode 100644 index 0000000..6b28c98 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/EventLeadContactTest.java @@ -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(); + } +}