diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index e2eceff..2b3fe28 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -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"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventController.java index 665d3b0..6067d61 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventController.java @@ -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>> salespersonOptions() { - return ResponseEntity.ok(adminEventService.salespersonOptions()); + public ResponseEntity>> salespersonOptions(@RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(adminEventService.salespersonOptions(companyId)); } @AppAuth @AdminModule("BO_EVENTS") diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java index fb64497..36f1e42 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java @@ -31,8 +31,8 @@ public class AdminEventLeadController { @AppAuth @AdminModule("BO_EVENT_LEADS") @GetMapping("/events") - public ResponseEntity>> events() { - return ResponseEntity.ok(adminEventLeadService.events()); + public ResponseEntity>> 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 diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadExportController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadExportController.java index 3a8f46e..1a96863 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadExportController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadExportController.java @@ -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); } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java index ae20811..856de7a 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java @@ -31,16 +31,18 @@ public class AdminLeadController { @GetMapping public ResponseEntity> 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 export(@RequestParam(required = false) String q) { - return xlsx("leads", adminLeadService.export(q)); + public ResponseEntity export(@RequestParam(required = false) String q, + @RequestParam(required = false) Long companyId) { + return xlsx("leads", adminLeadService.export(q, companyId)); } private static ResponseEntity xlsx(String prefix, byte[] bytes) { diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java index b4f3d34..2f83184 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java @@ -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 interestIds, String nextFollowUpDate, String notes) {} + List 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 interestIds, String nextFollowUpDate, String notes) { + this(leadUuid, name, mobile, email, companyName, jobTitle, salespersonId, temperature, status, interestIds, nextFollowUpDate, notes, null); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java index 158fc3e..d971af9 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java @@ -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 salespersonIds) {} +public record AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List salespersonIds, + Long companyId) { + public AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List salespersonIds) { + this(name, location, startDate, endDate, enabled, salespersonIds, null); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java index df705df..72da6cf 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java @@ -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); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java new file mode 100644 index 0000000..d189e20 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java @@ -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; +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java index c6f1e37..de8adc1 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -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 PAGE = new ParameterizedTypeReference<>() {}; - private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; private static final ParameterizedTypeReference>> 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> events() { - Map request = Map.of("property", Map.of("name", "", "enabled", "Y"), + public List> events(Long companyId) { + Map property = new LinkedHashMap<>(); + property.put("name", ""); + property.put("enabled", "Y"); + property.put("companyId", scope.scope(caller(), companyId)); + Map 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 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> 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> salespersonOptions(String eventUuid) { - Event event = loadEvent(eventUuid); + CompanyEvent event = loadEvent(eventUuid, null); List> out = new ArrayList<>(); for (Long id : teamIds(event.getUuid())) { Map 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 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 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> known = interests(caller.getCompanyId()); + if (r.salespersonId() != null) checkOnTeam(event.getUuid(), r.salespersonId(), event.getCompanyId()); + Map> known = interests(event.getCompanyId()); List interestIds = checkedInterests(known, r.interestIds(), List.of()); Map 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 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 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 p = search(event, salespersonId, temperature, status, interestId, leadType, page, size); List> rows = p == null || p.get("content") == null ? List.of() : (List>) p.get("content"); - Map> interests = rows.isEmpty() ? Map.of() : interests(caller.getCompanyId()); + Map> interests = rows.isEmpty() ? Map.of() : interests(event.getCompanyId()); Map> users = new HashMap<>(); Map 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> users = new HashMap<>(); Map>[] 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 m = view(r, interests[0], users); Map sp = (Map) 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 search(User caller, Event event, Long salespersonId, String temperature, String status, Long interestId, + private Map search(CompanyEvent event, Long salespersonId, String temperature, String status, Long interestId, String leadType, int page, int size) { Map 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 get(String eventUuid, String eventLeadUuid) { - User caller = caller(); - return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId()); + Map d = stored(eventUuid, eventLeadUuid); + return view(d, interests(longOrNull(d.get("companyId"))), new HashMap<>()); } public Map 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 current = stored(caller.getCompanyId(), eventUuid, eventLeadUuid); + Map 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> known = interests(caller.getCompanyId()); + Map> known = interests(longOrNull(current.get("companyId"))); List interestIds = checkedInterests(known, r.interestIds(), longs(current.get("interestIds"))); Map 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 stored(long companyId, String eventUuid, String eventLeadUuid) { - Event event = loadEvent(eventUuid); + private Map stored(String eventUuid, String eventLeadUuid) { + CompanyEvent event = loadEvent(eventUuid, null); long id = parseOr(eventLeadUuid, AdminEventLeadService::eventLeadNotFound); Map 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 view(Map d, long companyId) { - return view(d, interests(companyId), new HashMap<>()); - } - private Map view(Map d, Map> interests, Map> users) { Map 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> 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> interests(Long companyId) { List> 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> out = new LinkedHashMap<>(); if (rows != null) for (Map 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 user, Long companyId) { + return isActiveAdmin(user) && user.get("companyId") instanceof Number n && companyId != null && n.longValue() == companyId; + } + private static boolean isActiveAdmin(Map 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 longs(Object list) { if (!(list instanceof List l)) return List.of(); return l.stream().filter(Number.class::isInstance).map(o -> ((Number) o).longValue()).toList(); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java index e2585bd..bc1c4f2 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java @@ -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 = new ParameterizedTypeReference<>() {}; private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; private static final ParameterizedTypeReference PAGE = new ParameterizedTypeReference<>() {}; - private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; private static final Map 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 content, long totalElements, int totalPages, int number, int size) {} + public record EventPage(List content, long totalElements, int totalPages, int number, int size) {} - public Map list(String q, String enabled, int page, int size, String sortBy, String sortDir) { + public Map list(String q, String enabled, int page, int size, String sortBy, String sortDir, Long companyId) { Map 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 sort = Map.of("direction", "desc".equalsIgnoreCase(sortDir) ? "DESC" : "ASC", @@ -63,7 +66,7 @@ public class AdminEventService { } public Map get(String uuid) { - Event event = load(uuid); + CompanyEvent event = load(uuid); Map out = row(event); List> team = new ArrayList<>(); for (Long id : teamIds(event.getUuid())) { @@ -82,36 +85,41 @@ public class AdminEventService { public Map create(AdminEventRequest r) { Fields f = validate(r); User caller = caller(); - List team = checkedTeam(r.salespersonIds(), List.of()); - Event event = new Event(); + Long company = scope.requireCompanyForCreate(caller, r.companyId()); + List 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 update(String uuid, AdminEventRequest r) { Fields f = validate(r); User caller = caller(); - Event event = load(uuid); - List team = r.salespersonIds() == null ? null : checkedTeam(r.salespersonIds(), teamIds(event.getUuid())); + CompanyEvent event = load(uuid); + List 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> salespersonOptions() { - Map 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> salespersonOptions(Long companyId) { + Long company = scope.scope(caller(), companyId); + if (company == null) return List.of(); + Map 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 body = restTemplateUtil.postForEntity( url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request).getBody(); List> all = body == null || body.get("content") == null ? List.of() : (List>) 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 checkedTeam(List ids, List current) { + private List checkedTeam(List ids, List current, Long companyId) { List 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 user, Long companyId) { + return isActiveAdmin(user) && user.get("companyId") instanceof Number n && companyId != null && n.longValue() == companyId; + } + private static boolean isActiveAdmin(Map 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 userIds, User caller) { + private void replaceTeam(long eventUuid, List userIds, User caller, Long companyId) { Map 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 row(Event e) { + private static Map row(CompanyEvent e) { Map 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()); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java index 3a8de25..fda47e4 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java @@ -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 list(String q, int page, int size) { - Map p = search(caller().getCompanyId(), trimmed(q), page, size); + public Map list(String q, int page, int size, Long companyId) { + Long company = scope.scope(caller(), companyId); + Map p = search(company, trimmed(q), page, size); List> rows = p == null || p.get("content") == null ? List.of() : (List>) p.get("content"); Map> users = new HashMap<>(); Map 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> 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 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 get(String leadUuid) { - long id = parseOr(leadUuid, AdminLeadService::notFound); - Map 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 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 before = load(caller, id); Map 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 before = storedOrNull(caller.getCompanyId(), id); Map 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 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 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 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 load(User caller, long id) { + Map 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 row(Map d, Map> users) { Map 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> users = new HashMap<>(); Map 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")); diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventControllerTest.java index d1423a0..3941f55 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventControllerTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventControllerTest.java @@ -72,16 +72,16 @@ class AdminEventControllerTest { @Test void list_passesQueryParamsAndDefaults() throws Exception { - when(events.list(any(), any(), eq(0), eq(20), any(), any())).thenReturn(Map.of("content", List.of(row()), "totalElements", 1)); + when(events.list(any(), any(), eq(0), eq(20), any(), any(), any())).thenReturn(Map.of("content", List.of(row()), "totalElements", 1)); mvc.perform(get("/api/admin/events").param("q", "food").param("enabled", "Y").param("sortBy", "endDate").param("sortDir", "desc")) .andExpect(status().isOk()) .andExpect(content().json("{\"content\":[{\"uuid\":\"7123456789012345678\"}],\"totalElements\":1}")); - verify(events).list("food", "Y", 0, 20, "endDate", "desc"); + verify(events).list("food", "Y", 0, 20, "endDate", "desc", null); } @Test void salespersonOptions_isNotShadowedByTheUuidRoute() throws Exception { - when(events.salespersonOptions()).thenReturn(List.of(Map.of("id", 1, "name", "Amy", "username", "amy"))); + when(events.salespersonOptions(null)).thenReturn(List.of(Map.of("id", 1, "name", "Amy", "username", "amy"))); mvc.perform(get("/api/admin/events/salesperson-options")).andExpect(status().isOk()) .andExpect(content().json("[{\"id\":1,\"name\":\"Amy\",\"username\":\"amy\"}]")); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java index 02117b8..7be5554 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java @@ -59,7 +59,7 @@ class AdminEventLeadControllerTest { @Test void optionsEndpoints() throws Exception { - when(eventLeads.events()).thenReturn(List.of(Map.of("uuid", EV, "name", "Fair"))); + when(eventLeads.events(null)).thenReturn(List.of(Map.of("uuid", EV, "name", "Fair"))); mvc.perform(get("/api/admin/event-leads/events")).andExpect(status().isOk()) .andExpect(content().json("[{\"uuid\":\"" + EV + "\",\"name\":\"Fair\"}]", true)); when(eventLeads.interestOptions()).thenReturn(List.of(Map.of("id", 3, "name", "Cookware", "active", true))); @@ -85,15 +85,15 @@ class AdminEventLeadControllerTest { @Test void listPassesFiltersAndPaging() throws Exception { - when(eventLeads.list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25)).thenReturn(Map.of("content", List.of(), "totalElements", 0)); + when(eventLeads.list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25, null)).thenReturn(Map.of("content", List.of(), "totalElements", 0)); mvc.perform(get("/api/admin/event-leads/" + EV + "/leads").param("salespersonId", "21").param("temperature", "HOT") .param("status", "OPEN").param("interestId", "3").param("leadType", "NEW").param("page", "1").param("size", "25")) .andExpect(status().isOk()); - verify(eventLeads).list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25); + verify(eventLeads).list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25, null); - when(eventLeads.list(EV, null, null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of())); + when(eventLeads.list(EV, null, null, null, null, null, 0, 20, null)).thenReturn(Map.of("content", List.of())); mvc.perform(get("/api/admin/event-leads/" + EV + "/leads")).andExpect(status().isOk()); - verify(eventLeads).list(EV, null, null, null, null, null, 0, 20); + verify(eventLeads).list(EV, null, null, null, null, null, 0, 20, null); } @Test diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadControllerTest.java index cb24c97..7dd3c4c 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadControllerTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadControllerTest.java @@ -55,7 +55,7 @@ class AdminLeadControllerTest { @Test void listDefaultsPagingAndPassesQuery() throws Exception { - when(leads.list("ai", 0, 20)).thenReturn(Map.of("content", java.util.List.of(), "totalElements", 0)); + when(leads.list("ai", 0, 20, null)).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}")); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadExportControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadExportControllerTest.java index 1a4d39a..bee6175 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadExportControllerTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadExportControllerTest.java @@ -45,7 +45,7 @@ class AdminLeadExportControllerTest { @Test void leadExportReturnsTheFileWithHeaders() throws Exception { AdminLeadService leads = mock(AdminLeadService.class); - when(leads.export("ai")).thenReturn(new byte[]{1, 2, 3}); + when(leads.export("ai", null)).thenReturn(new byte[]{1, 2, 3}); MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminLeadController(leads)).build(); mvc.perform(get("/api/admin/leads/export").param("q", "ai")).andExpect(status().isOk()) .andExpect(header().string("Content-Type", XLSX)) @@ -56,7 +56,7 @@ class AdminLeadExportControllerTest { @Test void eventLeadExportPassesFiltersAndNamesTheFile() throws Exception { AdminEventLeadService svc = mock(AdminEventLeadService.class); - when(svc.export("77", 22L, "HOT", "OPEN", 3L, "NEW")).thenReturn(new byte[]{9}); + when(svc.export("77", 22L, "HOT", "OPEN", 3L, "NEW", null)).thenReturn(new byte[]{9}); MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminEventLeadExportController(svc)).build(); mvc.perform(get("/api/admin/event-leads/77/export").param("salespersonId", "22").param("temperature", "HOT") .param("status", "OPEN").param("interestId", "3").param("leadType", "NEW")).andExpect(status().isOk()) @@ -70,7 +70,7 @@ class AdminLeadExportControllerTest { // The service accepts " 77\r\n" (it trims before parsing); none of those characters may reach the header. AdminEventLeadService svc = mock(AdminEventLeadService.class); when(svc.export(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())).thenReturn(new byte[]{9}); + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())).thenReturn(new byte[]{9}); MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminEventLeadExportController(svc)).build(); mvc.perform(get("/api/admin/event-leads/{uuid}/export", " 77\r\n")).andExpect(status().isOk()) .andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.matchesPattern("attachment; filename=\"event-leads-77-\\d{8}-\\d{4}\\.xlsx\""))); diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java index a674297..c0a99db 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java @@ -5,7 +5,6 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; 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.errorhandler.CodedResponseStatusException; @@ -62,7 +61,7 @@ class AdminEventLeadExportTest { void setUp() { rest = mock(RestTemplateCustomUtil.class); AdminAuthenticationService auth = mock(AdminAuthenticationService.class); - service = new AdminEventLeadService(rest, auth); + service = new AdminEventLeadService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); http = mockStatic(HttpReqRespUtils.class); http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); @@ -71,7 +70,8 @@ class AdminEventLeadExportTest { caller.setUsername("sales1"); caller.setCompanyId(COMPANY); when(auth.loadUserByToken("tok")).thenReturn(caller); - Event e = new Event(); + com.solvway.mobile.api.dto.admin.CompanyEvent e = new com.solvway.mobile.api.dto.admin.CompanyEvent(); + e.setCompanyId(5L); e.setUuid(EV); e.setName("KL Food Fair 2027"); e.setEnabled(GeneralEnum.FlagYesNo.Y); @@ -127,7 +127,7 @@ class AdminEventLeadExportTest { } private byte[] export() { - return service.export(String.valueOf(EV), 22L, "HOT", null, 3L, null); + return service.export(String.valueOf(EV), 22L, "HOT", null, 3L, null, null); } private static Sheet sheet(byte[] bytes) throws Exception { @@ -209,7 +209,7 @@ class AdminEventLeadExportTest { @Test void invalidFilterIsStillRejectedBeforeAnything() { - assertThatThrownBy(() -> service.export(String.valueOf(EV), null, "BOILING", null, null, null)) + assertThatThrownBy(() -> service.export(String.valueOf(EV), null, "BOILING", null, null, null, null)) .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("INVALID_VALUE")); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceAuditChangesTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceAuditChangesTest.java index 53f048e..08c0aec 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceAuditChangesTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceAuditChangesTest.java @@ -2,7 +2,6 @@ package com.solvway.mobile.api.service; import com.fasterxml.jackson.databind.ObjectMapper; 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.dto.admin.AdminEventLeadUpdateRequest; @@ -43,7 +42,7 @@ class AdminEventLeadServiceAuditChangesTest { AuditChanges.clear(); rest = mock(RestTemplateCustomUtil.class); AdminAuthenticationService auth = mock(AdminAuthenticationService.class); - service = new AdminEventLeadService(rest, auth); + service = new AdminEventLeadService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); http = mockStatic(HttpReqRespUtils.class); http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); @@ -52,7 +51,8 @@ class AdminEventLeadServiceAuditChangesTest { caller.setUsername("sales1"); caller.setCompanyId(COMPANY); when(auth.loadUserByToken("tok")).thenReturn(caller); - Event e = new Event(); + com.solvway.mobile.api.dto.admin.CompanyEvent e = new com.solvway.mobile.api.dto.admin.CompanyEvent(); + e.setCompanyId(5L); e.setUuid(EV); e.setName("Fair"); e.setEnabled(GeneralEnum.FlagYesNo.Y); @@ -63,6 +63,7 @@ class AdminEventLeadServiceAuditChangesTest { Map.of("id", 4L, "companyId", COMPANY, "name", "Kitchen", "active", true, "sortOrder", 0)))); Map d = new LinkedHashMap<>(); d.put("eventLeadUuid", EL); + d.put("companyId", COMPANY); d.put("eventUuid", EV); d.put("name", "Aisyah"); d.put("salespersonUserId", 21L); @@ -71,7 +72,7 @@ class AdminEventLeadServiceAuditChangesTest { d.put("interestIds", List.of(3L)); d.put("nextFollowUpDate", "2027-01-20"); d.put("notes", "old note"); - when(rest.getForEntity(eq("/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}"), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL))) + when(rest.getForEntity(eq("/counter/eventLead/findByUuid/{eventLeadUuid}"), any(ParameterizedTypeReference.class), eq(EL))) .thenReturn(ResponseEntity.ok(d)); when(rest.postForEntity(eq("/counter/eventLead/update"), any(ParameterizedTypeReference.class), any())) .thenAnswer(i -> ResponseEntity.ok(new HashMap(Map.of("eventLeadUuid", EL, "eventUuid", EV)))); diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceCompanyScopeTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceCompanyScopeTest.java new file mode 100644 index 0000000..b0cd879 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceCompanyScopeTest.java @@ -0,0 +1,344 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +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.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 java.time.LocalDateTime; +import java.util.HashMap; +import java.util.LinkedHashMap; +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.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Company scoping (design decision 6) for the admin event-lead service. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminEventLeadServiceCompanyScopeTest { + + private static final String EVENTS = "/counter/event/findByPropertyAndPageable"; + private static final String EVENT = "/counter/event/findByUuid/{uuid}"; + private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}"; + private static final String USER = "/user/findById/{id}"; + private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}"; + private static final String MATCHES = "/counter/lead/findMatches"; + private static final String CAPTURE = "/counter/eventLead/capture"; + private static final String FIND = "/counter/eventLead/findByUuid/{eventLeadUuid}"; + private static final String UPDATE = "/counter/eventLead/update"; + private static final String SEARCH = "/counter/eventLead/findByEvent"; + private static final long EV = 3312726793093644288L; + private static final long EL = 3312853897594494976L; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminEventLeadService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + service = new AdminEventLeadService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0))); + when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(), 0, 0, 0, 100))); + when(rest.postForEntity(eq(MATCHES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of())); + when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(new HashMap<>((Map) i.getArgument(2)))); + when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(new HashMap<>((Map) i.getArgument(2)))); + when(rest.getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of())); + } + + @AfterEach + void close() { http.close(); } + + private void caller(Long companyId, boolean superAdmin) { + User u = new User(); + u.setId(21L); + u.setUsername("boss"); + u.setCompanyId(companyId); + if (superAdmin) { + Role r = new Role("Super"); + r.setId(1L); + u.setRoles(List.of(r)); + } + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private void stubEvent(long companyId) { + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(companyId); + e.setUuid(EV); + e.setName("Fair"); + e.setLocation("MITEC"); + e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0)); + e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + e.setEnabled(GeneralEnum.FlagYesNo.Y); + when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e)); + } + + private void stubTeam(long... ids) { + List> rows = new java.util.ArrayList<>(); + for (long id : ids) rows.add(Map.of("userId", id)); + when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(rows)); + } + + private void stubUser(long id, long companyId) { + Map u = new HashMap<>(); + u.put("id", id); + u.put("name", "User " + id); + u.put("username", "u" + id); + u.put("type", "A"); + u.put("enabled", true); + u.put("companyId", companyId); + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u)); + } + + private void stubStored(long companyId, Long salesperson) { + Map d = new LinkedHashMap<>(); + d.put("eventLeadUuid", EL); + d.put("companyId", companyId); + d.put("eventUuid", EV); + d.put("leadUuid", 1L); + d.put("name", "Aisyah"); + d.put("leadType", "NEW"); + d.put("salespersonUserId", salesperson); + d.put("status", "OPEN"); + d.put("interestIds", List.of()); + when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(EL))).thenReturn(ResponseEntity.ok(d)); + } + + private static AdminEventLeadCaptureRequest capture(Long companyId) { + return new AdminEventLeadCaptureRequest(null, "Aisyah", "012-345 6789", null, null, null, null, null, null, List.of(), null, null, companyId); + } + + private static AdminEventLeadUpdateRequest update(Long salesperson) { + return new AdminEventLeadUpdateRequest(salesperson, null, null, List.of(), null, null); + } + + private static void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + private static void assertEventNotFound(Runnable r) { + assertCoded(r, HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + } + + private Map sentOnce(String api) { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture()); + return (Map) c.getValue(); + } + + // --- events option list --- + + private Object eventsCompany(Long requested) { + service.events(requested); + Map request = sentOnce(EVENTS); + Map property = (Map) request.get("property"); + assertThat(property).containsKey("companyId"); + return property.get("companyId"); + } + + @Test + void events_staffIgnoresRequestedCompany() { + caller(5L, false); + assertThat(eventsCompany(9L)).isEqualTo(5L); + } + + @Test + void events_superPassesRequestedOrAll() { + caller(null, true); + assertThat(eventsCompany(7L)).isEqualTo(7L); + } + + @Test + void events_superWithoutCompanyListsAll() { + caller(null, true); + assertThat(eventsCompany(null)).isNull(); + } + + // --- list and export --- + + @Test + void list_andExport_otherCompanysEventIsNotFoundForStaff() { + caller(5L, false); + stubEvent(9L); + assertEventNotFound(() -> service.list(String.valueOf(EV), null, null, null, null, null, 0, 20, null)); + assertEventNotFound(() -> service.export(String.valueOf(EV), null, null, null, null, null, 9L)); + verify(rest, never()).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()); + } + + @Test + void list_staffIgnoresRequestedCompany() { + caller(5L, false); + stubEvent(5L); + service.list(String.valueOf(EV), null, null, null, null, null, 0, 20, 9L); + assertThat(sentOnce(SEARCH)).containsEntry("companyId", 5L).containsEntry("eventUuid", EV); + } + + @Test + void list_andExport_superRequestingAnotherCompanyThanTheEventsIsNotFound() { + caller(null, true); + stubEvent(9L); + assertEventNotFound(() -> service.list(String.valueOf(EV), null, null, null, null, null, 0, 20, 7L)); + assertEventNotFound(() -> service.export(String.valueOf(EV), null, null, null, null, null, 7L)); + } + + @Test + void list_andExport_superWithoutCompanyUsesTheEventsCompany() { + caller(null, true); + stubEvent(9L); + service.list(String.valueOf(EV), null, null, null, null, null, 0, 20, null); + assertThat(sentOnce(SEARCH)).containsEntry("companyId", 9L); + } + + @Test + void export_staffGetsOwnEventsRowsOnly() { + caller(5L, false); + stubEvent(5L); + service.export(String.valueOf(EV), null, null, null, null, null, 9L); + assertThat(sentOnce(SEARCH)).containsEntry("companyId", 5L); + } + + // --- detail and edit --- + + @Test + void get_andUpdate_otherCompanysEventLeadIsNotFoundForStaff() { + caller(5L, false); + stubEvent(9L); + stubStored(9L, null); + assertEventNotFound(() -> service.get(String.valueOf(EV), String.valueOf(EL))); + assertEventNotFound(() -> service.update(String.valueOf(EV), String.valueOf(EL), update(null))); + verify(rest, never()).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void get_superOpensAnyCompanysEventLead() { + caller(null, true); + stubEvent(9L); + stubStored(9L, null); + assertThat(service.get(String.valueOf(EV), String.valueOf(EL))).containsEntry("eventLeadUuid", String.valueOf(EL)); + } + + @Test + void update_writesTheStoredCompany() { + caller(null, true); + stubEvent(9L); + stubStored(9L, null); + service.update(String.valueOf(EV), String.valueOf(EL), update(null)); + assertThat(sentOnce(UPDATE)).containsEntry("companyId", 9L); + } + + @Test + void get_andUpdate_storedRecordWithoutCompanyIsNotFoundForStaff() { + caller(5L, false); + stubEvent(5L); + stubStored(5L, null); + Map d = new LinkedHashMap<>(); + d.put("eventLeadUuid", EL); + d.put("eventUuid", EV); + d.put("salespersonUserId", null); + when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(EL))).thenReturn(ResponseEntity.ok(d)); + assertCoded(() -> service.get(String.valueOf(EV), String.valueOf(EL)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND"); + assertCoded(() -> service.update(String.valueOf(EV), String.valueOf(EL), update(31L)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND"); + verify(rest, never()).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void update_salespersonOfAnotherCompanyIsRefused() { + caller(null, true); + stubEvent(9L); + stubStored(9L, null); + stubTeam(31L); + stubUser(31L, 5L); + assertCoded(() -> service.update(String.valueOf(EV), String.valueOf(EL), update(31L)), HttpStatus.BAD_REQUEST, "NOT_ON_TEAM"); + verify(rest, never()).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()); + } + + // --- capture and match --- + + @Test + void capture_andMatch_otherCompanysEventIsNotFoundForStaff() { + caller(5L, false); + stubEvent(9L); + assertEventNotFound(() -> service.capture(String.valueOf(EV), capture(9L))); + assertEventNotFound(() -> service.match(String.valueOf(EV), new AdminLeadMatchRequest("0123456789", null, 9L))); + verify(rest, never()).postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void capture_andMatch_superWithoutCompanyIsRefused() { + caller(null, true); + stubEvent(9L); + assertCoded(() -> service.capture(String.valueOf(EV), capture(null)), HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + assertCoded(() -> service.match(String.valueOf(EV), new AdminLeadMatchRequest("0123456789", null, null)), HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + verify(rest, never()).postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()); + verify(rest, never()).postForEntity(eq(MATCHES), any(ParameterizedTypeReference.class), any()); + } + + @Test + void capture_superWithMatchingCompanySavesTheEventsCompany_andMatchesInIt() { + caller(null, true); + stubEvent(9L); + service.capture(String.valueOf(EV), capture(9L)); + assertThat(sentOnce(CAPTURE)).containsEntry("companyId", 9L); + service.match(String.valueOf(EV), new AdminLeadMatchRequest("0123456789", null, 9L)); + assertThat(sentOnce(MATCHES)).containsEntry("companyId", 9L); + } + + @Test + void capture_superChoosingAnotherCompanyThanTheEventsIsNotFound() { + caller(null, true); + stubEvent(9L); + assertEventNotFound(() -> service.capture(String.valueOf(EV), capture(7L))); + } + + // --- event team --- + + @Test + void salespersonOptions_offerOnlyUsersOfTheEventsCompany() { + caller(null, true); + stubEvent(9L); + stubTeam(31L, 32L); + stubUser(31L, 9L); + stubUser(32L, 5L); + assertThat(service.salespersonOptions(String.valueOf(EV))).extracting(m -> m.get("id")).containsExactly(31L); + } + + @Test + void salespersonOptions_otherCompanysEventIsNotFoundForStaff() { + caller(5L, false); + stubEvent(9L); + assertEventNotFound(() -> service.salespersonOptions(String.valueOf(EV))); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java index 830a191..472d482 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java @@ -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.dto.admin.AdminEventLeadCaptureRequest; @@ -46,7 +45,7 @@ class AdminEventLeadServiceTest { private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}"; private static final String MATCHES = "/counter/lead/findMatches"; private static final String CAPTURE = "/counter/eventLead/capture"; - private static final String FIND = "/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}"; + private static final String FIND = "/counter/eventLead/findByUuid/{eventLeadUuid}"; private static final String UPDATE = "/counter/eventLead/update"; private static final String SEARCH = "/counter/eventLead/findByEvent"; @@ -63,7 +62,7 @@ class AdminEventLeadServiceTest { void setUp() { rest = mock(RestTemplateCustomUtil.class); AdminAuthenticationService auth = mock(AdminAuthenticationService.class); - service = new AdminEventLeadService(rest, auth); + service = new AdminEventLeadService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); http = mockStatic(HttpReqRespUtils.class); http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); @@ -90,7 +89,8 @@ class AdminEventLeadServiceTest { // --- stubs --- private void stubEvent(boolean enabled) { - Event e = new Event(); + com.solvway.mobile.api.dto.admin.CompanyEvent e = new com.solvway.mobile.api.dto.admin.CompanyEvent(); + e.setCompanyId(5L); e.setUuid(EV); e.setName("KL Food Fair 2027"); e.setLocation("MITEC"); @@ -112,6 +112,7 @@ class AdminEventLeadServiceTest { u.put("name", name); u.put("username", "u" + id); u.put("type", "A"); + u.put("companyId", COMPANY); u.put("enabled", enabled); when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u)); } @@ -128,6 +129,7 @@ class AdminEventLeadServiceTest { private static Map detailFrom(Map body) { Map d = new LinkedHashMap<>(); d.put("eventLeadUuid", EL); + d.put("companyId", COMPANY); d.put("eventUuid", body.getOrDefault("eventUuid", EV)); d.put("leadUuid", body.get("leadUuid") == null ? LEAD : body.get("leadUuid")); d.put("name", body.getOrDefault("name", "Aisyah")); @@ -149,6 +151,7 @@ class AdminEventLeadServiceTest { private void stubStored(long eventUuid, Long salespersonUserId, List interestIds) { Map d = new LinkedHashMap<>(); d.put("eventLeadUuid", EL); + d.put("companyId", COMPANY); d.put("eventUuid", eventUuid); d.put("leadUuid", LEAD); d.put("name", "Aisyah"); @@ -157,7 +160,7 @@ class AdminEventLeadServiceTest { d.put("salespersonUserId", salespersonUserId); d.put("status", "OPEN"); d.put("interestIds", interestIds); - when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL))).thenReturn(ResponseEntity.ok(d)); + when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(EL))).thenReturn(ResponseEntity.ok(d)); } private static AdminEventLeadCaptureRequest capture(String leadUuid, String name, String mobile, String email) { @@ -190,7 +193,8 @@ class AdminEventLeadServiceTest { @Test void eventsAreTheEnabledOnesNewestFirst() { - Event e = new Event(); + com.solvway.mobile.api.dto.admin.CompanyEvent e = new com.solvway.mobile.api.dto.admin.CompanyEvent(); + e.setCompanyId(5L); e.setUuid(EV); e.setName("KL Food Fair 2027"); e.setLocation("MITEC"); @@ -199,10 +203,10 @@ class AdminEventLeadServiceTest { when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any())) .thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(e), 1, 1, 0, 100))); - List> events = service.events(); + List> events = service.events(null); assertThat(events).containsExactly(Map.of("uuid", String.valueOf(EV), "name", "KL Food Fair 2027", "location", "MITEC", - "startDate", "2027-01-15", "endDate", "2027-01-17")); + "startDate", "2027-01-15", "endDate", "2027-01-17", "companyId", COMPANY)); Map body = sent(EVENTS); assertThat((Map) body.get("property")).containsEntry("enabled", "Y"); Map pageable = (Map) body.get("pageableRest"); @@ -212,12 +216,13 @@ class AdminEventLeadServiceTest { @Test void eventWithEmptyFieldsStillListsWithNulls() { - Event e = new Event(); + com.solvway.mobile.api.dto.admin.CompanyEvent e = new com.solvway.mobile.api.dto.admin.CompanyEvent(); + e.setCompanyId(5L); e.setUuid(EV); when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any())) .thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(e), 1, 1, 0, 100))); - Map row = service.events().get(0); + Map row = service.events(null).get(0); assertThat(row).containsEntry("uuid", String.valueOf(EV)).containsEntry("name", null) .containsEntry("location", null).containsEntry("startDate", null).containsEntry("endDate", null); @@ -364,7 +369,7 @@ class AdminEventLeadServiceTest { when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(1L))).thenReturn(ResponseEntity.ok().build()); assertCoded(() -> service.capture("1", capture(null, "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null); - assertCoded(() -> service.list("not-a-number", null, null, null, null, null, 0, 20), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null); + assertCoded(() -> service.list("not-a-number", null, null, null, null, null, 0, 20, null), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null); } // --- salesperson from the team --- @@ -480,7 +485,7 @@ class AdminEventLeadServiceTest { when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) .thenReturn(ResponseEntity.ok(Map.of("content", List.of(row), "totalElements", 1, "totalPages", 1, "number", 0, "size", 20))); - Map out = service.list(String.valueOf(EV), 22L, "HOT", "OPEN", 3L, "EXISTING", 0, 20); + Map out = service.list(String.valueOf(EV), 22L, "HOT", "OPEN", 3L, "EXISTING", 0, 20, null); assertThat(sent(SEARCH)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserId", 22L) .containsEntry("temperature", "HOT").containsEntry("status", "OPEN").containsEntry("interestId", 3L) @@ -505,7 +510,7 @@ class AdminEventLeadServiceTest { @Test void unknownEventLeadIsNotFound() { - when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL))) + when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(EL))) .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", null, null, null)); assertCoded(() -> service.get(String.valueOf(EV), String.valueOf(EL)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null); diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceCompanyScopeTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceCompanyScopeTest.java new file mode 100644 index 0000000..7e12750 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceCompanyScopeTest.java @@ -0,0 +1,229 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +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.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 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.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Company scoping (design decision 6) for the admin event service. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminEventServiceCompanyScopeTest { + + private static final String LIST = "/counter/event/findByPropertyAndPageable"; + private static final String BY_UUID = "/counter/event/findByUuid/{uuid}"; + private static final String SAVE = "/counter/event/save"; + private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}"; + private static final String REPLACE = "/counter/eventSalesperson/replace"; + private static final String USER = "/user/findById/{id}"; + private static final String USERS = "/user/findByPropertyAndPageable"; + private static final long EV = 701L; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminEventService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + service = new AdminEventService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(i.getArgument(2))); + when(rest.postForEntity(eq(REPLACE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of())); + when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of())); + when(rest.postForEntity(eq(LIST), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(), 0, 0, 0, 20))); + when(rest.postForEntity(eq(USERS), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("content", List.of()))); + } + + @AfterEach + void close() { http.close(); } + + private void caller(Long companyId, boolean superAdmin) { + User u = new User(); + u.setUsername("boss"); + u.setCompanyId(companyId); + if (superAdmin) { + Role r = new Role("Super"); + r.setId(1L); + u.setRoles(java.util.List.of(r)); + } + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private void stubEvent(long companyId) { + CompanyEvent e = new CompanyEvent(); + e.setUuid(EV); + e.setCompanyId(companyId); + e.setName("Fair"); + e.setLocation("MITEC"); + e.setDateStart(java.time.LocalDateTime.of(2027, 1, 15, 0, 0)); + e.setDateEnd(java.time.LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + when(rest.getForEntity(eq(BY_UUID), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e)); + } + + private void stubUser(long id, long companyId) { + Map u = new HashMap<>(); + u.put("id", id); + u.put("name", "User " + id); + u.put("username", "u" + id); + u.put("type", "A"); + u.put("enabled", true); + u.put("companyId", companyId); + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u)); + } + + private Object listedCompany(Long requested) { + service.list(null, null, 0, 20, null, null, requested); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(LIST), any(ParameterizedTypeReference.class), body.capture()); + Map property = (Map) ((Map) body.getValue()).get("property"); + assertThat(property).containsKey("companyId"); + return property.get("companyId"); + } + + private static AdminEventRequest req(Long companyId, List team) { + return new AdminEventRequest("Fair", "MITEC", "2027-01-15", "2027-01-17", null, team, companyId); + } + + private static void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + // --- list --- + + @Test + void list_staffIgnoresRequestedCompany() { + caller(5L, false); + assertThat(listedCompany(9L)).isEqualTo(5L); + } + + @Test + void list_superPassesRequestedCompany() { + caller(null, true); + assertThat(listedCompany(7L)).isEqualTo(7L); + } + + @Test + void list_superWithoutCompanyListsAll() { + caller(null, true); + assertThat(listedCompany(null)).isNull(); + } + + // --- by uuid --- + + @Test + void get_andUpdate_otherCompanyIsNotFoundForStaff() { + caller(5L, false); + stubEvent(9L); + assertCoded(() -> service.get(String.valueOf(EV)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.update(String.valueOf(EV), req(null, null)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void get_superWithoutCompanyOpensAnyEvent() { + caller(null, true); + stubEvent(9L); + assertThat(service.get(String.valueOf(EV))).containsEntry("companyId", 9L); + } + + @Test + void update_neverMovesTheEventAndKeepsItsCompany() { + caller(null, true); + stubEvent(9L); + service.update(String.valueOf(EV), req(3L, null)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat(((CompanyEvent) body.getValue()).getCompanyId()).isEqualTo(9L); + } + + // --- create --- + + @Test + void create_superWithoutCompanyIsRefused() { + caller(null, true); + assertCoded(() -> service.create(req(null, null)), HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_superSavesTheChosenCompany_staffGetsOwn() { + caller(null, true); + service.create(req(7L, null)); + caller(5L, false); + service.create(req(7L, null)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest, org.mockito.Mockito.times(2)).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat(body.getAllValues()).extracting(o -> ((CompanyEvent) o).getCompanyId()).containsExactly(7L, 5L); + } + + // --- team --- + + @Test + void create_refusesTeamMemberOfAnotherCompany() { + caller(5L, false); + stubUser(1, 5L); + stubUser(2, 9L); + assertCoded(() -> service.create(req(null, List.of(1L, 2L))), HttpStatus.BAD_REQUEST, "UNKNOWN_USER"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void update_refusesTeamMemberOfAnotherCompanyThanTheEvents() { + caller(null, true); + stubEvent(9L); + stubUser(1, 5L); + assertCoded(() -> service.update(String.valueOf(EV), req(null, List.of(1L))), HttpStatus.BAD_REQUEST, "UNKNOWN_USER"); + stubUser(1, 9L); + service.update(String.valueOf(EV), req(null, List.of(1L))); + verify(rest).postForEntity(eq(REPLACE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void salespersonOptions_offerOnlyTheScopedCompanysUsers() { + caller(5L, false); + service.salespersonOptions(9L); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(USERS), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) ((Map) body.getValue()).get("property")).containsEntry("companyId", 5L); + } + + @Test + void salespersonOptions_superWithoutCompanyGetsNobody() { + caller(null, true); + assertThat(service.salespersonOptions(null)).isEmpty(); + verify(rest, never()).postForEntity(eq(USERS), any(ParameterizedTypeReference.class), any()); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceTest.java index 45616d3..0fdbff3 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceTest.java @@ -52,7 +52,7 @@ class AdminEventServiceTest { void setUp() { rest = mock(RestTemplateCustomUtil.class); AdminAuthenticationService auth = mock(AdminAuthenticationService.class); - service = new AdminEventService(rest, auth); + service = new AdminEventService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); http = mockStatic(HttpReqRespUtils.class); http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); @@ -71,8 +71,9 @@ class AdminEventServiceTest { @AfterEach void close() { http.close(); } - private static Event event() { - Event e = new Event(); + private static com.solvway.mobile.api.dto.admin.CompanyEvent event() { + com.solvway.mobile.api.dto.admin.CompanyEvent e = new com.solvway.mobile.api.dto.admin.CompanyEvent(); + e.setCompanyId(5L); e.setId(11L); e.setUuid(UUID); e.setName("Old"); @@ -97,6 +98,7 @@ class AdminEventServiceTest { u.put("name", "User " + id); u.put("username", "u" + id); u.put("type", type); + u.put("companyId", 5L); u.put("enabled", enabled); when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u)); } @@ -150,7 +152,7 @@ class AdminEventServiceTest { return ResponseEntity.ok(new AdminEventService.EventPage(List.of(event()), 41, 3, 2, 20)); }); - Map out = service.list(" food ", "N", 2, 20, "startDate", "desc"); + Map out = service.list(" food ", "N", 2, 20, "startDate", "desc", null); Map body = (Map) sent.get(); assertThat((Map) body.get("property")).containsEntry("name", "food").containsEntry("enabled", "N"); @@ -160,7 +162,7 @@ class AdminEventServiceTest { assertThat(out).containsEntry("totalElements", 41L).containsEntry("totalPages", 3).containsEntry("number", 2).containsEntry("size", 20); Map row = ((List>) out.get("content")).get(0); assertThat(row).containsExactlyInAnyOrderEntriesOf(Map.of("uuid", "7123456789012345678", "name", "Old", "location", "Old place", - "startDate", "2026-05-01", "endDate", "2026-05-02", "enabled", true)); + "startDate", "2026-05-01", "endDate", "2026-05-02", "enabled", true, "companyId", 5L)); } @Test @@ -170,7 +172,7 @@ class AdminEventServiceTest { sent.set(i.getArgument(2)); return ResponseEntity.ok(new AdminEventService.EventPage(List.of(), 0, 0, 0, 20)); }); - service.list(null, null, 0, 20, null, null); + service.list(null, null, 0, 20, null, null, null); Map pageable = (Map) ((Map) sent.get()).get("pageableRest"); assertThat((List>) pageable.get("sorts")).containsExactly(Map.of("direction", "ASC", "property", "name")); } @@ -182,7 +184,7 @@ class AdminEventServiceTest { sent.set(i.getArgument(2)); return ResponseEntity.ok(new AdminEventService.EventPage(List.of(), 0, 0, 0, 20)); }); - service.list(null, null, 0, 20, null, null); + service.list(null, null, 0, 20, null, null, null); assertThat((Map) ((Map) sent.get()).get("property")) .containsEntry("name", "").containsEntry("enabled", ""); } @@ -191,7 +193,7 @@ class AdminEventServiceTest { void list_nullContentFromCounterGivesEmptyContent() { when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any())) .thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(null, 0, 0, 0, 20))); - assertThat((List) service.list(null, null, 0, 20, null, null).get("content")).isEmpty(); + assertThat((List) service.list(null, null, 0, 20, null, null, null).get("content")).isEmpty(); } @Test @@ -201,7 +203,7 @@ class AdminEventServiceTest { sent.set(i.getArgument(2)); return ResponseEntity.ok(new AdminEventService.EventPage(List.of(), 0, 0, 0, 20)); }); - service.list(null, null, 0, 20, "bogus", null); + service.list(null, null, 0, 20, "bogus", null, null); Map pageable = (Map) ((Map) sent.get()).get("pageableRest"); assertThat((List>) pageable.get("sorts")).containsExactly(Map.of("direction", "ASC", "property", "name")); } @@ -406,7 +408,7 @@ class AdminEventServiceTest { when(rest.postForEntity(eq(USERS), any(ParameterizedTypeReference.class), any())) .thenReturn(ResponseEntity.ok(Map.of("content", users))); - assertThat(service.salespersonOptions()).containsExactly( + assertThat(service.salespersonOptions(null)).containsExactly( Map.of("id", 4L, "name", "amy", "username", "a"), Map.of("id", 1L, "name", "Zed", "username", "z")); } } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadExportTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadExportTest.java index 730090f..816a9b9 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadExportTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadExportTest.java @@ -54,7 +54,7 @@ class AdminLeadExportTest { void setUp() { rest = mock(RestTemplateCustomUtil.class); AdminAuthenticationService auth = mock(AdminAuthenticationService.class); - service = new AdminLeadService(rest, auth); + service = new AdminLeadService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); http = mockStatic(HttpReqRespUtils.class); http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); @@ -118,7 +118,7 @@ class AdminLeadExportTest { @Test void headerLabelsAndOrder() throws Exception { stubRows(2); - Sheet s = sheet(service.export("x")); + Sheet s = sheet(service.export("x", null)); assertThat(s.getSheetName()).isEqualTo("Leads"); List header = new ArrayList<>(); s.getRow(0).forEach(c -> header.add(c.getStringCellValue())); @@ -129,7 +129,7 @@ class AdminLeadExportTest { @Test void cellTypesAndValues() throws Exception { stubRows(1); - Sheet s = sheet(service.export(null)); + Sheet s = sheet(service.export(null, null)); var r = s.getRow(1); assertThat(r.getCell(0).getStringCellValue()).isEqualTo("Lead 0"); assertThat(r.getCell(1).getCellType()).isEqualTo(CellType.STRING); @@ -148,7 +148,7 @@ class AdminLeadExportTest { r.put("latestSalespersonUserId", null); when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) .thenReturn(ResponseEntity.ok(Map.of("content", List.of(r), "totalElements", 1))); - var row = sheet(service.export(null)).getRow(1); + var row = sheet(service.export(null, null)).getRow(1); assertThat(row.getCell(5) == null || row.getCell(5).getCellType() == CellType.BLANK).isTrue(); assertThat(row.getCell(6) == null || row.getCell(6).getCellType() == CellType.BLANK).isTrue(); } @@ -156,7 +156,7 @@ class AdminLeadExportTest { @Test void collectsAllPagesOfOneHundredAndResolvesEachUserOnce() throws Exception { stubRows(230); - Sheet s = sheet(service.export(" acme ")); + Sheet s = sheet(service.export(" acme ", null)); assertThat(s.getLastRowNum()).isEqualTo(230); assertThat(s.getRow(230).getCell(0).getStringCellValue()).isEqualTo("Lead 229"); ArgumentCaptor bodies = ArgumentCaptor.forClass(Object.class); @@ -172,7 +172,7 @@ class AdminLeadExportTest { @Test void tooManyRowsIsRefusedAfterTheFirstPage() { stubRows(20001); - assertThatThrownBy(() -> service.export(null)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThatThrownBy(() -> service.export(null, null)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY); assertThat(e.getCode()).isEqualTo("EXPORT_TOO_LARGE"); assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("limit", 20000)); @@ -186,13 +186,13 @@ class AdminLeadExportTest { void exactlyTheLimitIsAllowed() throws Exception { when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) .thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 20000))); - assertThat(sheet(service.export(null)).getLastRowNum()).isEqualTo(0); + assertThat(sheet(service.export(null, null)).getLastRowNum()).isEqualTo(0); } @Test void auditLineHasUserListingAndCountOnly() { stubRows(2); - service.export("lead 1 secretterm"); + service.export("lead 1 secretterm", null); List lines = logs.list.stream().filter(e -> e.getLevel() == Level.INFO).map(ILoggingEvent::getFormattedMessage) .filter(m -> m.contains("lead export")).toList(); assertThat(lines).containsExactly("lead export by sales1: listing=leads rows=2"); diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceAuditChangesTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceAuditChangesTest.java index 547042a..f04ca8a 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceAuditChangesTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceAuditChangesTest.java @@ -31,7 +31,7 @@ import static org.mockito.Mockito.when; @SuppressWarnings({"unchecked", "rawtypes"}) class AdminLeadServiceAuditChangesTest { - private static final String DETAIL = "/counter/lead/detail/{companyId}/{leadUuid}"; + private static final String DETAIL = "/counter/lead/detail/{leadUuid}"; private static final String UPDATE = "/counter/lead/update"; private static final long LEAD = 3312853897040846848L; @@ -44,7 +44,7 @@ class AdminLeadServiceAuditChangesTest { AuditChanges.clear(); rest = mock(RestTemplateCustomUtil.class); AdminAuthenticationService auth = mock(AdminAuthenticationService.class); - service = new AdminLeadService(rest, auth); + service = new AdminLeadService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); http = mockStatic(HttpReqRespUtils.class); http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); @@ -65,11 +65,12 @@ class AdminLeadServiceAuditChangesTest { private void stored() { Map d = new HashMap<>(); d.put("leadUuid", LEAD); + d.put("companyId", 5L); d.put("name", "Old Name"); d.put("mobileE164", "+60123456701"); d.put("email", "old@example.test"); d.put("companyName", "Acme"); - when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(5L), eq(LEAD))).thenReturn(ResponseEntity.ok(d)); + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(LEAD))).thenReturn(ResponseEntity.ok(d)); } @Test @@ -95,7 +96,13 @@ class AdminLeadServiceAuditChangesTest { @Test void update_unreadableBeforeStateRecordsNothing() { - service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Brand New Name", "012-345 6701", null, null, null, null)); + // company scoping: the lead is read first (its company is the write company), so an unreadable lead is a 404 and nothing is recorded + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(LEAD))) + .thenThrow(org.springframework.web.client.HttpClientErrorException.create(org.springframework.http.HttpStatus.NOT_FOUND, "nf", null, null, null)); + + org.assertj.core.api.Assertions.assertThatThrownBy(() -> service.update(String.valueOf(LEAD), + new AdminLeadUpdateRequest("Brand New Name", "012-345 6701", null, null, null, null))) + .isInstanceOf(com.solvway.mobile.api.errorhandler.CodedResponseStatusException.class); assertThat(AuditChanges.current()).isNull(); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceCompanyScopeTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceCompanyScopeTest.java new file mode 100644 index 0000000..007fa37 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceCompanyScopeTest.java @@ -0,0 +1,200 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.Role; +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 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.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Company scoping (design decision 6) for the admin lead service. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminLeadServiceCompanyScopeTest { + + private static final String SEARCH = "/counter/lead/search"; + private static final String DETAIL = "/counter/lead/detail/{leadUuid}"; + private static final String UPDATE = "/counter/lead/update"; + private static final long LEAD = 3312853897040846848L; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminLeadService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + service = new AdminLeadService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + 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 caller(Long companyId, boolean superAdmin) { + User u = new User(); + u.setId(21L); + u.setUsername("boss"); + u.setCompanyId(companyId); + if (superAdmin) { + Role r = new Role("Super"); + r.setId(1L); + u.setRoles(List.of(r)); + } + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private void stubLead(long companyId) { + Map d = new HashMap<>(); + d.put("leadUuid", LEAD); + d.put("name", "Aisyah"); + d.put("mobileE164", "+60123456701"); + d.put("companyId", companyId); + d.put("history", List.of()); + d.put("sharedContacts", List.of()); + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(LEAD))).thenReturn(ResponseEntity.ok(d)); + } + + private static AdminLeadUpdateRequest req() { + return new AdminLeadUpdateRequest("Aisyah", "012-345 6701", null, null, null, null); + } + + private static void assertNotFound(Runnable r) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(e.getCode()).isEqualTo("LEAD_NOT_FOUND"); + }); + } + + private Object searchedCompany() { + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), body.capture()); + Map b = (Map) body.getValue(); + assertThat(b).containsKey("companyId"); + return b.get("companyId"); + } + + // --- list --- + + @Test + void list_staffIgnoresRequestedCompany() { + caller(5L, false); + service.list(null, 0, 20, 9L); + assertThat(searchedCompany()).isEqualTo(5L); + } + + @Test + void list_superPassesRequestedCompany() { + caller(null, true); + service.list(null, 0, 20, 7L); + assertThat(searchedCompany()).isEqualTo(7L); + } + + @Test + void list_superWithoutCompanyListsAll() { + caller(null, true); + service.list(null, 0, 20, null); + assertThat(searchedCompany()).isNull(); + } + + private void stubRows() { + 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", "companyId", 5L)), + new HashMap<>(Map.of("leadUuid", LEAD + 1, "name", "B", "companyId", 9L))), "totalElements", 2))); + } + + @Test + void list_rowsCarryTheirOwnCompanyId_underAllCompanies() { + caller(null, true); + stubRows(); + List> rows = (List>) service.list(null, 0, 20, null).get("content"); + assertThat(rows).extracting(r -> r.get("companyId")).containsExactly(5L, 9L); + } + + // --- export --- + + @Test + void export_staffIgnoresRequestedCompany() { + caller(5L, false); + service.export(null, 9L); + assertThat(searchedCompany()).isEqualTo(5L); + } + + @Test + void export_superPassesRequestedCompanyOrAll() { + caller(null, true); + service.export(null, 7L); + assertThat(searchedCompany()).isEqualTo(7L); + } + + @Test + void export_superWithoutCompanyExportsAll() { + caller(null, true); + service.export(null, null); + assertThat(searchedCompany()).isNull(); + } + + // --- detail and edit --- + + @Test + void get_andUpdate_otherCompanyIsNotFoundForStaff() { + caller(5L, false); + stubLead(9L); + assertNotFound(() -> service.get(String.valueOf(LEAD))); + assertNotFound(() -> service.update(String.valueOf(LEAD), req())); + verify(rest, never()).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void get_ownCompanyIsVisibleToStaff() { + caller(5L, false); + stubLead(5L); + assertThat(service.get(String.valueOf(LEAD))).containsEntry("companyId", 5L); + } + + @Test + void get_superWithoutCompanyOpensAnyLead() { + caller(null, true); + stubLead(9L); + assertThat(service.get(String.valueOf(LEAD))).containsEntry("companyId", 9L); + } + + @Test + void update_writesTheLeadsOwnCompany() { + caller(null, true); + stubLead(9L); + service.update(String.valueOf(LEAD), req()); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), body.capture()); + assertThat(((Map) body.getValue())).containsEntry("companyId", 9L); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceTest.java index 05044c7..c4e2a7a 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceTest.java @@ -33,7 +33,7 @@ import static org.mockito.Mockito.when; class AdminLeadServiceTest { private static final String SEARCH = "/counter/lead/search"; - private static final String DETAIL = "/counter/lead/detail/{companyId}/{leadUuid}"; + private static final String DETAIL = "/counter/lead/detail/{leadUuid}"; private static final String UPDATE = "/counter/lead/update"; private static final String USER = "/user/findById/{id}"; private static final long LEAD = 3312853897040846848L; @@ -49,7 +49,7 @@ class AdminLeadServiceTest { void setUp() { rest = mock(RestTemplateCustomUtil.class); AdminAuthenticationService auth = mock(AdminAuthenticationService.class); - service = new AdminLeadService(rest, auth); + service = new AdminLeadService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope()); when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); http = mockStatic(HttpReqRespUtils.class); http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); @@ -77,7 +77,7 @@ class AdminLeadServiceTest { } private Map searched(String q) { - service.list(q, 2, 10); + service.list(q, 2, 10, null); ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); verify(rest).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), body.capture()); return (Map) body.getValue(); @@ -125,7 +125,7 @@ class AdminLeadServiceTest { Map 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 out = service.list(null, 0, 20); + Map out = service.list(null, 0, 20, null); List> rows = (List>) out.get("content"); assertThat(out.get("totalElements")).isEqualTo(7); assertThat(rows.get(0)).containsEntry("leadUuid", String.valueOf(LEAD)).containsEntry("mobile", "+60123456701") @@ -140,7 +140,7 @@ class AdminLeadServiceTest { 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> rows = (List>) service.list(null, 0, 20).get("content"); + List> rows = (List>) service.list(null, 0, 20, null).get("content"); assertThat(rows.get(0)).containsEntry("latestSalesperson", null); } @@ -154,6 +154,7 @@ class AdminLeadServiceTest { Map h2 = new HashMap<>(Map.of("eventLeadUuid", EL + 1, "eventUuid", EV, "salespersonUserId", 21L)); Map 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("companyId", COMPANY); 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; @@ -161,7 +162,7 @@ class AdminLeadServiceTest { @Test void get_mapsHistoryAndSharedContacts() { - when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(COMPANY), eq(LEAD))).thenReturn(ResponseEntity.ok(detail())); + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(LEAD))).thenReturn(ResponseEntity.ok(detail())); Map 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"); @@ -182,7 +183,7 @@ class AdminLeadServiceTest { @Test void get_counter404Is404() { - when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(COMPANY), eq(LEAD))) + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), 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); } @@ -208,6 +209,7 @@ class AdminLeadServiceTest { @Test void update_counter404Is404() { + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(LEAD))).thenReturn(ResponseEntity.ok(detail())); 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); @@ -256,6 +258,7 @@ class AdminLeadServiceTest { @Test void update_normalisesAndSendsDoneBy() { + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(LEAD))).thenReturn(ResponseEntity.ok(detail())); service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest(" Aisyah ", "012-345 6701", " Aisyah@Example.TEST ", " ", " Buyer ", "")); ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); verify(rest).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), body.capture()); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSummary.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSummary.java index f9bed13..a24eb55 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSummary.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSummary.java @@ -4,4 +4,13 @@ import java.time.LocalDateTime; public record LeadSummary(long leadUuid, String name, String mobileE164, String email, String companyName, String jobTitle, long eventCount, Long lastEventUuid, String lastEventName, - LocalDateTime lastCapturedAt, Long latestSalespersonUserId) {} + LocalDateTime lastCapturedAt, Long latestSalespersonUserId, Long companyId) { + + /** Without the lead's own company id (single-company callers already know it). */ + public LeadSummary(long leadUuid, String name, String mobileE164, String email, String companyName, + String jobTitle, long eventCount, Long lastEventUuid, String lastEventName, + LocalDateTime lastCapturedAt, Long latestSalespersonUserId) { + this(leadUuid, name, mobileE164, email, companyName, jobTitle, eventCount, lastEventUuid, lastEventName, + lastCapturedAt, latestSalespersonUserId, null); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java index 3e12cf6..2539fa8 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java @@ -35,6 +35,7 @@ public interface LeadRepository extends JpaRepository { String getLastEventName(); java.time.LocalDateTime getLastCapturedAt(); Long getLatestSalespersonUserId(); + Long getCompanyId(); } /** The search condition uses only `lead` columns, so the count skips the aggregate joins. */ @@ -53,13 +54,13 @@ public interface LeadRepository extends JpaRepository { /** * Returns one row per lead with columns lead_uuid AS leadUuid, name, mobile_e164 AS mobileE164, email_normalised AS email, * company_name AS companyName, job_title AS jobTitle, eventCount, lastEventUuid, lastEventName, lastCapturedAt and - * latestSalespersonUserId. Native because JPQL has no window functions. Never-captured leads sort last. + * latestSalespersonUserId and companyId. Native because JPQL has no window functions. Never-captured leads sort last. */ @Query(nativeQuery = true, value = "SELECT l.uuid AS leadUuid, l.name AS name, l.mobile_e164 AS mobileE164, l.email_normalised AS email," + " l.company_name AS companyName, l.job_title AS jobTitle, COALESCE(c.cnt, 0) AS eventCount," + " last.event_uuid AS lastEventUuid, ev.name AS lastEventName, last.captured_at AS lastCapturedAt," - + " sp.salesperson_user_id AS latestSalespersonUserId" + SEARCH_FROM + + " sp.salesperson_user_id AS latestSalespersonUserId, l.company_id AS companyId" + SEARCH_FROM + " ORDER BY last.captured_at IS NULL, last.captured_at DESC, l.id DESC", countQuery = "SELECT COUNT(*) FROM `lead` l" + SEARCH_WHERE) Page search(@Param("companyId") Long companyId, @Param("q") String q, diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java index 12387f9..97bc7db 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java @@ -41,7 +41,7 @@ public class LeadService { return leadRepository.search(req.companyId(), q, digits, PageRequest.of(Math.max(req.page(), 0), size)) .map(r -> new LeadSummary(r.getLeadUuid(), r.getName(), r.getMobileE164(), r.getEmail(), r.getCompanyName(), r.getJobTitle(), r.getEventCount(), r.getLastEventUuid(), r.getLastEventName(), - r.getLastCapturedAt(), r.getLatestSalespersonUserId())); + r.getLastCapturedAt(), r.getLatestSalespersonUserId(), r.getCompanyId())); } /** A null company looks the lead up across all companies; the detail reports the lead's own company. */ diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceCompanyIdTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceCompanyIdTest.java new file mode 100644 index 0000000..61cc08a --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceCompanyIdTest.java @@ -0,0 +1,33 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.LeadSearchRequest; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** An all-companies lead search must tell each row's company. */ +class LeadServiceCompanyIdTest { + + @Test + void searchMapsTheRowsCompanyId() { + LeadRepository repo = mock(LeadRepository.class); + LeadRepository.SummaryRow row = mock(LeadRepository.SummaryRow.class); + when(row.getLeadUuid()).thenReturn(7L); + when(row.getCompanyId()).thenReturn(9L); + when(repo.search(any(), any(), any(), any(Pageable.class))).thenReturn(new PageImpl<>(List.of(row))); + + var s = new LeadService(repo, mock(EventLeadRepository.class)) + .search(new LeadSearchRequest(null, null, null, 0, 20)).getContent().get(0); + + assertThat(s.companyId()).isEqualTo(9L); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceTest.java index d8e5d5c..5b2519b 100644 --- a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceTest.java +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceTest.java @@ -110,6 +110,7 @@ class LeadServiceTest { when(row.getLastEventName()).thenReturn("Expo"); when(row.getLastCapturedAt()).thenReturn(at); when(row.getLatestSalespersonUserId()).thenReturn(11L); + when(row.getCompanyId()).thenReturn(null); // Mockito would otherwise answer 0 for a Long when(leadRepository.search(eq(COMPANY), any(), any(), any(Pageable.class))).thenReturn(new PageImpl<>(List.of(row))); LeadSummary s = service.search(new LeadSearchRequest(COMPANY, null, null, 0, 20)).getContent().get(0);