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

@@ -39,7 +39,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially
## 3. mobile-api
- [ ] 3.1 Add the leads admin API (design decision 4): list, detail and update under `/api/admin/leads`, with the module rules and the second check in code.
- [x] 3.1 Add the leads admin API (design decision 4): list, detail and update under `/api/admin/leads`, with the module rules and the second check in code.
Tests first:
- each validation code, with update normalisation the same as capture;
@@ -41,6 +41,9 @@ public class RestApiCounterServiceConstants {
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_LEAD_SEARCH="/counter/lead/search";
public static final String API_REST_COUNTER_LEAD_DETAIL="/counter/lead/detail/{companyId}/{leadUuid}";
public static final String API_REST_COUNTER_LEAD_UPDATE="/counter/lead/update";
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";
@@ -0,0 +1,48 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
import com.solvway.mobile.api.service.AdminLeadService;
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.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.Map;
/** Lead Listing, detail and edit. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin/leads")
@RequiredArgsConstructor
public class AdminLeadController {
private final AdminLeadService adminLeadService;
@AppAuth
@AdminModule("BO_LEADS")
@GetMapping
public ResponseEntity<Map<String, Object>> list(@RequestParam(required = false) String q,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return ResponseEntity.ok(adminLeadService.list(q, page, size));
}
@AppAuth
@AdminModule("BO_LEADS")
@GetMapping("/{leadUuid}")
public ResponseEntity<Map<String, Object>> get(@PathVariable String leadUuid) {
return ResponseEntity.ok(adminLeadService.get(leadUuid));
}
@AppAuth
@AdminModule(value = "BO_LEADS_EDIT", also = "BO_LEADS")
@PutMapping("/{leadUuid}")
public ResponseEntity<Map<String, Object>> update(@PathVariable String leadUuid, @RequestBody AdminLeadUpdateRequest request) {
return ResponseEntity.ok(adminLeadService.update(leadUuid, request));
}
}
@@ -0,0 +1,4 @@
package com.solvway.mobile.api.dto.admin;
/** A lead's own fields. mobile and email are normalised server-side; at least one is required. */
public record AdminLeadUpdateRequest(String name, String mobile, String email, String companyName, String jobTitle, String notes) {}
@@ -368,7 +368,7 @@ public class AdminEventLeadService {
return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled"));
}
private static String mobile(String input) {
static String mobile(String input) {
try {
return EventLeadContact.mobile(input);
} catch (IllegalArgumentException e) {
@@ -376,7 +376,7 @@ public class AdminEventLeadService {
}
}
private static String email(String input) {
static String email(String input) {
try {
return EventLeadContact.email(input);
} catch (IllegalArgumentException e) {
@@ -399,16 +399,16 @@ public class AdminEventLeadService {
return value;
}
private static String maxLength(String field, String value, int max) {
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) {
static String trimmed(String s) {
return s == null || s.isBlank() ? null : s.trim();
}
private static long parseOr(String s, java.util.function.Supplier<CodedResponseStatusException> notFound) {
static long parseOr(String s, java.util.function.Supplier<CodedResponseStatusException> notFound) {
try {
return Long.parseLong(s.trim());
} catch (RuntimeException e) {
@@ -421,11 +421,11 @@ public class AdminEventLeadService {
return l.stream().filter(Number.class::isInstance).map(o -> ((Number) o).longValue()).toList();
}
private static String str(Object o) {
static String str(Object o) {
return o == null ? null : String.valueOf(o);
}
private static CodedResponseStatusException required(List<String> fields) {
static CodedResponseStatusException required(List<String> fields) {
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: " + String.join(", ", fields), "REQUIRED_FIELD", fields.get(0));
e.getBody().setProperty("errors", fields);
return e;
@@ -439,7 +439,7 @@ public class AdminEventLeadService {
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) {
static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) {
CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code);
if (field != null) e.getBody().setProperty("details", Map.of("field", field));
return e;
@@ -0,0 +1,197 @@
package com.solvway.mobile.api.service;
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.AdminLeadUpdateRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
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.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.solvway.mobile.api.service.AdminEventLeadService.email;
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
import static com.solvway.mobile.api.service.AdminEventLeadService.maxLength;
import static com.solvway.mobile.api.service.AdminEventLeadService.mobile;
import static com.solvway.mobile.api.service.AdminEventLeadService.parseOr;
import static com.solvway.mobile.api.service.AdminEventLeadService.required;
import static com.solvway.mobile.api.service.AdminEventLeadService.str;
import static com.solvway.mobile.api.service.AdminEventLeadService.trimmed;
/**
* Lead Listing, detail and edit for the admin portal. Validates and normalises at this boundary; services-counter stores.
* Company comes from the logged-in admin. Uuids leave as strings (Snowflake longs). Never log a lead's name, mobile or email.
*/
@Service
@RequiredArgsConstructor
@SuppressWarnings("unchecked")
public class AdminLeadService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
public Map<String, Object> list(String q, int page, int size) {
String term = trimmed(q);
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller().getCompanyId());
body.put("q", term);
body.put("mobileDigits", mobileDigits(term));
body.put("page", Math.max(page, 0));
body.put("size", size);
Map<String, Object> p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_SEARCH), MAP, body).getBody();
List<Map<String, Object>> rows = p == null || p.get("content") == null ? List.of() : (List<Map<String, Object>>) p.get("content");
Map<Long, Map<String, Object>> users = new HashMap<>();
Map<String, Object> out = new LinkedHashMap<>();
out.put("content", rows.stream().map(r -> row(r, users)).toList());
out.put("totalElements", p == null ? 0 : p.get("totalElements"));
return out;
}
public Map<String, Object> get(String leadUuid) {
long id = parseOr(leadUuid, AdminLeadService::notFound);
Map<String, Object> d;
try {
d = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_DETAIL), MAP, caller().getCompanyId(), id).getBody();
} catch (HttpClientErrorException.NotFound e) {
throw notFound();
}
return detail(d);
}
public Map<String, Object> update(String leadUuid, AdminLeadUpdateRequest r) {
User caller = caller();
long id = parseOr(leadUuid, AdminLeadService::notFound);
String name = trimmed(r.name());
String mobile = mobile(r.mobile());
String email = email(r.email());
List<String> missing = new ArrayList<>();
if (name == null) missing.add("name");
if (mobile == null && email == null) { missing.add("mobile"); missing.add("email"); }
if (!missing.isEmpty()) throw required(missing);
maxLength("name", name, 100);
maxLength("email", email, 254);
String companyName = maxLength("companyName", trimmed(r.companyName()), 150);
String jobTitle = maxLength("jobTitle", trimmed(r.jobTitle()), 100);
String notes = maxLength("notes", trimmed(r.notes()), 2000);
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("leadUuid", id);
body.put("name", name);
body.put("mobileE164", mobile);
body.put("email", email);
body.put("companyName", companyName);
body.put("jobTitle", jobTitle);
body.put("notes", notes);
body.put("doneBy", caller.getUsername());
try {
return detail(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody());
} catch (HttpClientErrorException.NotFound e) {
throw notFound();
}
}
/** Digits to match against the stored E.164 mobile, or null when the term is not a phone-like number. */
private static String mobileDigits(String q) {
if (q == null) return null;
String d = q.replaceAll("[\\s\\-()]", "");
if (d.startsWith("+")) d = d.substring(1);
if (!d.matches("\\d+")) return null;
d = d.startsWith("60") ? d.substring(2) : d.startsWith("0") ? d.substring(1) : d;
return d.isEmpty() ? null : d;
}
private Map<String, Object> row(Map<String, Object> d, Map<Long, Map<String, Object>> users) {
Map<String, Object> m = new LinkedHashMap<>();
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("eventCount", d.get("eventCount"));
Map<String, Object> lastEvent = null;
if (d.get("lastEventUuid") != null) {
lastEvent = new LinkedHashMap<>();
lastEvent.put("uuid", str(d.get("lastEventUuid")));
lastEvent.put("name", d.get("lastEventName"));
}
m.put("lastEvent", lastEvent);
m.put("lastCapturedAt", d.get("lastCapturedAt"));
m.put("latestSalesperson", salesperson(d.get("latestSalespersonUserId"), users));
return m;
}
private Map<String, Object> detail(Map<String, Object> d) {
Map<Long, Map<String, Object>> users = new HashMap<>();
Map<String, Object> m = new LinkedHashMap<>();
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("notes", d.get("notes"));
m.put("createdAt", d.get("createdAt"));
m.put("updatedAt", d.get("updatedAt"));
m.put("updatedBy", d.get("updatedBy"));
List<Map<String, Object>> history = d.get("history") == null ? List.of() : (List<Map<String, Object>>) d.get("history");
m.put("history", history.stream().map(h -> {
Map<String, Object> e = new LinkedHashMap<>();
e.put("eventLeadUuid", str(h.get("eventLeadUuid")));
e.put("eventUuid", str(h.get("eventUuid")));
e.put("eventName", h.get("eventName"));
e.put("eventStart", h.get("eventStart"));
e.put("eventEnd", h.get("eventEnd"));
e.put("leadType", h.get("leadType"));
e.put("salesperson", salesperson(h.get("salespersonUserId"), users));
e.put("temperature", h.get("temperature"));
e.put("status", h.get("status"));
e.put("capturedAt", h.get("capturedAt"));
return e;
}).toList());
List<Map<String, Object>> shared = d.get("sharedContacts") == null ? List.of() : (List<Map<String, Object>>) d.get("sharedContacts");
m.put("sharedContacts", shared.stream().map(s -> {
Map<String, Object> e = new LinkedHashMap<>();
e.put("leadUuid", str(s.get("leadUuid")));
e.put("name", s.get("name"));
e.put("sameMobile", s.get("sameMobile"));
e.put("sameEmail", s.get("sameEmail"));
return e;
}).toList());
return m;
}
/** {id, name} or null; one user lookup per distinct id per request. */
private Map<String, Object> salesperson(Object id, Map<Long, Map<String, Object>> users) {
if (!(id instanceof Number n)) return null;
Map<String, Object> u = users.computeIfAbsent(n.longValue(), uid ->
restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, uid).getBody());
return Map.of("id", n.longValue(), "name", u == null ? String.valueOf(n) : String.valueOf(u.get("name")));
}
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);
}
private static CodedResponseStatusException notFound() {
return error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null);
}
}
@@ -21,6 +21,13 @@ public @interface AdminModule {
String[] value();
/**
* Modules the caller must hold in addition to the any-of {@link #value()}: every one of them, each checked like
* {@code value}. Super-admin still passes; {@link #ANY_ADMIN} ignores it. A method-level annotation
* replaces the class-level one entirely, {@code also} included; the two never combine.
*/
String[] also() default {};
/**
* Lets an admin whose first-login password change is pending ({@code login = N}) through. Only
* for the first-login and logout handlers; every other admin handler answers 403 while pending.
@@ -261,7 +261,12 @@ public class AppAccessAspect {
boolean granted = false;
if (declared != null) {
try {
granted = AdminModuleAccess.grantedAny(restTemplateUtil, roleIds, declared.value());
// Assigned only after every lookup returns, so a lookup that throws part-way never leaves access granted.
boolean all = AdminModuleAccess.grantedAny(restTemplateUtil, roleIds, declared.value());
for (String required : declared.also()) {
all = all && AdminModuleAccess.grantedAny(restTemplateUtil, roleIds, required);
}
granted = all;
} catch (Exception ex) {
log.error("[AppAccessAspect] admin module lookup failed, failing closed: {}", ex.getClass().getSimpleName());
}
@@ -0,0 +1,72 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
import com.solvway.mobile.api.service.AdminLeadService;
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.util.Arrays;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
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.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 AdminLeadControllerTest {
@Mock private AdminLeadService leads;
@InjectMocks private AdminLeadController controller;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
private static Method handler(String name) {
return Arrays.stream(AdminLeadController.class.getDeclaredMethods()).filter(m -> m.getName().equals(name)).findFirst().orElseThrow();
}
@Test
void readsNeedBoLeads_editNeedsBoLeadsEditAndBoLeads() {
for (String n : new String[]{"list", "get", "update"}) assertThat(handler(n).isAnnotationPresent(AppAuth.class)).as(n).isTrue();
assertThat(handler("list").getAnnotation(AdminModule.class).value()).containsExactly("BO_LEADS");
assertThat(handler("get").getAnnotation(AdminModule.class).value()).containsExactly("BO_LEADS");
AdminModule edit = handler("update").getAnnotation(AdminModule.class);
assertThat(edit.value()).containsExactly("BO_LEADS_EDIT");
assertThat(edit.also()).containsExactly("BO_LEADS");
}
@Test
void listDefaultsPagingAndPassesQuery() throws Exception {
when(leads.list("ai", 0, 20)).thenReturn(Map.of("content", java.util.List.of(), "totalElements", 0));
mvc.perform(get("/api/admin/leads").param("q", "ai")).andExpect(status().isOk())
.andExpect(content().json("{\"content\":[],\"totalElements\":0}"));
}
@Test
void getAndPut() throws Exception {
when(leads.get("42")).thenReturn(Map.of("leadUuid", "42"));
mvc.perform(get("/api/admin/leads/42")).andExpect(status().isOk()).andExpect(content().json("{\"leadUuid\":\"42\"}"));
when(leads.update(org.mockito.ArgumentMatchers.eq("42"), any(AdminLeadUpdateRequest.class))).thenReturn(Map.of("leadUuid", "42"));
mvc.perform(put("/api/admin/leads/42").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"A\",\"mobile\":\"012\"}"))
.andExpect(status().isOk());
verify(leads).update("42", new AdminLeadUpdateRequest("A", "012", null, null, null, null));
}
}
@@ -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");
}
}
@@ -96,6 +96,13 @@ class AppAccessAspectAdminTest {
}
}
static class Also {
@AppAuth
@AdminModule(value = "BO_LEADS_EDIT", also = "BO_LEADS")
public void edit() {
}
}
@AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true)
static class PendingAtClassLevel {
@AppAuth
@@ -339,4 +346,70 @@ class AppAccessAspectAdminTest {
expect(HttpStatus.FORBIDDEN);
}
}
private void alsoModules() {
when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO")))
.thenReturn(ResponseEntity.ok(List.of(
Map.of("name", "BO_LEADS", "roles", List.of(Map.of("id", 5), Map.of("id", 6), Map.of("id", 2))),
Map.of("name", "BO_LEADS_EDIT", "roles", List.of(Map.of("id", 6), Map.of("id", 7), Map.of("id", 2))))));
}
@Test
void also_callerMissingTheAlsoModule_isForbidden() throws Throwable {
alsoModules();
target(Also.class, "edit");
when(guard.check(TOK, false)).thenReturn(admin(7L));
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
http(h, TOK, "A");
expect(HttpStatus.FORBIDDEN);
}
}
@Test
void also_callerHoldingBothModules_isAllowed() throws Throwable {
alsoModules();
target(Also.class, "edit");
when(guard.check(TOK, false)).thenReturn(admin(6L));
when(joinPoint.proceed()).thenReturn("ok");
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
http(h, TOK, "A");
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
}
}
@Test
void also_superAdminPasses() throws Throwable {
target(Also.class, "edit");
when(guard.check(TOK, false)).thenReturn(admin(1L));
when(joinPoint.proceed()).thenReturn("ok");
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
http(h, TOK, "A");
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
}
}
@Test
void also_injectedRoleAdmin2Alone_grantsNothing() throws Throwable {
alsoModules();
target(Also.class, "edit");
when(guard.check(TOK, false)).thenReturn(admin(2L));
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
http(h, TOK, "A");
expect(HttpStatus.FORBIDDEN);
}
}
@Test
void also_lookupFailingAfterTheFirstModuleGranted_failsClosed() throws Throwable {
// The first lookup grants BO_LEADS_EDIT; the also lookup then fails. A thrown lookup must never leave access granted.
when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO")))
.thenReturn(ResponseEntity.ok(List.of(Map.of("name", "BO_LEADS_EDIT", "roles", List.of(Map.of("id", 6))))))
.thenThrow(new IllegalStateException("system down"));
target(Also.class, "edit");
when(guard.check(TOK, false)).thenReturn(admin(6L));
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
http(h, TOK, "A");
expect(HttpStatus.FORBIDDEN);
}
}
}