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
13 KiB
Design
Context
Change 4a (openspec/changes/archive/2026-11-27-add-event-lead-capture/) added the lead tables in service-counter, matching and capture, the Event Leads Listing, and /api/admin/event-leads/** in mobile-api.
Rules reused from 4a:
- Contacts are normalised with libphonenumber (
EventLeadContactinmobile-api). - Validation codes:
REQUIRED_FIELD,TOO_LONG,INVALID_MOBILE,INVALID_EMAIL. - The company id is always taken from the caller.
- Uuids travel as JSON strings.
Access control:
@AdminModuleallows a caller holding any one of the listed modules (AppAccessAspect).AdminModuleAccess.grantedAnychecks modules in code.- Only modules of type
Mcan be granted on the Roles screen (AdminAclService.isGrantable); typeAis refused withUNKNOWN_MODULE. The sidebar hides anMmodule that has no url and no children (aclSidebar.ts, with a test). - The portal checks access with
useAdminAuth().hasModule(name).
Data facts:
eventlives in the sameservice-counterschema asevent_lead, so the two can be joined.eventhas nocompany_id(a known gap, recorded in 4a's design).services-systemalready shipsorg.apache.poi:poi-ooxml4.1.0.
See proposal.md for why.
Goals / Non-Goals
Goals:
- The Lead Listing with per-lead aggregates that are correct when read.
- Lead detail with event history and shared-contact warnings.
- Lead edit under its own permission.
- xlsx exports that match the screen, under their own permission.
Non-Goals:
- Reports.
- Merging leads.
- Stored or denormalised aggregates.
- An async or emailed export.
- Exporting more than 20,000 rows.
- Lead creation outside event capture.
Decisions
1. Database
Index: add KEY idx_event_lead_company_lead (company_id, lead_uuid) to event_lead. It serves the per-lead aggregation and the event history.
Module rows: three rows in service-system.module, all area BO with parent 40000000. The ids are free, because 4a used 40200000 and 40300000, and change 2 used 40700000 and 40800000.
| id | name | desc | type | url | icon_name |
|---|---|---|---|---|---|
| 40400000 | BO_LEADS |
Leads | M |
/leads |
Users |
| 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.
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.
Files: sql/01-lead-index.sql, sql/02-lead-modules.sql, sql/99-rollback.sql, all mirrored in local/seed/03-colite.sql.
2. Lead search (services-counter)
Endpoint: POST /counter/lead/search with {companyId, q, page, size} returns a Spring Page of rows: {leadUuid, name, mobileE164, email, companyName, jobTitle, eventCount, lastEventUuid, lastEventName, lastCapturedAt, latestSalespersonUserId}.
Query: a native MySQL 8 query, because JPQL cannot express the window functions it needs.
last: fromevent_lead,ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) = 1gives the most recent capture and its event. Joiningeventon uuid gives that event's name.cnt:COUNT(*)perlead_uuid.sp: the same window, restricted tosalesperson_user_id IS NOT NULL, gives the latest salesperson.leadis LEFT JOINed to all three, so a lead with no capture still lists, with 0 events.- Every derived table filters
company_id = :companyId.
Order: last.captured_at DESC (nulls last), then l.id DESC. A count query uses the same search condition.
Search term: q is trimmed. Blank means no filter.
- Name and email: otherwise the term matches
LOWER(l.name) LIKE %q%orl.email_normalised LIKE %q%, using a lowercasedqwith%and_escaped. - Mobile: if the term, with spaces,
-,(,)and a leading+removed, is all digits, mobile-api also sends a digits key. The leading0and any60prefix are dropped first, so012-345 6701becomes123456701. The query then addsl.mobile_e164 LIKE %<digits>%. ponytail:LIKE '%…%'scans the company's leads. It is fine at phase-1 volume; add a FULLTEXT or n-gram index if search becomes slow.
Page size: capped at 100, as in 4a.
3. Lead detail and update (services-counter)
Detail: GET /counter/lead/detail/{companyId}/{leadUuid} returns {lead fields, history[], sharedContacts[]}. An unknown uuid or another company's lead gives 404 LEAD_NOT_FOUND.
history: the lead'sevent_leadrows joined toevent, orderedcaptured_at DESC, id DESC. Each entry haseventLeadUuid, eventUuid, eventName, eventStart, eventEnd, leadType, salespersonUserId, temperature, status, capturedAt.sharedContacts: other leads in the company with the samemobile_e164or the sameemail_normalised, at most 20. Each entry hasleadUuid, name, sameMobile, sameEmail. Null values match nothing, which reuses the shape of the 4afindMatchesquery, excluding the lead itself.
Update: POST /counter/lead/update with {companyId, leadUuid, name, mobileE164, email, companyName, jobTitle, notes, doneBy}. It is one @Transactional method that sets the six fields as given and sets updatedBy and updatedAt. It returns the detail.
- The counter checks the company and existence, which gives 404.
- Validation lives in
mobile-api, as in 4a.
4. mobile-api
Leads API: AdminLeadController at /api/admin/leads.
| Method and path | Module |
|---|---|
GET /api/admin/leads?q&page&size |
BO_LEADS |
GET /api/admin/leads/{leadUuid} |
BO_LEADS |
PUT /api/admin/leads/{leadUuid} |
BO_LEADS_EDIT and BO_LEADS |
GET /api/admin/leads/export?q |
BO_LEADS_EXPORT and BO_LEADS |
Second required module: @AdminModule is any-of. It gains an attribute String[] also() default {}: AppAccessAspect additionally requires every module listed in also, each checked with AdminModuleAccess.grantedAny, failing closed. Super admin still passes, and the injected ROLE_ADMIN still grants nothing. This keeps the rule in the one place that already knows the caller's roles, rather than copying it into handlers.
- The update handler is
@AdminModule(value = "BO_LEADS_EDIT", also = "BO_LEADS"). - The Lead Listing export handler is
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_LEADS").
Event leads export: GET /api/admin/event-leads/{eventUuid}/export?<4a filters> is @AdminModule(value = "BO_LEADS_EXPORT", also = "BO_EVENT_LEADS").
Listing rows:
- Uuids are strings.
latestSalespersonis{id, name}or null, with names resolved through oneusersmap per request, as in 4a.lastEventis{uuid, name}or null.lastCapturedAtis included.
Detail: the history's salesperson names are resolved the same way. sharedContacts is passed through.
Update validation: the update reuses 4a's EventLeadContact and its validation helpers:
nameis required;- at least one of mobile or email is required (
REQUIRED_FIELDwith anerrors[]list); - the limits are name 100, email 254, companyName 150 and jobTitle 100 (
TOO_LONG); - notes are limited to 2000 characters (
TOO_LONG); - invalid contacts give
INVALID_MOBILEorINVALID_EMAIL.
The shared helpers move from AdminEventLeadService to a small package-private LeadValidation class only if both services need them. Otherwise they are duplicated in a minimal way. This is the builder's call; the shortest diff wins.
5. xlsx export
Paging: mobile-api pages through the same counter search it serves on screen, in pages of 100, building rows with the same view mapping as the JSON listing. That way the columns cannot drift from the screen.
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. 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/yyyyformat. Capture time usesdd/mm/yyyy hh:mm. - Interests: joined with
,. - Lead type and status: written as their display words (
New,Existing,Open, …). - The workbook is disposed in a
finally.
Response headers:
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheetContent-Disposition: attachment; filename="leads-YYYYMMDD-HHmm.xlsx", orevent-leads-<event uuid>-YYYYMMDD-HHmm.xlsxfor an event.
Column order:
- Lead Listing: Name, Mobile, Email, Company, Events, Last event, Latest salesperson.
- Event Leads Listing (the same as 4a's table): Name, Mobile, Email, Lead type, Salesperson, Temperature, Status, Interests, Next follow-up.
Audit: one INFO log line per export, lead export by <username>: listing=<leads|event-leads:<eventUuid>> rows=<n>. It carries no search term and no lead data.
Dependency: org.apache.poi:poi-ooxml 4.1.0 is added to solvway-mobile-api/pom.xml. It is already in the repo, and the version matches services-system. Check mvn dependency:tree for clashes, such as commons-compress or xmlbeans, and record the result in the task.
6. Portal
Download route:
app/api/leads/export/route.tsandapp/api/event-leads/[eventUuid]/export/route.ts. Next.js resolves these before the 4a[...path]catch-all.- Both call a binary variant of
callMobileApithat returns the upstream body and headers on success, and the sameApiResulterror shape on failure. The route passes the bytes through withContent-TypeandContent-Disposition. ponytail:the route buffers the file in memory (up to the 20,000-row cap); stream it if files get large.
JSON route: app/api/leads/[...path]/route.ts is a copy of the 4a proxy pattern, with dot-segment rejection, for list, detail and update.
Export button: an Export button on both listings, shown only when hasModule("BO_LEADS_EXPORT").
- It fetches the route with the current query, turns the response into a Blob, and downloads it under the filename from
Content-Disposition. - On failure it shows the mapped message on the page:
EXPORT_TOO_LARGEgives "More than 20,000 rows. Narrow the search or filters." Other errors show at form level. - The button is disabled while the export runs.
/leads (Lead Listing):
- Desktop-first, like the other back-office listings.
- A search box (
FilterSearch). - A
DataTablewith the seven columns, withuseFitPageSize. - Rows link to
/leads/{leadUuid}. /leadsmaps toBO_LEADSinrouteModules.
/leads/{leadUuid} (lead detail):
- One column at phone width, like the event-floor pages.
- Lead fields: read-only without
BO_LEADS_EDIT. With it, they are an edit form using the 4a key-in form's field and error patterns (type="tel", 44px targets). - Shared-contact warning: an alert naming each lead and linking to it.
- Event history: a list of cards. Each links to
/event-leads/{eventUuid}/{eventLeadUuid}when the user hasBO_EVENT_LEADS. - Not found: 404
LEAD_NOT_FOUNDshows a not-found state.
Event lead edit page: gains a "View lead" link to /leads/{leadUuid} when hasModule("BO_LEADS").
i18n: new keys prefixed Leads; existing Lead* keys are reused.
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.
- 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
eventtable and recorded there. The joins here only read event names for rows already scoped byevent_lead.company_id. - POI 4.1.0 is old. It is already in the repo, and upgrading it platform-wide is a separate change.