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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-30 20:30:46 +08:00
1 parent de2ae63cea
commit ec504fd529
31 files changed
+1096 -190

No files matched your search

@@ -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\"}]"));
}
@@ -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
@@ -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}"));
}
@@ -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,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"));
}
@@ -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))));
@@ -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)));
}
}
@@ -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);
@@ -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());
}
}
@@ -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"));
}
}
@@ -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");
@@ -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();
}
@@ -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);
}
}
@@ -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());