feat: lead listing, lead detail and xlsx export (change 4b) #9
No files matched your search
@@ -127,7 +127,7 @@ The shared helpers move from `AdminEventLeadService` to a small package-private
|
||||
|
||||
**Size limit:** the first page's `totalElements` is checked before any row is written. Above 20,000 the request fails with 422 `EXPORT_TOO_LARGE` and `details.limit = 20000`. `ponytail:` this is a synchronous export with a hard cap; move to an async, emailed export if the cap becomes a problem.
|
||||
|
||||
**Writer:** POI `SXSSFWorkbook` with a 100-row window, writing straight to the response output stream.
|
||||
**Writer:** POI `SXSSFWorkbook` with a 100-row window. The file is written to a byte array and then returned, so a page that fails part-way still gives a clean JSON error. `ponytail:` this buffers up to the 20,000-row cap in memory; stream to the response if the cap is raised.
|
||||
- **Header:** the first row holds the on-screen column labels in English, matching the portal's default messages.
|
||||
- **Mobile:** written as a string cell, so it stays text.
|
||||
- **Dates:** written as date cells with the `dd/mm/yyyy` format. Capture time uses `dd/mm/yyyy hh:mm`.
|
||||
|
||||
@@ -52,7 +52,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially
|
||||
- Scope: `solvway-mobile-api/src/**` (lead files)
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`.
|
||||
|
||||
- [ ] 3.2 Add both xlsx exports (design decision 5):
|
||||
- [x] 3.2 Add both xlsx exports (design decision 5):
|
||||
- Add `poi-ooxml` 4.1.0 to `solvway-mobile-api/pom.xml` and record the `dependency:tree` result.
|
||||
- Add the `export` endpoints for leads and event leads.
|
||||
|
||||
|
||||
@@ -107,6 +107,12 @@
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>3.0.8</version>
|
||||
</dependency>
|
||||
<!-- xlsx export of the lead listings; same version as solvway-services-system -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>4.1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
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.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/** Event Leads Listing xlsx export. Separate from AdminEventLeadController, whose handlers all need BO_EVENT_LEADS alone. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/event-leads")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminEventLeadExportController {
|
||||
private final AdminEventLeadService adminEventLeadService;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/export")
|
||||
public ResponseEntity<byte[]> export(@PathVariable String eventUuid,
|
||||
@RequestParam(required = false) Long salespersonId,
|
||||
@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);
|
||||
// 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);
|
||||
}
|
||||
|
||||
private static ResponseEntity<byte[]> xlsx(String prefix, byte[] bytes) {
|
||||
String stamp = java.time.ZonedDateTime.now(java.time.ZoneId.of("Asia/Kuala_Lumpur")).format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd-HHmm"));
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + prefix + "-" + stamp + ".xlsx\"")
|
||||
.body(bytes);
|
||||
}
|
||||
}
|
||||
+17
@@ -5,6 +5,8 @@ import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.service.AdminLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
@@ -32,6 +34,21 @@ public class AdminLeadController {
|
||||
return ResponseEntity.ok(adminLeadService.list(q, page, size));
|
||||
}
|
||||
|
||||
@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));
|
||||
}
|
||||
|
||||
private static ResponseEntity<byte[]> xlsx(String prefix, byte[] bytes) {
|
||||
String stamp = java.time.ZonedDateTime.now(java.time.ZoneId.of("Asia/Kuala_Lumpur")).format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd-HHmm"));
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + prefix + "-" + stamp + ".xlsx\"")
|
||||
.body(bytes);
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_LEADS")
|
||||
@GetMapping("/{leadUuid}")
|
||||
|
||||
+44
-11
@@ -21,6 +21,7 @@ import org.springframework.web.client.HttpClientErrorException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
@@ -176,17 +177,7 @@ public class AdminEventLeadService {
|
||||
String leadType, int page, int size) {
|
||||
User caller = caller();
|
||||
Event event = loadEvent(eventUuid);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("salespersonUserId", salespersonId);
|
||||
body.put("temperature", oneOf("temperature", temperature, TEMPERATURES));
|
||||
body.put("status", oneOf("status", status, STATUSES));
|
||||
body.put("interestId", interestId);
|
||||
body.put("leadType", oneOf("leadType", leadType, LEAD_TYPES));
|
||||
body.put("page", Math.max(page, 0));
|
||||
body.put("size", size);
|
||||
Map<String, Object> p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), MAP, body).getBody();
|
||||
Map<String, Object> p = search(caller, 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>> users = new HashMap<>();
|
||||
@@ -199,6 +190,48 @@ public class AdminEventLeadService {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
User caller = caller();
|
||||
Event event = loadEvent(eventUuid);
|
||||
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),
|
||||
r -> {
|
||||
if (interests[0] == null) interests[0] = interests(caller.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");
|
||||
return Arrays.asList(m.get("name"), m.get("mobile"), m.get("email"), label(m.get("leadType")),
|
||||
sp == null ? null : sp.get("name"), label(m.get("temperature")), label(m.get("status")),
|
||||
String.join(", ", ((List<Map<String, Object>>) m.get("interests")).stream().map(i -> String.valueOf(i.get("name"))).toList()),
|
||||
follow == null ? null : LocalDate.parse(follow));
|
||||
});
|
||||
}
|
||||
|
||||
/** HOT becomes Hot. */
|
||||
private static String label(Object code) {
|
||||
String s = code == null ? null : code.toString();
|
||||
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,
|
||||
String leadType, int page, int size) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("salespersonUserId", salespersonId);
|
||||
body.put("temperature", oneOf("temperature", temperature, TEMPERATURES));
|
||||
body.put("status", oneOf("status", status, STATUSES));
|
||||
body.put("interestId", interestId);
|
||||
body.put("leadType", oneOf("leadType", leadType, LEAD_TYPES));
|
||||
body.put("page", Math.max(page, 0));
|
||||
body.put("size", size);
|
||||
return restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), MAP, body).getBody();
|
||||
}
|
||||
|
||||
public Map<String, Object> get(String eventUuid, String eventLeadUuid) {
|
||||
User caller = caller();
|
||||
return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId());
|
||||
|
||||
+31
-8
@@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -42,14 +43,7 @@ public class AdminLeadService {
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
public Map<String, Object> list(String q, int page, int size) {
|
||||
String term = trimmed(q);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller().getCompanyId());
|
||||
body.put("q", term);
|
||||
body.put("mobileDigits", mobileDigits(term));
|
||||
body.put("page", Math.max(page, 0));
|
||||
body.put("size", size);
|
||||
Map<String, Object> p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_SEARCH), MAP, body).getBody();
|
||||
Map<String, Object> p = search(caller().getCompanyId(), 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<>();
|
||||
@@ -58,6 +52,35 @@ public class AdminLeadService {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
User caller = caller();
|
||||
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),
|
||||
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"),
|
||||
name(m.get("lastEvent")), name(m.get("latestSalesperson")));
|
||||
});
|
||||
}
|
||||
|
||||
private static Object name(Object m) {
|
||||
return m == null ? null : ((Map<String, Object>) m).get("name");
|
||||
}
|
||||
|
||||
private Map<String, Object> search(Long companyId, String term, int page, int size) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", companyId);
|
||||
body.put("q", term);
|
||||
body.put("mobileDigits", mobileDigits(term));
|
||||
body.put("page", Math.max(page, 0));
|
||||
body.put("size", size);
|
||||
return restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_SEARCH), MAP, body).getBody();
|
||||
}
|
||||
|
||||
public Map<String, Object> get(String leadUuid) {
|
||||
long id = parseOr(leadUuid, AdminLeadService::notFound);
|
||||
Map<String, Object> d;
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntFunction;
|
||||
|
||||
/** Builds the xlsx of a lead listing by paging the listing's own search. Never logs lead data or the search term. */
|
||||
final class LeadExport {
|
||||
static final int PAGE = 100;
|
||||
static final int MAX_ROWS = 20000;
|
||||
private static final Logger log = LoggerFactory.getLogger(LeadExport.class);
|
||||
|
||||
private LeadExport() {}
|
||||
|
||||
/**
|
||||
* @param fetch returns the raw counter page (content, totalElements) for a 0-based page index
|
||||
* @param cells turns one raw row into cell values: String, Number, LocalDate or null (blank)
|
||||
* @param listing audit label, e.g. "leads"
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static byte[] build(String user, String listing, String sheetName, List<String> headers,
|
||||
IntFunction<Map<String, Object>> fetch, Function<Map<String, Object>, List<Object>> cells) {
|
||||
Map<String, Object> first = fetch.apply(0);
|
||||
long total = first == null || first.get("totalElements") == null ? 0 : ((Number) first.get("totalElements")).longValue();
|
||||
if (total > MAX_ROWS) {
|
||||
CodedResponseStatusException e = new CodedResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"Too many rows to export; narrow the search", "EXPORT_TOO_LARGE");
|
||||
e.getBody().setProperty("details", Map.of("limit", MAX_ROWS));
|
||||
throw e;
|
||||
}
|
||||
SXSSFWorkbook wb = new SXSSFWorkbook(100);
|
||||
try {
|
||||
Sheet sheet = wb.createSheet(sheetName);
|
||||
Row head = sheet.createRow(0);
|
||||
for (int c = 0; c < headers.size(); c++) head.createCell(c).setCellValue(headers.get(c));
|
||||
CellStyle dateStyle = wb.createCellStyle();
|
||||
dateStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("dd/mm/yyyy"));
|
||||
int r = 1;
|
||||
for (int p = 0; p * PAGE < total; p++) {
|
||||
Map<String, Object> page = p == 0 ? first : fetch.apply(p);
|
||||
List<Map<String, Object>> rows = page == null || page.get("content") == null ? List.of() : (List<Map<String, Object>>) page.get("content");
|
||||
for (Map<String, Object> raw : rows) {
|
||||
Row row = sheet.createRow(r++);
|
||||
List<Object> values = cells.apply(raw);
|
||||
for (int c = 0; c < values.size(); c++) {
|
||||
Object v = values.get(c);
|
||||
if (v == null) continue;
|
||||
var cell = row.createCell(c);
|
||||
if (v instanceof Number n) cell.setCellValue(n.doubleValue());
|
||||
else if (v instanceof LocalDate d) { cell.setCellValue(java.sql.Date.valueOf(d)); cell.setCellStyle(dateStyle); }
|
||||
else cell.setCellValue(String.valueOf(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
wb.write(out);
|
||||
log.info("lead export by {}: listing={} rows={}", user, listing, r - 1);
|
||||
return out.toByteArray();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} finally {
|
||||
wb.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
+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