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

@@ -40,6 +40,11 @@ public class RestApiCounterServiceConstants {
public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}";
public static final String API_REST_COUNTER_INTEREST_SAVE="/counter/interest/save";
public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds";
public static final String API_REST_COUNTER_LEAD_FIND_MATCHES="/counter/lead/findMatches";
public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture";
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}";
public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update";
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT="/counter/eventLead/findByEvent";
//Event Product
public static final String API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID = "/counter/eventProduct/findByEventUuid/{eventUuid}";
@@ -0,0 +1,93 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
import com.solvway.mobile.api.service.AdminEventLeadService;
import com.solvway.mobile.api.useraccess.AdminModule;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/** Event-floor lead capture: events, options, match, capture, listing and edit. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin/event-leads")
@RequiredArgsConstructor
public class AdminEventLeadController {
private final AdminEventLeadService adminEventLeadService;
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@GetMapping("/events")
public ResponseEntity<List<Map<String, Object>>> events() {
return ResponseEntity.ok(adminEventLeadService.events());
}
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@GetMapping("/interest-options")
public ResponseEntity<List<Map<String, Object>>> interestOptions() {
return ResponseEntity.ok(adminEventLeadService.interestOptions());
}
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@GetMapping("/{eventUuid}/salesperson-options")
public ResponseEntity<List<Map<String, Object>>> salespersonOptions(@PathVariable String eventUuid) {
return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid));
}
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@PostMapping("/{eventUuid}/match")
public ResponseEntity<Map<String, Object>> match(@PathVariable String eventUuid, @RequestBody AdminLeadMatchRequest request) {
return ResponseEntity.ok(adminEventLeadService.match(eventUuid, request));
}
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@PostMapping("/{eventUuid}")
public ResponseEntity<Map<String, Object>> capture(@PathVariable String eventUuid, @RequestBody AdminEventLeadCaptureRequest request) {
return ResponseEntity.ok(adminEventLeadService.capture(eventUuid, request));
}
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@GetMapping("/{eventUuid}/leads")
public ResponseEntity<Map<String, Object>> list(@PathVariable String eventUuid,
@RequestParam(required = false) Long salespersonId,
@RequestParam(required = false) String temperature,
@RequestParam(required = false) String status,
@RequestParam(required = false) Long interestId,
@RequestParam(required = false) String leadType,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return ResponseEntity.ok(adminEventLeadService.list(eventUuid, salespersonId, temperature, status, interestId, leadType, page, size));
}
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@GetMapping("/{eventUuid}/leads/{eventLeadUuid}")
public ResponseEntity<Map<String, Object>> get(@PathVariable String eventUuid, @PathVariable String eventLeadUuid) {
return ResponseEntity.ok(adminEventLeadService.get(eventUuid, eventLeadUuid));
}
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@PutMapping("/{eventUuid}/leads/{eventLeadUuid}")
public ResponseEntity<Map<String, Object>> update(@PathVariable String eventUuid, @PathVariable String eventLeadUuid,
@RequestBody AdminEventLeadUpdateRequest request) {
return ResponseEntity.ok(adminEventLeadService.update(eventUuid, eventLeadUuid, request));
}
}
@@ -0,0 +1,8 @@
package com.solvway.mobile.api.dto.admin;
import java.util.List;
/** Step 2 of capture. leadUuid is the picked match as a string, or null for a new person. nextFollowUpDate is YYYY-MM-DD. */
public record AdminEventLeadCaptureRequest(String leadUuid, String name, String mobile, String email, String companyName,
String jobTitle, Long salespersonId, String temperature, String status,
List<Long> interestIds, String nextFollowUpDate, String notes) {}
@@ -0,0 +1,7 @@
package com.solvway.mobile.api.dto.admin;
import java.util.List;
/** An event lead's working fields. nextFollowUpDate is YYYY-MM-DD; null clears it. */
public record AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List<Long> interestIds,
String nextFollowUpDate, String notes) {}
@@ -0,0 +1,4 @@
package com.solvway.mobile.api.dto.admin;
/** Step 1 of capture: the mobile and/or email to look up. */
public record AdminLeadMatchRequest(String mobile, String email) {}
@@ -0,0 +1,447 @@
package com.solvway.mobile.api.service;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.model.Event;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Lead capture at events for the admin portal. Validates and normalises at this boundary; services-counter stores.
* Company comes from the logged-in admin, never the request. Uuids leave as strings (Snowflake longs).
* Never log a lead's name, mobile or email.
*/
@Service
@RequiredArgsConstructor
@SuppressWarnings("unchecked")
public class AdminEventLeadService {
private static final Set<String> TEMPERATURES = Set.of("HOT", "WARM", "COLD");
private static final Set<String> STATUSES = Set.of("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST");
private static final Set<String> LEAD_TYPES = Set.of("NEW", "EXISTING");
private static final int EVENT_PAGE = 100;
private static final ObjectMapper JSON = new ObjectMapper();
private static final ParameterizedTypeReference<AdminEventService.EventPage> PAGE = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<Event> EVENT = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
// --- options ---
/** Enabled events, newest start first. ponytail: one page of 100; add paging when a company has more enabled events. */
public List<Map<String, Object>> events() {
Map<String, Object> request = Map.of("property", Map.of("name", "", "enabled", "Y"),
"pageableRest", Map.of("number", 0, "size", EVENT_PAGE, "sorts", List.of(Map.of("direction", "DESC", "property", "dateStart"))));
AdminEventService.EventPage p = restTemplateUtil.postForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE), PAGE, request).getBody();
if (p == null || p.content() == null) return List.of();
return p.content().stream().map(e -> {
Map<String, Object> m = new LinkedHashMap<>();
m.put("uuid", String.valueOf(e.getUuid()));
m.put("name", e.getName());
m.put("location", e.getLocation());
m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
return m;
}).toList();
}
public List<Map<String, Object>> interestOptions() {
return interests(caller().getCompanyId()).values().stream().filter(i -> Boolean.TRUE.equals(i.get("active"))).toList();
}
public List<Map<String, Object>> salespersonOptions(String eventUuid) {
Event event = loadEvent(eventUuid);
List<Map<String, Object>> out = new ArrayList<>();
for (Long id : teamIds(event.getUuid())) {
Map<String, Object> u = user(id);
if (isActiveAdmin(u)) out.add(Map.of("id", id, "name", String.valueOf(u.get("name")), "username", String.valueOf(u.get("username"))));
}
return out;
}
// --- capture ---
public Map<String, Object> match(String eventUuid, AdminLeadMatchRequest r) {
User caller = caller();
String mobile = mobile(r.mobile());
String email = email(r.email());
if (mobile == null && email == null) throw required(List.of("mobile", "email"));
Event event = loadEvent(eventUuid);
Map<String, Object> out = new LinkedHashMap<>();
out.put("mobile", mobile);
out.put("email", email);
out.put("candidates", findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream().map(m -> {
Map<String, Object> c = new LinkedHashMap<>();
c.put("leadUuid", str(m.get("leadUuid")));
c.put("name", m.get("name"));
c.put("mobile", m.get("mobileE164"));
c.put("email", m.get("email"));
c.put("companyName", m.get("companyName"));
c.put("jobTitle", m.get("jobTitle"));
c.put("eventLeadUuid", str(m.get("eventLeadUuid")));
return c;
}).toList());
return out;
}
public Map<String, Object> capture(String eventUuid, AdminEventLeadCaptureRequest r) {
User caller = caller();
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 temperature = oneOf("temperature", r.temperature(), TEMPERATURES);
String status = oneOf("status", r.status(), STATUSES);
LocalDate followUp = date(r.nextFollowUpDate());
Long leadUuid = r.leadUuid() == null ? null : parseOr(r.leadUuid(), () -> error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null));
Event event = loadEvent(eventUuid);
if (event.getEnabled() != GeneralEnum.FlagYesNo.Y) {
throw error(HttpStatus.CONFLICT, "This event is disabled and cannot take new leads", "EVENT_DISABLED", null);
}
if (r.salespersonId() != null) checkOnTeam(event.getUuid(), r.salespersonId());
Map<Long, Map<String, Object>> known = interests(caller.getCompanyId());
List<Long> interestIds = checkedInterests(known, r.interestIds(), List.of());
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("eventUuid", event.getUuid());
body.put("leadUuid", leadUuid);
body.put("name", name);
body.put("mobileE164", mobile);
body.put("email", email);
body.put("companyName", companyName);
body.put("jobTitle", jobTitle);
body.put("salespersonUserId", r.salespersonId());
body.put("temperature", temperature);
body.put("status", status);
body.put("interestIds", interestIds);
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
body.put("notes", trimmed(r.notes()));
body.put("doneBy", caller.getUsername());
try {
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_CAPTURE), MAP, body).getBody(),
known, new HashMap<>());
} catch (HttpClientErrorException.Conflict e) {
Object existing = conflictEventLeadUuid(e);
if (existing == null) existing = findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream()
.filter(m -> Objects.equals(str(m.get("leadUuid")), str(leadUuid))).map(m -> m.get("eventLeadUuid"))
.filter(Objects::nonNull).findFirst().orElse(null);
CodedResponseStatusException ex = new CodedResponseStatusException(HttpStatus.CONFLICT,
"This person is already captured at this event", "ALREADY_CAPTURED");
if (existing != null) ex.getBody().setProperty("details", Map.of("eventLeadUuid", str(existing)));
throw ex;
} catch (HttpClientErrorException.NotFound e) {
throw error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null);
}
}
// --- listing and edit ---
public Map<String, Object> list(String eventUuid, Long salespersonId, String temperature, String status, Long interestId,
String leadType, int page, int size) {
User caller = caller();
Event event = loadEvent(eventUuid);
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("eventUuid", event.getUuid());
body.put("salespersonUserId", salespersonId);
body.put("temperature", oneOf("temperature", temperature, TEMPERATURES));
body.put("status", oneOf("status", status, STATUSES));
body.put("interestId", interestId);
body.put("leadType", oneOf("leadType", leadType, LEAD_TYPES));
body.put("page", Math.max(page, 0));
body.put("size", size);
Map<String, Object> p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), 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>> interests = rows.isEmpty() ? Map.of() : interests(caller.getCompanyId());
Map<Long, Map<String, Object>> users = new HashMap<>();
Map<String, Object> out = new LinkedHashMap<>();
out.put("content", rows.stream().map(row -> view(row, interests, users)).toList());
out.put("totalElements", p == null ? 0 : p.get("totalElements"));
out.put("totalPages", p == null ? 0 : p.get("totalPages"));
out.put("number", p == null ? 0 : p.get("number"));
out.put("size", p == null ? size : p.get("size"));
return out;
}
public Map<String, Object> get(String eventUuid, String eventLeadUuid) {
User caller = caller();
return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId());
}
public Map<String, Object> update(String eventUuid, String eventLeadUuid, AdminEventLeadUpdateRequest r) {
User caller = caller();
String temperature = oneOf("temperature", r.temperature(), TEMPERATURES);
String status = oneOf("status", r.status(), STATUSES);
LocalDate followUp = date(r.nextFollowUpDate());
Map<String, Object> current = stored(caller.getCompanyId(), eventUuid, eventLeadUuid);
Long currentSalesperson = current.get("salespersonUserId") == null ? null : ((Number) current.get("salespersonUserId")).longValue();
if (r.salespersonId() != null && !r.salespersonId().equals(currentSalesperson)) {
checkOnTeam(((Number) current.get("eventUuid")).longValue(), r.salespersonId());
}
Map<Long, Map<String, Object>> known = interests(caller.getCompanyId());
List<Long> interestIds = checkedInterests(known, r.interestIds(), longs(current.get("interestIds")));
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("eventLeadUuid", ((Number) current.get("eventLeadUuid")).longValue());
body.put("salespersonUserId", r.salespersonId());
body.put("temperature", temperature);
body.put("status", status);
body.put("interestIds", interestIds);
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
body.put("notes", trimmed(r.notes()));
body.put("doneBy", caller.getUsername());
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(),
known, new HashMap<>());
}
// --- rules ---
/** A salesperson newly set must be an active admin on the event's current team. */
private void checkOnTeam(long eventUuid, long userId) {
if (!teamIds(eventUuid).contains(userId) || !isActiveAdmin(user(userId))) {
throw error(HttpStatus.BAD_REQUEST, "The salesperson must be an active member of the event's team", "NOT_ON_TEAM", "salespersonId");
}
}
/** Ids must be the company's interests; one newly added must be active, one already on the lead may stay. */
private static List<Long> checkedInterests(Map<Long, Map<String, Object>> known, List<Long> requested, List<Long> current) {
List<Long> ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList()));
for (Long id : ids) {
Map<String, Object> interest = known.get(id);
if (interest == null) throw error(HttpStatus.BAD_REQUEST, "Unknown interest " + id, "INVALID_VALUE", "interestIds");
if (!Boolean.TRUE.equals(interest.get("active")) && !current.contains(id)) {
throw error(HttpStatus.BAD_REQUEST, "Interest " + interest.get("name") + " is no longer active", "INACTIVE_INTEREST", "interestIds");
}
}
return ids;
}
private Map<String, Object> stored(long companyId, String eventUuid, String eventLeadUuid) {
Event event = loadEvent(eventUuid);
long id = parseOr(eventLeadUuid, AdminEventLeadService::eventLeadNotFound);
Map<String, Object> d;
try {
d = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID), MAP, companyId, id).getBody();
} catch (HttpClientErrorException.NotFound e) {
throw eventLeadNotFound();
}
if (d == null || !(d.get("eventUuid") instanceof Number n) || n.longValue() != event.getUuid()) throw eventLeadNotFound();
return d;
}
// --- views ---
private Map<String, Object> view(Map<String, Object> d, long companyId) {
return view(d, interests(companyId), new HashMap<>());
}
private Map<String, Object> view(Map<String, Object> d, Map<Long, Map<String, Object>> interests, Map<Long, Map<String, Object>> users) {
Map<String, Object> m = new LinkedHashMap<>();
m.put("eventLeadUuid", str(d.get("eventLeadUuid")));
m.put("eventUuid", str(d.get("eventUuid")));
m.put("leadUuid", str(d.get("leadUuid")));
m.put("name", d.get("name"));
m.put("mobile", d.get("mobileE164"));
m.put("email", d.get("email"));
m.put("companyName", d.get("companyName"));
m.put("jobTitle", d.get("jobTitle"));
m.put("leadType", d.get("leadType"));
Object sp = d.get("salespersonUserId");
if (sp instanceof Number n) {
Map<String, Object> u = users.computeIfAbsent(n.longValue(), this::user);
m.put("salesperson", Map.of("id", n.longValue(), "name", u == null ? String.valueOf(n) : String.valueOf(u.get("name"))));
} else {
m.put("salesperson", null);
}
m.put("temperature", d.get("temperature"));
m.put("status", d.get("status"));
m.put("interests", longs(d.get("interestIds")).stream().map(id -> {
Map<String, Object> i = interests.get(id);
return Map.<String, Object>of("id", id, "name", i == null ? String.valueOf(id) : i.get("name"),
"active", i != null && Boolean.TRUE.equals(i.get("active")));
}).toList());
m.put("nextFollowUpDate", d.get("nextFollowUpDate"));
m.put("notes", d.get("notes"));
m.put("capturedAt", d.get("capturedAt"));
return m;
}
// --- lookups ---
private List<Map<String, Object>> findMatches(long companyId, long eventUuid, String mobile, String email) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", companyId);
body.put("eventUuid", eventUuid);
body.put("mobileE164", mobile);
body.put("email", email);
List<Map<String, Object>> rows = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_FIND_MATCHES), MAP_LIST, body).getBody();
return rows == null ? List.of() : rows;
}
/** id -> {id, name, active}, in the counter's order (sort order, then name). */
private Map<Long, Map<String, Object>> interests(long companyId) {
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId).getBody();
Map<Long, Map<String, Object>> out = new LinkedHashMap<>();
if (rows != null) for (Map<String, Object> r : rows) {
long id = ((Number) r.get("id")).longValue();
out.put(id, Map.of("id", id, "name", String.valueOf(r.get("name")), "active", Boolean.TRUE.equals(r.get("active"))));
}
return out;
}
private List<Long> teamIds(long eventUuid) {
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID), MAP_LIST, eventUuid).getBody();
return rows == null ? List.of() : rows.stream().map(m -> ((Number) m.get("userId")).longValue()).toList();
}
private Map<String, Object> user(Long id) {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody();
}
private Event loadEvent(String uuid) {
long id = parseOr(uuid, AdminEventLeadService::eventNotFound);
Event event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
if (event == null) throw eventNotFound();
return event;
}
private User caller() {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
return caller;
}
private String url(String api) {
return restTemplateUtil.getURLforApiService(api);
}
// --- small helpers ---
private static Object conflictEventLeadUuid(HttpClientErrorException e) {
try {
return JSON.readValue(e.getResponseBodyAsString(), Map.class).get("eventLeadUuid");
} catch (Exception ignored) {
return null;
}
}
private static boolean isActiveAdmin(Map<String, Object> user) {
return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled"));
}
private static String mobile(String input) {
try {
return EventLeadContact.mobile(input);
} catch (IllegalArgumentException e) {
throw error(HttpStatus.BAD_REQUEST, "Enter a valid mobile number", "INVALID_MOBILE", "mobile");
}
}
private static String email(String input) {
try {
return EventLeadContact.email(input);
} catch (IllegalArgumentException e) {
throw error(HttpStatus.BAD_REQUEST, "Enter a valid email address", "INVALID_EMAIL", "email");
}
}
private static LocalDate date(String input) {
if (input == null || input.isBlank()) return null;
try {
return LocalDate.parse(input.trim());
} catch (DateTimeParseException e) {
throw error(HttpStatus.BAD_REQUEST, "Use a date like 2027-01-20", "INVALID_DATE", "nextFollowUpDate");
}
}
private static String oneOf(String field, String value, Set<String> allowed) {
if (value == null || value.isBlank()) return null;
if (!allowed.contains(value)) throw error(HttpStatus.BAD_REQUEST, "Unknown " + field + " " + value, "INVALID_VALUE", field);
return value;
}
private static String maxLength(String field, String value, int max) {
if (value != null && value.length() > max) throw error(HttpStatus.BAD_REQUEST, field + " is too long", "TOO_LONG", field);
return value;
}
private static String trimmed(String s) {
return s == null || s.isBlank() ? null : s.trim();
}
private static long parseOr(String s, java.util.function.Supplier<CodedResponseStatusException> notFound) {
try {
return Long.parseLong(s.trim());
} catch (RuntimeException e) {
throw notFound.get();
}
}
private static List<Long> longs(Object list) {
if (!(list instanceof List<?> l)) return List.of();
return l.stream().filter(Number.class::isInstance).map(o -> ((Number) o).longValue()).toList();
}
private static String str(Object o) {
return o == null ? null : String.valueOf(o);
}
private static CodedResponseStatusException required(List<String> fields) {
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: " + String.join(", ", fields), "REQUIRED_FIELD", fields.get(0));
e.getBody().setProperty("errors", fields);
return e;
}
private static CodedResponseStatusException eventNotFound() {
return error(HttpStatus.NOT_FOUND, "Event not found", "EVENT_NOT_FOUND", null);
}
private static CodedResponseStatusException eventLeadNotFound() {
return error(HttpStatus.NOT_FOUND, "Event lead not found", "EVENT_LEAD_NOT_FOUND", null);
}
private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) {
CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code);
if (field != null) e.getBody().setProperty("details", Map.of("field", field));
return e;
}
}
@@ -0,0 +1,38 @@
package com.solvway.mobile.api.service;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* Normalises a lead's contact values so the same person always has the same value: mobile numbers to E.164
* (a number without a country code is Malaysian), emails trimmed and lowercased. Blank input is null;
* anything that is not a valid number or email address throws IllegalArgumentException.
*/
final class EventLeadContact {
private static final PhoneNumberUtil PHONES = PhoneNumberUtil.getInstance();
private static final Pattern EMAIL = Pattern.compile("[^\\s@]+@[^\\s@]+\\.[^\\s@]+");
private EventLeadContact() {}
static String mobile(String input) {
if (input == null || input.isBlank()) return null;
try {
Phonenumber.PhoneNumber number = PHONES.parse(input.trim(), "MY");
if (PHONES.isValidNumber(number)) return PHONES.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);
} catch (NumberParseException ignored) {
// falls through to the refusal below
}
throw new IllegalArgumentException("not a valid phone number");
}
static String email(String input) {
if (input == null || input.isBlank()) return null;
String email = input.trim().toLowerCase(Locale.ROOT);
if (!EMAIL.matcher(email).matches()) throw new IllegalArgumentException("not an email address");
return email;
}
}