feat: company-scoped events, leads, event leads and exports

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-30 20:30:46 +08:00
1 parent de2ae63cea
commit ec504fd529
31 files changed
+1096 -190

No files matched your search

@@ -42,10 +42,10 @@ public class RestApiCounterServiceConstants {
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_DETAIL="/counter/lead/detail/{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_FIND_BY_UUID="/counter/eventLead/findByUuid/{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";
@@ -26,14 +26,15 @@ public class AdminEventController {
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String sortBy,
@RequestParam(required = false) String sortDir) {
return ResponseEntity.ok(adminEventService.list(q, enabled, page, size, sortBy, sortDir));
@RequestParam(required = false) String sortDir,
@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(adminEventService.list(q, enabled, page, size, sortBy, sortDir, companyId));
}
@AppAuth
@AdminModule("BO_EVENTS")
@GetMapping("/events/salesperson-options")
public ResponseEntity<List<Map<String, Object>>> salespersonOptions() {
return ResponseEntity.ok(adminEventService.salespersonOptions());
public ResponseEntity<List<Map<String, Object>>> salespersonOptions(@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(adminEventService.salespersonOptions(companyId));
}
@AppAuth
@AdminModule("BO_EVENTS")
@@ -31,8 +31,8 @@ public class AdminEventLeadController {
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@GetMapping("/events")
public ResponseEntity<List<Map<String, Object>>> events() {
return ResponseEntity.ok(adminEventLeadService.events());
public ResponseEntity<List<Map<String, Object>>> events(@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(adminEventLeadService.events(companyId));
}
@AppAuth
@@ -74,8 +74,9 @@ public class AdminEventLeadController {
@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));
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(adminEventLeadService.list(eventUuid, salespersonId, temperature, status, interestId, leadType, page, size, companyId));
}
@AppAuth
@@ -30,8 +30,9 @@ public class AdminEventLeadExportController {
@RequestParam(required = false) String temperature,
@RequestParam(required = false) String status,
@RequestParam(required = false) Long interestId,
@RequestParam(required = false) String leadType) {
byte[] file = adminEventLeadService.export(eventUuid, salespersonId, temperature, status, interestId, leadType);
@RequestParam(required = false) String leadType,
@RequestParam(required = false) Long companyId) {
byte[] file = adminEventLeadService.export(eventUuid, salespersonId, temperature, status, interestId, leadType, companyId);
// The service has already parsed the uuid as a number, so its digits are the canonical uuid; nothing else reaches the header.
return xlsx("event-leads-" + eventUuid.replaceAll("\\D", ""), file);
}
@@ -31,16 +31,18 @@ public class AdminLeadController {
@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));
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(adminLeadService.list(q, page, size, companyId));
}
@Audited(action = "LEAD_EXPORT")
@AppAuth
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_LEADS")
@GetMapping("/export")
public ResponseEntity<byte[]> export(@RequestParam(required = false) String q) {
return xlsx("leads", adminLeadService.export(q));
public ResponseEntity<byte[]> export(@RequestParam(required = false) String q,
@RequestParam(required = false) Long companyId) {
return xlsx("leads", adminLeadService.export(q, companyId));
}
private static ResponseEntity<byte[]> xlsx(String prefix, byte[] bytes) {
@@ -2,7 +2,16 @@ 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. */
/**
* Step 2 of capture. leadUuid is the picked match as a string, or null for a new person. nextFollowUpDate is YYYY-MM-DD.
* companyId is read from a super admin only; staff get their own company.
*/
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) {}
List<Long> interestIds, String nextFollowUpDate, String notes, Long companyId) {
public 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) {
this(leadUuid, name, mobile, email, companyName, jobTitle, salespersonId, temperature, status, interestIds, nextFollowUpDate, notes, null);
}
}
@@ -4,6 +4,14 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
/** Create/update body. Dates are kept as text so a malformed date answers INVALID_DATE, not a bind error. enabled is update-only. */
/**
* Create/update body. Dates are kept as text so a malformed date answers INVALID_DATE, not a bind error. enabled is update-only.
* companyId is read on create only, and only from a super admin; staff get their own company and an edit never moves an event.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public record AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List<Long> salespersonIds) {}
public record AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List<Long> salespersonIds,
Long companyId) {
public AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List<Long> salespersonIds) {
this(name, location, startDate, endDate, enabled, salespersonIds, null);
}
}
@@ -1,4 +1,8 @@
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) {}
/** Step 1 of capture: the mobile and/or email to look up. companyId is read from a super admin only. */
public record AdminLeadMatchRequest(String mobile, String email, Long companyId) {
public AdminLeadMatchRequest(String mobile, String email) {
this(mobile, email, null);
}
}
@@ -0,0 +1,12 @@
package com.solvway.mobile.api.dto.admin;
import com.solvway.core.model.Event;
import lombok.Getter;
import lombok.Setter;
/** The counter's Event with the company it belongs to (core Event does not carry one). */
@Getter
@Setter
public class CompanyEvent extends Event {
private Long companyId;
}
@@ -1,7 +1,6 @@
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;
@@ -9,7 +8,9 @@ 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.dto.admin.CompanyEvent;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.useraccess.AuditChanges;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -34,7 +35,7 @@ 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).
* Staff are limited to their own company; a super admin chooses one. A record's writes always use the record's company. Uuids leave as strings (Snowflake longs).
* Never log a lead's name, mobile or email.
*/
@Service
@@ -48,18 +49,23 @@ public class AdminEventLeadService {
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<CompanyEvent> 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;
private final AdminCompanyScope scope;
// --- 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"),
public List<Map<String, Object>> events(Long companyId) {
Map<String, Object> property = new LinkedHashMap<>();
property.put("name", "");
property.put("enabled", "Y");
property.put("companyId", scope.scope(caller(), companyId));
Map<String, Object> request = Map.of("property", property,
"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();
@@ -67,6 +73,7 @@ public class AdminEventLeadService {
return p.content().stream().map(e -> {
Map<String, Object> m = new LinkedHashMap<>();
m.put("uuid", String.valueOf(e.getUuid()));
m.put("companyId", e.getCompanyId());
m.put("name", e.getName());
m.put("location", e.getLocation());
m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
@@ -76,15 +83,15 @@ public class AdminEventLeadService {
}
public List<Map<String, Object>> interestOptions() {
return interests(caller().getCompanyId()).values().stream().filter(i -> Boolean.TRUE.equals(i.get("active"))).toList();
return interests(scope.scope(caller(), null)).values().stream().filter(i -> Boolean.TRUE.equals(i.get("active"))).toList();
}
public List<Map<String, Object>> salespersonOptions(String eventUuid) {
Event event = loadEvent(eventUuid);
CompanyEvent event = loadEvent(eventUuid, null);
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"))));
if (isActiveAdminOf(u, event.getCompanyId())) out.add(Map.of("id", id, "name", String.valueOf(u.get("name")), "username", String.valueOf(u.get("username"))));
}
return out;
}
@@ -96,11 +103,11 @@ public class AdminEventLeadService {
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);
CompanyEvent event = loadEvent(eventUuid, scope.requireCompanyForCreate(caller, r.companyId()));
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 -> {
out.put("candidates", findMatches(event.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"));
@@ -132,16 +139,16 @@ public class AdminEventLeadService {
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);
CompanyEvent event = loadEvent(eventUuid, scope.requireCompanyForCreate(caller, r.companyId()));
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());
if (r.salespersonId() != null) checkOnTeam(event.getUuid(), r.salespersonId(), event.getCompanyId());
Map<Long, Map<String, Object>> known = interests(event.getCompanyId());
List<Long> interestIds = checkedInterests(known, r.interestIds(), List.of());
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("companyId", event.getCompanyId());
body.put("eventUuid", event.getUuid());
body.put("leadUuid", leadUuid);
body.put("name", name);
@@ -161,7 +168,7 @@ public class AdminEventLeadService {
known, new HashMap<>());
} catch (HttpClientErrorException.Conflict e) {
Object existing = conflictEventLeadUuid(e);
if (existing == null) existing = findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream()
if (existing == null) existing = findMatches(event.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,
@@ -176,12 +183,11 @@ public class AdminEventLeadService {
// --- 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> p = search(caller, event, salespersonId, temperature, status, interestId, leadType, page, size);
String leadType, int page, int size, Long companyId) {
CompanyEvent event = loadEvent(eventUuid, companyId);
Map<String, Object> p = search(event, salespersonId, temperature, status, interestId, leadType, page, size);
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>> interests = rows.isEmpty() ? Map.of() : interests(event.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());
@@ -193,16 +199,16 @@ public class AdminEventLeadService {
}
/** The whole filtered listing as xlsx, paged 100 at a time. ponytail: buffers up to 20000 rows in memory; stream to the response if that grows. */
public byte[] export(String eventUuid, Long salespersonId, String temperature, String status, Long interestId, String leadType) {
public byte[] export(String eventUuid, Long salespersonId, String temperature, String status, Long interestId, String leadType, Long companyId) {
User caller = caller();
Event event = loadEvent(eventUuid);
CompanyEvent event = loadEvent(eventUuid, companyId);
Map<Long, Map<String, Object>> users = new HashMap<>();
Map<Long, Map<String, Object>>[] interests = new Map[1];
return LeadExport.build(caller.getUsername(), "event-leads:" + event.getUuid(), "Event leads",
List.of("Name", "Mobile", "Email", "Lead type", "Salesperson", "Temperature", "Status", "Interests", "Next follow-up"),
page -> search(caller, event, salespersonId, temperature, status, interestId, leadType, page, LeadExport.PAGE),
page -> search(event, salespersonId, temperature, status, interestId, leadType, page, LeadExport.PAGE),
r -> {
if (interests[0] == null) interests[0] = interests(caller.getCompanyId());
if (interests[0] == null) interests[0] = interests(event.getCompanyId());
Map<String, Object> m = view(r, interests[0], users);
Map<String, Object> sp = (Map<String, Object>) m.get("salesperson");
String follow = (String) m.get("nextFollowUpDate");
@@ -219,10 +225,10 @@ public class AdminEventLeadService {
return s == null || s.isEmpty() ? null : s.charAt(0) + s.substring(1).toLowerCase();
}
private Map<String, Object> search(User caller, Event event, Long salespersonId, String temperature, String status, Long interestId,
private Map<String, Object> search(CompanyEvent event, Long salespersonId, String temperature, String status, Long interestId,
String leadType, int page, int size) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("companyId", event.getCompanyId());
body.put("eventUuid", event.getUuid());
body.put("salespersonUserId", salespersonId);
body.put("temperature", oneOf("temperature", temperature, TEMPERATURES));
@@ -235,8 +241,8 @@ public class AdminEventLeadService {
}
public Map<String, Object> get(String eventUuid, String eventLeadUuid) {
User caller = caller();
return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId());
Map<String, Object> d = stored(eventUuid, eventLeadUuid);
return view(d, interests(longOrNull(d.get("companyId"))), new HashMap<>());
}
public Map<String, Object> update(String eventUuid, String eventLeadUuid, AdminEventLeadUpdateRequest r) {
@@ -244,16 +250,16 @@ public class AdminEventLeadService {
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);
Map<String, Object> current = stored(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());
checkOnTeam(((Number) current.get("eventUuid")).longValue(), r.salespersonId(), longOrNull(current.get("companyId")));
}
Map<Long, Map<String, Object>> known = interests(caller.getCompanyId());
Map<Long, Map<String, Object>> known = interests(longOrNull(current.get("companyId")));
List<Long> interestIds = checkedInterests(known, r.interestIds(), longs(current.get("interestIds")));
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("companyId", current.get("companyId")); // the record's own company, never a request value
body.put("eventLeadUuid", ((Number) current.get("eventLeadUuid")).longValue());
body.put("salespersonUserId", r.salespersonId());
body.put("temperature", temperature);
@@ -277,9 +283,9 @@ public class AdminEventLeadService {
// --- 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))) {
/** A salesperson newly set must be an active admin of the event's company on the event's current team. */
private void checkOnTeam(long eventUuid, long userId, Long companyId) {
if (!teamIds(eventUuid).contains(userId) || !isActiveAdminOf(user(userId), companyId)) {
throw error(HttpStatus.BAD_REQUEST, "The salesperson must be an active member of the event's team", "NOT_ON_TEAM", "salespersonId");
}
}
@@ -297,29 +303,28 @@ public class AdminEventLeadService {
return ids;
}
private Map<String, Object> stored(long companyId, String eventUuid, String eventLeadUuid) {
Event event = loadEvent(eventUuid);
private Map<String, Object> stored(String eventUuid, String eventLeadUuid) {
CompanyEvent event = loadEvent(eventUuid, null);
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();
d = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID), MAP, id).getBody();
} catch (HttpClientErrorException.NotFound e) {
throw eventLeadNotFound();
}
if (d == null || !(d.get("eventUuid") instanceof Number n) || n.longValue() != event.getUuid()) throw eventLeadNotFound();
Long company = scope.scope(caller(), null);
if (company != null && !company.equals(longOrNull(d.get("companyId")))) 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("companyId", d.get("companyId"));
m.put("leadUuid", str(d.get("leadUuid")));
m.put("name", d.get("name"));
m.put("mobile", d.get("mobileE164"));
@@ -359,10 +364,10 @@ public class AdminEventLeadService {
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) {
/** id -> {id, name, active}, in the counter's order (sort order, then name). Interests are one shared list: the counter ignores the path company. */
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();
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId == null ? 0L : companyId).getBody(); // ponytail: 0 when no company is known; drop the path variable when the counter does
Map<Long, Map<String, Object>> out = new LinkedHashMap<>();
if (rows != null) for (Map<String, Object> r : rows) {
long id = ((Number) r.get("id")).longValue();
@@ -381,10 +386,13 @@ public class AdminEventLeadService {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody();
}
private Event loadEvent(String uuid) {
/** The event, or 404 when it is missing or outside the caller's scope (staff: own company; super: the requested one, or any). */
private CompanyEvent loadEvent(String uuid, Long requestedCompanyId) {
long id = parseOr(uuid, AdminEventLeadService::eventNotFound);
Event event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
CompanyEvent event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
if (event == null) throw eventNotFound();
Long company = scope.scope(caller(), requestedCompanyId);
if (company != null && !company.equals(event.getCompanyId())) throw eventNotFound();
return event;
}
@@ -408,6 +416,10 @@ public class AdminEventLeadService {
}
}
private static boolean isActiveAdminOf(Map<String, Object> user, Long companyId) {
return isActiveAdmin(user) && user.get("companyId") instanceof Number n && companyId != null && n.longValue() == companyId;
}
private static boolean isActiveAdmin(Map<String, Object> user) {
return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled"));
}
@@ -460,6 +472,10 @@ public class AdminEventLeadService {
}
}
private static Long longOrNull(Object o) {
return o instanceof Number n ? n.longValue() : null;
}
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();
@@ -2,13 +2,14 @@ package com.solvway.mobile.api.service;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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.AdminEventRequest;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
@@ -38,18 +39,20 @@ public class AdminEventService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<EventPage> PAGE = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<Event> EVENT = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<CompanyEvent> EVENT = new ParameterizedTypeReference<>() {};
private static final Map<String, String> SORTS = Map.of("name", "name", "startDate", "dateStart", "endDate", "dateEnd");
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
private final AdminCompanyScope scope;
/** The slice of a Spring Page this service reads. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record EventPage(List<Event> content, long totalElements, int totalPages, int number, int size) {}
public record EventPage(List<CompanyEvent> content, long totalElements, int totalPages, int number, int size) {}
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir) {
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir, Long companyId) {
Map<String, Object> property = new LinkedHashMap<>();
property.put("companyId", scope.scope(caller(), companyId));
property.put("name", q == null ? "" : q.trim());
property.put("enabled", "Y".equals(enabled) || "N".equals(enabled) ? enabled : "");
Map<String, Object> sort = Map.of("direction", "desc".equalsIgnoreCase(sortDir) ? "DESC" : "ASC",
@@ -63,7 +66,7 @@ public class AdminEventService {
}
public Map<String, Object> get(String uuid) {
Event event = load(uuid);
CompanyEvent event = load(uuid);
Map<String, Object> out = row(event);
List<Map<String, Object>> team = new ArrayList<>();
for (Long id : teamIds(event.getUuid())) {
@@ -82,36 +85,41 @@ public class AdminEventService {
public Map<String, Object> create(AdminEventRequest r) {
Fields f = validate(r);
User caller = caller();
List<Long> team = checkedTeam(r.salespersonIds(), List.of());
Event event = new Event();
Long company = scope.requireCompanyForCreate(caller, r.companyId());
List<Long> team = checkedTeam(r.salespersonIds(), List.of(), company);
CompanyEvent event = new CompanyEvent();
event.setCompanyId(company);
apply(event, f);
event.setCreateBy(caller.getUsername());
event.setDoneBy(caller.getUsername());
Event saved = save(event);
replaceTeam(saved.getUuid(), team, caller);
CompanyEvent saved = save(event);
replaceTeam(saved.getUuid(), team, caller, company);
return row(saved);
}
public Map<String, Object> update(String uuid, AdminEventRequest r) {
Fields f = validate(r);
User caller = caller();
Event event = load(uuid);
List<Long> team = r.salespersonIds() == null ? null : checkedTeam(r.salespersonIds(), teamIds(event.getUuid()));
CompanyEvent event = load(uuid);
List<Long> team = r.salespersonIds() == null ? null : checkedTeam(r.salespersonIds(), teamIds(event.getUuid()), event.getCompanyId());
apply(event, f);
if (r.enabled() != null) event.setEnabled(r.enabled() ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N);
event.setDoneBy(caller.getUsername());
Event saved = save(event);
if (team != null) replaceTeam(saved.getUuid(), team, caller);
CompanyEvent saved = save(event);
if (team != null) replaceTeam(saved.getUuid(), team, caller, event.getCompanyId());
return row(saved);
}
public List<Map<String, Object>> salespersonOptions() {
Map<String, Object> request = Map.of("property", Map.of("type", "A"),
/** Active admins of the chosen company; a super admin who has not chosen one is offered nobody. */
public List<Map<String, Object>> salespersonOptions(Long companyId) {
Long company = scope.scope(caller(), companyId);
if (company == null) return List.of();
Map<String, Object> request = Map.of("property", Map.of("type", "A", "companyId", company),
"pageableRest", Map.of("number", 0, "size", 10000, "sorts", List.of(Map.of("direction", "ASC", "property", "id"))));
Map<String, Object> body = restTemplateUtil.postForEntity(
url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request).getBody();
List<Map<String, Object>> all = body == null || body.get("content") == null ? List.of() : (List<Map<String, Object>>) body.get("content");
// ponytail: loads all admins (staff-sized) like AdminUserService.list; not company-scoped yet.
// ponytail: loads all of one company's admins (staff-sized) like AdminUserService.list.
return all.stream().filter(AdminEventService::isActiveAdmin)
.sorted(Comparator.comparing(m -> String.valueOf(m.get("name")).toLowerCase()))
.map(m -> {
@@ -156,7 +164,7 @@ public class AdminEventService {
}
}
private static void apply(Event e, Fields f) {
private static void apply(CompanyEvent e, Fields f) {
e.setName(f.name());
e.setLocation(f.location());
e.setDateStart(f.start().atStartOfDay());
@@ -164,19 +172,23 @@ public class AdminEventService {
}
/**
* Duplicates collapse; every id added to the team must be an enabled admin user. Someone already on the team
* Duplicates collapse; every id added to the team must be an enabled admin user of the event's company. Someone already on the team
* stays even if deactivated since, so an unrelated edit does not fail until an admin removes them.
*/
private List<Long> checkedTeam(List<Long> ids, List<Long> current) {
private List<Long> checkedTeam(List<Long> ids, List<Long> current, Long companyId) {
List<Long> team = ids == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(ids));
for (Long id : team) {
if (id == null || !current.contains(id) && !isActiveAdmin(user(id))) {
if (id == null || !current.contains(id) && !isActiveAdminOf(user(id), companyId)) {
throw error(HttpStatus.BAD_REQUEST, "Unknown or inactive admin user " + id, "UNKNOWN_USER", "salespersonIds");
}
}
return team;
}
private static boolean isActiveAdminOf(Map<String, Object> user, Long companyId) {
return isActiveAdmin(user) && user.get("companyId") instanceof Number n && companyId != null && n.longValue() == companyId;
}
private static boolean isActiveAdmin(Map<String, Object> user) {
return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled"));
}
@@ -192,10 +204,10 @@ public class AdminEventService {
}
/** The event already exists when this fails, so the client gets the uuid to retry the team save on. */
private void replaceTeam(long eventUuid, List<Long> userIds, User caller) {
private void replaceTeam(long eventUuid, List<Long> userIds, User caller, Long companyId) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("eventUuid", eventUuid);
body.put("companyId", caller.getCompanyId());
body.put("companyId", companyId);
body.put("userIds", userIds);
body.put("doneBy", caller.getUsername());
try {
@@ -208,27 +220,31 @@ public class AdminEventService {
}
}
private Event load(String uuid) {
/** Another company's event answers 404 to staff, exactly like a missing one; a super admin may open any. */
private CompanyEvent load(String uuid) {
long id;
try {
id = Long.parseLong(uuid);
} catch (NumberFormatException e) {
throw notFound();
}
Event event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
CompanyEvent event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
if (event == null) throw notFound();
Long company = scope.scope(caller(), null);
if (company != null && !company.equals(event.getCompanyId())) throw notFound();
return event;
}
private Event save(Event event) {
Event saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SAVE), EVENT, event).getBody();
private CompanyEvent save(CompanyEvent event) {
CompanyEvent saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SAVE), EVENT, event).getBody();
if (saved == null) throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Event could not be saved", "SAVE_FAILED", null);
return saved;
}
private static Map<String, Object> row(Event e) {
private static Map<String, Object> row(CompanyEvent e) {
Map<String, Object> m = new LinkedHashMap<>();
m.put("uuid", String.valueOf(e.getUuid()));
m.put("companyId", e.getCompanyId());
m.put("name", e.getName());
m.put("location", e.getLocation());
m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
@@ -6,6 +6,7 @@ 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.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.useraccess.AuditChanges;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
@@ -33,7 +34,7 @@ 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.
* Staff see their own company only; a super admin sees the chosen company, or all. Uuids leave as strings (Snowflake longs). Never log a lead's name, mobile or email.
*/
@Service
@RequiredArgsConstructor
@@ -43,9 +44,11 @@ public class AdminLeadService {
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
private final AdminCompanyScope scope;
public Map<String, Object> list(String q, int page, int size) {
Map<String, Object> p = search(caller().getCompanyId(), trimmed(q), page, size);
public Map<String, Object> list(String q, int page, int size, Long companyId) {
Long company = scope.scope(caller(), companyId);
Map<String, Object> p = search(company, trimmed(q), page, size);
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<>();
@@ -55,13 +58,14 @@ public class AdminLeadService {
}
/** The whole search as xlsx, paged 100 at a time. ponytail: buffers up to 20000 rows in memory; stream to the response if that grows. */
public byte[] export(String q) {
public byte[] export(String q, Long companyId) {
User caller = caller();
Long company = scope.scope(caller, companyId);
String term = trimmed(q);
Map<Long, Map<String, Object>> users = new HashMap<>();
return LeadExport.build(caller.getUsername(), "leads", "Leads",
List.of("Name", "Mobile", "Email", "Company", "Events", "Last event", "Latest salesperson"),
page -> search(caller.getCompanyId(), term, page, LeadExport.PAGE),
page -> search(company, term, page, LeadExport.PAGE),
r -> {
Map<String, Object> m = row(r, users);
return Arrays.asList(m.get("name"), m.get("mobile"), m.get("email"), m.get("companyName"), m.get("eventCount"),
@@ -84,14 +88,7 @@ public class AdminLeadService {
}
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);
return detail(load(caller(), parseOr(leadUuid, AdminLeadService::notFound)));
}
public Map<String, Object> update(String leadUuid, AdminLeadUpdateRequest r) {
@@ -110,8 +107,9 @@ public class AdminLeadService {
String jobTitle = maxLength("jobTitle", trimmed(r.jobTitle()), 100);
String notes = maxLength("notes", trimmed(r.notes()), 2000);
Map<String, Object> before = load(caller, id);
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("companyId", before.get("companyId")); // the lead's own company, never a request value
body.put("leadUuid", id);
body.put("name", name);
body.put("mobileE164", mobile);
@@ -120,31 +118,32 @@ public class AdminLeadService {
body.put("jobTitle", jobTitle);
body.put("notes", notes);
body.put("doneBy", caller.getUsername());
Map<String, Object> before = storedOrNull(caller.getCompanyId(), id);
Map<String, Object> saved;
try {
saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody();
} catch (HttpClientErrorException.NotFound e) {
throw notFound();
}
// field names only: lead values are personal data. No readable before-state means nothing is recorded.
if (before != null) {
List<String> changed = new ArrayList<>();
for (String f : List.of("name", "mobileE164", "email", "companyName", "jobTitle", "notes")) {
if (!Objects.equals(before.get(f), body.get(f))) changed.add("mobileE164".equals(f) ? "phone" : f);
}
if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new));
// field names only: lead values are personal data.
List<String> changed = new ArrayList<>();
for (String f : List.of("name", "mobileE164", "email", "companyName", "jobTitle", "notes")) {
if (!Objects.equals(before.get(f), body.get(f))) changed.add("mobileE164".equals(f) ? "phone" : f);
}
if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new));
return detail(saved);
}
/** Best-effort read of the lead before it is changed, for the audit trail only. */
private Map<String, Object> storedOrNull(Long companyId, long id) {
/** The lead, or 404 when it is missing or (for staff) belongs to another company. A super admin may open any. */
private Map<String, Object> load(User caller, long id) {
Map<String, Object> d;
try {
return restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_DETAIL), MAP, companyId, id).getBody();
} catch (RuntimeException e) {
return null;
d = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_DETAIL), MAP, id).getBody();
} catch (HttpClientErrorException.NotFound e) {
throw notFound();
}
Long company = scope.scope(caller, null);
if (d == null || company != null && !(d.get("companyId") instanceof Number n && n.longValue() == company)) throw notFound();
return d;
}
/** Digits to match against the stored E.164 mobile, or null when the term is not a phone-like number. */
@@ -160,6 +159,7 @@ public class AdminLeadService {
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("companyId", d.get("companyId"));
m.put("name", d.get("name"));
m.put("mobile", d.get("mobileE164"));
m.put("email", d.get("email"));
@@ -182,6 +182,7 @@ public class AdminLeadService {
Map<Long, Map<String, Object>> users = new HashMap<>();
Map<String, Object> m = new LinkedHashMap<>();
m.put("leadUuid", str(d.get("leadUuid")));
m.put("companyId", d.get("companyId"));
m.put("name", d.get("name"));
m.put("mobile", d.get("mobileE164"));
m.put("email", d.get("email"));