fix: export route timeout and nullable lead fields from the branch review

The export routes wait up to 120 s as the design says, instead of the
30 s default. Event names and updatedAt can be null, and a history card
for a removed event shows no empty name line. Notes on export paging
and on url-less folder modules in the ACL menu.

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-27 17:35:35 +08:00
1 parent 0593b5379c
commit 29a3f13503
9 files changed
+16 -10

No files matched your search

@@ -51,7 +51,7 @@ See proposal.md for why.
| 40500000 | `BO_LEADS_EDIT` | Edit leads | `M` | NULL | NULL |
| 40600000 | `BO_LEADS_EXPORT` | Export leads | `M` | NULL | NULL |
**Edit and Export modules:** these are url-less `M` modules, so they can be granted and never show in the sidebar. A first draft used type `A`, which the Roles screen cannot grant. The ACL menu that `/api/admin/me` returns (`ModuleService.findAllUrlByArea` in `services-system`) used to keep only modules with a url or type `A` modules, so these two never reached the portal's `hasModule`. The menu now also keeps a type `M` module that has a parent. Found in the browser check (task 4.3).
**Edit and Export modules:** these are url-less `M` modules, so they can be granted and never show in the sidebar. A first draft used type `A`, which the Roles screen cannot grant. The ACL menu that `/api/admin/me` returns (`ModuleService.findAllUrlByArea` in `services-system`) used to keep only modules with a url or type `A` modules, so these two never reached the portal's `hasModule`. The menu now also keeps a type `M` module that has a parent. Found in the browser check (task 4.3). As a side effect, a url-less folder module granted directly also appears in `/me`, so `hasModule(<folder>)` is true for that role. Do not rely on `hasModule` for folder modules. The sidebar still hides a url-less `M` with no children.
**Placement:** the two modules sit directly under the root, not under `BO_LEADS`. That way a role with only `BO_EVENT_LEADS` can still be given export.
@@ -182,7 +182,7 @@ The shared helpers move from `AdminEventLeadService` to a small package-private
## Risks / Trade-offs
- **Aggregates are computed on every read.** This is a window query over the company's event leads. It is fine at phase-1 volume; the index helps. If it gets slow, store the aggregates on `lead`, which is approach B, rejected for now.
- **An export holds a request open until done.** At 20,000 rows this is about 200 counter calls in sequence. The cap bounds it. The portal timeout for the export route is raised to 120 s.
- **An export holds a request open until done.** At 20,000 rows this is about 200 counter calls in sequence. The cap bounds it. The portal timeout for the export route is raised to 120 s. Each page re-runs the search, so a large Lead Listing export gets slower than linear; if exports get slow, raise the export page size or switch to keyset paging.
- **The latest salesperson is the latest one set, not necessarily the latest capture's.** This matches the WhatsApp owner rule in the design doc and is deliberate.
- **Event lookups are not company-scoped.** This is inherited from 4a's `event` table and recorded there. The joins here only read event names for rows already scoped by `event_lead.company_id`.
- **POI 4.1.0 is old.** It is already in the repo, and upgrading it platform-wide is a separate change.
@@ -25,7 +25,7 @@ describe("/api/event-leads/[eventUuid]/export", () => {
it("forwards the query string and passes bytes and headers through", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: true, data: { body: new Uint8Array([9]).buffer, contentType: "application/x-xlsx", contentDisposition: 'attachment; filename="e.xlsx"' } });
const res = await GET(req("/x?status=OPEN&leadType=NEW"), ctx("e-1"));
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/event-leads/e-1/export?status=OPEN&leadType=NEW", { token: "jwt-abc" });
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/event-leads/e-1/export?status=OPEN&leadType=NEW", { token: "jwt-abc", timeoutMs: 120_000 }); // design: the export route waits up to 120 s
expect(res.headers.get("content-type")).toBe("application/x-xlsx");
expect(res.headers.get("content-disposition")).toBe('attachment; filename="e.xlsx"');
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([9]));
@@ -11,7 +11,7 @@ export async function GET(req: NextRequest, { params }: Ctx) {
if (!token) return unauthorized();
const { eventUuid } = await params;
if (eventUuid === "." || eventUuid === "..") return badRequest("Invalid path.");
const result = await callMobileApiBinary(`/api/admin/event-leads/${encodeURIComponent(eventUuid)}/export${new URL(req.url).search}`, { token });
const result = await callMobileApiBinary(`/api/admin/event-leads/${encodeURIComponent(eventUuid)}/export${new URL(req.url).search}`, { token, timeoutMs: 120_000 });
if (!result.ok) return errorResponse(result);
const { body, contentType, contentDisposition } = result.data;
return new NextResponse(body, {
@@ -24,7 +24,7 @@ describe("/api/leads/export", () => {
it("forwards the query string and passes bytes and headers through", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: true, data: { body: new Uint8Array([1, 2, 3]).buffer, contentType: "application/x-xlsx", contentDisposition: 'attachment; filename="l.xlsx"' } });
const res = await GET(req("/api/leads/export?q=ann"));
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/leads/export?q=ann", { token: "jwt-abc" });
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/leads/export?q=ann", { token: "jwt-abc", timeoutMs: 120_000 }); // design: the export route waits up to 120 s
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/x-xlsx");
expect(res.headers.get("content-disposition")).toBe('attachment; filename="l.xlsx"');
@@ -7,7 +7,7 @@ import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApiBinary(`/api/admin/leads/export${new URL(req.url).search}`, { token });
const result = await callMobileApiBinary(`/api/admin/leads/export${new URL(req.url).search}`, { token, timeoutMs: 120_000 });
if (!result.ok) return errorResponse(result);
const { body, contentType, contentDisposition } = result.data;
return new NextResponse(body, {
@@ -215,4 +215,9 @@ describe("LeadPage", { timeout: 20000 }, () => {
const card = screen.getByTestId("history-card");
expect(card.textContent).not.toMatch(/\s-\s/);
});
it("leaves no empty name line for an event whose record is gone", async () => {
await open({ history: [LEAD.history[0], { ...LEAD.history[1], eventName: null }] });
expect(screen.getAllByTestId("history-card")[1].querySelectorAll("p:empty")).toHaveLength(0);
});
});
@@ -185,7 +185,7 @@ function Lead() {
{lead.history.map((h) => {
const card = (
<div data-testid="history-card" className="min-h-11 space-y-1 rounded-lg border p-4">
<p className="font-medium">{h.eventName}</p>
{h.eventName && <p className="font-medium">{h.eventName}</p>}
{h.eventStart && h.eventEnd && (
<p className="text-sm text-muted-foreground">{formatDmy(h.eventStart.slice(0, 10))} - {formatDmy(h.eventEnd.slice(0, 10))}</p>
)}
+3 -3
View File
@@ -243,7 +243,7 @@ export interface LeadRow {
companyName: string | null;
jobTitle: string | null;
eventCount: number;
lastEvent: { uuid: string; name: string } | null;
lastEvent: { uuid: string; name: string | null } | null;
lastCapturedAt: string | null;
latestSalesperson: { id: number; name: string } | null;
}
@@ -251,7 +251,7 @@ export interface LeadRow {
export interface LeadHistoryEntry {
eventLeadUuid: string;
eventUuid: string;
eventName: string;
eventName: string | null;
eventStart: string | null;
eventEnd: string | null;
leadType: LeadType;
@@ -280,7 +280,7 @@ export interface LeadUpdatePayload {
export interface LeadDetail extends LeadUpdatePayload {
leadUuid: string;
createdAt: string;
updatedAt: string;
updatedAt: string | null;
updatedBy: string | null;
history: LeadHistoryEntry[];
sharedContacts: SharedContact[];
@@ -50,6 +50,7 @@ final class LeadExport {
CellStyle dateStyle = wb.createCellStyle();
dateStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("dd/mm/yyyy"));
int r = 1;
// ponytail: offset paging over a live ordering, so a capture made mid-export can repeat or skip a row, and each page re-runs the search (about 200 queries at the 20k cap). Upgrade: a larger export page size or keyset paging if exports get slow or volumes grow.
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");