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
+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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user