feat(mobile-api): leads admin API and @AdminModule(also)

List, detail and update under /api/admin/leads. Update validates and
normalises like capture and needs both Edit leads and Leads, enforced by
the new also() attribute, which fails closed if any lookup throws.

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 16:15:36 +08:00
1 parent 6855906cf1
commit 963735d524
11 files changed
+686 -10

No files matched your search

@@ -0,0 +1,267 @@
package com.solvway.mobile.api.service;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
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.util.HashMap;
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminLeadServiceTest {
private static final String SEARCH = "/counter/lead/search";
private static final String DETAIL = "/counter/lead/detail/{companyId}/{leadUuid}";
private static final String UPDATE = "/counter/lead/update";
private static final String USER = "/user/findById/{id}";
private static final long LEAD = 3312853897040846848L;
private static final long EV = 3312726793093644288L;
private static final long EL = 3312853897594494976L;
private static final long COMPANY = 5L;
private RestTemplateCustomUtil rest;
private AdminLeadService service;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
service = new AdminLeadService(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);
stubUser(21L, "Sales One");
stubUser(22L, "Sales Two");
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()))
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0)));
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()))
.thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
}
@AfterEach
void close() { http.close(); }
private void stubUser(long id, String name) {
Map<String, Object> u = new HashMap<>();
u.put("id", id);
u.put("name", name);
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u));
}
private Map<String, Object> searched(String q) {
service.list(q, 2, 10);
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), body.capture());
return (Map<String, Object>) body.getValue();
}
// --- list ---
@Test
void list_sendsCompanyPagingAndTrimmedQuery() {
Map<String, Object> b = searched(" aisyah ");
assertThat(b).containsEntry("companyId", COMPANY).containsEntry("q", "aisyah").containsEntry("page", 2).containsEntry("size", 10)
.containsEntry("mobileDigits", null);
}
@Test
void list_blankQueryIsNull() {
assertThat(searched(" ")).containsEntry("q", null).containsEntry("mobileDigits", null);
}
@Test
void list_digitsKey() {
assertThat(searched("012-345 6701")).containsEntry("mobileDigits", "123456701");
}
@Test
void list_digitsKeyDropsPlusAndCountryCode() {
assertThat(searched("+60 12-345 6701")).containsEntry("mobileDigits", "123456701");
}
@Test
void list_digitsKeyShortCountryCodePrefix() {
assertThat(searched("6012")).containsEntry("mobileDigits", "12");
}
@Test
void list_textHasNoDigitsKey() {
assertThat(searched("aisyah")).containsEntry("mobileDigits", null);
}
@Test
void list_mapsRowsWithStringUuidsAndResolvesRepeatedSalespersonOnce() {
Map<String, Object> r1 = new HashMap<>(Map.of("leadUuid", LEAD, "name", "Aisyah", "mobileE164", "+60123456701", "email", "a@x.test",
"eventCount", 2, "lastEventUuid", EV, "lastEventName", "Fair", "lastCapturedAt", "2027-01-15T10:00:00",
"latestSalespersonUserId", 22L));
Map<String, Object> r2 = new HashMap<>(Map.of("leadUuid", LEAD + 1, "name", "Bob", "eventCount", 0, "latestSalespersonUserId", 22L));
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()))
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(r1, r2), "totalElements", 7)));
Map<String, Object> out = service.list(null, 0, 20);
List<Map<String, Object>> rows = (List<Map<String, Object>>) out.get("content");
assertThat(out.get("totalElements")).isEqualTo(7);
assertThat(rows.get(0)).containsEntry("leadUuid", String.valueOf(LEAD)).containsEntry("mobile", "+60123456701")
.containsEntry("eventCount", 2).containsEntry("lastCapturedAt", "2027-01-15T10:00:00")
.containsEntry("lastEvent", Map.of("uuid", String.valueOf(EV), "name", "Fair"))
.containsEntry("latestSalesperson", Map.of("id", 22L, "name", "Sales Two"));
assertThat(rows.get(1)).containsEntry("lastEvent", null).containsEntry("latestSalesperson", Map.of("id", 22L, "name", "Sales Two"));
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(22L));
}
@Test
void list_rowWithoutSalespersonHasNull() {
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()))
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(new HashMap<>(Map.of("leadUuid", LEAD, "name", "A"))), "totalElements", 1)));
List<Map<String, Object>> rows = (List<Map<String, Object>>) service.list(null, 0, 20).get("content");
assertThat(rows.get(0)).containsEntry("latestSalesperson", null);
}
// --- detail ---
private Map<String, Object> detail() {
Map<String, Object> h = new HashMap<>(Map.of("eventLeadUuid", EL, "eventUuid", EV, "eventName", "Fair", "leadType", "NEW",
"salespersonUserId", 21L, "temperature", "HOT", "status", "OPEN", "capturedAt", "2027-01-15T10:00:00"));
h.put("eventStart", "2027-01-15T00:00:00");
h.put("eventEnd", "2027-01-17T23:59:59");
Map<String, Object> h2 = new HashMap<>(Map.of("eventLeadUuid", EL + 1, "eventUuid", EV, "salespersonUserId", 21L));
Map<String, Object> d = new HashMap<>(Map.of("leadUuid", LEAD, "name", "Aisyah", "mobileE164", "+60123456701", "email", "a@x.test",
"companyName", "Acme", "jobTitle", "Buyer", "notes", "n", "createdAt", "c", "updatedAt", "u", "updatedBy", "sales1"));
d.put("history", List.of(h, h2));
d.put("sharedContacts", List.of(Map.of("leadUuid", LEAD + 5, "name", "Twin", "sameMobile", true, "sameEmail", false)));
return d;
}
@Test
void get_mapsHistoryAndSharedContacts() {
when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(COMPANY), eq(LEAD))).thenReturn(ResponseEntity.ok(detail()));
Map<String, Object> v = service.get(String.valueOf(LEAD));
assertThat(v).containsEntry("leadUuid", String.valueOf(LEAD)).containsEntry("mobile", "+60123456701")
.containsEntry("companyName", "Acme").containsEntry("notes", "n").containsEntry("updatedBy", "sales1");
List<Map<String, Object>> history = (List<Map<String, Object>>) v.get("history");
assertThat(history.get(0)).containsEntry("eventLeadUuid", String.valueOf(EL)).containsEntry("eventUuid", String.valueOf(EV))
.containsEntry("eventName", "Fair").containsEntry("eventStart", "2027-01-15T00:00:00").containsEntry("leadType", "NEW")
.containsEntry("salesperson", Map.of("id", 21L, "name", "Sales One")).containsEntry("temperature", "HOT")
.containsEntry("status", "OPEN").containsEntry("capturedAt", "2027-01-15T10:00:00");
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L));
assertThat((List<Map<String, Object>>) v.get("sharedContacts")).containsExactly(
Map.of("leadUuid", String.valueOf(LEAD + 5), "name", "Twin", "sameMobile", true, "sameEmail", false));
}
@Test
void get_unparsableUuidIs404() {
assertCoded(() -> service.get("abc"), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null);
}
@Test
void get_counter404Is404() {
when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(COMPANY), eq(LEAD)))
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
assertCoded(() -> service.get(String.valueOf(LEAD)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null);
}
// --- update ---
private static AdminLeadUpdateRequest req(String name, String mobile, String email) {
return new AdminLeadUpdateRequest(name, mobile, email, null, null, null);
}
private 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);
});
}
@Test
void update_unparsableUuidIs404() {
assertCoded(() -> service.update("abc", req("A", "0123456701", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null);
}
@Test
void update_counter404Is404() {
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()))
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
assertCoded(() -> service.update(String.valueOf(LEAD), req("A", "012-345 6701", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null);
}
@Test
void update_nameRequired() {
assertThatThrownBy(() -> service.update(String.valueOf(LEAD), req(" ", "012-345 6701", null)))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD");
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("name"));
});
}
@Test
void update_contactRequired() {
assertThatThrownBy(() -> service.update(String.valueOf(LEAD), req("A", " ", null)))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD");
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("mobile", "email"));
});
}
@Test
void update_nameAndContactMissingListsNameFirst() {
assertThatThrownBy(() -> service.update(String.valueOf(LEAD), req(null, null, null)))
.isInstanceOfSatisfying(CodedResponseStatusException.class,
e -> assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("name", "mobile", "email")));
}
@Test
void update_invalidMobileAndEmail() {
assertCoded(() -> service.update(String.valueOf(LEAD), req("A", "12", null)), HttpStatus.BAD_REQUEST, "INVALID_MOBILE", "mobile");
assertCoded(() -> service.update(String.valueOf(LEAD), req("A", null, "nope")), HttpStatus.BAD_REQUEST, "INVALID_EMAIL", "email");
}
@Test
void update_tooLong() {
String ok = "0123456701";
assertCoded(() -> service.update(String.valueOf(LEAD), req("x".repeat(101), ok, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "name");
assertCoded(() -> service.update(String.valueOf(LEAD), req("A", null, "a".repeat(250) + "@x.test")), HttpStatus.BAD_REQUEST, "TOO_LONG", "email");
assertCoded(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("A", ok, null, "x".repeat(151), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "companyName");
assertCoded(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("A", ok, null, null, "x".repeat(101), null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "jobTitle");
assertCoded(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("A", ok, null, null, null, "x".repeat(2001))), HttpStatus.BAD_REQUEST, "TOO_LONG", "notes");
}
@Test
void update_normalisesAndSendsDoneBy() {
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest(" Aisyah ", "012-345 6701", " Aisyah@Example.TEST ", " ", " Buyer ", ""));
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), body.capture());
assertThat((Map<String, Object>) body.getValue()).containsEntry("companyId", COMPANY).containsEntry("leadUuid", LEAD)
.containsEntry("name", "Aisyah").containsEntry("mobileE164", "+60123456701").containsEntry("email", "aisyah@example.test")
.containsEntry("companyName", null).containsEntry("jobTitle", "Buyer").containsEntry("notes", null)
.containsEntry("doneBy", "sales1");
}
}