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