feat(mobile-api): xlsx export of the lead and event lead listings
Same columns and filters as the screen, all pages, refused above 20,000 rows. Mobiles are text and dates are dates. Each export is logged with user, listing and row count only. Adds poi-ooxml 4.1.0, as in services-system. 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
963735d524
commit
eab4053c06
11 files changed
+729
-21
No files matched your search
+78
@@ -0,0 +1,78 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.service.AdminLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
class AdminLeadExportControllerTest {
|
||||
private static final String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
|
||||
private static Method export(Class<?> c) {
|
||||
return Arrays.stream(c.getDeclaredMethods()).filter(m -> m.getName().equals("export")).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
@Test
|
||||
void leadExportNeedsExportAndBoLeads() {
|
||||
Method m = export(AdminLeadController.class);
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).isTrue();
|
||||
assertThat(m.getAnnotation(AdminModule.class).value()).containsExactly("BO_LEADS_EXPORT");
|
||||
assertThat(m.getAnnotation(AdminModule.class).also()).containsExactly("BO_LEADS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventLeadExportNeedsExportAndBoEventLeads() {
|
||||
Method m = export(AdminEventLeadExportController.class);
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).isTrue();
|
||||
assertThat(m.getAnnotation(AdminModule.class).value()).containsExactly("BO_LEADS_EXPORT");
|
||||
assertThat(m.getAnnotation(AdminModule.class).also()).containsExactly("BO_EVENT_LEADS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void leadExportReturnsTheFileWithHeaders() throws Exception {
|
||||
AdminLeadService leads = mock(AdminLeadService.class);
|
||||
when(leads.export("ai")).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))
|
||||
.andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.matchesPattern("attachment; filename=\"leads-\\d{8}-\\d{4}\\.xlsx\"")))
|
||||
.andExpect(content().bytes(new byte[]{1, 2, 3}));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventLeadExportPassesFiltersAndNamesTheFile() throws Exception {
|
||||
AdminEventLeadService svc = mock(AdminEventLeadService.class);
|
||||
when(svc.export("77", 22L, "HOT", "OPEN", 3L, "NEW")).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())
|
||||
.andExpect(header().string("Content-Type", XLSX))
|
||||
.andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.matchesPattern("attachment; filename=\"event-leads-77-\\d{8}-\\d{4}\\.xlsx\"")))
|
||||
.andExpect(content().bytes(new byte[]{9}));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventLeadExportFilenameKeepsOnlyTheUuidDigits() throws Exception {
|
||||
// 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});
|
||||
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\"")));
|
||||
}
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
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;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
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.slf4j.LoggerFactory;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
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.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEventLeadExportTest {
|
||||
|
||||
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
|
||||
private static final String USER = "/user/findById/{id}";
|
||||
private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final String SEARCH = "/counter/eventLead/findByEvent";
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long COMPANY = 5L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminEventLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private ListAppender<ILoggingEvent> logs;
|
||||
private Logger root;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEventLeadService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setId(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(COMPANY);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
e.setName("KL Food Fair 2027");
|
||||
e.setEnabled(GeneralEnum.FlagYesNo.Y);
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
stubUser(21L, "Sales One");
|
||||
stubUser(22L, "Sales Two");
|
||||
when(rest.getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(COMPANY))).thenReturn(ResponseEntity.ok(List.of(
|
||||
Map.of("id", 3L, "name", "Cookware", "active", true), Map.of("id", 5L, "name", "Old", "active", false))));
|
||||
root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logs = new ListAppender<>();
|
||||
logs.start();
|
||||
root.addAppender(logs);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
root.detachAppender(logs);
|
||||
}
|
||||
|
||||
private void stubUser(long id, String name) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("id", id);
|
||||
u.put("name", name);
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private static Map<String, Object> row(int i) {
|
||||
Map<String, Object> r = new LinkedHashMap<>();
|
||||
r.put("eventLeadUuid", 2000L + i);
|
||||
r.put("eventUuid", EV);
|
||||
r.put("leadUuid", 1000L + i);
|
||||
r.put("name", "Lead " + i);
|
||||
r.put("mobileE164", "+60123456" + String.format("%03d", i));
|
||||
r.put("email", "lead" + i + "@example.com");
|
||||
r.put("leadType", i % 2 == 0 ? "NEW" : "EXISTING");
|
||||
r.put("salespersonUserId", i % 2 == 0 ? 21L : 22L);
|
||||
r.put("temperature", "HOT");
|
||||
r.put("status", "QUALIFIED");
|
||||
r.put("nextFollowUpDate", "2027-01-20");
|
||||
r.put("interestIds", List.of(3, 5));
|
||||
return r;
|
||||
}
|
||||
|
||||
private void stubRows(int total) {
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> {
|
||||
Map<String, Object> b = i.getArgument(2);
|
||||
int page = (Integer) b.get("page"), size = (Integer) b.get("size");
|
||||
List<Map<String, Object>> content = new ArrayList<>();
|
||||
for (int n = page * size; n < Math.min(total, (page + 1) * size); n++) content.add(row(n));
|
||||
return ResponseEntity.ok(Map.of("content", content, "totalElements", total));
|
||||
});
|
||||
}
|
||||
|
||||
private byte[] export() {
|
||||
return service.export(String.valueOf(EV), 22L, "HOT", null, 3L, null);
|
||||
}
|
||||
|
||||
private static Sheet sheet(byte[] bytes) throws Exception {
|
||||
return new XSSFWorkbook(new ByteArrayInputStream(bytes)).getSheetAt(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void headerLabelsAndOrder() throws Exception {
|
||||
stubRows(2);
|
||||
Sheet s = sheet(export());
|
||||
assertThat(s.getSheetName()).isEqualTo("Event leads");
|
||||
List<String> header = new ArrayList<>();
|
||||
s.getRow(0).forEach(c -> header.add(c.getStringCellValue()));
|
||||
assertThat(header).containsExactly("Name", "Mobile", "Email", "Lead type", "Salesperson", "Temperature", "Status", "Interests", "Next follow-up");
|
||||
assertThat(s.getLastRowNum()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cellTypesAndValues() throws Exception {
|
||||
stubRows(2);
|
||||
Sheet s = sheet(export());
|
||||
var r = s.getRow(1);
|
||||
assertThat(r.getCell(1).getCellType()).isEqualTo(CellType.STRING);
|
||||
assertThat(r.getCell(1).getStringCellValue()).isEqualTo("+60123456000");
|
||||
assertThat(r.getCell(3).getStringCellValue()).isEqualTo("New");
|
||||
assertThat(s.getRow(2).getCell(3).getStringCellValue()).isEqualTo("Existing");
|
||||
assertThat(r.getCell(4).getStringCellValue()).isEqualTo("Sales One");
|
||||
assertThat(r.getCell(5).getStringCellValue()).isEqualTo("Hot");
|
||||
assertThat(r.getCell(6).getStringCellValue()).isEqualTo("Qualified");
|
||||
assertThat(r.getCell(7).getStringCellValue()).isEqualTo("Cookware, Old");
|
||||
var d = r.getCell(8);
|
||||
assertThat(d.getCellType()).isEqualTo(CellType.NUMERIC);
|
||||
assertThat(DateUtil.isCellDateFormatted(d)).isTrue();
|
||||
assertThat(d.getCellStyle().getDataFormatString()).isEqualTo("dd/mm/yyyy");
|
||||
assertThat(d.getDateCellValue().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate()).isEqualTo(LocalDate.of(2027, 1, 20));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOptionalFieldsAreBlank() throws Exception {
|
||||
Map<String, Object> r = row(0);
|
||||
r.put("salespersonUserId", null);
|
||||
r.put("temperature", null);
|
||||
r.put("nextFollowUpDate", null);
|
||||
r.put("interestIds", List.of());
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(r), "totalElements", 1)));
|
||||
var row = sheet(export()).getRow(1);
|
||||
for (int c : new int[]{4, 5, 8}) assertThat(row.getCell(c) == null || row.getCell(c).getCellType() == CellType.BLANK).as("col " + c).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectsAllPagesWithTheScreenFiltersAndLoadsLookupsOnce() throws Exception {
|
||||
stubRows(230);
|
||||
Sheet s = sheet(export());
|
||||
assertThat(s.getLastRowNum()).isEqualTo(230);
|
||||
ArgumentCaptor<Object> bodies = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest, times(3)).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), bodies.capture());
|
||||
for (Object b : bodies.getAllValues()) {
|
||||
assertThat((Map<String, Object>) b).containsEntry("size", 100).containsEntry("eventUuid", EV).containsEntry("salespersonUserId", 22L)
|
||||
.containsEntry("temperature", "HOT").containsEntry("interestId", 3L);
|
||||
}
|
||||
verify(rest, times(1)).getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV));
|
||||
verify(rest, times(1)).getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(COMPANY));
|
||||
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L));
|
||||
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(22L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tooManyRowsIsRefusedAfterTheFirstPage() {
|
||||
stubRows(20001);
|
||||
assertThatThrownBy(this::export).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));
|
||||
});
|
||||
verify(rest, times(1)).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any());
|
||||
assertThat(logs.list.stream().filter(e -> e.getFormattedMessage().contains("lead export"))).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidFilterIsStillRejectedBeforeAnything() {
|
||||
assertThatThrownBy(() -> service.export(String.valueOf(EV), null, "BOILING", null, null, null))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("INVALID_VALUE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditLineHasUserListingAndCountOnly() {
|
||||
stubRows(2);
|
||||
export();
|
||||
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=event-leads:" + EV + " rows=2");
|
||||
String all = String.join("\n", logs.list.stream().map(ILoggingEvent::getFormattedMessage).toList());
|
||||
assertThat(all).doesNotContain("Lead 0").doesNotContain("+6012345").doesNotContain("example.com").doesNotContain("HOT");
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
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.slf4j.LoggerFactory;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.ArrayList;
|
||||
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.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminLeadExportTest {
|
||||
|
||||
private static final String SEARCH = "/counter/lead/search";
|
||||
private static final String USER = "/user/findById/{id}";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private ListAppender<ILoggingEvent> logs;
|
||||
private Logger root;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminLeadService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setId(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(5L);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
stubUser(21L, "Sales One");
|
||||
stubUser(22L, "Sales Two");
|
||||
root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logs = new ListAppender<>();
|
||||
logs.start();
|
||||
root.addAppender(logs);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
root.detachAppender(logs);
|
||||
}
|
||||
|
||||
private void stubUser(long id, String name) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("id", id);
|
||||
u.put("name", name);
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private static Map<String, Object> row(int i) {
|
||||
Map<String, Object> r = new LinkedHashMap<>();
|
||||
r.put("leadUuid", 1000L + i);
|
||||
r.put("name", "Lead " + i);
|
||||
r.put("mobileE164", "+60123456" + String.format("%03d", i));
|
||||
r.put("email", "lead" + i + "@example.com");
|
||||
r.put("companyName", "Acme " + i);
|
||||
r.put("jobTitle", "Buyer");
|
||||
r.put("eventCount", 3);
|
||||
r.put("lastEventUuid", 77L);
|
||||
r.put("lastEventName", "KL Food Fair");
|
||||
r.put("lastCapturedAt", "2027-01-15T10:00:00");
|
||||
r.put("latestSalespersonUserId", i % 2 == 0 ? 21L : 22L);
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Counter stub: {@code total} rows, served by the requested page and size. */
|
||||
private void stubRows(int total) {
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> {
|
||||
Map<String, Object> b = i.getArgument(2);
|
||||
int page = (Integer) b.get("page"), size = (Integer) b.get("size");
|
||||
List<Map<String, Object>> content = new ArrayList<>();
|
||||
for (int n = page * size; n < Math.min(total, (page + 1) * size); n++) content.add(row(n));
|
||||
return ResponseEntity.ok(Map.of("content", content, "totalElements", total));
|
||||
});
|
||||
}
|
||||
|
||||
private static Sheet sheet(byte[] bytes) throws Exception {
|
||||
return new XSSFWorkbook(new ByteArrayInputStream(bytes)).getSheetAt(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void headerLabelsAndOrder() throws Exception {
|
||||
stubRows(2);
|
||||
Sheet s = sheet(service.export("x"));
|
||||
assertThat(s.getSheetName()).isEqualTo("Leads");
|
||||
List<String> header = new ArrayList<>();
|
||||
s.getRow(0).forEach(c -> header.add(c.getStringCellValue()));
|
||||
assertThat(header).containsExactly("Name", "Mobile", "Email", "Company", "Events", "Last event", "Latest salesperson");
|
||||
assertThat(s.getLastRowNum()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cellTypesAndValues() throws Exception {
|
||||
stubRows(1);
|
||||
Sheet s = sheet(service.export(null));
|
||||
var r = s.getRow(1);
|
||||
assertThat(r.getCell(0).getStringCellValue()).isEqualTo("Lead 0");
|
||||
assertThat(r.getCell(1).getCellType()).isEqualTo(CellType.STRING);
|
||||
assertThat(r.getCell(1).getStringCellValue()).isEqualTo("+60123456000");
|
||||
assertThat(r.getCell(4).getCellType()).isEqualTo(CellType.NUMERIC);
|
||||
assertThat(r.getCell(4).getNumericCellValue()).isEqualTo(3.0);
|
||||
assertThat(r.getCell(5).getStringCellValue()).isEqualTo("KL Food Fair");
|
||||
assertThat(r.getCell(6).getStringCellValue()).isEqualTo("Sales One");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullLastEventAndSalespersonAreBlank() throws Exception {
|
||||
Map<String, Object> r = row(0);
|
||||
r.put("lastEventUuid", null);
|
||||
r.put("lastEventName", null);
|
||||
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);
|
||||
assertThat(row.getCell(5) == null || row.getCell(5).getCellType() == CellType.BLANK).isTrue();
|
||||
assertThat(row.getCell(6) == null || row.getCell(6).getCellType() == CellType.BLANK).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectsAllPagesOfOneHundredAndResolvesEachUserOnce() throws Exception {
|
||||
stubRows(230);
|
||||
Sheet s = sheet(service.export(" acme "));
|
||||
assertThat(s.getLastRowNum()).isEqualTo(230);
|
||||
assertThat(s.getRow(230).getCell(0).getStringCellValue()).isEqualTo("Lead 229");
|
||||
ArgumentCaptor<Object> bodies = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest, times(3)).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), bodies.capture());
|
||||
for (Object b : bodies.getAllValues()) {
|
||||
assertThat((Map<String, Object>) b).containsEntry("size", 100).containsEntry("q", "acme");
|
||||
}
|
||||
assertThat(bodies.getAllValues().stream().map(b -> ((Map<String, Object>) b).get("page"))).containsExactly(0, 1, 2);
|
||||
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L));
|
||||
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(22L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tooManyRowsIsRefusedAfterTheFirstPage() {
|
||||
stubRows(20001);
|
||||
assertThatThrownBy(() -> service.export(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));
|
||||
});
|
||||
verify(rest, times(1)).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any());
|
||||
verify(rest, times(0)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), any());
|
||||
assertThat(logs.list.stream().filter(e -> e.getFormattedMessage().contains("lead export"))).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditLineHasUserListingAndCountOnly() {
|
||||
stubRows(2);
|
||||
service.export("lead 1 secretterm");
|
||||
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");
|
||||
String all = String.join("\n", logs.list.stream().map(ILoggingEvent::getFormattedMessage).toList());
|
||||
assertThat(all).doesNotContain("secretterm").doesNotContain("Lead 0").doesNotContain("+6012345").doesNotContain("example.com");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user