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:
ngqileandClaude Opus 5.5 committed 2026-11-27 11:37:27 +08:00
1 parent 5d768b1566
commit fe9d9bd38d
12 files changed
+1312 -1

No files matched your search

@@ -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);
}
}
@@ -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");
}
}
@@ -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();
}
}