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

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