From 5453302b5cf1771dcc1cfb2542c0e880ae580d1f Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 15:09:03 +0800 Subject: [PATCH 01/11] docs(openspec): propose add-lead-listing-export Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-lead-listing-export/.openspec.yaml | 2 + .../changes/add-lead-listing-export/design.md | 186 ++++++++++++++++++ .../add-lead-listing-export/proposal.md | 56 ++++++ .../specs/lead-export/spec.md | 51 +++++ .../specs/lead-records/spec.md | 92 +++++++++ .../changes/add-lead-listing-export/tasks.md | 108 ++++++++++ 6 files changed, 495 insertions(+) create mode 100644 openspec/changes/add-lead-listing-export/.openspec.yaml create mode 100644 openspec/changes/add-lead-listing-export/design.md create mode 100644 openspec/changes/add-lead-listing-export/proposal.md create mode 100644 openspec/changes/add-lead-listing-export/specs/lead-export/spec.md create mode 100644 openspec/changes/add-lead-listing-export/specs/lead-records/spec.md create mode 100644 openspec/changes/add-lead-listing-export/tasks.md diff --git a/openspec/changes/add-lead-listing-export/.openspec.yaml b/openspec/changes/add-lead-listing-export/.openspec.yaml new file mode 100644 index 0000000..8c7aa0b --- /dev/null +++ b/openspec/changes/add-lead-listing-export/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-27 diff --git a/openspec/changes/add-lead-listing-export/design.md b/openspec/changes/add-lead-listing-export/design.md new file mode 100644 index 0000000..efb0727 --- /dev/null +++ b/openspec/changes/add-lead-listing-export/design.md @@ -0,0 +1,186 @@ +# 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 (`EventLeadContact` in `mobile-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:** +- `@AdminModule` allows a caller holding any one of the listed modules (`AppAccessAspect`). `AdminModuleAccess.grantedAny` checks modules in code. +- Modules of type `A` (action) are granted like any module and show in the Roles access tree. The sidebar never shows them (`aclSidebar.ts`). +- The portal checks access with `useAdminAuth().hasModule(name)`. + +**Data facts:** +- `event` lives in the same `service-counter` schema as `event_lead`, so the two can be joined. `event` has no `company_id` (a known gap, recorded in 4a's design). +- `services-system` already ships `org.apache.poi:poi-ooxml` 4.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 | `A` | NULL | NULL | +| 40600000 | `BO_LEADS_EXPORT` | Export leads | `A` | NULL | NULL | + +**Placement:** the two action 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`: from `event_lead`, `ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) = 1` gives the most recent capture and its event. Joining `event` on uuid gives that event's name. +- `cnt`: `COUNT(*)` per `lead_uuid`. +- `sp`: the same window, restricted to `salesperson_user_id IS NOT NULL`, gives the latest salesperson. +- `lead` is 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%` or `l.email_normalised LIKE %q%`, using a lowercased `q` with `%` and `_` escaped. +- **Mobile:** if the term, with spaces, `-`, `(`, `)` and a leading `+` removed, is all digits, mobile-api also sends a digits key. The leading `0` and any `60` prefix are dropped first, so `012-345 6701` becomes `123456701`. The query then adds `l.mobile_e164 LIKE %%`. +- `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's `event_lead` rows joined to `event`, ordered `captured_at DESC, id DESC`. Each entry has `eventLeadUuid, eventUuid, eventName, eventStart, eventEnd, leadType, salespersonUserId, temperature, status, capturedAt`. +- `sharedContacts`: other leads in the company with the same `mobile_e164` or the same `email_normalised`, at most 20. Each entry has `leadUuid, name, sameMobile, sameEmail`. Null values match nothing, which reuses the shape of the 4a `findMatches` query, 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` | +| `GET /api/admin/leads/export?q` | `BO_LEADS_EXPORT` | + +**Second check in code:** `@AdminModule` is any-of, so two handlers re-check a module with `AdminModuleAccess.grantedAny`, which gives 403 `FORBIDDEN` when it fails: +- the update handler also checks `BO_LEADS`; +- the export handler also checks `BO_LEADS`. + +**Event leads export:** `GET /api/admin/event-leads/{eventUuid}/export?<4a filters>` carries `@AdminModule("BO_LEADS_EXPORT")` and re-checks `BO_EVENT_LEADS` in code. + +**Listing rows:** +- Uuids are strings. +- `latestSalesperson` is `{id, name}` or null, with names resolved through one `users` map per request, as in 4a. +- `lastEvent` is `{uuid, name}` or null. +- `lastCapturedAt` is 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: +- `name` is required; +- at least one of mobile or email is required (`REQUIRED_FIELD` with an `errors[]` 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_MOBILE` or `INVALID_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, writing straight to the response output stream. +- **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`. +- **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.sheet` +- `Content-Disposition: attachment; filename="leads-YYYYMMDD-HHmm.xlsx"`, or `event-leads--YYYYMMDD-HHmm.xlsx` for 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 : listing=> rows=`. 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.ts` and `app/api/event-leads/[eventUuid]/export/route.ts`. Next.js resolves these before the 4a `[...path]` catch-all. +- Both call a binary variant of `callMobileApi` that returns the upstream body and headers on success, and the same `ApiResult` error shape on failure. The route passes the bytes through with `Content-Type` and `Content-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_LARGE` gives "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 `DataTable` with the seven columns, with `useFitPageSize`. +- Rows link to `/leads/{leadUuid}`. +- `/leads` maps to `BO_LEADS` in `routeModules`. + +**`/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 has `BO_EVENT_LEADS`. +- **Not found:** 404 `LEAD_NOT_FOUND` shows 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 `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. diff --git a/openspec/changes/add-lead-listing-export/proposal.md b/openspec/changes/add-lead-listing-export/proposal.md new file mode 100644 index 0000000..000895f --- /dev/null +++ b/openspec/changes/add-lead-listing-export/proposal.md @@ -0,0 +1,56 @@ +# Proposal + +## Why + +Change 4a lets staff capture leads at an event and work them one event at a time. Staff still cannot see a person across events, correct a lead's details, or take a list out to work it elsewhere. This is change 4b of the design's change 4 (see `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md`, Listings and Access). It completes what go-live needs for leads. + +## What Changes + +- **Lead Listing** (`/leads`): every lead in the company in one list. Search by name, mobile or email. Each row shows name, mobile, email, company, number of events, last event and latest salesperson, all worked out when the list is read. Server-side paging, newest capture first. +- **Lead detail** (`/leads/{leadUuid}`): the lead's fields, plus its event history. The history lists every event the lead was captured at, newest first, with lead type, salesperson, temperature and status. When another lead in the company shares this lead's mobile or email, the page shows a warning naming that lead. Nothing is merged. +- **Lead edit** on the detail page: name, mobile, email, company, job title and notes. These use the same normalisation and validation as capture. A save that makes the mobile or email the same as another lead's is allowed, and the warning then shows. +- **xlsx export** of the Lead Listing and of the Event Leads Listing. Each export has exactly the columns shown on screen and applies the current search or filters, across all pages, not just the visible one. + - Mobile numbers are written as text, so Excel keeps the `+`. + - Dates are written as real dates. + - The export stops at 20,000 rows; above that, staff are asked to narrow the filters. + - The file is built in `mobile-api` with Apache POI's streaming writer. + - Each export is logged with the username, the listing and the row count, but never with lead data. +- **Permissions**: + - New menu module `BO_LEADS` (`/leads`) to view the Lead Listing and lead detail. + - New action modules `BO_LEADS_EDIT` (edit a lead) and `BO_LEADS_EXPORT` (export either listing). Action modules never show in the sidebar. + - An export also needs the listing's own module: `BO_LEADS` for the Lead Listing, `BO_EVENT_LEADS` for the Event Leads Listing. +- **Link from the event lead edit page** to the lead detail page, for users who hold `BO_LEADS`. +- **New dependency** `org.apache.poi:poi-ooxml` 4.1.0 in `mobile-api`. It is the same library and version that `services-system` already uses for its spreadsheet exports. +- **New index** `event_lead (company_id, lead_uuid)` for the per-lead aggregation and the event history. + +Not in this change: reports beyond the on-screen listings, merging leads, and per-salesperson visibility. + +## Capabilities + +### New Capabilities +- `lead-records`: the company-wide Lead Listing, the lead detail page with event history and shared-contact warnings, and lead edits. +- `lead-export`: xlsx exports of the Lead Listing and the Event Leads Listing, and the export permission. + +### Modified Capabilities +None. The Event Leads Listing (`event-lead-capture`) keeps its requirements; the export of it is specified in `lead-export`. + +## Impact + +- `solvway-services-counter`: + - a lead search (a native query with window functions for the latest capture and the latest salesperson); + - lead detail with history and shared contacts; + - lead update. +- `solvway-mobile-api`: + - `AdminLeadController` and its service; + - xlsx export endpoints for both listings; + - the poi-ooxml dependency. +- `solvway-admin-portal`: + - `app/leads/**` pages (the listing, and a phone-friendly detail page); + - an Export button on both listings, shown only with `BO_LEADS_EXPORT`; + - a binary-safe download route; + - services, types and i18n; + - a `routeModules` entry; + - a "View lead" link on the event lead edit page. +- Database: one new index on `service-counter`.`event_lead`, and three `service-system`.`module` rows. Additive only. +- `local/seed/03-colite.sql` mirrors the index and the module rows. +- No change to the gateway, existing tables or existing endpoints. diff --git a/openspec/changes/add-lead-listing-export/specs/lead-export/spec.md b/openspec/changes/add-lead-listing-export/specs/lead-export/spec.md new file mode 100644 index 0000000..1cb9d78 --- /dev/null +++ b/openspec/changes/add-lead-listing-export/specs/lead-export/spec.md @@ -0,0 +1,51 @@ +## Purpose + +Staff with export permission take a lead listing out of the system as an Excel file that matches what they see on screen. + +## ADDED Requirements + +### Requirement: Listing export + +The system SHALL export the Lead Listing and the Event Leads Listing as an `.xlsx` file that the browser downloads. The file SHALL hold the on-screen columns in the same order, with the current search or filters applied across all pages. Mobile numbers SHALL be stored as text and dates as dates. + +#### Scenario: Export what is on screen + +- **GIVEN** the Event Leads Listing for `KL Food Fair` filtered to temperature Hot, with 45 matching leads over 3 pages +- **WHEN** the user exports +- **THEN** the file has one header row and 45 lead rows +- **AND** the header row lists name, mobile, email, lead type, salesperson, temperature, status, interests and next follow-up + +#### Scenario: Lead Listing export with a search + +- **WHEN** the user searches `aisyah` on Leads and exports +- **THEN** the file holds only the matching leads, with the Lead Listing's columns + +#### Scenario: Mobile kept as text + +- **WHEN** the exported file is opened in Excel +- **THEN** a mobile shows as `+60123456701`, not as a number + +### Requirement: Export size limit + +An export of more than 20,000 rows SHALL be refused, and the listing page SHALL show a message asking the user to narrow the search or filters. + +#### Scenario: Too many rows + +- **WHEN** the export would hold more than 20,000 rows +- **THEN** no file is produced and the page asks the user to narrow the filters + +### Requirement: Export permission + +Exporting SHALL require `BO_LEADS_EXPORT` together with the listing's own module: `BO_LEADS` for the Lead Listing, `BO_EVENT_LEADS` for the Event Leads Listing. +- **Button:** the Export button SHALL show only to users who hold the export permission. +- **Audit:** each export SHALL be recorded with the username, the listing and the row count, and SHALL NOT record lead data. + +#### Scenario: No export permission + +- **WHEN** a user with `BO_EVENT_LEADS` but not `BO_LEADS_EXPORT` opens an event's leads +- **THEN** no Export button shows, and calling the export endpoint responds 403 + +#### Scenario: Export permission without the listing + +- **WHEN** a user with `BO_LEADS_EXPORT` but not `BO_LEADS` calls the Lead Listing export endpoint +- **THEN** it responds 403 diff --git a/openspec/changes/add-lead-listing-export/specs/lead-records/spec.md b/openspec/changes/add-lead-listing-export/specs/lead-records/spec.md new file mode 100644 index 0000000..48f4c96 --- /dev/null +++ b/openspec/changes/add-lead-listing-export/specs/lead-records/spec.md @@ -0,0 +1,92 @@ +## Purpose + +Staff see every lead in the company, look up a person's history across events, and correct a lead's details without merging people. + +## ADDED Requirements + +### Requirement: Lead listing + +The system SHALL let a user with `BO_LEADS` list every lead in their own company and no other. Each row SHALL show name, mobile, email, company, the number of events the lead was captured at, the last event (the event of its most recent capture) and the latest salesperson (from the most recent capture that has one). The list SHALL be ordered by most recent capture first and paged on the server. + +#### Scenario: Counts and latest values + +- **GIVEN** lead `Aisyah` was captured at `KL Food Fair` with salesperson `Ali`, then at `Penang Expo` with no salesperson +- **WHEN** a user with `BO_LEADS` opens Leads +- **THEN** Aisyah's row shows 2 events, last event `Penang Expo`, and latest salesperson `Ali` + +#### Scenario: Other company's leads hidden + +- **GIVEN** a lead belongs to another company +- **WHEN** a user lists or searches leads +- **THEN** that lead is never returned + +#### Scenario: No module + +- **WHEN** a user without `BO_LEADS` opens Leads or a lead detail page, or calls a leads endpoint +- **THEN** the page shows not-authorised and the endpoint responds 403 + +### Requirement: Lead search + +The Lead Listing SHALL be searchable by one term matching name, mobile or email. A term made of digits and phone punctuation SHALL match mobiles regardless of a leading `0`, `+60`, spaces or dashes. + +#### Scenario: Search by mobile in local format + +- **GIVEN** a lead with mobile `+60123456701` +- **WHEN** the user searches `012-345 6701` +- **THEN** that lead is listed + +#### Scenario: Search by name or email + +- **WHEN** the user searches `aisyah` +- **THEN** leads whose name or email contains `aisyah`, ignoring case, are listed + +### Requirement: Lead detail + +The system SHALL show a lead's details: +- **Fields:** name, mobile, email, company, job title and notes. +- **Event history:** every event the lead was captured at, newest capture first, with the event name and dates, lead type, salesperson, temperature, status and capture date. +- **Shared contacts:** when another lead in the company has the same mobile or the same email, the page SHALL warn and name each such lead. The leads SHALL NOT be merged. +- **Width:** the page SHALL work at phone width. + +#### Scenario: Event history + +- **GIVEN** a lead captured at two events +- **WHEN** a user with `BO_LEADS` opens the lead +- **THEN** both events are listed, newest capture first, each with its lead type, salesperson, temperature and status + +#### Scenario: Shared mobile warning + +- **GIVEN** leads `Test Visitor One` and `Test Visitor Two` both have mobile `+60123456701` +- **WHEN** a user opens `Test Visitor One` +- **THEN** the page warns that `Test Visitor Two` has the same mobile +- **AND** both leads stay separate + +#### Scenario: Unknown or other company's lead + +- **WHEN** a user opens a lead uuid that does not exist in their company +- **THEN** the page shows not-found and the endpoint responds 404 + +### Requirement: Lead edit + +The system SHALL let a user with both `BO_LEADS` and `BO_LEADS_EDIT` change a lead's name, mobile, email, company, job title and notes, with the same normalisation, required fields, length limits and errors as capture. A save that gives the lead the same mobile or email as another lead SHALL be allowed and SHALL NOT merge them. A user without `BO_LEADS_EDIT` SHALL see the lead read-only. + +#### Scenario: Correct a lead + +- **WHEN** a user with `BO_LEADS_EDIT` changes the email to ` Aisyah@Example.TEST ` and the company to `Example Co`, and saves +- **THEN** the lead stores `aisyah@example.test` and `Example Co` + +#### Scenario: Save that shares a contact + +- **GIVEN** another lead has mobile `+60123456701` +- **WHEN** the user sets this lead's mobile to `0123456701` and saves +- **THEN** the save succeeds and the shared-mobile warning names the other lead + +#### Scenario: Invalid input refused + +- **WHEN** the user clears both mobile and email, or enters mobile `12`, and saves +- **THEN** the save is refused, nothing changes, and the error shows under the field + +#### Scenario: Read-only without edit permission + +- **WHEN** a user with `BO_LEADS` but not `BO_LEADS_EDIT` opens a lead, or calls the lead update endpoint +- **THEN** the page shows no edit controls and the endpoint responds 403 diff --git a/openspec/changes/add-lead-listing-export/tasks.md b/openspec/changes/add-lead-listing-export/tasks.md new file mode 100644 index 0000000..2604bb0 --- /dev/null +++ b/openspec/changes/add-lead-listing-export/tasks.md @@ -0,0 +1,108 @@ +# Tasks + +Design: `design.md` (decision numbers below refer to it). All tasks run serially. Each task touches a hotspot (SQL or `pom.xml`) or files the next task builds on. Every task is TDD: tests first, run red, then implement. + +## 1. Database + +- [ ] 1.1 Write the SQL files (design decision 1): + - `sql/01-lead-index.sql`: `ALTER TABLE event_lead ADD KEY idx_event_lead_company_lead (company_id, lead_uuid)`. + - `sql/02-lead-modules.sql`: the three module rows. + - `sql/99-rollback.sql`. + + Mirror them into `local/seed/03-colite.sql`. Then apply the index and the module rows to the running local database, because a reset would wipe its test data. + - Scope: `openspec/changes/add-lead-listing-export/sql/**`, `local/seed/**` + - Verify: a read-only `SHOW INDEX FROM event_lead` and `SELECT` on `module` show the new index and the three rows. + +## 2. services-counter + +- [ ] 2.1 Add lead search, detail and update (design decisions 2 and 3): + - `POST /counter/lead/search`: the native query with `cnt`, `last` and `sp`. + - `GET /counter/lead/detail/{companyId}/{leadUuid}`: the lead with its history and shared contacts. + - `POST /counter/lead/update`: `@Transactional`. + + Tests first. The unit tests cover: + - the page size cap; + - blank `q`; + - escaping of `%` and `_`; + - passing the digits key; + - 404 for another company's lead; + - update sets the six fields plus `updatedBy` and `updatedAt`, and is transactional; + - shared contacts exclude the lead itself and ignore nulls. + + Prove the native query live against local MySQL through the gateway: + - counts, last event and latest non-null salesperson; + - a lead with no capture; + - order; + - each search form (name, email, `012-345 6701`). + - Scope: `solvway-services-counter/src/**` (lead files and `dto/`) + - Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`. + +## 3. mobile-api + +- [ ] 3.1 Add the leads admin API (design decision 4): list, detail and update under `/api/admin/leads`, with the module rules and the second check in code. + + Tests first: + - each validation code, with update normalisation the same as capture; + - the digits key built from `012-345 6701` and from `+60 12-345 6701`; + - the update is refused 403 without `BO_LEADS`, even with `BO_LEADS_EDIT`; + - uuids are strings; + - the latest salesperson and history names are resolved once per request. + + Live check through the gateway. + - 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): + - 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. + + Tests first: + - the header row and column order of each export; + - the mobile cell is a string; + - follow-up and capture cells are dates; + - all pages are collected; + - more than 20,000 rows gives 422 `EXPORT_TOO_LARGE` before any write; + - 403 without the listing module; + - the audit log line has no lead data. + + Tests read the workbook back with POI. Live check: download both files through the gateway and open them with POI. + - Scope: `solvway-mobile-api/pom.xml`, `solvway-mobile-api/src/**` + - Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`. + +## 4. Portal + +- [ ] 4.1 Add the Lead Listing and lead detail (design decision 6): + - the leads data layer: route `app/api/leads/[...path]`, service, types, and `/leads` mapped to `BO_LEADS`; + - the `/leads` listing with search; + - the `/leads/[leadUuid]` detail page, with an edit form when the user has `BO_LEADS_EDIT`, the shared-contact warning, the event history and not-found; + - a "View lead" link on the event lead edit page when the user has `BO_LEADS`. + + `Leads*` i18n keys. Tests first, one per portal-visible `lead-records` scenario. + - Scope: `solvway-admin-portal/app/leads/**`, `solvway-admin-portal/app/api/leads/**`, `solvway-admin-portal/app/lib/**`, `solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/**` + - Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`. + +- [ ] 4.2 Add the Export buttons (design decision 6): + - a binary variant of `callMobileApi` with the same error shape; + - the `app/api/leads/export` and `app/api/event-leads/[eventUuid]/export` routes, which pass through `Content-Type` and `Content-Disposition`; + - an Export button on both listings when the user has `BO_LEADS_EXPORT`. It sends the current search or filters, downloads via Blob under the server's filename, shows `EXPORT_TOO_LARGE` and other errors on the page, and is disabled while running. + + Tests first. + - Scope: `solvway-admin-portal/app/api/**/export/**`, `solvway-admin-portal/app/lib/**`, `solvway-admin-portal/app/leads/page*`, `solvway-admin-portal/app/event-leads/[eventUuid]/page*` + - Verify: as 4.1. + +## 5. Browser check + +- [ ] 5.1 Rebuild the changed services and drive the portal with Playwright, using only local dev data and made-up test leads. + - **Desktop:** + - Grant the three modules to a role. + - On Leads, check the counts, last event and latest salesperson of a lead captured at two events. + - Search by name, by email and by `012-345 6701`. + - Open a lead and check the history and the shared-mobile warning. + - Edit the email and company. + - Try an invalid mobile. + - Export Leads with a search, and export an event's leads with a filter. Open both files and check the columns, the rows and that the mobile is text. + - **360×780:** the lead detail page and its edit form. + - **Restricted users:** + - A user without `BO_LEADS_EDIT` sees the lead read-only. + - A user without `BO_LEADS_EXPORT` sees no Export button, and the export API returns 403. + - A user without `BO_LEADS` gets not-authorised on `/leads`. -- 2.54.1 From a1d9a82d88ae466410ee158705183c7567ed4f69 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 15:42:43 +0800 Subject: [PATCH 02/11] feat(db): event_lead lead index and the Leads, Edit leads and Export leads modules Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 10 ++++++++++ .../add-lead-listing-export/sql/01-lead-index.sql | 5 +++++ .../add-lead-listing-export/sql/02-lead-modules.sql | 9 +++++++++ .../add-lead-listing-export/sql/99-rollback.sql | 8 ++++++++ openspec/changes/add-lead-listing-export/tasks.md | 2 +- 5 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/add-lead-listing-export/sql/01-lead-index.sql create mode 100644 openspec/changes/add-lead-listing-export/sql/02-lead-modules.sql create mode 100644 openspec/changes/add-lead-listing-export/sql/99-rollback.sql diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index f1ca439..1039e33 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -108,3 +108,13 @@ CREATE TABLE `event_lead_interest` ( `company_id` bigint NOT NULL, PRIMARY KEY (`event_lead_id`, `interest_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- add-lead-listing-export/sql/01-lead-index.sql (still USE `service-counter` from above) +ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_lead` (`company_id`, `lead_uuid`); + +-- add-lead-listing-export/sql/02-lead-modules.sql +USE `service-system`; +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40400000, 'BO_LEADS', 'Leads', 'BO', 'M', 40000000, '/leads', 'Users'), + (40500000, 'BO_LEADS_EDIT', 'Edit leads', 'BO', 'A', 40000000, NULL, NULL), + (40600000, 'BO_LEADS_EXPORT', 'Export leads', 'BO', 'A', 40000000, NULL, NULL); diff --git a/openspec/changes/add-lead-listing-export/sql/01-lead-index.sql b/openspec/changes/add-lead-listing-export/sql/01-lead-index.sql new file mode 100644 index 0000000..f801e56 --- /dev/null +++ b/openspec/changes/add-lead-listing-export/sql/01-lead-index.sql @@ -0,0 +1,5 @@ +-- Co-Lite change 4b: index for per-lead aggregation (Lead Listing) and a lead's event history. +-- Target: `service-counter`. Additive only. Run once. +USE `service-counter`; + +ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_lead` (`company_id`, `lead_uuid`); diff --git a/openspec/changes/add-lead-listing-export/sql/02-lead-modules.sql b/openspec/changes/add-lead-listing-export/sql/02-lead-modules.sql new file mode 100644 index 0000000..f8e2411 --- /dev/null +++ b/openspec/changes/add-lead-listing-export/sql/02-lead-modules.sql @@ -0,0 +1,9 @@ +-- Co-Lite change 4b: Leads menu module and the Edit leads / Export leads action modules (area BO). +-- The action modules sit under the root so a role with only Event leads can be given export. +-- Target: `service-system`.`module`. Additive only. Run once. +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40400000, 'BO_LEADS', 'Leads', 'BO', 'M', 40000000, '/leads', 'Users'), + (40500000, 'BO_LEADS_EDIT', 'Edit leads', 'BO', 'A', 40000000, NULL, NULL), + (40600000, 'BO_LEADS_EXPORT', 'Export leads', 'BO', 'A', 40000000, NULL, NULL); diff --git a/openspec/changes/add-lead-listing-export/sql/99-rollback.sql b/openspec/changes/add-lead-listing-export/sql/99-rollback.sql new file mode 100644 index 0000000..0e2853d --- /dev/null +++ b/openspec/changes/add-lead-listing-export/sql/99-rollback.sql @@ -0,0 +1,8 @@ +-- Rollback for add-lead-listing-export. Removes the three modules with their grants and the event_lead index. +-- No lead data is touched. +USE `service-system`; +DELETE FROM `modules_roles` WHERE `module_id` IN (40400000, 40500000, 40600000); +DELETE FROM `module` WHERE `id` IN (40400000, 40500000, 40600000); + +USE `service-counter`; +ALTER TABLE `event_lead` DROP KEY `idx_event_lead_company_lead`; diff --git a/openspec/changes/add-lead-listing-export/tasks.md b/openspec/changes/add-lead-listing-export/tasks.md index 2604bb0..81e4313 100644 --- a/openspec/changes/add-lead-listing-export/tasks.md +++ b/openspec/changes/add-lead-listing-export/tasks.md @@ -4,7 +4,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially ## 1. Database -- [ ] 1.1 Write the SQL files (design decision 1): +- [x] 1.1 Write the SQL files (design decision 1): - `sql/01-lead-index.sql`: `ALTER TABLE event_lead ADD KEY idx_event_lead_company_lead (company_id, lead_uuid)`. - `sql/02-lead-modules.sql`: the three module rows. - `sql/99-rollback.sql`. -- 2.54.1 From e75ef80dc05e1e689f926ad10f8723a60779deea Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 15:59:02 +0800 Subject: [PATCH 03/11] feat(services-counter): lead search, detail and update Search lists every lead in the company with its event count, last event and latest salesperson, worked out at read time. Detail adds the event history and other leads sharing the mobile or email. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-lead-listing-export/tasks.md | 2 +- .../counter/controller/LeadController.java | 25 ++ .../services/counter/dto/LeadDetail.java | 8 + .../counter/dto/LeadHistoryEntry.java | 8 + .../counter/dto/LeadSearchRequest.java | 4 + .../services/counter/dto/LeadSummary.java | 7 + .../counter/dto/LeadUpdateRequest.java | 4 + .../services/counter/dto/SharedContact.java | 4 + .../counter/repo/EventLeadRepository.java | 5 + .../services/counter/repo/LeadRepository.java | 43 ++++ .../services/counter/service/LeadService.java | 90 ++++++++ .../controller/LeadControllerTest.java | 49 ++++ .../counter/service/LeadServiceTest.java | 214 ++++++++++++++++++ 13 files changed, 462 insertions(+), 1 deletion(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadDetail.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadHistoryEntry.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSearchRequest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSummary.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadUpdateRequest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/SharedContact.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/controller/LeadControllerTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceTest.java diff --git a/openspec/changes/add-lead-listing-export/tasks.md b/openspec/changes/add-lead-listing-export/tasks.md index 81e4313..8899d1d 100644 --- a/openspec/changes/add-lead-listing-export/tasks.md +++ b/openspec/changes/add-lead-listing-export/tasks.md @@ -15,7 +15,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially ## 2. services-counter -- [ ] 2.1 Add lead search, detail and update (design decisions 2 and 3): +- [x] 2.1 Add lead search, detail and update (design decisions 2 and 3): - `POST /counter/lead/search`: the native query with `cnt`, `last` and `sp`. - `GET /counter/lead/detail/{companyId}/{leadUuid}`: the lead with its history and shared contacts. - `POST /counter/lead/update`: `@Transactional`. diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java new file mode 100644 index 0000000..316ca7d --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java @@ -0,0 +1,25 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.dto.*; +import com.solvway.services.counter.service.LeadService; +import lombok.AllArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/counter") +@AllArgsConstructor +public class LeadController { + private final LeadService leadService; + + @PostMapping("/lead/search") + public Page search(@RequestBody LeadSearchRequest req) { return leadService.search(req); } + + @GetMapping("/lead/detail/{companyId}/{leadUuid}") + public LeadDetail detail(@PathVariable("companyId") long companyId, @PathVariable("leadUuid") long leadUuid) { + return leadService.detail(companyId, leadUuid); + } + + @PostMapping("/lead/update") + public LeadDetail update(@RequestBody LeadUpdateRequest req) { return leadService.update(req); } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadDetail.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadDetail.java new file mode 100644 index 0000000..e9843b0 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadDetail.java @@ -0,0 +1,8 @@ +package com.solvway.services.counter.dto; + +import java.time.LocalDateTime; +import java.util.List; + +public record LeadDetail(long leadUuid, String name, String mobileE164, String email, String companyName, + String jobTitle, String notes, LocalDateTime createdAt, LocalDateTime updatedAt, + String updatedBy, List history, List sharedContacts) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadHistoryEntry.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadHistoryEntry.java new file mode 100644 index 0000000..052d1e2 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadHistoryEntry.java @@ -0,0 +1,8 @@ +package com.solvway.services.counter.dto; + +import java.time.LocalDateTime; + +/** One capture of the lead at an event; event fields are null when the event no longer exists. */ +public record LeadHistoryEntry(long eventLeadUuid, long eventUuid, String eventName, LocalDateTime eventStart, + LocalDateTime eventEnd, String leadType, Long salespersonUserId, String temperature, + String status, LocalDateTime capturedAt) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSearchRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSearchRequest.java new file mode 100644 index 0000000..a316658 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSearchRequest.java @@ -0,0 +1,4 @@ +package com.solvway.services.counter.dto; + +/** q is free text (name or email); mobileDigits is digits only. Both optional. */ +public record LeadSearchRequest(long companyId, String q, String mobileDigits, int page, int size) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSummary.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSummary.java new file mode 100644 index 0000000..f9bed13 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSummary.java @@ -0,0 +1,7 @@ +package com.solvway.services.counter.dto; + +import java.time.LocalDateTime; + +public record LeadSummary(long leadUuid, String name, String mobileE164, String email, String companyName, + String jobTitle, long eventCount, Long lastEventUuid, String lastEventName, + LocalDateTime lastCapturedAt, Long latestSalespersonUserId) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadUpdateRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadUpdateRequest.java new file mode 100644 index 0000000..f5ccb07 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadUpdateRequest.java @@ -0,0 +1,4 @@ +package com.solvway.services.counter.dto; + +public record LeadUpdateRequest(long companyId, long leadUuid, String name, String mobileE164, String email, + String companyName, String jobTitle, String notes, String doneBy) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/SharedContact.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/SharedContact.java new file mode 100644 index 0000000..e593070 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/SharedContact.java @@ -0,0 +1,4 @@ +package com.solvway.services.counter.dto; + +/** Another lead sharing this lead's mobile and/or email. */ +public record SharedContact(long leadUuid, String name, boolean sameMobile, boolean sameEmail) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java index 12cea09..0c93dbc 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java @@ -37,4 +37,9 @@ public interface EventLeadRepository extends JpaRepository { @Param("salespersonUserId") Long salespersonUserId, @Param("temperature") String temperature, @Param("status") String status, @Param("interestId") Long interestId, @Param("leadType") String leadType, Pageable pageable); + + /** Rows are [EventLead, Event]; Event is null when the event row is gone. Newest capture first. */ + @Query("SELECT e, ev FROM EventLead e LEFT JOIN Event ev ON ev.uuid = e.eventUuid" + + " WHERE e.companyId = :companyId AND e.leadUuid = :leadUuid ORDER BY e.capturedAt DESC, e.id DESC") + List history(@Param("companyId") long companyId, @Param("leadUuid") long leadUuid); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java index e5f7b48..a2ba928 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java @@ -1,6 +1,7 @@ package com.solvway.services.counter.repo; import com.solvway.services.counter.model.Lead; +import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -19,4 +20,46 @@ public interface LeadRepository extends JpaRepository { @Param("email") String email, Pageable pageable); Optional findByUuidAndCompanyId(long uuid, long companyId); + + interface SummaryRow { + long getLeadUuid(); + String getName(); + String getMobileE164(); + String getEmail(); + String getCompanyName(); + String getJobTitle(); + long getEventCount(); + Long getLastEventUuid(); + String getLastEventName(); + java.time.LocalDateTime getLastCapturedAt(); + Long getLatestSalespersonUserId(); + } + + /** The search condition uses only `lead` columns, so the count skips the aggregate joins. */ + String SEARCH_WHERE = " WHERE l.company_id = :companyId AND ((:q IS NULL AND :digits IS NULL) OR LOWER(l.name) LIKE :q ESCAPE '\\\\'" + + " OR l.email_normalised LIKE :q ESCAPE '\\\\' OR (:digits IS NOT NULL AND l.mobile_e164 LIKE :digits))"; + + String SEARCH_FROM = " FROM `lead` l" + + " LEFT JOIN (SELECT lead_uuid, COUNT(*) cnt FROM event_lead WHERE company_id = :companyId GROUP BY lead_uuid) c ON c.lead_uuid = l.uuid" + + " LEFT JOIN (SELECT lead_uuid, event_uuid, captured_at, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn" + + " FROM event_lead WHERE company_id = :companyId) last ON last.lead_uuid = l.uuid AND last.rn = 1" + + " LEFT JOIN `event` ev ON ev.uuid = last.event_uuid" + + " LEFT JOIN (SELECT lead_uuid, salesperson_user_id, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn" + + " FROM event_lead WHERE company_id = :companyId AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1" + + SEARCH_WHERE; + + /** + * Returns one row per lead with columns lead_uuid AS leadUuid, name, mobile_e164 AS mobileE164, email_normalised AS email, + * company_name AS companyName, job_title AS jobTitle, eventCount, lastEventUuid, lastEventName, lastCapturedAt and + * latestSalespersonUserId. Native because JPQL has no window functions. Never-captured leads sort last. + */ + @Query(nativeQuery = true, + value = "SELECT l.uuid AS leadUuid, l.name AS name, l.mobile_e164 AS mobileE164, l.email_normalised AS email," + + " l.company_name AS companyName, l.job_title AS jobTitle, COALESCE(c.cnt, 0) AS eventCount," + + " last.event_uuid AS lastEventUuid, ev.name AS lastEventName, last.captured_at AS lastCapturedAt," + + " sp.salesperson_user_id AS latestSalespersonUserId" + SEARCH_FROM + + " ORDER BY last.captured_at IS NULL, last.captured_at DESC, l.id DESC", + countQuery = "SELECT COUNT(*) FROM `lead` l" + SEARCH_WHERE) + Page search(@Param("companyId") long companyId, @Param("q") String q, + @Param("digits") String digits, Pageable pageable); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java new file mode 100644 index 0000000..a24e431 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java @@ -0,0 +1,90 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.LeadDetail; +import com.solvway.services.counter.dto.LeadHistoryEntry; +import com.solvway.services.counter.dto.LeadSearchRequest; +import com.solvway.services.counter.dto.LeadSummary; +import com.solvway.services.counter.dto.LeadUpdateRequest; +import com.solvway.services.counter.dto.SharedContact; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import lombok.AllArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; + +/** Lead directory: search, detail with event history and shared contacts, and edit. Never log lead PII. */ +@Service +@AllArgsConstructor +public class LeadService { + private static final int MAX_SHARED = 20; + private static final int MAX_PAGE_SIZE = 100; + + private final LeadRepository leadRepository; + private final EventLeadRepository eventLeadRepository; + + public Page search(LeadSearchRequest req) { + String q = req.q() == null || req.q().isBlank() ? null + : "%" + req.q().trim().toLowerCase().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"; + String digits = req.mobileDigits() == null || req.mobileDigits().isBlank() ? null : "%" + req.mobileDigits().trim() + "%"; + int size = req.size() < 1 ? 20 : Math.min(req.size(), MAX_PAGE_SIZE); + return leadRepository.search(req.companyId(), q, digits, PageRequest.of(Math.max(req.page(), 0), size)) + .map(r -> new LeadSummary(r.getLeadUuid(), r.getName(), r.getMobileE164(), r.getEmail(), r.getCompanyName(), + r.getJobTitle(), r.getEventCount(), r.getLastEventUuid(), r.getLastEventName(), + r.getLastCapturedAt(), r.getLatestSalespersonUserId())); + } + + public LeadDetail detail(long companyId, long leadUuid) { + return detail(find(companyId, leadUuid)); + } + + @Transactional + public LeadDetail update(LeadUpdateRequest req) { + Lead lead = find(req.companyId(), req.leadUuid()); + lead.setName(req.name()); + lead.setMobileE164(req.mobileE164()); + lead.setEmailNormalised(req.email()); + lead.setCompanyName(req.companyName()); + lead.setJobTitle(req.jobTitle()); + lead.setNotes(req.notes()); + lead.setUpdatedBy(req.doneBy()); + lead.setUpdatedAt(LocalDateTime.now()); + return detail(leadRepository.saveAndFlush(lead)); + } + + private Lead find(long companyId, long leadUuid) { + return leadRepository.findByUuidAndCompanyId(leadUuid, companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND")); + } + + private LeadDetail detail(Lead l) { + List history = eventLeadRepository.history(l.getCompanyId(), l.getUuid()).stream().map(r -> { + EventLead e = (EventLead) r[0]; + Event ev = (Event) r[1]; + return new LeadHistoryEntry(e.getUuid(), e.getEventUuid(), ev == null ? null : ev.getName(), + ev == null ? null : ev.getDateStart(), ev == null ? null : ev.getDateEnd(), e.getLeadType(), + e.getSalespersonUserId(), e.getTemperature(), e.getStatus(), e.getCapturedAt()); + }).toList(); + // One extra row so the cap still holds after the lead itself is filtered out. + List shared = leadRepository.findMatches(l.getCompanyId(), l.getMobileE164(), l.getEmailNormalised(), + PageRequest.of(0, MAX_SHARED + 1)).stream() + .filter(o -> o.getUuid() != l.getUuid()) + .limit(MAX_SHARED) + .map(o -> new SharedContact(o.getUuid(), o.getName(), + l.getMobileE164() != null && Objects.equals(l.getMobileE164(), o.getMobileE164()), + l.getEmailNormalised() != null && Objects.equals(l.getEmailNormalised(), o.getEmailNormalised()))) + .toList(); + return new LeadDetail(l.getUuid(), l.getName(), l.getMobileE164(), l.getEmailNormalised(), l.getCompanyName(), + l.getJobTitle(), l.getNotes(), l.getCreatedAt(), l.getUpdatedAt(), l.getUpdatedBy(), history, shared); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/LeadControllerTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/LeadControllerTest.java new file mode 100644 index 0000000..68d0939 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/LeadControllerTest.java @@ -0,0 +1,49 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.dto.LeadDetail; +import com.solvway.services.counter.dto.LeadSearchRequest; +import com.solvway.services.counter.dto.LeadSummary; +import com.solvway.services.counter.dto.LeadUpdateRequest; +import com.solvway.services.counter.service.LeadService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** LeadController delegates to the service and returns its result. */ +@ExtendWith(MockitoExtension.class) +class LeadControllerTest { + + @Mock private LeadService service; + + @Test + void searchDelegates() { + LeadSearchRequest req = new LeadSearchRequest(42L, "a", null, 0, 20); + Page out = Page.empty(); + when(service.search(req)).thenReturn(out); + + assertThat(new LeadController(service).search(req)).isSameAs(out); + } + + @Test + void detailDelegates() { + LeadDetail out = mock(LeadDetail.class); + when(service.detail(42L, 7L)).thenReturn(out); + + assertThat(new LeadController(service).detail(42L, 7L)).isSameAs(out); + } + + @Test + void updateDelegates() { + LeadUpdateRequest req = mock(LeadUpdateRequest.class); + LeadDetail out = mock(LeadDetail.class); + when(service.update(req)).thenReturn(out); + + assertThat(new LeadController(service).update(req)).isSameAs(out); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceTest.java new file mode 100644 index 0000000..d8e5d5c --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadServiceTest.java @@ -0,0 +1,214 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.LeadDetail; +import com.solvway.services.counter.dto.LeadSearchRequest; +import com.solvway.services.counter.dto.LeadSummary; +import com.solvway.services.counter.dto.LeadUpdateRequest; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +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.verify; +import static org.mockito.Mockito.when; + +/** LeadService: lead search, detail and update. */ +@ExtendWith(MockitoExtension.class) +class LeadServiceTest { + + private static final long COMPANY = 42L; + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + + private LeadService service; + + @BeforeEach + void setUp() { + service = new LeadService(leadRepository, eventLeadRepository); + } + + private Pageable search(String q, String digits, int page, int size) { + when(leadRepository.search(eq(COMPANY), any(), any(), any(Pageable.class))).thenReturn(Page.empty()); + service.search(new LeadSearchRequest(COMPANY, q, digits, page, size)); + ArgumentCaptor p = ArgumentCaptor.forClass(Pageable.class); + verify(leadRepository).search(eq(COMPANY), any(), any(), p.capture()); + return p.getValue(); + } + + private String[] searchArgs(String q, String digits) { + when(leadRepository.search(eq(COMPANY), any(), any(), any(Pageable.class))).thenReturn(Page.empty()); + service.search(new LeadSearchRequest(COMPANY, q, digits, 0, 20)); + ArgumentCaptor qc = ArgumentCaptor.forClass(String.class); + ArgumentCaptor dc = ArgumentCaptor.forClass(String.class); + verify(leadRepository).search(eq(COMPANY), qc.capture(), dc.capture(), any(Pageable.class)); + return new String[]{qc.getValue(), dc.getValue()}; + } + + @Test + void pageAndSizeAreClamped() { + Pageable p = search("a", null, -3, 1000); + assertThat(p.getPageNumber()).isZero(); + assertThat(p.getPageSize()).isEqualTo(100); + } + + @Test + void sizeBelowOneDefaultsToTwenty() { + assertThat(search("a", null, 2, 0).getPageSize()).isEqualTo(20); + } + + @Test + void blankQueryAndDigitsBecomeNull() { + assertThat(searchArgs(" ", " ")).containsExactly(null, null); + } + + @Test + void queryIsTrimmedLowercasedAndWrapped() { + assertThat(searchArgs(" Aisyah ", null)[0]).isEqualTo("%aisyah%"); + } + + @Test + void likeWildcardsAndBackslashAreEscaped() { + assertThat(searchArgs("50%_a\\B", null)[0]).isEqualTo("%50\\%\\_a\\\\b%"); + } + + @Test + void digitsArePassedAsContains() { + assertThat(searchArgs("a", "12345")[1]).isEqualTo("%12345%"); + } + + @Test + void searchMapsProjectionRows() { + LeadRepository.SummaryRow row = mock(LeadRepository.SummaryRow.class); + LocalDateTime at = LocalDateTime.of(2026, 1, 2, 3, 4); + when(row.getLeadUuid()).thenReturn(7L); + when(row.getName()).thenReturn("Aisyah"); + when(row.getEventCount()).thenReturn(3L); + when(row.getLastEventUuid()).thenReturn(9L); + when(row.getLastEventName()).thenReturn("Expo"); + when(row.getLastCapturedAt()).thenReturn(at); + when(row.getLatestSalespersonUserId()).thenReturn(11L); + when(leadRepository.search(eq(COMPANY), any(), any(), any(Pageable.class))).thenReturn(new PageImpl<>(List.of(row))); + + LeadSummary s = service.search(new LeadSearchRequest(COMPANY, null, null, 0, 20)).getContent().get(0); + + assertThat(s).isEqualTo(new LeadSummary(7L, "Aisyah", null, null, null, null, 3L, 9L, "Expo", at, 11L)); + } + + @Test + void detailIs404ForUnknownOrOtherCompanyLead() { + when(leadRepository.findByUuidAndCompanyId(7L, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.detail(COMPANY, 7L)) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(e.getReason()).isEqualTo("LEAD_NOT_FOUND"); + }); + } + + @Test + void detailListsHistoryWithOrWithoutEventAndSharedContactsExcludingSelf() { + Lead me = lead(7L, "Me", "+601", "me@x.com"); + when(leadRepository.findByUuidAndCompanyId(7L, COMPANY)).thenReturn(Optional.of(me)); + EventLead el = new EventLead(); + el.setUuid(70L); + el.setEventUuid(1000L); + el.setLeadType("NEW"); + Event ev = new Event(); + ev.setName("Expo"); + EventLead orphan = new EventLead(); + orphan.setUuid(71L); + orphan.setEventUuid(2000L); + when(eventLeadRepository.history(COMPANY, 7L)).thenReturn(List.of(new Object[]{el, ev}, new Object[]{orphan, null})); + when(leadRepository.findMatches(eq(COMPANY), eq("+601"), eq("me@x.com"), any(Pageable.class))).thenReturn(List.of( + me, lead(8L, "SameMobile", "+601", "other@x.com"), lead(9L, "SameEmail", "+602", "me@x.com"), + lead(10L, "Both", "+601", "me@x.com"))); + + LeadDetail d = service.detail(COMPANY, 7L); + + assertThat(d.history()).extracting("eventLeadUuid", "eventName").containsExactly( + org.assertj.core.groups.Tuple.tuple(70L, "Expo"), org.assertj.core.groups.Tuple.tuple(71L, null)); + assertThat(d.sharedContacts()).extracting("leadUuid", "sameMobile", "sameEmail").containsExactly( + org.assertj.core.groups.Tuple.tuple(8L, true, false), org.assertj.core.groups.Tuple.tuple(9L, false, true), + org.assertj.core.groups.Tuple.tuple(10L, true, true)); + } + + @Test + void sharedContactsAreCappedAtTwenty() { + Lead me = lead(7L, "Me", "+601", null); + when(leadRepository.findByUuidAndCompanyId(7L, COMPANY)).thenReturn(Optional.of(me)); + when(eventLeadRepository.history(COMPANY, 7L)).thenReturn(List.of()); + when(leadRepository.findMatches(eq(COMPANY), eq("+601"), eq(null), any(Pageable.class))).thenReturn( + java.util.stream.LongStream.range(100, 125).mapToObj(i -> lead(i, "n", "+601", null)).toList()); + + assertThat(service.detail(COMPANY, 7L).sharedContacts()).hasSize(20); + } + + @Test + void updateSetsSixFieldsAndAudit() { + Lead me = lead(7L, "Old", "+601", "old@x.com"); + when(leadRepository.findByUuidAndCompanyId(7L, COMPANY)).thenReturn(Optional.of(me)); + when(leadRepository.saveAndFlush(me)).thenReturn(me); + when(eventLeadRepository.history(COMPANY, 7L)).thenReturn(List.of()); + when(leadRepository.findMatches(eq(COMPANY), any(), any(), any(Pageable.class))).thenReturn(List.of()); + + LeadDetail d = service.update(new LeadUpdateRequest(COMPANY, 7L, "New", "+609", null, "Acme", "CEO", "note", "bob")); + + assertThat(me.getName()).isEqualTo("New"); + assertThat(me.getMobileE164()).isEqualTo("+609"); + assertThat(me.getEmailNormalised()).isNull(); + assertThat(me.getCompanyName()).isEqualTo("Acme"); + assertThat(me.getJobTitle()).isEqualTo("CEO"); + assertThat(me.getNotes()).isEqualTo("note"); + assertThat(me.getUpdatedBy()).isEqualTo("bob"); + assertThat(me.getUpdatedAt()).isNotNull(); + assertThat(d.name()).isEqualTo("New"); + assertThat(d.updatedBy()).isEqualTo("bob"); + } + + @Test + void updateIs404ForUnknownLead() { + when(leadRepository.findByUuidAndCompanyId(7L, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.update(new LeadUpdateRequest(COMPANY, 7L, "n", null, null, null, null, null, "bob"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("LEAD_NOT_FOUND")); + } + + @Test + void updateIsOneTransaction() throws Exception { + assertThat(LeadService.class.getMethod("update", LeadUpdateRequest.class) + .isAnnotationPresent(Transactional.class)).isTrue(); + } + + private static Lead lead(long uuid, String name, String mobile, String email) { + Lead l = new Lead(); + l.setUuid(uuid); + l.setCompanyId(COMPANY); + l.setName(name); + l.setMobileE164(mobile); + l.setEmailNormalised(email); + return l; + } +} -- 2.54.1 From 6ab495ad3e47a1b78f32903e421640bd8cbf0cc3 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 15:59:38 +0800 Subject: [PATCH 04/11] docs(openspec): enforce the second module with @AdminModule(also) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-lead-listing-export/design.md | 12 ++++++------ openspec/changes/add-lead-listing-export/tasks.md | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/openspec/changes/add-lead-listing-export/design.md b/openspec/changes/add-lead-listing-export/design.md index efb0727..6da8cdc 100644 --- a/openspec/changes/add-lead-listing-export/design.md +++ b/openspec/changes/add-lead-listing-export/design.md @@ -93,14 +93,14 @@ See proposal.md for why. |---|---| | `GET /api/admin/leads?q&page&size` | `BO_LEADS` | | `GET /api/admin/leads/{leadUuid}` | `BO_LEADS` | -| `PUT /api/admin/leads/{leadUuid}` | `BO_LEADS_EDIT` | -| `GET /api/admin/leads/export?q` | `BO_LEADS_EXPORT` | +| `PUT /api/admin/leads/{leadUuid}` | `BO_LEADS_EDIT` and `BO_LEADS` | +| `GET /api/admin/leads/export?q` | `BO_LEADS_EXPORT` and `BO_LEADS` | -**Second check in code:** `@AdminModule` is any-of, so two handlers re-check a module with `AdminModuleAccess.grantedAny`, which gives 403 `FORBIDDEN` when it fails: -- the update handler also checks `BO_LEADS`; -- the export handler also checks `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>` carries `@AdminModule("BO_LEADS_EXPORT")` and re-checks `BO_EVENT_LEADS` in code. +**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. diff --git a/openspec/changes/add-lead-listing-export/tasks.md b/openspec/changes/add-lead-listing-export/tasks.md index 8899d1d..dfb2019 100644 --- a/openspec/changes/add-lead-listing-export/tasks.md +++ b/openspec/changes/add-lead-listing-export/tasks.md @@ -44,7 +44,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially Tests first: - each validation code, with update normalisation the same as capture; - the digits key built from `012-345 6701` and from `+60 12-345 6701`; - - the update is refused 403 without `BO_LEADS`, even with `BO_LEADS_EDIT`; + - `@AdminModule(also=…)` in `AppAccessAspect`: missing an `also` module gives 403, super admin passes, injected `ROLE_ADMIN` grants nothing; the update is refused 403 without `BO_LEADS`, even with `BO_LEADS_EDIT`; - uuids are strings; - the latest salesperson and history names are resolved once per request. -- 2.54.1 From 6855906cf102df80b76de1256dcf92c960fccb68 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 16:12:21 +0800 Subject: [PATCH 05/11] fix(db): make Edit leads and Export leads grantable url-less M modules The Roles screen only grants type M modules, so type A could never be granted. A url-less M module with no children stays out of the sidebar. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 4 ++-- openspec/changes/add-lead-listing-export/design.md | 10 ++++++---- openspec/changes/add-lead-listing-export/proposal.md | 2 +- .../add-lead-listing-export/sql/02-lead-modules.sql | 7 ++++--- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 1039e33..4fa0862 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -116,5 +116,5 @@ ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_lead` (`company_id`, `l USE `service-system`; INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES (40400000, 'BO_LEADS', 'Leads', 'BO', 'M', 40000000, '/leads', 'Users'), - (40500000, 'BO_LEADS_EDIT', 'Edit leads', 'BO', 'A', 40000000, NULL, NULL), - (40600000, 'BO_LEADS_EXPORT', 'Export leads', 'BO', 'A', 40000000, NULL, NULL); + (40500000, 'BO_LEADS_EDIT', 'Edit leads', 'BO', 'M', 40000000, NULL, NULL), + (40600000, 'BO_LEADS_EXPORT', 'Export leads', 'BO', 'M', 40000000, NULL, NULL); diff --git a/openspec/changes/add-lead-listing-export/design.md b/openspec/changes/add-lead-listing-export/design.md index 6da8cdc..220e103 100644 --- a/openspec/changes/add-lead-listing-export/design.md +++ b/openspec/changes/add-lead-listing-export/design.md @@ -12,7 +12,7 @@ Change 4a (`openspec/changes/archive/2026-11-27-add-event-lead-capture/`) added **Access control:** - `@AdminModule` allows a caller holding any one of the listed modules (`AppAccessAspect`). `AdminModuleAccess.grantedAny` checks modules in code. -- Modules of type `A` (action) are granted like any module and show in the Roles access tree. The sidebar never shows them (`aclSidebar.ts`). +- Only modules of type `M` can be granted on the Roles screen (`AdminAclService.isGrantable`); type `A` is refused with `UNKNOWN_MODULE`. The sidebar hides an `M` module that has no url and no children (`aclSidebar.ts`, with a test). - The portal checks access with `useAdminAuth().hasModule(name)`. **Data facts:** @@ -48,10 +48,12 @@ See proposal.md for why. | id | name | desc | type | url | icon_name | |---|---|---|---|---|---| | 40400000 | `BO_LEADS` | Leads | `M` | `/leads` | `Users` | -| 40500000 | `BO_LEADS_EDIT` | Edit leads | `A` | NULL | NULL | -| 40600000 | `BO_LEADS_EXPORT` | Export leads | `A` | NULL | NULL | +| 40500000 | `BO_LEADS_EDIT` | Edit leads | `M` | NULL | NULL | +| 40600000 | `BO_LEADS_EXPORT` | Export leads | `M` | NULL | NULL | -**Placement:** the two action modules sit directly under the root, not under `BO_LEADS`. That way a role with only `BO_EVENT_LEADS` can still be given export. +**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`. diff --git a/openspec/changes/add-lead-listing-export/proposal.md b/openspec/changes/add-lead-listing-export/proposal.md index 000895f..a665803 100644 --- a/openspec/changes/add-lead-listing-export/proposal.md +++ b/openspec/changes/add-lead-listing-export/proposal.md @@ -17,7 +17,7 @@ Change 4a lets staff capture leads at an event and work them one event at a time - Each export is logged with the username, the listing and the row count, but never with lead data. - **Permissions**: - New menu module `BO_LEADS` (`/leads`) to view the Lead Listing and lead detail. - - New action modules `BO_LEADS_EDIT` (edit a lead) and `BO_LEADS_EXPORT` (export either listing). Action modules never show in the sidebar. + - New modules `BO_LEADS_EDIT` (edit a lead) and `BO_LEADS_EXPORT` (export either listing). They have no url, so they never show in the sidebar. - An export also needs the listing's own module: `BO_LEADS` for the Lead Listing, `BO_EVENT_LEADS` for the Event Leads Listing. - **Link from the event lead edit page** to the lead detail page, for users who hold `BO_LEADS`. - **New dependency** `org.apache.poi:poi-ooxml` 4.1.0 in `mobile-api`. It is the same library and version that `services-system` already uses for its spreadsheet exports. diff --git a/openspec/changes/add-lead-listing-export/sql/02-lead-modules.sql b/openspec/changes/add-lead-listing-export/sql/02-lead-modules.sql index f8e2411..a05a886 100644 --- a/openspec/changes/add-lead-listing-export/sql/02-lead-modules.sql +++ b/openspec/changes/add-lead-listing-export/sql/02-lead-modules.sql @@ -1,9 +1,10 @@ -- Co-Lite change 4b: Leads menu module and the Edit leads / Export leads action modules (area BO). --- The action modules sit under the root so a role with only Event leads can be given export. +-- Edit and Export are url-less M modules: grantable on the Roles screen (only type M is), hidden from the sidebar +-- (a url-less M with no children renders nothing). They sit under the root so a role with only Event leads can be given export. -- Target: `service-system`.`module`. Additive only. Run once. USE `service-system`; INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES (40400000, 'BO_LEADS', 'Leads', 'BO', 'M', 40000000, '/leads', 'Users'), - (40500000, 'BO_LEADS_EDIT', 'Edit leads', 'BO', 'A', 40000000, NULL, NULL), - (40600000, 'BO_LEADS_EXPORT', 'Export leads', 'BO', 'A', 40000000, NULL, NULL); + (40500000, 'BO_LEADS_EDIT', 'Edit leads', 'BO', 'M', 40000000, NULL, NULL), + (40600000, 'BO_LEADS_EXPORT', 'Export leads', 'BO', 'M', 40000000, NULL, NULL); -- 2.54.1 From 963735d524bb112187ac3741e2d7e2cc9202112f Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 16:15:36 +0800 Subject: [PATCH 06/11] feat(mobile-api): leads admin API and @AdminModule(also) List, detail and update under /api/admin/leads. Update validates and normalises like capture and needs both Edit leads and Leads, enforced by the new also() attribute, which fails closed if any lookup throws. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-lead-listing-export/tasks.md | 2 +- .../api/RestApiCounterServiceConstants.java | 3 + .../controller/admin/AdminLeadController.java | 48 ++++ .../api/dto/admin/AdminLeadUpdateRequest.java | 4 + .../api/service/AdminEventLeadService.java | 16 +- .../mobile/api/service/AdminLeadService.java | 197 +++++++++++++ .../mobile/api/useraccess/AdminModule.java | 7 + .../api/useraccess/AppAccessAspect.java | 7 +- .../admin/AdminLeadControllerTest.java | 72 +++++ .../api/service/AdminLeadServiceTest.java | 267 ++++++++++++++++++ .../useraccess/AppAccessAspectAdminTest.java | 73 +++++ 11 files changed, 686 insertions(+), 10 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadUpdateRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceTest.java diff --git a/openspec/changes/add-lead-listing-export/tasks.md b/openspec/changes/add-lead-listing-export/tasks.md index dfb2019..5b1b30d 100644 --- a/openspec/changes/add-lead-listing-export/tasks.md +++ b/openspec/changes/add-lead-listing-export/tasks.md @@ -39,7 +39,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially ## 3. mobile-api -- [ ] 3.1 Add the leads admin API (design decision 4): list, detail and update under `/api/admin/leads`, with the module rules and the second check in code. +- [x] 3.1 Add the leads admin API (design decision 4): list, detail and update under `/api/admin/leads`, with the module rules and the second check in code. Tests first: - each validation code, with update normalisation the same as capture; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index af58433..e2eceff 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -41,6 +41,9 @@ public class RestApiCounterServiceConstants { public static final String API_REST_COUNTER_INTEREST_SAVE="/counter/interest/save"; public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds"; public static final String API_REST_COUNTER_LEAD_FIND_MATCHES="/counter/lead/findMatches"; + public static final String API_REST_COUNTER_LEAD_SEARCH="/counter/lead/search"; + public static final String API_REST_COUNTER_LEAD_DETAIL="/counter/lead/detail/{companyId}/{leadUuid}"; + public static final String API_REST_COUNTER_LEAD_UPDATE="/counter/lead/update"; public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture"; public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}"; public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java new file mode 100644 index 0000000..c9d8c10 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java @@ -0,0 +1,48 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +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.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +/** Lead Listing, detail and edit. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin/leads") +@RequiredArgsConstructor +public class AdminLeadController { + private final AdminLeadService adminLeadService; + + @AppAuth + @AdminModule("BO_LEADS") + @GetMapping + public ResponseEntity> list(@RequestParam(required = false) String q, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ResponseEntity.ok(adminLeadService.list(q, page, size)); + } + + @AppAuth + @AdminModule("BO_LEADS") + @GetMapping("/{leadUuid}") + public ResponseEntity> get(@PathVariable String leadUuid) { + return ResponseEntity.ok(adminLeadService.get(leadUuid)); + } + + @AppAuth + @AdminModule(value = "BO_LEADS_EDIT", also = "BO_LEADS") + @PutMapping("/{leadUuid}") + public ResponseEntity> update(@PathVariable String leadUuid, @RequestBody AdminLeadUpdateRequest request) { + return ResponseEntity.ok(adminLeadService.update(leadUuid, request)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadUpdateRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadUpdateRequest.java new file mode 100644 index 0000000..69e8712 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadUpdateRequest.java @@ -0,0 +1,4 @@ +package com.solvway.mobile.api.dto.admin; + +/** A lead's own fields. mobile and email are normalised server-side; at least one is required. */ +public record AdminLeadUpdateRequest(String name, String mobile, String email, String companyName, String jobTitle, String notes) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java index 78df6f5..d70a4b1 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -368,7 +368,7 @@ public class AdminEventLeadService { return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled")); } - private static String mobile(String input) { + static String mobile(String input) { try { return EventLeadContact.mobile(input); } catch (IllegalArgumentException e) { @@ -376,7 +376,7 @@ public class AdminEventLeadService { } } - private static String email(String input) { + static String email(String input) { try { return EventLeadContact.email(input); } catch (IllegalArgumentException e) { @@ -399,16 +399,16 @@ public class AdminEventLeadService { return value; } - private static String maxLength(String field, String value, int max) { + static String maxLength(String field, String value, int max) { if (value != null && value.length() > max) throw error(HttpStatus.BAD_REQUEST, field + " is too long", "TOO_LONG", field); return value; } - private static String trimmed(String s) { + static String trimmed(String s) { return s == null || s.isBlank() ? null : s.trim(); } - private static long parseOr(String s, java.util.function.Supplier notFound) { + static long parseOr(String s, java.util.function.Supplier notFound) { try { return Long.parseLong(s.trim()); } catch (RuntimeException e) { @@ -421,11 +421,11 @@ public class AdminEventLeadService { return l.stream().filter(Number.class::isInstance).map(o -> ((Number) o).longValue()).toList(); } - private static String str(Object o) { + static String str(Object o) { return o == null ? null : String.valueOf(o); } - private static CodedResponseStatusException required(List fields) { + static CodedResponseStatusException required(List fields) { CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: " + String.join(", ", fields), "REQUIRED_FIELD", fields.get(0)); e.getBody().setProperty("errors", fields); return e; @@ -439,7 +439,7 @@ public class AdminEventLeadService { return error(HttpStatus.NOT_FOUND, "Event lead not found", "EVENT_LEAD_NOT_FOUND", null); } - private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) { + static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) { CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code); if (field != null) e.getBody().setProperty("details", Map.of("field", field)); return e; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java new file mode 100644 index 0000000..ecfa460 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java @@ -0,0 +1,197 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static com.solvway.mobile.api.service.AdminEventLeadService.email; +import static com.solvway.mobile.api.service.AdminEventLeadService.error; +import static com.solvway.mobile.api.service.AdminEventLeadService.maxLength; +import static com.solvway.mobile.api.service.AdminEventLeadService.mobile; +import static com.solvway.mobile.api.service.AdminEventLeadService.parseOr; +import static com.solvway.mobile.api.service.AdminEventLeadService.required; +import static com.solvway.mobile.api.service.AdminEventLeadService.str; +import static com.solvway.mobile.api.service.AdminEventLeadService.trimmed; + +/** + * Lead Listing, detail and edit for the admin portal. Validates and normalises at this boundary; services-counter stores. + * Company comes from the logged-in admin. Uuids leave as strings (Snowflake longs). Never log a lead's name, mobile or email. + */ +@Service +@RequiredArgsConstructor +@SuppressWarnings("unchecked") +public class AdminLeadService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + + public Map list(String q, int page, int size) { + String term = trimmed(q); + Map 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 p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_SEARCH), MAP, body).getBody(); + List> rows = p == null || p.get("content") == null ? List.of() : (List>) p.get("content"); + Map> users = new HashMap<>(); + Map out = new LinkedHashMap<>(); + out.put("content", rows.stream().map(r -> row(r, users)).toList()); + out.put("totalElements", p == null ? 0 : p.get("totalElements")); + return out; + } + + public Map get(String leadUuid) { + long id = parseOr(leadUuid, AdminLeadService::notFound); + Map d; + try { + d = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_DETAIL), MAP, caller().getCompanyId(), id).getBody(); + } catch (HttpClientErrorException.NotFound e) { + throw notFound(); + } + return detail(d); + } + + public Map update(String leadUuid, AdminLeadUpdateRequest r) { + User caller = caller(); + long id = parseOr(leadUuid, AdminLeadService::notFound); + String name = trimmed(r.name()); + String mobile = mobile(r.mobile()); + String email = email(r.email()); + List missing = new ArrayList<>(); + if (name == null) missing.add("name"); + if (mobile == null && email == null) { missing.add("mobile"); missing.add("email"); } + if (!missing.isEmpty()) throw required(missing); + maxLength("name", name, 100); + maxLength("email", email, 254); + String companyName = maxLength("companyName", trimmed(r.companyName()), 150); + String jobTitle = maxLength("jobTitle", trimmed(r.jobTitle()), 100); + String notes = maxLength("notes", trimmed(r.notes()), 2000); + + Map body = new LinkedHashMap<>(); + body.put("companyId", caller.getCompanyId()); + body.put("leadUuid", id); + body.put("name", name); + body.put("mobileE164", mobile); + body.put("email", email); + body.put("companyName", companyName); + body.put("jobTitle", jobTitle); + body.put("notes", notes); + body.put("doneBy", caller.getUsername()); + try { + return detail(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody()); + } catch (HttpClientErrorException.NotFound e) { + throw notFound(); + } + } + + /** Digits to match against the stored E.164 mobile, or null when the term is not a phone-like number. */ + private static String mobileDigits(String q) { + if (q == null) return null; + String d = q.replaceAll("[\\s\\-()]", ""); + if (d.startsWith("+")) d = d.substring(1); + if (!d.matches("\\d+")) return null; + d = d.startsWith("60") ? d.substring(2) : d.startsWith("0") ? d.substring(1) : d; + return d.isEmpty() ? null : d; + } + + private Map row(Map d, Map> users) { + Map m = new LinkedHashMap<>(); + m.put("leadUuid", str(d.get("leadUuid"))); + m.put("name", d.get("name")); + m.put("mobile", d.get("mobileE164")); + m.put("email", d.get("email")); + m.put("companyName", d.get("companyName")); + m.put("jobTitle", d.get("jobTitle")); + m.put("eventCount", d.get("eventCount")); + Map lastEvent = null; + if (d.get("lastEventUuid") != null) { + lastEvent = new LinkedHashMap<>(); + lastEvent.put("uuid", str(d.get("lastEventUuid"))); + lastEvent.put("name", d.get("lastEventName")); + } + m.put("lastEvent", lastEvent); + m.put("lastCapturedAt", d.get("lastCapturedAt")); + m.put("latestSalesperson", salesperson(d.get("latestSalespersonUserId"), users)); + return m; + } + + private Map detail(Map d) { + Map> users = new HashMap<>(); + Map m = new LinkedHashMap<>(); + m.put("leadUuid", str(d.get("leadUuid"))); + m.put("name", d.get("name")); + m.put("mobile", d.get("mobileE164")); + m.put("email", d.get("email")); + m.put("companyName", d.get("companyName")); + m.put("jobTitle", d.get("jobTitle")); + m.put("notes", d.get("notes")); + m.put("createdAt", d.get("createdAt")); + m.put("updatedAt", d.get("updatedAt")); + m.put("updatedBy", d.get("updatedBy")); + List> history = d.get("history") == null ? List.of() : (List>) d.get("history"); + m.put("history", history.stream().map(h -> { + Map e = new LinkedHashMap<>(); + e.put("eventLeadUuid", str(h.get("eventLeadUuid"))); + e.put("eventUuid", str(h.get("eventUuid"))); + e.put("eventName", h.get("eventName")); + e.put("eventStart", h.get("eventStart")); + e.put("eventEnd", h.get("eventEnd")); + e.put("leadType", h.get("leadType")); + e.put("salesperson", salesperson(h.get("salespersonUserId"), users)); + e.put("temperature", h.get("temperature")); + e.put("status", h.get("status")); + e.put("capturedAt", h.get("capturedAt")); + return e; + }).toList()); + List> shared = d.get("sharedContacts") == null ? List.of() : (List>) d.get("sharedContacts"); + m.put("sharedContacts", shared.stream().map(s -> { + Map e = new LinkedHashMap<>(); + e.put("leadUuid", str(s.get("leadUuid"))); + e.put("name", s.get("name")); + e.put("sameMobile", s.get("sameMobile")); + e.put("sameEmail", s.get("sameEmail")); + return e; + }).toList()); + return m; + } + + /** {id, name} or null; one user lookup per distinct id per request. */ + private Map salesperson(Object id, Map> users) { + if (!(id instanceof Number n)) return null; + Map u = users.computeIfAbsent(n.longValue(), uid -> + restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, uid).getBody()); + return Map.of("id", n.longValue(), "name", u == null ? String.valueOf(n) : String.valueOf(u.get("name"))); + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null); + return caller; + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } + + private static CodedResponseStatusException notFound() { + return error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java index 5f54f2e..25e35bb 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java @@ -21,6 +21,13 @@ public @interface AdminModule { String[] value(); + /** + * Modules the caller must hold in addition to the any-of {@link #value()}: every one of them, each checked like + * {@code value}. Super-admin still passes; {@link #ANY_ADMIN} ignores it. A method-level annotation + * replaces the class-level one entirely, {@code also} included; the two never combine. + */ + String[] also() default {}; + /** * Lets an admin whose first-login password change is pending ({@code login = N}) through. Only * for the first-login and logout handlers; every other admin handler answers 403 while pending. diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java index 252e6a2..2f38ac9 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java @@ -261,7 +261,12 @@ public class AppAccessAspect { boolean granted = false; if (declared != null) { try { - granted = AdminModuleAccess.grantedAny(restTemplateUtil, roleIds, declared.value()); + // Assigned only after every lookup returns, so a lookup that throws part-way never leaves access granted. + boolean all = AdminModuleAccess.grantedAny(restTemplateUtil, roleIds, declared.value()); + for (String required : declared.also()) { + all = all && AdminModuleAccess.grantedAny(restTemplateUtil, roleIds, required); + } + granted = all; } catch (Exception ex) { log.error("[AppAccessAspect] admin module lookup failed, failing closed: {}", ex.getClass().getSimpleName()); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadControllerTest.java new file mode 100644 index 0000000..cb24c97 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadControllerTest.java @@ -0,0 +1,72 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest; +import com.solvway.mobile.api.service.AdminLeadService; +import com.solvway.mobile.api.useraccess.AdminModule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +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 java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminLeadControllerTest { + + @Mock private AdminLeadService leads; + @InjectMocks private AdminLeadController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + private static Method handler(String name) { + return Arrays.stream(AdminLeadController.class.getDeclaredMethods()).filter(m -> m.getName().equals(name)).findFirst().orElseThrow(); + } + + @Test + void readsNeedBoLeads_editNeedsBoLeadsEditAndBoLeads() { + for (String n : new String[]{"list", "get", "update"}) assertThat(handler(n).isAnnotationPresent(AppAuth.class)).as(n).isTrue(); + assertThat(handler("list").getAnnotation(AdminModule.class).value()).containsExactly("BO_LEADS"); + assertThat(handler("get").getAnnotation(AdminModule.class).value()).containsExactly("BO_LEADS"); + AdminModule edit = handler("update").getAnnotation(AdminModule.class); + assertThat(edit.value()).containsExactly("BO_LEADS_EDIT"); + assertThat(edit.also()).containsExactly("BO_LEADS"); + } + + @Test + void listDefaultsPagingAndPassesQuery() throws Exception { + when(leads.list("ai", 0, 20)).thenReturn(Map.of("content", java.util.List.of(), "totalElements", 0)); + mvc.perform(get("/api/admin/leads").param("q", "ai")).andExpect(status().isOk()) + .andExpect(content().json("{\"content\":[],\"totalElements\":0}")); + } + + @Test + void getAndPut() throws Exception { + when(leads.get("42")).thenReturn(Map.of("leadUuid", "42")); + mvc.perform(get("/api/admin/leads/42")).andExpect(status().isOk()).andExpect(content().json("{\"leadUuid\":\"42\"}")); + when(leads.update(org.mockito.ArgumentMatchers.eq("42"), any(AdminLeadUpdateRequest.class))).thenReturn(Map.of("leadUuid", "42")); + mvc.perform(put("/api/admin/leads/42").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"A\",\"mobile\":\"012\"}")) + .andExpect(status().isOk()); + verify(leads).update("42", new AdminLeadUpdateRequest("A", "012", null, null, null, null)); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceTest.java new file mode 100644 index 0000000..05044c7 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadServiceTest.java @@ -0,0 +1,267 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +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.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.HashMap; +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 AdminLeadServiceTest { + + private static final String SEARCH = "/counter/lead/search"; + private static final String DETAIL = "/counter/lead/detail/{companyId}/{leadUuid}"; + private static final String UPDATE = "/counter/lead/update"; + private static final String USER = "/user/findById/{id}"; + private static final long LEAD = 3312853897040846848L; + private static final long EV = 3312726793093644288L; + private static final long EL = 3312853897594494976L; + private static final long COMPANY = 5L; + + private RestTemplateCustomUtil rest; + private AdminLeadService service; + private MockedStatic http; + + @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(COMPANY); + when(auth.loadUserByToken("tok")).thenReturn(caller); + stubUser(21L, "Sales One"); + stubUser(22L, "Sales Two"); + when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0))); + when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(i.getArgument(2))); + } + + @AfterEach + void close() { http.close(); } + + private void stubUser(long id, String name) { + Map 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 Map searched(String q) { + service.list(q, 2, 10); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), body.capture()); + return (Map) body.getValue(); + } + + // --- list --- + + @Test + void list_sendsCompanyPagingAndTrimmedQuery() { + Map b = searched(" aisyah "); + assertThat(b).containsEntry("companyId", COMPANY).containsEntry("q", "aisyah").containsEntry("page", 2).containsEntry("size", 10) + .containsEntry("mobileDigits", null); + } + + @Test + void list_blankQueryIsNull() { + assertThat(searched(" ")).containsEntry("q", null).containsEntry("mobileDigits", null); + } + + @Test + void list_digitsKey() { + assertThat(searched("012-345 6701")).containsEntry("mobileDigits", "123456701"); + } + + @Test + void list_digitsKeyDropsPlusAndCountryCode() { + assertThat(searched("+60 12-345 6701")).containsEntry("mobileDigits", "123456701"); + } + + @Test + void list_digitsKeyShortCountryCodePrefix() { + assertThat(searched("6012")).containsEntry("mobileDigits", "12"); + } + + @Test + void list_textHasNoDigitsKey() { + assertThat(searched("aisyah")).containsEntry("mobileDigits", null); + } + + @Test + void list_mapsRowsWithStringUuidsAndResolvesRepeatedSalespersonOnce() { + Map r1 = new HashMap<>(Map.of("leadUuid", LEAD, "name", "Aisyah", "mobileE164", "+60123456701", "email", "a@x.test", + "eventCount", 2, "lastEventUuid", EV, "lastEventName", "Fair", "lastCapturedAt", "2027-01-15T10:00:00", + "latestSalespersonUserId", 22L)); + Map r2 = new HashMap<>(Map.of("leadUuid", LEAD + 1, "name", "Bob", "eventCount", 0, "latestSalespersonUserId", 22L)); + when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(r1, r2), "totalElements", 7))); + Map out = service.list(null, 0, 20); + List> rows = (List>) out.get("content"); + assertThat(out.get("totalElements")).isEqualTo(7); + assertThat(rows.get(0)).containsEntry("leadUuid", String.valueOf(LEAD)).containsEntry("mobile", "+60123456701") + .containsEntry("eventCount", 2).containsEntry("lastCapturedAt", "2027-01-15T10:00:00") + .containsEntry("lastEvent", Map.of("uuid", String.valueOf(EV), "name", "Fair")) + .containsEntry("latestSalesperson", Map.of("id", 22L, "name", "Sales Two")); + assertThat(rows.get(1)).containsEntry("lastEvent", null).containsEntry("latestSalesperson", Map.of("id", 22L, "name", "Sales Two")); + verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(22L)); + } + + @Test + void list_rowWithoutSalespersonHasNull() { + when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(new HashMap<>(Map.of("leadUuid", LEAD, "name", "A"))), "totalElements", 1))); + List> rows = (List>) service.list(null, 0, 20).get("content"); + assertThat(rows.get(0)).containsEntry("latestSalesperson", null); + } + + // --- detail --- + + private Map detail() { + Map h = new HashMap<>(Map.of("eventLeadUuid", EL, "eventUuid", EV, "eventName", "Fair", "leadType", "NEW", + "salespersonUserId", 21L, "temperature", "HOT", "status", "OPEN", "capturedAt", "2027-01-15T10:00:00")); + h.put("eventStart", "2027-01-15T00:00:00"); + h.put("eventEnd", "2027-01-17T23:59:59"); + Map h2 = new HashMap<>(Map.of("eventLeadUuid", EL + 1, "eventUuid", EV, "salespersonUserId", 21L)); + Map d = new HashMap<>(Map.of("leadUuid", LEAD, "name", "Aisyah", "mobileE164", "+60123456701", "email", "a@x.test", + "companyName", "Acme", "jobTitle", "Buyer", "notes", "n", "createdAt", "c", "updatedAt", "u", "updatedBy", "sales1")); + d.put("history", List.of(h, h2)); + d.put("sharedContacts", List.of(Map.of("leadUuid", LEAD + 5, "name", "Twin", "sameMobile", true, "sameEmail", false))); + return d; + } + + @Test + void get_mapsHistoryAndSharedContacts() { + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(COMPANY), eq(LEAD))).thenReturn(ResponseEntity.ok(detail())); + Map v = service.get(String.valueOf(LEAD)); + assertThat(v).containsEntry("leadUuid", String.valueOf(LEAD)).containsEntry("mobile", "+60123456701") + .containsEntry("companyName", "Acme").containsEntry("notes", "n").containsEntry("updatedBy", "sales1"); + List> history = (List>) v.get("history"); + assertThat(history.get(0)).containsEntry("eventLeadUuid", String.valueOf(EL)).containsEntry("eventUuid", String.valueOf(EV)) + .containsEntry("eventName", "Fair").containsEntry("eventStart", "2027-01-15T00:00:00").containsEntry("leadType", "NEW") + .containsEntry("salesperson", Map.of("id", 21L, "name", "Sales One")).containsEntry("temperature", "HOT") + .containsEntry("status", "OPEN").containsEntry("capturedAt", "2027-01-15T10:00:00"); + verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L)); + assertThat((List>) v.get("sharedContacts")).containsExactly( + Map.of("leadUuid", String.valueOf(LEAD + 5), "name", "Twin", "sameMobile", true, "sameEmail", false)); + } + + @Test + void get_unparsableUuidIs404() { + assertCoded(() -> service.get("abc"), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null); + } + + @Test + void get_counter404Is404() { + when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(COMPANY), eq(LEAD))) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); + assertCoded(() -> service.get(String.valueOf(LEAD)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null); + } + + // --- update --- + + private static AdminLeadUpdateRequest req(String name, String mobile, String email) { + return new AdminLeadUpdateRequest(name, mobile, email, null, null, null); + } + + private void assertCoded(Runnable r, HttpStatus status, String code, String field) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + if (field != null) assertThat((Map) e.getBody().getProperties().get("details")).containsEntry("field", field); + }); + } + + @Test + void update_unparsableUuidIs404() { + assertCoded(() -> service.update("abc", req("A", "0123456701", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null); + } + + @Test + void update_counter404Is404() { + when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any())) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); + assertCoded(() -> service.update(String.valueOf(LEAD), req("A", "012-345 6701", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null); + } + + @Test + void update_nameRequired() { + assertThatThrownBy(() -> service.update(String.valueOf(LEAD), req(" ", "012-345 6701", null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD"); + assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("name")); + }); + } + + @Test + void update_contactRequired() { + assertThatThrownBy(() -> service.update(String.valueOf(LEAD), req("A", " ", null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD"); + assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("mobile", "email")); + }); + } + + @Test + void update_nameAndContactMissingListsNameFirst() { + assertThatThrownBy(() -> service.update(String.valueOf(LEAD), req(null, null, null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, + e -> assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("name", "mobile", "email"))); + } + + @Test + void update_invalidMobileAndEmail() { + assertCoded(() -> service.update(String.valueOf(LEAD), req("A", "12", null)), HttpStatus.BAD_REQUEST, "INVALID_MOBILE", "mobile"); + assertCoded(() -> service.update(String.valueOf(LEAD), req("A", null, "nope")), HttpStatus.BAD_REQUEST, "INVALID_EMAIL", "email"); + } + + @Test + void update_tooLong() { + String ok = "0123456701"; + assertCoded(() -> service.update(String.valueOf(LEAD), req("x".repeat(101), ok, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "name"); + assertCoded(() -> service.update(String.valueOf(LEAD), req("A", null, "a".repeat(250) + "@x.test")), HttpStatus.BAD_REQUEST, "TOO_LONG", "email"); + assertCoded(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("A", ok, null, "x".repeat(151), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "companyName"); + assertCoded(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("A", ok, null, null, "x".repeat(101), null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "jobTitle"); + assertCoded(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("A", ok, null, null, null, "x".repeat(2001))), HttpStatus.BAD_REQUEST, "TOO_LONG", "notes"); + } + + @Test + void update_normalisesAndSendsDoneBy() { + service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest(" Aisyah ", "012-345 6701", " Aisyah@Example.TEST ", " ", " Buyer ", "")); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("companyId", COMPANY).containsEntry("leadUuid", LEAD) + .containsEntry("name", "Aisyah").containsEntry("mobileE164", "+60123456701").containsEntry("email", "aisyah@example.test") + .containsEntry("companyName", null).containsEntry("jobTitle", "Buyer").containsEntry("notes", null) + .containsEntry("doneBy", "sales1"); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java index a6be84b..42dea6e 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java @@ -96,6 +96,13 @@ class AppAccessAspectAdminTest { } } + static class Also { + @AppAuth + @AdminModule(value = "BO_LEADS_EDIT", also = "BO_LEADS") + public void edit() { + } + } + @AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true) static class PendingAtClassLevel { @AppAuth @@ -339,4 +346,70 @@ class AppAccessAspectAdminTest { expect(HttpStatus.FORBIDDEN); } } + + private void alsoModules() { + when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO"))) + .thenReturn(ResponseEntity.ok(List.of( + Map.of("name", "BO_LEADS", "roles", List.of(Map.of("id", 5), Map.of("id", 6), Map.of("id", 2))), + Map.of("name", "BO_LEADS_EDIT", "roles", List.of(Map.of("id", 6), Map.of("id", 7), Map.of("id", 2)))))); + } + + @Test + void also_callerMissingTheAlsoModule_isForbidden() throws Throwable { + alsoModules(); + target(Also.class, "edit"); + when(guard.check(TOK, false)).thenReturn(admin(7L)); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } + + @Test + void also_callerHoldingBothModules_isAllowed() throws Throwable { + alsoModules(); + target(Also.class, "edit"); + when(guard.check(TOK, false)).thenReturn(admin(6L)); + when(joinPoint.proceed()).thenReturn("ok"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok"); + } + } + + @Test + void also_superAdminPasses() throws Throwable { + target(Also.class, "edit"); + when(guard.check(TOK, false)).thenReturn(admin(1L)); + when(joinPoint.proceed()).thenReturn("ok"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok"); + } + } + + @Test + void also_injectedRoleAdmin2Alone_grantsNothing() throws Throwable { + alsoModules(); + target(Also.class, "edit"); + when(guard.check(TOK, false)).thenReturn(admin(2L)); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } + + @Test + void also_lookupFailingAfterTheFirstModuleGranted_failsClosed() throws Throwable { + // The first lookup grants BO_LEADS_EDIT; the also lookup then fails. A thrown lookup must never leave access granted. + when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO"))) + .thenReturn(ResponseEntity.ok(List.of(Map.of("name", "BO_LEADS_EDIT", "roles", List.of(Map.of("id", 6)))))) + .thenThrow(new IllegalStateException("system down")); + target(Also.class, "edit"); + when(guard.check(TOK, false)).thenReturn(admin(6L)); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } } -- 2.54.1 From eab4053c06cd1e959fc7159ae0f09c3d16248fc4 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 16:32:56 +0800 Subject: [PATCH 07/11] 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 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-lead-listing-export/design.md | 2 +- .../changes/add-lead-listing-export/tasks.md | 2 +- solvway-mobile-api/pom.xml | 6 + .../admin/AdminEventLeadExportController.java | 44 ++++ .../controller/admin/AdminLeadController.java | 17 ++ .../api/service/AdminEventLeadService.java | 55 ++++- .../mobile/api/service/AdminLeadService.java | 39 ++- .../mobile/api/service/LeadExport.java | 79 ++++++ .../admin/AdminLeadExportControllerTest.java | 78 ++++++ .../api/service/AdminEventLeadExportTest.java | 226 ++++++++++++++++++ .../api/service/AdminLeadExportTest.java | 202 ++++++++++++++++ 11 files changed, 729 insertions(+), 21 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadExportController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/LeadExport.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadExportControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadExportTest.java diff --git a/openspec/changes/add-lead-listing-export/design.md b/openspec/changes/add-lead-listing-export/design.md index 220e103..37ce7d5 100644 --- a/openspec/changes/add-lead-listing-export/design.md +++ b/openspec/changes/add-lead-listing-export/design.md @@ -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`. diff --git a/openspec/changes/add-lead-listing-export/tasks.md b/openspec/changes/add-lead-listing-export/tasks.md index 5b1b30d..61bcf4c 100644 --- a/openspec/changes/add-lead-listing-export/tasks.md +++ b/openspec/changes/add-lead-listing-export/tasks.md @@ -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. diff --git a/solvway-mobile-api/pom.xml b/solvway-mobile-api/pom.xml index 3e451a0..7cf811f 100644 --- a/solvway-mobile-api/pom.xml +++ b/solvway-mobile-api/pom.xml @@ -107,6 +107,12 @@ groovy 3.0.8 + + + org.apache.poi + poi-ooxml + 4.1.0 + diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadExportController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadExportController.java new file mode 100644 index 0000000..6bb49bb --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadExportController.java @@ -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 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 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); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java index c9d8c10..05a7198 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLeadController.java @@ -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 export(@RequestParam(required = false) String q) { + return xlsx("leads", adminLeadService.export(q)); + } + + private static ResponseEntity 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}") diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java index d70a4b1..f55bff6 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -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 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 p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), MAP, body).getBody(); + Map p = search(caller, event, salespersonId, temperature, status, interestId, leadType, page, size); List> rows = p == null || p.get("content") == null ? List.of() : (List>) p.get("content"); Map> interests = rows.isEmpty() ? Map.of() : interests(caller.getCompanyId()); Map> 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> users = new HashMap<>(); + Map>[] 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 m = view(r, interests[0], users); + Map sp = (Map) 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>) 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 search(User caller, Event event, Long salespersonId, String temperature, String status, Long interestId, + String leadType, int page, int size) { + Map 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 get(String eventUuid, String eventLeadUuid) { User caller = caller(); return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId()); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java index ecfa460..11fb23c 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLeadService.java @@ -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 list(String q, int page, int size) { - String term = trimmed(q); - Map 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 p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_SEARCH), MAP, body).getBody(); + Map p = search(caller().getCompanyId(), trimmed(q), page, size); List> rows = p == null || p.get("content") == null ? List.of() : (List>) p.get("content"); Map> users = new HashMap<>(); Map 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> 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 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) m).get("name"); + } + + private Map search(Long companyId, String term, int page, int size) { + Map 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 get(String leadUuid) { long id = parseOr(leadUuid, AdminLeadService::notFound); Map d; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/LeadExport.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/LeadExport.java new file mode 100644 index 0000000..df4272c --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/LeadExport.java @@ -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 headers, + IntFunction> fetch, Function, List> cells) { + Map 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 page = p == 0 ? first : fetch.apply(p); + List> rows = page == null || page.get("content") == null ? List.of() : (List>) page.get("content"); + for (Map raw : rows) { + Row row = sheet.createRow(r++); + List 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(); + } + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadExportControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadExportControllerTest.java new file mode 100644 index 0000000..1a4d39a --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLeadExportControllerTest.java @@ -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\""))); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java new file mode 100644 index 0000000..a674297 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java @@ -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 http; + private ListAppender 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 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 row(int i) { + Map 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 b = i.getArgument(2); + int page = (Integer) b.get("page"), size = (Integer) b.get("size"); + List> 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 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 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 bodies = ArgumentCaptor.forClass(Object.class); + verify(rest, times(3)).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), bodies.capture()); + for (Object b : bodies.getAllValues()) { + assertThat((Map) 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 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"); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadExportTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadExportTest.java new file mode 100644 index 0000000..730090f --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLeadExportTest.java @@ -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 http; + private ListAppender 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 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 row(int i) { + Map 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 b = i.getArgument(2); + int page = (Integer) b.get("page"), size = (Integer) b.get("size"); + List> 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 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 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 bodies = ArgumentCaptor.forClass(Object.class); + verify(rest, times(3)).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), bodies.capture()); + for (Object b : bodies.getAllValues()) { + assertThat((Map) b).containsEntry("size", 100).containsEntry("q", "acme"); + } + assertThat(bodies.getAllValues().stream().map(b -> ((Map) 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 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"); + } +} -- 2.54.1 From 82b6943474b5f766b63f6b4216f8ac73299f5fca Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 16:53:44 +0800 Subject: [PATCH 08/11] feat(admin-portal): leads listing and lead detail Lead Listing with search and server paging, lead detail with event history, shared-contact warning and an edit form under BO_LEADS_EDIT, and a View lead link from the event lead edit page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-lead-listing-export/tasks.md | 2 +- .../app/api/leads/[[...path]]/route.test.ts | 58 +++++ .../app/api/leads/[[...path]]/route.ts | 23 ++ .../[eventUuid]/[eventLeadUuid]/page.tsx | 7 + .../[eventLeadUuid]/view-lead.test.tsx | 47 ++++ .../app/leads/[leadUuid]/page.test.tsx | 218 ++++++++++++++++++ .../app/leads/[leadUuid]/page.tsx | 216 +++++++++++++++++ solvway-admin-portal/app/leads/page.test.tsx | 71 ++++++ solvway-admin-portal/app/leads/page.tsx | 100 ++++++++ .../app/lib/i18n/defaultMessages.ts | 11 + .../app/lib/routeModules.test.ts | 3 +- solvway-admin-portal/app/lib/routeModules.ts | 1 + .../app/lib/services/adminLeads.test.ts | 37 +++ .../app/lib/services/adminLeads.ts | 17 ++ solvway-admin-portal/app/lib/types.ts | 52 +++++ 15 files changed, 861 insertions(+), 2 deletions(-) create mode 100644 solvway-admin-portal/app/api/leads/[[...path]]/route.test.ts create mode 100644 solvway-admin-portal/app/api/leads/[[...path]]/route.ts create mode 100644 solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/view-lead.test.tsx create mode 100644 solvway-admin-portal/app/leads/[leadUuid]/page.test.tsx create mode 100644 solvway-admin-portal/app/leads/[leadUuid]/page.tsx create mode 100644 solvway-admin-portal/app/leads/page.test.tsx create mode 100644 solvway-admin-portal/app/leads/page.tsx create mode 100644 solvway-admin-portal/app/lib/services/adminLeads.test.ts create mode 100644 solvway-admin-portal/app/lib/services/adminLeads.ts diff --git a/openspec/changes/add-lead-listing-export/tasks.md b/openspec/changes/add-lead-listing-export/tasks.md index 61bcf4c..d4f007f 100644 --- a/openspec/changes/add-lead-listing-export/tasks.md +++ b/openspec/changes/add-lead-listing-export/tasks.md @@ -71,7 +71,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially ## 4. Portal -- [ ] 4.1 Add the Lead Listing and lead detail (design decision 6): +- [x] 4.1 Add the Lead Listing and lead detail (design decision 6): - the leads data layer: route `app/api/leads/[...path]`, service, types, and `/leads` mapped to `BO_LEADS`; - the `/leads` listing with search; - the `/leads/[leadUuid]` detail page, with an edit form when the user has `BO_LEADS_EDIT`, the shared-contact warning, the event history and not-found; diff --git a/solvway-admin-portal/app/api/leads/[[...path]]/route.test.ts b/solvway-admin-portal/app/api/leads/[[...path]]/route.test.ts new file mode 100644 index 0000000..763d618 --- /dev/null +++ b/solvway-admin-portal/app/api/leads/[[...path]]/route.test.ts @@ -0,0 +1,58 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET, PUT } from "./route"; + +type Req = Parameters[0]; +const ctx = (...path: string[]) => ({ params: Promise.resolve({ path: path.length ? path : undefined }) }); +const req = (url: string, init?: RequestInit) => new Request(`http://localhost${url}`, init) as unknown as Req; + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset(); + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } }); +}); + +describe("/api/leads/[[...path]]", () => { + it("returns 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await GET(req("/api/leads"), ctx()); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("forwards the list call (no path) with the query string", async () => { + const res = await GET(req("/api/leads?q=ann&page=0&size=20"), ctx()); + expect(res.status).toBe(200); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads?q=ann&page=0&size=20", { token: "jwt-abc" }); + }); + + it("forwards the detail GET and the PUT body", async () => { + await GET(req("/api/leads/l-1"), ctx("l-1")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/l-1", { token: "jwt-abc" }); + await PUT(req("/api/leads/l-1", { method: "PUT", body: JSON.stringify({ name: "Ann" }) }), ctx("l-1")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/l-1", { method: "PUT", body: { name: "Ann" }, token: "jwt-abc" }); + }); + + it("rejects dot segments so the proxy cannot leave /api/admin/leads", async () => { + const res = await GET(req("/api/leads/x"), ctx("..", "users")); + expect(res.status).toBe(400); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("encodes path segments", async () => { + await GET(req("/api/leads/a"), ctx("a/b")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/a%2Fb", { token: "jwt-abc" }); + }); + + it("passes upstream 404 with its code", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Lead not found", status: 404, code: "LEAD_NOT_FOUND" }); + const res = await GET(req("/api/leads/zz"), ctx("zz")); + expect(res.status).toBe(404); + expect(((await res.json()) as Record).code).toBe("LEAD_NOT_FOUND"); + }); +}); diff --git a/solvway-admin-portal/app/api/leads/[[...path]]/route.ts b/solvway-admin-portal/app/api/leads/[[...path]]/route.ts new file mode 100644 index 0000000..f8237f5 --- /dev/null +++ b/solvway-admin-portal/app/api/leads/[[...path]]/route.ts @@ -0,0 +1,23 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +// One proxy for every /api/admin/leads endpoint; mobile-api owns validation and the BO_LEADS guards. +type Ctx = { params: Promise<{ path?: string[] }> }; + +async function forward(req: NextRequest, { params }: Ctx, method?: "PUT") { + const token = await getToken(); + if (!token) return unauthorized(); + const { path = [] } = await params; // [[...path]]: the list call has no segment + if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path."); + const target = `/api/admin/leads${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`; + const result = method + ? await callMobileApi(target, { method, body: await req.json().catch(() => ({})), token }) + : await callMobileApi(target, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} + +export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx); +export const PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT"); diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx index dbccea6..5bc3ed0 100644 --- a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx @@ -9,6 +9,7 @@ import { DatePicker } from "@/app/components/ui/date-picker"; import { Label } from "@/app/components/ui/label"; import { PageHeader } from "@/app/components/ui/page-header"; import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states"; +import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { RequireModule } from "@/app/lib/RequireModule"; import { ApiError } from "@/app/lib/clientApi"; import { formatDmy } from "@/app/lib/date-input"; @@ -35,6 +36,7 @@ type LoadState = "loading" | "notFound" | "error" | Loaded; function EventLead() { const t = useT(); const router = useRouter(); + const { hasModule } = useAdminAuth(); const { eventUuid, eventLeadUuid } = useParams<{ eventUuid: string; eventLeadUuid: string }>(); const [state, setState] = useState("loading"); const [reloadKey, setReloadKey] = useState(0); @@ -145,6 +147,11 @@ function EventLead() { {lead.email &&

{lead.email}

} {lead.companyName &&

{lead.companyName}

} {lead.jobTitle &&

{lead.jobTitle}

} + {hasModule("BO_LEADS") && ( + + )}

{t("LeadCaptured")} {formatDmy(lead.capturedAt.slice(0, 10))}

diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/view-lead.test.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/view-lead.test.tsx new file mode 100644 index 0000000..08ee325 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/view-lead.test.tsx @@ -0,0 +1,47 @@ +import { render, screen } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ + getEventLead: vi.fn(), listEventSalespeople: vi.fn(), listEventLeadInterests: vi.fn(), useAdminAuth: vi.fn(), +})); +vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({ + ...(await importActual()), + getEventLead: mocks.getEventLead, + listEventSalespeople: mocks.listEventSalespeople, + listEventLeadInterests: mocks.listEventLeadInterests, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("next/navigation", async () => ({ + ...(await import("@/test/memoryRouter")).navigationMock, + useParams: () => ({ eventUuid: "evt-1", eventLeadUuid: "el-1" }), +})); + +import EventLeadPage from "./page"; + +const grant = (...modules: string[]) => + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => modules.includes(m) }); + +beforeEach(() => { + mocks.getEventLead.mockReset().mockResolvedValue({ + eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "l-1", name: "Ann Lead", mobile: null, email: "ann@x.com", + companyName: null, jobTitle: null, leadType: "NEW", salesperson: null, temperature: null, status: "OPEN", + interests: [], nextFollowUpDate: null, notes: null, capturedAt: "2026-11-20T09:30:00Z", + }); + mocks.listEventSalespeople.mockReset().mockResolvedValue([]); + mocks.listEventLeadInterests.mockReset().mockResolvedValue([]); +}); + +describe("EventLeadPage View lead link", () => { + it("links to the lead with BO_LEADS", async () => { + grant("BO_EVENT_LEADS", "BO_LEADS"); + render(); + expect(await screen.findByRole("link", { name: "View lead" })).toHaveAttribute("href", "/leads/l-1"); + }); + + it("hides the link without BO_LEADS", async () => { + grant("BO_EVENT_LEADS"); + render(); + await screen.findByLabelText("Status"); + expect(screen.queryByRole("link", { name: "View lead" })).toBeNull(); + }); +}); diff --git a/solvway-admin-portal/app/leads/[leadUuid]/page.test.tsx b/solvway-admin-portal/app/leads/[leadUuid]/page.test.tsx new file mode 100644 index 0000000..68c0b2a --- /dev/null +++ b/solvway-admin-portal/app/leads/[leadUuid]/page.test.tsx @@ -0,0 +1,218 @@ +import { render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ getLead: vi.fn(), updateLead: vi.fn(), useAdminAuth: vi.fn() })); +vi.mock("@/app/lib/services/adminLeads", async (importActual) => ({ + ...(await importActual()), + getLead: mocks.getLead, + updateLead: mocks.updateLead, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("next/navigation", async () => ({ + ...(await import("@/test/memoryRouter")).navigationMock, + useParams: () => ({ leadUuid: "l-1" }), +})); + +import { ApiError } from "@/app/lib/clientApi"; +import { memoryRouter } from "@/test/memoryRouter"; +import LeadPage from "./page"; + +const SERVER_MSG = "Server says: internal detail xyz"; +const apiError = (code: string, extra: Record = {}, status = 400) => + new ApiError(SERVER_MSG, status, { code, errors: [], details: {}, ...extra }); + +const LEAD = { + leadUuid: "l-1", name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: "Example Co", jobTitle: "CEO", + notes: "VIP", createdAt: "2026-11-01T00:00:00Z", updatedAt: "2026-11-02T00:00:00Z", updatedBy: "admin", + history: [ + { eventLeadUuid: "el-2", eventUuid: "e-2", eventName: "Penang Expo", eventStart: "2026-11-20T00:00:00", eventEnd: "2026-11-22T00:00:00", + leadType: "EXISTING", salesperson: null, temperature: "COLD", status: "OPEN", capturedAt: "2026-11-20T09:30:00Z" }, + { eventLeadUuid: "el-1", eventUuid: "e-1", eventName: "KL Food Fair", eventStart: "2026-10-05T00:00:00", eventEnd: "2026-10-06T00:00:00", + leadType: "NEW", salesperson: { id: 7, name: "Ali" }, temperature: "HOT", status: "WON", capturedAt: "2026-10-05T10:00:00Z" }, + ], + sharedContacts: [] as unknown[], +}; +const PAYLOAD = { name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: "Example Co", jobTitle: "CEO", notes: "VIP" }; + +const grant = (...modules: string[]) => + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => modules.includes(m) }); + +async function open(lead: Record = {}) { + mocks.getLead.mockResolvedValue({ ...LEAD, ...lead }); + render(); + await screen.findByText("Penang Expo"); + return userEvent.setup(); +} + +beforeEach(() => { + memoryRouter.reset("/leads/l-1"); + mocks.getLead.mockReset(); + mocks.updateLead.mockReset().mockResolvedValue(LEAD); + grant("BO_LEADS", "BO_LEADS_EDIT", "BO_EVENT_LEADS"); +}); + +describe("LeadPage", { timeout: 20000 }, () => { + it("renders NotAuthorized without BO_LEADS", () => { + grant("BO_LEADS_EDIT"); + render(); + expect(screen.getByTestId("not-authorized")).toBeInTheDocument(); + expect(mocks.getLead).not.toHaveBeenCalled(); + }); + + it("lists event history newest first with type, salesperson, temperature, status and dates", async () => { + await open(); + const cards = screen.getAllByTestId("history-card"); + expect(cards.map((c) => within(c).getByText(/Penang Expo|KL Food Fair/).textContent)).toEqual(["Penang Expo", "KL Food Fair"]); + const first = within(cards[1]); + expect(first.getByText("New")).toBeVisible(); + expect(first.getByText("Ali")).toBeVisible(); + expect(first.getByText("Hot")).toBeVisible(); + expect(first.getByText("Won")).toBeVisible(); + expect(first.getByText("05/10/2026 - 06/10/2026")).toBeVisible(); + expect(first.getByText("Captured 05/10/2026")).toBeVisible(); + }); + + it("links history cards to the event lead only with BO_EVENT_LEADS", async () => { + await open(); + expect(screen.getAllByTestId("history-card")[0].closest("a") ?? within(screen.getAllByTestId("history-card")[0]).getByRole("link")) + .toHaveAttribute("href", "/event-leads/e-2/el-2"); + }); + + it("shows plain history cards without BO_EVENT_LEADS", async () => { + grant("BO_LEADS"); + await open(); + expect(screen.getAllByTestId("history-card")).toHaveLength(2); + expect(screen.queryByRole("link", { name: /Penang Expo/ })).toBeNull(); + }); + + it("warns about a shared mobile and links the other lead", async () => { + await open({ sharedContacts: [{ leadUuid: "l-2", name: "Test Visitor Two", sameMobile: true, sameEmail: false }] }); + const alert = screen.getByRole("alert"); + expect(alert).toHaveTextContent("Same mobile as"); + expect(within(alert).getByRole("link", { name: "Test Visitor Two" })).toHaveAttribute("href", "/leads/l-2"); + }); + + it("shows no warning without shared contacts", async () => { + await open(); + expect(screen.queryByRole("alert")).toBeNull(); + }); + + it("prefills an edit form with phone-friendly inputs", async () => { + await open(); + const mobile = screen.getByLabelText("Mobile"); + expect(mobile).toHaveValue("+60123456701"); + expect(mobile).toHaveAttribute("type", "tel"); + expect(mobile).toHaveAttribute("inputmode", "tel"); + expect(mobile).toHaveAttribute("autocomplete", "tel"); + expect(screen.getByLabelText("Email")).toHaveAttribute("type", "email"); + expect(screen.getByLabelText("Notes")).toHaveValue("VIP"); + }); + + it("saves the exact payload and shows the returned values with a success message", async () => { + const user = await open(); + mocks.updateLead.mockResolvedValue({ ...LEAD, email: "aisyah@example.test", companyName: "Example Co Ltd" }); + await user.clear(screen.getByLabelText("Email")); + await user.type(screen.getByLabelText("Email"), " Aisyah@Example.TEST "); + await user.clear(screen.getByLabelText("Company")); + await user.type(screen.getByLabelText("Company"), "Example Co Ltd"); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(mocks.updateLead).toHaveBeenCalledWith("l-1", { ...PAYLOAD, email: "Aisyah@Example.TEST", companyName: "Example Co Ltd" }); + expect(await screen.findByText("Lead saved.")).toBeVisible(); + expect(screen.getByLabelText("Email")).toHaveValue("aisyah@example.test"); + expect(memoryRouter.push).not.toHaveBeenCalled(); + }); + + it("sends blank optional fields as null", async () => { + const user = await open(); + await user.clear(screen.getByLabelText("Company")); + await user.clear(screen.getByLabelText("Notes")); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(mocks.updateLead).toHaveBeenCalledWith("l-1", { ...PAYLOAD, companyName: null, notes: null }); + }); + + it("shows an invalid mobile under the Mobile field with the mapped text", async () => { + const user = await open(); + mocks.updateLead.mockRejectedValue(apiError("INVALID_MOBILE", { details: { field: "mobile" } })); + await user.click(screen.getByRole("button", { name: "Save" })); + const mobile = await screen.findByLabelText("Mobile"); + expect(mobile).toHaveAttribute("aria-invalid", "true"); + const err = document.getElementById(mobile.getAttribute("aria-describedby")!)!; + expect(err).toHaveTextContent("Enter a valid mobile number."); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it("marks every field listed by REQUIRED_FIELD", async () => { + const user = await open(); + mocks.updateLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name", "email"] })); + await user.click(screen.getByRole("button", { name: "Save" })); + await screen.findAllByText("This field is required."); + expect(screen.getByLabelText("Name")).toHaveAttribute("aria-invalid", "true"); + expect(screen.getByLabelText("Email")).toHaveAttribute("aria-invalid", "true"); + expect(screen.getByLabelText("Mobile")).not.toHaveAttribute("aria-invalid"); + }); + + it("never fails silently: unknown codes show a form-level message", async () => { + const user = await open(); + mocks.updateLead.mockRejectedValue(apiError("SOMETHING_ELSE", {}, 500)); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("Could not save the lead. Please try again.")).toBeVisible(); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it("is read-only without BO_LEADS_EDIT", async () => { + grant("BO_LEADS"); + await open(); + expect(screen.queryByRole("button", { name: "Save" })).toBeNull(); + expect(screen.queryByRole("textbox")).toBeNull(); + expect(screen.getByText("+60123456701")).toBeVisible(); + expect(screen.getByText("a@x.test")).toBeVisible(); + expect(screen.getByText("VIP")).toBeVisible(); + }); + + it("shows not-found with a Back link on LEAD_NOT_FOUND", async () => { + mocks.getLead.mockRejectedValue(apiError("LEAD_NOT_FOUND", {}, 404)); + render(); + expect(await screen.findByText("Lead not found")).toBeVisible(); + expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/leads"); + }); + + it("shows an error state with retry on other load failures", async () => { + mocks.getLead.mockRejectedValueOnce(apiError("BOOM", {}, 500)); + render(); + expect(await screen.findByText("Failed to load the lead")).toBeVisible(); + mocks.getLead.mockResolvedValue(LEAD); + await userEvent.click(screen.getByRole("button", { name: /retry/i })); + expect(await screen.findByText("Penang Expo")).toBeVisible(); + }); + + it("shows the shared-contact warning returned by a save", async () => { + const user = await open(); + mocks.updateLead.mockResolvedValue({ ...LEAD, sharedContacts: [{ leadUuid: "l-9", name: "Other Person", sameMobile: true, sameEmail: false }] }); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByRole("link", { name: "Other Person" })).toHaveAttribute("href", "/leads/l-9"); + }); + + it("clears the saved message once the user edits again", async () => { + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("Lead saved.")).toBeVisible(); + await user.type(screen.getByLabelText("Notes"), "!"); + expect(screen.queryByText("Lead saved.")).toBeNull(); + }); + + it("names each read-only value by its label", async () => { + grant("BO_LEADS"); + await open(); + const email = screen.getByText("a@x.test"); + expect(email.tagName).toBe("DD"); + expect(email.previousElementSibling?.tagName).toBe("DT"); + expect(email.previousElementSibling).toHaveTextContent("Email"); + }); + + it("hides the dates line of an event without dates", async () => { + await open({ history: [{ ...LEAD.history[0], eventStart: null, eventEnd: null }] }); + const card = screen.getByTestId("history-card"); + expect(card.textContent).not.toMatch(/\s-\s/); + }); +}); diff --git a/solvway-admin-portal/app/leads/[leadUuid]/page.tsx b/solvway-admin-portal/app/leads/[leadUuid]/page.tsx new file mode 100644 index 0000000..3198c69 --- /dev/null +++ b/solvway-admin-portal/app/leads/[leadUuid]/page.tsx @@ -0,0 +1,216 @@ +"use client"; + +import { useEffect, useState, type FormEvent } from "react"; +import { useParams } from "next/navigation"; +import Link from "next/link"; +import { Alert } from "@/app/components/ui/alert"; +import { Badge } from "@/app/components/ui/badge"; +import { Button } from "@/app/components/ui/button"; +import { Label } from "@/app/components/ui/label"; +import { PageHeader } from "@/app/components/ui/page-header"; +import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states"; +import { useAdminAuth } from "@/app/lib/AdminAuthContext"; +import { RequireModule } from "@/app/lib/RequireModule"; +import { ApiError } from "@/app/lib/clientApi"; +import { formatDmy } from "@/app/lib/date-input"; +import { getLead, updateLead } from "@/app/lib/services/adminLeads"; +import type { LeadDetail } from "@/app/lib/types"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +const TEMPERATURES: Record = { HOT: "LeadHot", WARM: "LeadWarm", COLD: "LeadCold" }; +const STATUSES: Record = { OPEN: "LeadOpen", CONTACTED: "LeadContacted", QUALIFIED: "LeadQualified", WON: "LeadWon", LOST: "LeadLost" }; +const CODE_MESSAGE: Record = { + REQUIRED_FIELD: "LeadErrRequired", + TOO_LONG: "LeadErrTooLong", + INVALID_MOBILE: "LeadErrInvalidMobile", + INVALID_EMAIL: "LeadErrInvalidEmail", +}; +// Codes that name their field themselves when the server omits details.field. +const IMPLIED_FIELD: Record = { INVALID_MOBILE: "mobile", INVALID_EMAIL: "email" }; +const FIELDS = [ + ["name", "LeadName"], ["mobile", "LeadMobile"], ["email", "Email"], ["companyName", "LeadCompany"], ["jobTitle", "LeadJobTitle"], ["notes", "LeadNotes"], +] as const; +type Field = (typeof FIELDS)[number][0]; +const INPUT_CLASS = "min-h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30"; +const INPUT_ATTRS: Partial>> = { + mobile: { type: "tel", inputMode: "tel", autoComplete: "tel" }, + email: { type: "email", autoComplete: "email" }, +}; +const TALL = "min-h-11"; + +type LoadState = "loading" | "notFound" | "error" | LeadDetail; +const blankToNull = (v: string) => (v.trim() === "" ? null : v); +const toValues = (l: LeadDetail): Record => ({ + name: l.name, mobile: l.mobile ?? "", email: l.email ?? "", companyName: l.companyName ?? "", jobTitle: l.jobTitle ?? "", notes: l.notes ?? "", +}); + +function Lead() { + const t = useT(); + const { hasModule } = useAdminAuth(); + const { leadUuid } = useParams<{ leadUuid: string }>(); + const [state, setState] = useState("loading"); + const [reloadKey, setReloadKey] = useState(0); + const [values, setValues] = useState>(toValues({ name: "", mobile: null, email: null, companyName: null, jobTitle: null, notes: null } as LeadDetail)); + const [fieldErrors, setFieldErrors] = useState>({}); + const [formError, setFormError] = useState(null); + const [saved, setSaved] = useState(false); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let cancelled = false; + getLead(leadUuid) + .then((lead) => { + if (cancelled) return; + setValues(toValues(lead)); + setState(lead); + }) + .catch((err) => { + if (cancelled) return; + const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined; + setState(code === "LEAD_NOT_FOUND" ? "notFound" : "error"); + }); + return () => { cancelled = true; }; + }, [leadUuid, reloadKey]); + + if (state === "loading") return ; + if (state === "notFound") { + return ( + {t("Back")}} + /> + ); + } + if (state === "error") { + return { setState("loading"); setReloadKey((k) => k + 1); }} />; + } + const lead = state; + const canEdit = hasModule("BO_LEADS_EDIT"); + + async function onSave(event: FormEvent) { + event.preventDefault(); + setFieldErrors({}); + setFormError(null); + setSaved(false); + setBusy(true); + try { + const updated = await updateLead(leadUuid, { + name: values.name, + mobile: blankToNull(values.mobile), + email: blankToNull(values.email), + companyName: blankToNull(values.companyName), + jobTitle: blankToNull(values.jobTitle), + notes: blankToNull(values.notes), + }); + setValues(toValues(updated)); + setState(updated); + setSaved(true); + } catch (err) { + const data = err instanceof ApiError + ? (err.data as { code?: string; errors?: string[]; details?: { field?: unknown } } | undefined) + : undefined; + const code = data?.code; + const named = code === "REQUIRED_FIELD" ? data?.errors ?? [] : [typeof data?.details?.field === "string" ? data.details.field : IMPLIED_FIELD[code ?? ""]]; + const known = FIELDS.map(([f]) => f as string); + const fields = named.filter((f): f is string => !!f && known.includes(f)); + // A named field the form does not render, or an unmapped code, must not make the failure silent. + if (code && CODE_MESSAGE[code] && fields.length && fields.length === named.length) { + setFieldErrors(Object.fromEntries(fields.map((f) => [f, t(CODE_MESSAGE[code])]))); + } else { + setFormError(t("LeadSaveFailed")); + } + } finally { + setBusy(false); + } + } + + const sharedLabel = (s: LeadDetail["sharedContacts"][number]) => + t(s.sameMobile && s.sameEmail ? "LeadsSameMobileEmailAs" : s.sameMobile ? "LeadsSameMobileAs" : "LeadsSameEmailAs"); + + return ( +
+ + + {lead.sharedContacts.length > 0 && ( + +
+ {lead.sharedContacts.map((s) => ( +

+ {sharedLabel(s)}{" "} + {s.name} +

+ ))} +
+
+ )} + + {formError && } + {saved &&

{t("LeadsSaved")}

} + + {canEdit ? ( +
+ {FIELDS.map(([f, label]) => { + const err = fieldErrors[f]; + return ( +
+ + {f === "notes" ? ( +