diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 2197a4a..f1ca439 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -23,6 +23,11 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES (40100000, 'BO_EVENTS', 'Events', 'BO', 'M', 40000000, '/events', 'CalendarDays'); +-- add-event-lead-capture/sql/02-lead-modules.sql +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40200000, 'BO_EVENT_LEADS', 'Event leads', 'BO', 'M', 40000000, '/event-leads', 'ClipboardList'), + (40300000, 'BO_INTERESTS', 'Interests', 'BO', 'M', 40000000, '/interests', 'Tags'); + -- Dev admin: super admin, company 1, password already set (login 'Y', no first-login change). INSERT INTO `user` (`id`, `email`, `enabled`, `name`, `password`, `username`, `groupid`, `branchid`, `login`, `status`, `type`, `create_by`, `create_date`, `done_by`, `company_id`) @@ -43,3 +48,63 @@ CREATE TABLE `event_salesperson` ( UNIQUE KEY `uk_event_salesperson_event_user` (`event_uuid`, `user_id`), KEY `idx_event_salesperson_event` (`event_uuid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- add-event-lead-capture/sql/01-lead-tables.sql (still USE `service-counter` from above) +CREATE TABLE `lead` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `uuid` bigint NOT NULL, + `company_id` bigint NOT NULL, + `name` varchar(100) NOT NULL, + `mobile_e164` varchar(20) DEFAULT NULL, + `email_normalised` varchar(254) DEFAULT NULL, + `company_name` varchar(150) DEFAULT NULL, + `job_title` varchar(100) DEFAULT NULL, + `notes` text, + `created_by` varchar(255) DEFAULT NULL, + `created_at` datetime DEFAULT CURRENT_TIMESTAMP, + `updated_by` varchar(255) DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_lead_uuid` (`uuid`), + KEY `idx_lead_company_mobile` (`company_id`, `mobile_e164`), + KEY `idx_lead_company_email` (`company_id`, `email_normalised`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `event_lead` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `uuid` bigint NOT NULL, + `company_id` bigint NOT NULL, + `event_uuid` bigint NOT NULL, + `lead_uuid` bigint NOT NULL, + `salesperson_user_id` bigint DEFAULT NULL, + `lead_type` varchar(8) NOT NULL, + `temperature` varchar(4) DEFAULT NULL, + `status` varchar(10) NOT NULL DEFAULT 'OPEN', + `next_follow_up_date` date DEFAULT NULL, + `notes` text, + `captured_by` varchar(255) DEFAULT NULL, + `captured_at` datetime DEFAULT CURRENT_TIMESTAMP, + `updated_by` varchar(255) DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_event_lead_uuid` (`uuid`), + UNIQUE KEY `uk_event_lead_event_lead` (`event_uuid`, `lead_uuid`), + KEY `idx_event_lead_company_event` (`company_id`, `event_uuid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `interest` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `name` varchar(100) NOT NULL, + `active` bit(1) NOT NULL DEFAULT b'1', + `sort_order` int NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_interest_company_name` (`company_id`, `name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `event_lead_interest` ( + `event_lead_id` bigint NOT NULL, + `interest_id` bigint NOT NULL, + `company_id` bigint NOT NULL, + PRIMARY KEY (`event_lead_id`, `interest_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/openspec/changes/add-event-lead-capture/.openspec.yaml b/openspec/changes/add-event-lead-capture/.openspec.yaml new file mode 100644 index 0000000..8c7aa0b --- /dev/null +++ b/openspec/changes/add-event-lead-capture/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-27 diff --git a/openspec/changes/add-event-lead-capture/design.md b/openspec/changes/add-event-lead-capture/design.md new file mode 100644 index 0000000..8513264 --- /dev/null +++ b/openspec/changes/add-event-lead-capture/design.md @@ -0,0 +1,183 @@ +# Design + +## Context + +- Change 3 added events (`service-counter`.`event`, Snowflake `uuid`) and each event's team (`event_salesperson`). It also added `/api/admin/events` in `mobile-api` and the portal Events screens. The uuid travels as a JSON string, dates as `YYYY-MM-DD`, and errors as a ProblemDetail with `code`, `errors[]` and a flat `details` object. The portal forwards only those fields. +- `services-counter` models generate uuids with `SnowflakeIdWorker.getUUID()` from core-libs. +- `mobile-api` knows the logged-in admin's `companyId` (`AdminAuthenticationService`), and change 3 already writes it onto team rows. +- The portal's `DataTable` has no phone layout. The Users and Events pages use it with `FilterPanel` and `useListFilters`. The date picker from change 3 works on touch. +- Nothing in the repo parses phone numbers. `services-system` already has the `company` table and `user.company_id` (change 2). +- Back-office modules in use: 40000000 root, 40100000 `BO_EVENTS`, 40700000 `BO_USERS`, 40800000 `BO_ROLES`. The icon map already has `ClipboardList` and `Tags`. + +## Goals / Non-Goals + +**Goals:** +- Capture a lead at an event in seconds on a phone, with New/Existing decided by the rules in the foundation design. +- One event's leads listed, filtered and edited on the floor. +- An interest list to tag leads. + +**Non-Goals:** +- Lead Listing, lead detail, lead field edits after capture, and CSV exports. These are in 4b. +- Merging leads, per-salesperson visibility, visitor self-registration, and an audit log beyond `updated_by` and `updated_at`. + +## Decisions + +### 1. Tables (schema `service-counter`) + +- **`lead`** + - Columns: `id` PK, `uuid` bigint unique, `company_id` NOT NULL, `name` varchar(100) NOT NULL, `mobile_e164` varchar(20) NULL, `email_normalised` varchar(254) NULL, `company_name` varchar(150), `job_title` varchar(100), `notes` text, `created_by`, `created_at`, `updated_by`, `updated_at`. + - Indexes, not unique: `(company_id, mobile_e164)` and `(company_id, email_normalised)`. +- **`event_lead`** + - Columns: `id` PK, `uuid` bigint unique, `company_id` NOT NULL, `event_uuid`, `lead_uuid`, `salesperson_user_id` NULL, `lead_type` varchar(8) (`NEW`/`EXISTING`), `temperature` varchar(4) NULL (`HOT`/`WARM`/`COLD`), `status` varchar(10) NOT NULL default `OPEN` (`OPEN`/`CONTACTED`/`QUALIFIED`/`WON`/`LOST`), `next_follow_up_date` date NULL, `notes` text, `captured_by`, `captured_at`, `updated_by`, `updated_at`. + - Unique `(event_uuid, lead_uuid)`; index `(company_id, event_uuid)`. +- **`interest`** + - Columns: `id` PK, `company_id` NOT NULL, `name` varchar(100) NOT NULL, `active` bit NOT NULL default 1, `sort_order` int NOT NULL default 0. + - Unique `(company_id, name)`. +- **`event_lead_interest`** + - Columns: `event_lead_id`, `interest_id`, `company_id` NOT NULL. + - PK `(event_lead_id, interest_id)`. + +`user_id` and `event_uuid` cross into other tables without foreign keys, like `event_salesperson`. Every query on the new tables filters on `company_id`, which comes from the logged-in admin and never from the request. `ponytail:` the change-3 `event` table has no `company_id`, so event lookups are not company-scoped; add it with the multi-company move. + +**Calls I made:** +- Name is required: a lead with no name cannot be followed up. +- Temperature is optional, because it is often unknown at capture. +- Status defaults to `OPEN`. + +### 2. Normalisation and validation in `mobile-api` + +Validation lives at the boundary, as in change 3. `services-counter` stores what it is given. + +- **Mobile:** `PhoneNumberUtil.parse(input, "MY")`. It must be a valid number, then it is formatted as E.164. `012-345 6789`, `0123456789`, `+60 12-345 6789` and `60123456789` all become `+60123456789`. + - Invalid input answers 400 `INVALID_MOBILE` with `details.field = mobile`. + - **Dependency:** `com.googlecode.libphonenumber:libphonenumber`, latest 8.x, pinned in `solvway-mobile-api/pom.xml`. Justification: nothing in the repo parses phone numbers, and getting it wrong creates duplicate leads (an anti-goal in the foundation design). +- **Email:** trimmed and lowercased. It must look like `x@y.z` (one `@`, a dot after it, no spaces), or the answer is 400 `INVALID_EMAIL`. +- **Required fields:** + - At least one of mobile or email, else `REQUIRED_FIELD` with `errors: ["mobile","email"]`. + - Name, else `REQUIRED_FIELD` with `errors: ["name"]`. +- **Lengths:** as in the tables, else `TOO_LONG` with the field. +- **Enum values:** temperature and status must be in their lists, else `INVALID_VALUE` with the field. + +### 3. Capture is two steps; the write is one transaction + +1. **Match.** `POST /api/admin/event-leads/{eventUuid}/match` with `{mobile, email}` normalises both values and returns `{mobile, email, candidates}`. + - Each candidate is `{leadUuid, name, mobile, email, companyName, eventLeadUuid}`. `eventLeadUuid` is set when that lead is already captured at this event. + - The candidates are the company's leads matching either value (`services-counter` `POST /counter/lead/findMatches`), at most 20, newest first. +2. **Capture.** `POST /api/admin/event-leads/{eventUuid}` with the lead fields, `leadUuid` (null for a new person), `salespersonId`, `temperature`, `status`, `interestIds`, `nextFollowUpDate` and `notes`. + - `mobile-api` validates and normalises, checks the event (decision 5) and the salesperson (decision 4), then calls `services-counter` `POST /counter/eventLead/capture`. + - That endpoint runs one `@Transactional` method: + - **`leadUuid` null:** insert a new `lead`; the event lead is `NEW`. + - **`leadUuid` set:** load that lead in the same company, else 404 `LEAD_NOT_FOUND`. Fill only its null or blank fields, never overwrite. The event lead is `EXISTING`. + - In both cases it inserts the `event_lead` and its interests. + - The lead and its event lead are saved together or not at all, unlike change 3's two-call create. + - **Already captured:** if the lead is already at this event (checked first, and enforced by the unique key for races), the answer is 409 `ALREADY_CAPTURED` with `details.eventLeadUuid`. The portal opens that event lead. + - **NEW versus EXISTING:** follows the foundation rules. A lead picked from the candidates existed before this capture, so it is `EXISTING`. "Different person" sends `leadUuid` null, so it is `NEW`, even when the value matches another lead. + +**Why two steps:** staff must see the candidates before the system decides. A single call cannot ask "which one is this?". + +`ponytail:` two staff capturing the same new person at the same moment can create two leads with the same mobile. That is allowed by design (non-unique index) and is fixed later by merge, which is not in phase 1. + +### 4. Salesperson must be on the event's team + +`salespersonId` is optional. + +- **A new or changed value** must be an id on the event's current team (`/counter/eventSalesperson/findByEventUuid`) that is also an enabled admin user. Otherwise the answer is 400 `NOT_ON_TEAM` with `details.field = salespersonId`. +- **An unchanged value** passes even if that person has since left the team or been deactivated. This mirrors change 3's team rule. +- **Options:** `GET /api/admin/event-leads/{eventUuid}/salesperson-options` returns the active team members. +- **Default on capture:** the form preselects the capturing user if they are on the team. + +### 5. Events open for capture + +The event picker and capture accept enabled events only. `GET /api/admin/event-leads/events` returns enabled events as `{uuid, name, location, startDate, endDate}`, sorted by start date descending. It uses `findByPropertyAndPageable` with `enabled=Y` and a page size of 100. + +- `ponytail:` one page of 100 events; add paging when a company has more enabled events than that. +- **Disabled events:** capture to a disabled event answers 409 `EVENT_DISABLED`. Listing and editing that event's leads still work, through a direct link from the listing URL. +- **Unknown event:** answers 404. + +### 6. Listing + +`GET /api/admin/event-leads/{eventUuid}/leads` takes `page`, `size`, `salespersonId`, `temperature`, `status`, `interestId` and `leadType`. It is sorted by `captured_at` descending, with `id` descending as a tie-breaker. That way, rows that tie on the sort column cannot repeat or go missing across pages, as change 3's review found for events. + +- **Backend:** `services-counter` `POST /counter/eventLead/findByEvent` runs one JPQL query joining `event_lead` and `lead`, with optional filters. The interest filter is an `exists` subquery. Interest ids for the page are fetched in one `in` query, not one per row. +- **Salesperson names:** resolved in `mobile-api` with one `services-system` user lookup per distinct salesperson on the page. +- **Each row:** `{eventLeadUuid, leadUuid, name, mobile, email, leadType, salesperson: {id, name}, temperature, status, interests: [{id, name}], nextFollowUpDate}`. + +### 7. Event lead edit + +- **Read:** `GET /api/admin/event-leads/{eventUuid}/leads/{eventLeadUuid}` returns the row, plus the lead's company name, job title and the event lead's notes. The lead's own fields are shown read-only; editing them is in 4b. +- **Update:** `PUT` takes `salespersonId`, `temperature`, `status`, `interestIds`, `nextFollowUpDate` and `notes`. `services-counter` `POST /counter/eventLead/update` replaces those fields and the interest set in one transaction and sets `updated_by` and `updated_at`. +- **Not found:** an event lead that is unknown or belongs to another event answers 404. + +### 8. Interests + +**Admin screen:** `/api/admin/interests` (`BO_INTERESTS`). + +- **List:** active and inactive interests, ordered by sort order, then name. +- **Create** with name. +- **Update:** name, active, sort order. + +**Rules:** +- Name is required, at most 100 characters, and unique in the company, case-insensitive. A duplicate answers 409 `DUPLICATE_NAME`. +- There is no delete. An interest is deactivated, so past tags keep their name. + +**Capture form options:** `GET /api/admin/event-leads/interest-options` (`BO_EVENT_LEADS`) returns active interests. An inactive interest already on an event lead still shows on that lead and can be removed, but cannot be newly added (`INACTIVE_INTEREST`). + +**Backend:** `services-counter` provides `/counter/interest/findByCompany/{companyId}`, `/counter/interest/save`, and `findByIds` (unused in phase 1: `mobile-api` reads the whole company list once per request). + +### 9. Modules and access + +Module rows: +- `40200000 BO_EVENT_LEADS`: 'Event leads', url `/event-leads`, icon `ClipboardList`. +- `40300000 BO_INTERESTS`: 'Interests', url `/interests`, icon `Tags`. + +Both are area BO, type M, parent 40000000. Every endpoint carries `@AppAuth` and `@AdminModule`. All staff with `BO_EVENT_LEADS` see all of the company's leads, as the foundation design says. + +`BO_EVENT_LEADS` covers viewing, capturing and editing event leads. The foundation design's separate "edit leads" permission is for the lead record itself, so it comes with lead edits in 4b. + +### 10. Portal screens + +The event-floor screens are responsive down to 360 px. Interests is desktop-first. + +- **`/event-leads`: event picker.** Enabled events as tappable cards, with today's running events first. +- **`/event-leads/[eventUuid]`: listing.** + - Above `md`: `DataTable`. + - Below `md`: a card list showing name, mobile, NEW/EXISTING badge, temperature, status and next follow-up. Same data and paging. + - Filters in `FilterPanel`, plus an "Add lead" button. +- **`/event-leads/[eventUuid]/new`: key-in form.** + - **Step 1:** + - Mobile is `type="tel"`, `inputMode="tel"`, `autoComplete="tel"`; email is `type="email"`. + - "Check" calls match. + - With no candidates, step 2 opens as a new person. + - With candidates, each shows as a card with "This person" or, if already captured here, "Open". Below them is "Different person". + - **Step 2:** + - Fields: name, company, job title, salesperson (team), temperature, interests (checkboxes), next follow-up (date picker), notes. + - Matched lead values are prefilled and read-only where they already exist. + - **Layout:** single column, touch targets of at least 44 px. +- **`/event-leads/[eventUuid]/[eventLeadUuid]`: edit page.** The lead's details read-only, the editable fields from decision 7, and the same layout. +- **`/interests`:** a table with add, rename, active toggle and sort order. + +## Risks / Trade-offs + +- **The same person typed in two formats:** E.164 normalisation via libphonenumber, with a test table of Malaysian formats. +- **Two leads for one person through concurrent capture or "different person":** allowed by design; merge is later. +- **Lead and event lead saved separately:** they are not. One transaction in `services-counter` (decision 3). +- **Listing N+1:** + - Interests are fetched in one batch per page. + - Salesperson names use one lookup per distinct salesperson on the page (bounded by team size). `ponytail:` batch the lookup if teams grow large. +- **Leads hold customer PII:** + - Names, mobiles and emails are never logged. + - Every query is filtered by the caller's company. + - Local seeds carry no lead data. +- **New dependency:** libphonenumber, pure Java with no transitive dependencies. + +## Migration Plan + +Additive SQL in `sql/` of this change: +1. `01-lead-tables.sql`: `lead`, `event_lead`, `interest`, `event_lead_interest` in `service-counter`. +2. `02-lead-modules.sql`: the `BO_EVENT_LEADS` and `BO_INTERESTS` module rows. + +These are mirrored in `local/seed/03-colite.sql`. To roll back, `sql/99-rollback.sql` drops the four tables and deletes the two module rows and their `modules_roles` rows. + +## Open Questions + +None blocking. 4b covers the lead record edits and exports. diff --git a/openspec/changes/add-event-lead-capture/proposal.md b/openspec/changes/add-event-lead-capture/proposal.md new file mode 100644 index 0000000..3da0a80 --- /dev/null +++ b/openspec/changes/add-event-lead-capture/proposal.md @@ -0,0 +1,39 @@ +# Proposal + +## Why + +Go-live success is one thing: staff can track leads at an event. This change delivers that. A salesperson opens an event on a phone or iPad, keys a lead in, and the system says whether the person is new or already known. Staff then work through that event's leads. See `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md` (Lead data model, Capture and matching rules, Listings, Access). Change 3 added events and each event's team of salespeople; this change uses that team. + +The design's change 4 is split. This is 4a: the event floor. 4b adds the Lead Listing, the lead detail page with lead edits, and both CSV exports. + +## What Changes + +- **Interests**: an admin-managed list of products and services used to tag leads (add, rename, reorder, deactivate). New `BO_INTERESTS` module. +- **Lead tables in `services-counter`**: `lead` (one row per person), `event_lead` (one row per lead per event), `interest`, `event_lead_interest`. All carry `company_id`. +- **Key-in form**: staff enter a mobile and/or an email. The mobile is normalised to E.164 (default +60) and the email trimmed and lowercased. Matching leads in the company are shown; staff pick one (EXISTING) or capture a different person (NEW). No match creates a new lead (NEW). Picking a match fills only the lead's blank fields. A lead already captured at this event is not captured again; the form opens that event lead. +- **Event Leads Listing**: one event's leads with name, mobile, email, NEW/EXISTING, salesperson, temperature, status, interests and next follow-up. Filters: salesperson, temperature, status, interest, NEW/EXISTING. Server-side paging. +- **Event lead edit**: salesperson, temperature, status, interests, next follow-up date and notes. +- **Salesperson from the team**: a lead's salesperson must be on the event's team (change 3). A salesperson already set stays allowed after they leave the team or are deactivated. +- **Phone-width screens**: the event picker, listing (cards on phones), key-in form and event lead edit work on a phone and an iPad. +- **New module `BO_EVENT_LEADS`** (`/event-leads`) for the whole event-floor workflow: pick an event, list, capture and edit its leads. +- **New dependency** `com.googlecode.libphonenumber:libphonenumber` in `mobile-api`, for phone normalisation. Nothing in the repo parses phone numbers today, and hand-rolled parsing is how one person becomes two leads. + +Not in this change (4b): Lead Listing, lead detail and lead edits, CSV exports, and the export permission. + +## Capabilities + +### New Capabilities +- `lead-interests`: managing the interest list used to tag leads. +- `event-lead-capture`: capturing leads at an event with New/Existing matching, listing and editing an event's leads. + +### Modified Capabilities +None. + +## Impact + +- `solvway-services-counter`: `Interest`, `Lead`, `EventLead` entities, repositories, a transactional capture endpoint, match, listing and update endpoints. +- `solvway-mobile-api`: `AdminInterestController`, `AdminEventLeadController` and services; libphonenumber dependency. +- `solvway-admin-portal`: `app/interests/**`, `app/event-leads/**` pages, route handlers, services, types, i18n, route-module map entries. +- Database: four new `service-counter` tables and two `service-system`.`module` rows. Additive only. +- `local/seed/03-colite.sql`: mirrors the new tables and modules. +- No change to the gateway, the `event` table or existing endpoints. diff --git a/openspec/changes/add-event-lead-capture/specs/event-lead-capture/spec.md b/openspec/changes/add-event-lead-capture/specs/event-lead-capture/spec.md new file mode 100644 index 0000000..a099cba --- /dev/null +++ b/openspec/changes/add-event-lead-capture/specs/event-lead-capture/spec.md @@ -0,0 +1,152 @@ +# Spec Delta + +## Purpose + +Staff capture leads at an event, learn whether each person is new or already known, and work through the event's leads. + +## ADDED Requirements + +### Requirement: Choose an event + +The system SHALL let a user with `BO_EVENT_LEADS` choose among the company's enabled events to capture and list leads. Capturing a lead for a disabled event SHALL be refused. + +#### Scenario: Only enabled events offered + +- **GIVEN** an enabled event `KL Food Fair 2027` and a disabled event `Penang Expo` +- **WHEN** a user with `BO_EVENT_LEADS` opens Event leads +- **THEN** `KL Food Fair 2027` is offered and `Penang Expo` is not + +#### Scenario: Disabled event refuses capture + +- **WHEN** a lead is submitted for a disabled event +- **THEN** the capture is refused and nothing is saved + +#### Scenario: No module + +- **WHEN** a user without `BO_EVENT_LEADS` opens Event leads or calls an event-leads endpoint +- **THEN** the page shows not-authorised and the endpoint responds 403 + +### Requirement: Contact normalisation + +The system SHALL require a mobile number, an email, or both, for every captured lead, and a name. The system SHALL normalise a mobile number to E.164, treating a number without a country code as Malaysian (+60), and SHALL refuse a number that is not valid. The system SHALL trim and lowercase an email and refuse one that is not an email address. + +#### Scenario: Malaysian formats are one number + +- **WHEN** staff enter `012-345 6789`, `0123456789`, `+60 12-345 6789` or `60123456789` +- **THEN** each is stored and matched as `+60123456789` + +#### Scenario: Email case and spaces + +- **WHEN** staff enter ` Aisyah@Example.COM ` +- **THEN** it is stored and matched as `aisyah@example.com` + +#### Scenario: Neither mobile nor email + +- **WHEN** staff submit a lead with no mobile and no email +- **THEN** the capture is refused and both fields are named + +#### Scenario: Invalid mobile + +- **WHEN** staff enter `12345` as the mobile +- **THEN** the capture is refused with a message on the mobile field + +### Requirement: New or existing lead + +The system SHALL show, before capture, the company's leads matching the entered mobile or email. A capture with no match or as a different person SHALL create a new lead marked NEW. A capture of a picked match SHALL be marked EXISTING and SHALL fill only that lead's blank fields. The mark SHALL never be recalculated. The lead and its event lead SHALL be saved together or not at all. + +#### Scenario: First time seen + +- **GIVEN** no lead with mobile `+60123456789` +- **WHEN** staff capture `Aisyah` with `0123456789` at `KL Food Fair 2027` +- **THEN** a new lead is created and the event lead is NEW + +#### Scenario: Known person picked + +- **GIVEN** a lead `Aisyah` with mobile `+60123456789` and no email, captured at an earlier event +- **WHEN** staff enter `012-345 6789` and `aisyah@example.com`, and pick `Aisyah` from the matches +- **THEN** the event lead is EXISTING +- **AND** the lead now has email `aisyah@example.com` and its name is unchanged + +#### Scenario: Stored values are not overwritten + +- **GIVEN** a lead with company `Acme` +- **WHEN** staff pick that lead and enter company `Other Co` +- **THEN** the lead's company stays `Acme` + +#### Scenario: Mobile and email match different people + +- **GIVEN** lead `A` with mobile `+60123456789` and lead `B` with email `b@example.com` +- **WHEN** staff enter that mobile and that email +- **THEN** both `A` and `B` are shown as matches and nothing is merged + +#### Scenario: Different person + +- **GIVEN** a lead with mobile `+60123456789` +- **WHEN** staff choose a different person and capture `Ahmad` with that mobile +- **THEN** a second lead `Ahmad` is created and the event lead is NEW + +#### Scenario: Already captured at this event + +- **GIVEN** `Aisyah` is already captured at `KL Food Fair 2027` +- **WHEN** staff enter her mobile there again +- **THEN** the match shows she is already captured and offers to open that event lead +- **AND** a capture of her at the same event is refused without creating anything + +### Requirement: Salesperson from the event team + +The system SHALL let staff set an event lead's salesperson, which MAY be empty. A salesperson newly set on an event lead SHALL be an active member of that event's team. A salesperson already set SHALL remain allowed after they leave the team or are deactivated. + +#### Scenario: Team member assigned + +- **GIVEN** `KL Food Fair 2027` has `sales1` and `sales2` on its team +- **WHEN** staff capture a lead with salesperson `sales2` +- **THEN** the event lead's salesperson is `sales2` + +#### Scenario: Outsider refused + +- **GIVEN** `sales3` is not on the team of `KL Food Fair 2027` +- **WHEN** staff set `sales3` as an event lead's salesperson there +- **THEN** the save is refused with a message on the salesperson field + +#### Scenario: Salesperson later removed from team + +- **GIVEN** an event lead whose salesperson is `sales1` +- **WHEN** `sales1` is removed from the event's team and staff edit the lead's status +- **THEN** the save succeeds and the salesperson stays `sales1` + +### Requirement: Event leads listing + +The system SHALL list one event's leads, newest capture first, paginated on the server, showing name, mobile, email, NEW or EXISTING, salesperson, temperature, status, interests and next follow-up date. The listing SHALL be filterable by salesperson, temperature, status, interest and NEW or EXISTING, and SHALL be usable at phone width. + +#### Scenario: Filter by temperature + +- **GIVEN** a HOT lead and a COLD lead at an event +- **WHEN** staff filter by HOT +- **THEN** only the HOT lead is listed + +#### Scenario: Filter by interest + +- **GIVEN** a lead tagged `Cookware` and a lead tagged `Kitchen appliances` +- **WHEN** staff filter by `Cookware` +- **THEN** only the lead tagged `Cookware` is listed + +#### Scenario: Phone width + +- **WHEN** staff open the listing on a 360 px wide screen +- **THEN** each lead shows as a card with name, mobile, NEW or EXISTING, temperature, status and next follow-up, with no sideways scrolling + +### Requirement: Event lead edit + +The system SHALL let staff with `BO_EVENT_LEADS` change an event lead's salesperson, temperature, status, interests, next follow-up date and notes. Temperature SHALL be HOT, WARM, COLD or empty. Status SHALL be OPEN, CONTACTED, QUALIFIED, WON or LOST, and a new event lead SHALL be OPEN. Only active interests SHALL be newly added; an inactive interest already on the event lead SHALL stay until removed. + +#### Scenario: Work a lead + +- **GIVEN** an OPEN event lead +- **WHEN** staff set status CONTACTED, temperature HOT and next follow-up 2027-01-20 +- **THEN** the listing shows CONTACTED, HOT and 20/01/2027 for that lead + +#### Scenario: Inactive interest kept + +- **GIVEN** an event lead tagged `Cookware`, and `Cookware` is then deactivated +- **WHEN** staff change the lead's status +- **THEN** the save succeeds and the lead is still tagged `Cookware` diff --git a/openspec/changes/add-event-lead-capture/specs/lead-interests/spec.md b/openspec/changes/add-event-lead-capture/specs/lead-interests/spec.md new file mode 100644 index 0000000..149b59b --- /dev/null +++ b/openspec/changes/add-event-lead-capture/specs/lead-interests/spec.md @@ -0,0 +1,34 @@ +# Spec Delta + +## Purpose + +Admins with the Interests module maintain the list of products and services that leads are tagged with. + +## ADDED Requirements + +### Requirement: Interest list + +The system SHALL let an admin with `BO_INTERESTS` list, add, rename, reorder, deactivate and reactivate interests for their company. An interest name SHALL be required, at most 100 characters, and unique within the company ignoring case. Interests SHALL NOT be deletable. + +#### Scenario: Add interest + +- **WHEN** an admin with `BO_INTERESTS` adds `Kitchen appliances` +- **THEN** it is listed as active + +#### Scenario: Duplicate name + +- **GIVEN** an interest `Kitchen appliances` +- **WHEN** an admin adds `kitchen APPLIANCES` +- **THEN** the save is refused and the name is reported as a duplicate + +#### Scenario: Deactivate + +- **GIVEN** an active interest `Cookware` +- **WHEN** an admin deactivates it +- **THEN** it is still listed, marked inactive +- **AND** it is no longer offered when capturing a lead + +#### Scenario: No module + +- **WHEN** an admin without `BO_INTERESTS` opens the Interests page or calls an interests endpoint +- **THEN** the page shows not-authorised and the endpoint responds 403 diff --git a/openspec/changes/add-event-lead-capture/sql/01-lead-tables.sql b/openspec/changes/add-event-lead-capture/sql/01-lead-tables.sql new file mode 100644 index 0000000..56ed01e --- /dev/null +++ b/openspec/changes/add-event-lead-capture/sql/01-lead-tables.sql @@ -0,0 +1,64 @@ +-- Co-Lite change 4a: leads, event leads and interests. +-- Target: `service-counter`. Additive only. Run once. +-- salesperson_user_id points at `service-system`.`user` and event_uuid at `event`; no foreign keys, mobile-api checks them on write. +-- interest.name is unique per company; the utf8mb4 default collation makes that case-insensitive. +USE `service-counter`; + +CREATE TABLE `lead` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `uuid` bigint NOT NULL, + `company_id` bigint NOT NULL, + `name` varchar(100) NOT NULL, + `mobile_e164` varchar(20) DEFAULT NULL, + `email_normalised` varchar(254) DEFAULT NULL, + `company_name` varchar(150) DEFAULT NULL, + `job_title` varchar(100) DEFAULT NULL, + `notes` text, + `created_by` varchar(255) DEFAULT NULL, + `created_at` datetime DEFAULT CURRENT_TIMESTAMP, + `updated_by` varchar(255) DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_lead_uuid` (`uuid`), + KEY `idx_lead_company_mobile` (`company_id`, `mobile_e164`), + KEY `idx_lead_company_email` (`company_id`, `email_normalised`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `event_lead` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `uuid` bigint NOT NULL, + `company_id` bigint NOT NULL, + `event_uuid` bigint NOT NULL, + `lead_uuid` bigint NOT NULL, + `salesperson_user_id` bigint DEFAULT NULL, + `lead_type` varchar(8) NOT NULL, + `temperature` varchar(4) DEFAULT NULL, + `status` varchar(10) NOT NULL DEFAULT 'OPEN', + `next_follow_up_date` date DEFAULT NULL, + `notes` text, + `captured_by` varchar(255) DEFAULT NULL, + `captured_at` datetime DEFAULT CURRENT_TIMESTAMP, + `updated_by` varchar(255) DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_event_lead_uuid` (`uuid`), + UNIQUE KEY `uk_event_lead_event_lead` (`event_uuid`, `lead_uuid`), + KEY `idx_event_lead_company_event` (`company_id`, `event_uuid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `interest` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `name` varchar(100) NOT NULL, + `active` bit(1) NOT NULL DEFAULT b'1', + `sort_order` int NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_interest_company_name` (`company_id`, `name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `event_lead_interest` ( + `event_lead_id` bigint NOT NULL, + `interest_id` bigint NOT NULL, + `company_id` bigint NOT NULL, + PRIMARY KEY (`event_lead_id`, `interest_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/openspec/changes/add-event-lead-capture/sql/02-lead-modules.sql b/openspec/changes/add-event-lead-capture/sql/02-lead-modules.sql new file mode 100644 index 0000000..ad7cefd --- /dev/null +++ b/openspec/changes/add-event-lead-capture/sql/02-lead-modules.sql @@ -0,0 +1,7 @@ +-- Co-Lite change 4a: Event leads and Interests back-office modules (area BO). +-- Target: `service-system`.`module`. Additive only. Run once. +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40200000, 'BO_EVENT_LEADS', 'Event leads', 'BO', 'M', 40000000, '/event-leads', 'ClipboardList'), + (40300000, 'BO_INTERESTS', 'Interests', 'BO', 'M', 40000000, '/interests', 'Tags'); diff --git a/openspec/changes/add-event-lead-capture/sql/99-rollback.sql b/openspec/changes/add-event-lead-capture/sql/99-rollback.sql new file mode 100644 index 0000000..e38fb4b --- /dev/null +++ b/openspec/changes/add-event-lead-capture/sql/99-rollback.sql @@ -0,0 +1,11 @@ +-- Rollback for add-event-lead-capture. Drops the lead tables and the two modules with their grants. +-- Destroys every captured lead: take a backup first. +USE `service-system`; +DELETE FROM `modules_roles` WHERE `module_id` IN (40200000, 40300000); +DELETE FROM `module` WHERE `id` IN (40200000, 40300000); + +USE `service-counter`; +DROP TABLE IF EXISTS `event_lead_interest`; +DROP TABLE IF EXISTS `interest`; +DROP TABLE IF EXISTS `event_lead`; +DROP TABLE IF EXISTS `lead`; diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md new file mode 100644 index 0000000..9004faf --- /dev/null +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -0,0 +1,147 @@ +# Tasks + +Design: `design.md` (decision numbers below refer to it). Every task runs serially, and each task touches either a hotspot (SQL, `pom.xml`) or files the next task builds on. Every task is TDD: tests first, run red, then implement. + +## 1. Database + +- [x] 1.1 Write the SQL files: + - `sql/01-lead-tables.sql`: the four tables exactly as in design decision 1, with engine InnoDB and charset utf8mb4. + - `sql/02-lead-modules.sql`: two module rows, `40200000 BO_EVENT_LEADS` 'Event leads' `/event-leads` `ClipboardList` and `40300000 BO_INTERESTS` 'Interests' `/interests` `Tags`. Both are area BO, type M, parent 40000000. + - `sql/99-rollback.sql`. + + Mirror the tables and module rows into `local/seed/03-colite.sql`. Seed no lead data. + - Scope: `openspec/changes/add-event-lead-capture/sql/**`, `local/seed/**` + - Verify: `docker compose -f local/docker-compose.yml down -v && local/up.sh` exits 0, then a read-only SELECT shows the four tables and both module rows. + +## 2. services-counter + +- [x] 2.1 Add the interests backend (design decision 8): + - `Interest` entity and repository. + - `GET /counter/interest/findByCompany/{companyId}`, ordered by sort order then name. + - `POST /counter/interest/save`, which creates or updates by id within the company. + - `POST /counter/interest/findByIds` with `{companyId, ids}`. + + Tests first: + - ordering; + - save then find; + - a duplicate name in the same company (case-insensitive) is refused; + - the same name in another company is allowed; + - `findByIds` ignores other companies' ids. + - Scope: `solvway-services-counter/src/**/*Interest*`, plus a `dto/` record if needed. + - Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`. + +- [x] 2.2 Add the lead backend (design decisions 3, 6, 7): + - `Lead`, `EventLead` and `EventLeadInterest` entities and repositories. Uuids come from `SnowflakeIdWorker.getUUID()`. + - `EventLeadController` and service: + - `POST /counter/lead/findMatches` with `{companyId, mobileE164, email}`: leads matching either value in the company, at most 20, newest first. Each match carries the `eventLeadUuid` when the lead is already captured at the given `eventUuid`. + - `POST /counter/eventLead/capture`: one `@Transactional` method. + - With `leadUuid` null, insert a new lead and mark the event lead NEW. + - With `leadUuid` set, load the lead in the company and fill only its blank fields; mark the event lead EXISTING. + - Already at the event: 409 `ALREADY_CAPTURED` with the `eventLeadUuid`. A lead from another company: 404. + - `GET /counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}`. + - `POST /counter/eventLead/update`: replaces salesperson, temperature, status, follow-up, notes and the interest set in one transaction. + - `POST /counter/eventLead/findByEvent`: paged, with optional filters on salesperson, temperature, status, interest (an `exists` subquery) and lead type. Sorted by `captured_at` desc, then `id` desc. Interest ids for the page come from one `in` query. + + Tests first, for each of these: + - New capture. + - Existing capture fills only blanks, never overwriting stored values. + - A duplicate capture at the same event is refused and nothing is written. + - A failure inserting interests rolls back the lead and the event lead. + - Matching by mobile only, by email only, and both values matching different leads. + - Company isolation in match, capture, find and listing. + - Each listing filter. + - Paging order with equal `captured_at`. + - Update replaces the interest set. + - Scope: `solvway-services-counter/src/**/*Lead*`, plus `dto/` records if needed. + - Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`. + +## 3. mobile-api + +- [x] 3.1 Add the interests admin API (design decision 8). `AdminInterestController` with `GET`, `POST` and `PUT /api/admin/interests`, all `@AppAuth @AdminModule("BO_INTERESTS")`. The company id comes from the caller. + + Validation: + - Name is required, else `REQUIRED_FIELD`. + - At most 100 characters, else `TOO_LONG`. + - A duplicate answers 409 `DUPLICATE_NAME`. + - Errors use the `details` and `errors` contract from change 3. + + Tests first, for each `lead-interests` scenario the API decides. + - Scope: `solvway-mobile-api/src/**/*Interest*`, `solvway-mobile-api/src/main/java/**/constants/**` + - Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`. + +- [x] 3.2 Add the event-leads admin API (design decisions 2–7). + - Add `com.googlecode.libphonenumber:libphonenumber` (latest 8.x, exact version) to `solvway-mobile-api/pom.xml`. + - `AdminEventLeadController` and `AdminEventLeadService` under `/api/admin/event-leads`, all `@AppAuth @AdminModule("BO_EVENT_LEADS")`: + - `GET /events` + - `GET /interest-options` + - `GET /{eventUuid}/salesperson-options` + - `POST /{eventUuid}/match` + - `POST /{eventUuid}` (capture) + - `GET /{eventUuid}/leads` + - `GET /{eventUuid}/leads/{eventLeadUuid}` + - `PUT /{eventUuid}/leads/{eventLeadUuid}` + - Uuids are JSON strings. Dates are `YYYY-MM-DD`. + - Codes: + - `REQUIRED_FIELD`, `TOO_LONG`, `INVALID_MOBILE`, `INVALID_EMAIL`, `INVALID_VALUE`; + - `NOT_ON_TEAM` (salesperson rule, decision 4); + - `INACTIVE_INTEREST`; + - `EVENT_DISABLED` (409); + - `ALREADY_CAPTURED` (409, `details.eventLeadUuid`); + - 404 for an unknown event or event lead. + - Never log a lead's name, mobile or email. + + Tests first: + - A table test of the Malaysian mobile formats in the spec, plus invalid input. + - Email normalisation. + - Each `event-lead-capture` scenario the API decides. + - The salesperson keep-existing rule. + - The inactive-interest keep rule. + - An exact-JSON test that uuids are strings. + - Scope: `solvway-mobile-api/pom.xml`, `solvway-mobile-api/src/**/*EventLead*`, `solvway-mobile-api/src/main/java/**/constants/**`, `solvway-mobile-api/src/main/java/**/dto/admin/**` + - Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`. + +## 4. Admin portal + +- [x] 4.1 Add the Interests screen (`app/interests/page.tsx`, desktop-first, following the Roles page pattern). It provides a table with add, rename, active toggle and sort order. It needs route handlers `app/api/interests/**`, a service, types, `Int*` i18n keys and `/interests` mapped to `BO_INTERESTS` in `routeModules`. + + Tests first (vitest), for each portal-visible `lead-interests` scenario. + - Scope: `solvway-admin-portal/app/interests/**`, `solvway-admin-portal/app/api/interests/**`, `solvway-admin-portal/app/lib/**` + - Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`. + +- [x] 4.2 Add the event-floor screens (design decision 10): + - Pages: + - `app/event-leads/page.tsx`: event picker. + - `app/event-leads/[eventUuid]/page.tsx`: listing. `DataTable` at `md` and up; a card list below `md`, with filters. + - `app/event-leads/[eventUuid]/new/page.tsx`: two-step key-in form. Step 1 is match, with candidate cards and "This person", "Open" and "Different person". Step 2 is the details. + - `app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx`: edit. + - `ALREADY_CAPTURED` opens the existing event lead. + - Supporting code: + - route handlers `app/api/event-leads/**`; + - service, types, `Lead*` i18n keys; + - `/event-leads` mapped to `BO_EVENT_LEADS`. + - Mobile input attributes: `type="tel"`, `inputMode="tel"` and `autoComplete="tel"`. + - Touch targets of at least 44 px. + - Reuse the change-3 `DatePicker` for the follow-up date. + + Tests first (vitest), for each portal-visible `event-lead-capture` scenario. They include the match step's three outcomes, and the card list rendering below `md` (assert the card markup is present, not the layout). + - Scope: `solvway-admin-portal/app/event-leads/**`, `solvway-admin-portal/app/api/event-leads/**`, `solvway-admin-portal/app/components/event-leads/**`, `solvway-admin-portal/app/lib/**` + - Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`. + +## 5. Verification + +- [x] 5.1 Rebuild the stack and drive the portal with Playwright, using only local dev data and test leads made up for this check. + - At desktop width: + - Grant `BO_EVENT_LEADS` and `BO_INTERESTS` to a role. + - Add interests, try a duplicate, and deactivate one. + - Capture a NEW lead. + - Capture the same mobile in another format at another event. It shows as a match; pick it, and it is EXISTING with its blanks filled. + - Capture a different person with the same mobile. + - Show the already-captured block. + - Show that an outsider salesperson is refused. + - Show the invalid mobile and missing contact errors. + - Filter the listing, and edit status, temperature and follow-up. + - At 360×780: the event picker, listing cards, key-in form and edit page. + - A user without the modules gets not-authorised. + + Screenshots go in `verification/`. + - Verify: each scenario observed as specified, and `local/smoke.sh` prints `smoke: OK`. diff --git a/solvway-admin-portal/app/api/event-leads/[...path]/route.test.ts b/solvway-admin-portal/app/api/event-leads/[...path]/route.test.ts new file mode 100644 index 0000000..a7a868a --- /dev/null +++ b/solvway-admin-portal/app/api/event-leads/[...path]/route.test.ts @@ -0,0 +1,62 @@ +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, POST, PUT } from "./route"; + +type Req = Parameters[0]; +const ctx = (...path: string[]) => ({ params: Promise.resolve({ path }) }); +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/event-leads/[...path]", () => { + it("returns 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await GET(req("/api/event-leads/events"), ctx("events")); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("forwards GET with the query string", async () => { + const res = await GET(req("/api/event-leads/9/leads?status=OPEN&page=0&size=20"), ctx("9", "leads")); + expect(res.status).toBe(200); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/leads?status=OPEN&page=0&size=20", { token: "jwt-abc" }); + }); + + it("forwards POST and PUT bodies", async () => { + await POST(req("/api/event-leads/9/match", { method: "POST", body: JSON.stringify({ mobile: "0123" }) }), ctx("9", "match")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/match", { method: "POST", body: { mobile: "0123" }, token: "jwt-abc" }); + await PUT(req("/api/event-leads/9/leads/7", { method: "PUT", body: JSON.stringify({ status: "WON" }) }), ctx("9", "leads", "7")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/leads/7", { method: "PUT", body: { status: "WON" }, token: "jwt-abc" }); + }); + + it("rejects dot segments so the proxy cannot leave /api/admin/event-leads", async () => { + const res = await GET(req("/api/event-leads/x"), ctx("..", "users")); + expect(res.status).toBe(400); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("encodes path segments", async () => { + await GET(req("/api/event-leads/a"), ctx("a/b")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/a%2Fb", { token: "jwt-abc" }); + }); + + it("passes upstream 409 with code and details", async () => { + mocks.callMobileApi.mockResolvedValue({ + ok: false, error: "Already captured", status: 409, code: "ALREADY_CAPTURED", details: { eventLeadUuid: "55" }, + }); + const res = await POST(req("/api/event-leads/9", { method: "POST", body: "{}" }), ctx("9")); + expect(res.status).toBe(409); + const json = (await res.json()) as Record; + expect(json.code).toBe("ALREADY_CAPTURED"); + expect(json.details).toEqual({ eventLeadUuid: "55" }); + }); +}); diff --git a/solvway-admin-portal/app/api/event-leads/[...path]/route.ts b/solvway-admin-portal/app/api/event-leads/[...path]/route.ts new file mode 100644 index 0000000..f1f852a --- /dev/null +++ b/solvway-admin-portal/app/api/event-leads/[...path]/route.ts @@ -0,0 +1,24 @@ +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/event-leads endpoint; mobile-api owns validation and the BO_EVENT_LEADS guard. +type Ctx = { params: Promise<{ path: string[] }> }; + +async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "PUT") { + const token = await getToken(); + if (!token) return unauthorized(); + const { path } = await params; + if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path."); + const target = `/api/admin/event-leads/${path.map(encodeURIComponent).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 POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST"); +export const PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT"); diff --git a/solvway-admin-portal/app/api/interests/[id]/route.test.ts b/solvway-admin-portal/app/api/interests/[id]/route.test.ts new file mode 100644 index 0000000..36b2a7e --- /dev/null +++ b/solvway-admin-portal/app/api/interests/[id]/route.test.ts @@ -0,0 +1,106 @@ +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 { PUT } from "./route"; + +function ctx(id: string) { + return { params: Promise.resolve({ id }) }; +} +function putReq(body: unknown) { + return new Request("http://localhost/api/interests/4", { + method: "PUT", + body: JSON.stringify(body), + }) as unknown as Parameters[0]; +} + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset(); +}); + +describe("PUT /api/interests/[id]", () => { + it("returns 401 when there is no session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await PUT(putReq({ name: "New" }), ctx("4")); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("requires a name when updating name", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + const empty = await PUT(putReq({}), ctx("4")); + expect(empty.status).toBe(400); + const ws = await PUT(putReq({ name: " " }), ctx("4")); + expect(ws.status).toBe(400); + expect(((await ws.json()) as Record).code).toBe("REQUIRED_FIELD"); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("trims the name before sending", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 4, name: "Updated" } }); + await PUT(putReq({ name: " Updated " }), ctx("4")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests/4", { + method: "PUT", + body: { name: "Updated" }, + token: "jwt-abc", + }); + }); + + it("forwards { name } to PUT /api/admin/interests/{id}", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 4, name: "New" } }); + await PUT(putReq({ name: "New", active: true, sortOrder: 10 }), ctx("4")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests/4", { + method: "PUT", + body: { name: "New", active: true, sortOrder: 10 }, + token: "jwt-abc", + }); + }); + + it("forwards { active: false } without name for deactivation", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 4, active: false, name: "Old" } }); + await PUT(putReq({ active: false }), ctx("4")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests/4", { + method: "PUT", + body: { active: false }, + token: "jwt-abc", + }); + }); + + it("passes upstream 409 with code and details to the client", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ + ok: false, + error: "Duplicate name", + status: 409, + code: "DUPLICATE_NAME", + details: { field: "name" }, + }); + const res = await PUT(putReq({ name: "Dup" }), ctx("4")); + expect(res.status).toBe(409); + const json = await res.json() as Record; + expect(json.error).toBe("Duplicate name"); + expect(json.code).toBe("DUPLICATE_NAME"); + expect(json.details).toEqual({ field: "name" }); + }); + + it("passes upstream 403 with code to the client", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ + ok: false, + error: "Not authorized", + status: 403, + code: "NOT_AUTHORIZED", + }); + const res = await PUT(putReq({ active: true }), ctx("4")); + expect(res.status).toBe(403); + const json = await res.json() as Record; + expect(json.error).toBe("Not authorized"); + expect(json.code).toBe("NOT_AUTHORIZED"); + }); +}); diff --git a/solvway-admin-portal/app/api/interests/[id]/route.ts b/solvway-admin-portal/app/api/interests/[id]/route.ts new file mode 100644 index 0000000..b06b8d7 --- /dev/null +++ b/solvway-admin-portal/app/api/interests/[id]/route.ts @@ -0,0 +1,35 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute"; +import type { AdminInterestEntity } from "@/app/lib/types"; + +type Ctx = { params: Promise<{ id: string }> }; + +export async function PUT(req: NextRequest, { params }: Ctx) { + const token = await getToken(); + if (!token) return unauthorized(); + const { id } = await params; + const body = await req.json().catch(() => ({})); + const payload: Record = {}; + if ("name" in body && body.name !== undefined) { + const trimmed = String(body.name).trim(); + if (!trimmed) return badRequest("Name is required.", { code: "REQUIRED_FIELD", details: { field: "name" } }); + payload.name = trimmed; + } + if ("active" in body) payload.active = body.active; + if ("sortOrder" in body) payload.sortOrder = body.sortOrder; + if (Object.keys(payload).length === 0) { + return badRequest("At least one field is required."); + } + const result = await callMobileApi( + `/api/admin/interests/${encodeURIComponent(id)}`, + { + method: "PUT", + body: payload, + token, + }, + ); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/interests/route.test.ts b/solvway-admin-portal/app/api/interests/route.test.ts new file mode 100644 index 0000000..2e58012 --- /dev/null +++ b/solvway-admin-portal/app/api/interests/route.test.ts @@ -0,0 +1,105 @@ +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, POST } from "./route"; + +function getReq() { + return new Request("http://localhost/api/interests") as unknown as Parameters[0]; +} +function postReq(body: unknown) { + return new Request("http://localhost/api/interests", { + method: "POST", + body: JSON.stringify(body), + }) as unknown as Parameters[0]; +} + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset(); +}); + +describe("GET /api/interests", () => { + it("returns 401 when there is no session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await GET(getReq()); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("forwards to GET /api/admin/interests", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] }); + await GET(getReq()); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests", { token: "jwt-abc" }); + }); +}); + +describe("POST /api/interests", () => { + it("returns 401 when there is no session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await POST(postReq({ name: "Test" })); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("requires a name, blocks empty/whitespace", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + const empty = await POST(postReq({})); + expect(empty.status).toBe(400); + const ws = await POST(postReq({ name: " " })); + expect(ws.status).toBe(400); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("trims the name before sending", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1, name: "Workshop" } }); + await POST(postReq({ name: " Workshop " })); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests", { + method: "POST", + body: { name: "Workshop" }, + token: "jwt-abc", + }); + }); + + it("forwards name, active, sortOrder to POST /api/admin/interests", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1, name: "Test" } }); + await POST(postReq({ name: "Test", active: true, sortOrder: 5 })); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests", { + method: "POST", + body: { name: "Test", active: true, sortOrder: 5 }, + token: "jwt-abc", + }); + }); + + it("returns REQUIRED_FIELD code for a blank name", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + const res = await POST(postReq({ name: " " })); + expect(res.status).toBe(400); + expect(((await res.json()) as Record).code).toBe("REQUIRED_FIELD"); + }); + + it("passes upstream 409 with code and details to the client", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ + ok: false, error: "Duplicate name", status: 409, code: "DUPLICATE_NAME", details: { field: "name" }, + }); + const res = await POST(postReq({ name: "Dup" })); + expect(res.status).toBe(409); + const json = (await res.json()) as Record; + expect(json.code).toBe("DUPLICATE_NAME"); + expect(json.details).toEqual({ field: "name" }); + }); + + it("passes upstream 403 with code to the client", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Not authorized", status: 403, code: "NOT_AUTHORIZED" }); + const res = await POST(postReq({ name: "X" })); + expect(res.status).toBe(403); + expect(((await res.json()) as Record).code).toBe("NOT_AUTHORIZED"); + }); +}); diff --git a/solvway-admin-portal/app/api/interests/route.ts b/solvway-admin-portal/app/api/interests/route.ts new file mode 100644 index 0000000..d1f8c70 --- /dev/null +++ b/solvway-admin-portal/app/api/interests/route.ts @@ -0,0 +1,33 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute"; +import type { AdminInterestEntity } from "@/app/lib/types"; + +export async function GET(_req: NextRequest) { + const token = await getToken(); + if (!token) return unauthorized(); + const result = await callMobileApi("/api/admin/interests", { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} + +export async function POST(req: NextRequest) { + const token = await getToken(); + if (!token) return unauthorized(); + const body = await req.json().catch(() => ({})); + const name = (body as Partial).name?.trim(); + if (!name) { + return badRequest("Name is required.", { code: "REQUIRED_FIELD", details: { field: "name" } }); + } + const result = await callMobileApi( + "/api/admin/interests", + { + method: "POST", + body: { name, active: (body as Partial).active, sortOrder: (body as Partial).sortOrder }, + token, + }, + ); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.test.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.test.tsx new file mode 100644 index 0000000..93d3a74 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.test.tsx @@ -0,0 +1,236 @@ +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { pickDate } from "@/test/pickDate"; + +const mocks = vi.hoisted(() => ({ + getEventLead: vi.fn(), + updateEventLead: vi.fn(), + listEventSalespeople: vi.fn(), + listEventLeadInterests: vi.fn(), + useAdminAuth: vi.fn(), +})); +vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({ + ...(await importActual()), + getEventLead: mocks.getEventLead, + updateEventLead: mocks.updateEventLead, + 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 { ApiError } from "@/app/lib/clientApi"; +import { memoryRouter } from "@/test/memoryRouter"; +import EventLeadPage from "./page"; + +const SERVER_MSG = "Server says: internal detail xyz"; +const apiError = (code: string, extra: { details?: Record } = {}, status = 400) => + new ApiError(SERVER_MSG, status, { code, errors: [], details: {}, ...extra }); + +const LEAD = { + eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "l-1", + name: "Ann Lead", mobile: "+6591111111", email: "ann@x.com", companyName: "Acme", jobTitle: "CEO", + leadType: "NEW", salesperson: { id: 7, name: "Jane Sales" }, temperature: "WARM", status: "CONTACTED", + interests: [{ id: 1, name: "Product A", active: true }, { id: 2, name: "Product B", active: false }], + nextFollowUpDate: "2026-12-01", notes: "Call back", capturedAt: "2026-11-20T09:30:00Z", +}; +const PAYLOAD = { salespersonId: 7, temperature: "WARM", status: "CONTACTED", interestIds: [1, 2], nextFollowUpDate: "2026-12-01", notes: "Call back" }; + +async function open(lead: Record = {}) { + mocks.getEventLead.mockResolvedValue({ ...LEAD, ...lead }); + render(); + await screen.findByLabelText("Status"); + return userEvent.setup(); +} + +beforeEach(() => { + memoryRouter.reset("/event-leads/evt-1/el-1"); + mocks.getEventLead.mockReset(); + mocks.updateEventLead.mockReset().mockResolvedValue(LEAD); + mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 8, name: "Bob Other", username: "bob" }]); + mocks.listEventLeadInterests.mockReset().mockResolvedValue([ + { id: 1, name: "Product A", active: true }, + { id: 3, name: "Product C", active: true }, + ]); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true }); +}); + +describe("EventLeadPage", { timeout: 20000 }, () => { + it("renders NotAuthorized when the module is absent", () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false }); + render(); + expect(screen.getByTestId("not-authorized")).toBeInTheDocument(); + }); + + it("shows the lead contact read-only with type badge and captured date", async () => { + await open(); + expect(screen.getByText("Ann Lead")).toBeVisible(); + expect(screen.getByText("+6591111111")).toBeVisible(); + expect(screen.getByText("ann@x.com")).toBeVisible(); + expect(screen.getByText("Acme")).toBeVisible(); + expect(screen.getByText("CEO")).toBeVisible(); + expect(screen.getByText("New")).toBeVisible(); + expect(screen.getByText(/20\/11\/2026/)).toBeVisible(); + expect(screen.queryByLabelText("Name")).toBeNull(); + expect(screen.queryByLabelText("Mobile")).toBeNull(); + }); + + it("shows the Existing badge for an existing lead", async () => { + await open({ leadType: "EXISTING" }); + expect(screen.getByText("Existing")).toBeVisible(); + }); + + it("prefills the editable fields from the event lead", async () => { + await open(); + expect(screen.getByLabelText("Salesperson")).toHaveValue("7"); + expect(screen.getByLabelText("Temperature")).toHaveValue("WARM"); + expect(screen.getByLabelText("Status")).toHaveValue("CONTACTED"); + expect(screen.getByLabelText("Product A")).toBeChecked(); + expect(screen.getByLabelText("Next follow-up")).toHaveValue("01/12/2026"); + expect(screen.getByLabelText("Notes")).toHaveValue("Call back"); + }); + + it("keeps the current salesperson selectable when not on the event team list", async () => { + await open(); + const select = screen.getByLabelText("Salesperson"); + expect(within(select).getByRole("option", { name: "Jane Sales" })).toBeInTheDocument(); + expect(within(select).getByRole("option", { name: "Bob Other" })).toBeInTheDocument(); + expect(within(select).getByRole("option", { name: "None" })).toBeInTheDocument(); + }); + + it("lists an inactive interest already on the lead (not in the options list) as checked, once", async () => { + await open(); + expect(screen.getByLabelText("Product A")).toBeChecked(); + expect(screen.getByLabelText("Product B")).toBeChecked(); + expect(screen.getByLabelText("Product C")).not.toBeChecked(); + expect(screen.getAllByLabelText("Product A")).toHaveLength(1); + }); + + it("unchecking the inactive interest saves interestIds without it", async () => { + const user = await open(); + await user.click(screen.getByLabelText("Product B")); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", { ...PAYLOAD, interestIds: [1] }); + }); + + it("saves unchanged values with all six fields, then goes back to the list", async () => { + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", PAYLOAD); + await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1")); + }); + + it("saves edited values", async () => { + const user = await open(); + await user.selectOptions(screen.getByLabelText("Salesperson"), "8"); + await user.selectOptions(screen.getByLabelText("Temperature"), "HOT"); + await user.selectOptions(screen.getByLabelText("Status"), "WON"); + await user.click(screen.getByLabelText("Product B")); + await user.click(screen.getByLabelText("Product C")); + pickDate("Next follow-up", "2026-12-05"); + const notes = screen.getByLabelText("Notes"); + await user.clear(notes); + await user.type(notes, "Signed"); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", { + salespersonId: 8, temperature: "HOT", status: "WON", interestIds: [1, 3], nextFollowUpDate: "2026-12-05", notes: "Signed", + }); + }); + + it("sends null for emptied fields", async () => { + const user = await open(); + await user.selectOptions(screen.getByLabelText("Salesperson"), ""); + await user.selectOptions(screen.getByLabelText("Temperature"), ""); + await user.clear(screen.getByLabelText("Notes")); + await user.click(screen.getByLabelText("Product A")); + await user.click(screen.getByLabelText("Product B")); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", { + salespersonId: null, temperature: null, status: "CONTACTED", interestIds: [], nextFollowUpDate: "2026-12-01", notes: null, + }); + }); + + it("has a Back link to the event's leads", async () => { + await open(); + expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/event-leads/evt-1"); + }); + + it("uses touch targets of at least 44px", async () => { + await open(); + for (const label of ["Salesperson", "Temperature", "Status"]) expect(screen.getByLabelText(label)).toHaveClass("min-h-11"); + expect(screen.getByLabelText("Product A").closest("label")).toHaveClass("min-h-11"); + expect(screen.getByRole("button", { name: "Save" })).toHaveClass("min-h-11"); + expect(screen.getByRole("link", { name: "Back" })).toHaveClass("min-h-11"); + }); + + it("shows a not-found state with a Back link for EVENT_LEAD_NOT_FOUND", async () => { + mocks.getEventLead.mockRejectedValue(apiError("EVENT_LEAD_NOT_FOUND", {}, 404)); + render(); + expect(await screen.findByText("Lead not found")).toBeVisible(); + expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/event-leads/evt-1"); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + expect(screen.queryByRole("button", { name: "Save" })).toBeNull(); + }); + + it("shows an error with retry for other load failures, and retry reloads", async () => { + mocks.getEventLead.mockRejectedValueOnce(apiError("BOOM", {}, 500)).mockResolvedValue(LEAD); + render(); + expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the lead"); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + await userEvent.setup().click(screen.getByRole("button", { name: "Retry" })); + expect(await screen.findByLabelText("Status")).toBeVisible(); + }); + + it.each([ + ["TOO_LONG", "notes", "Notes", "Too long."], + ["INVALID_DATE", "nextFollowUpDate", "Next follow-up", "Enter a valid date."], + ["NOT_ON_TEAM", "salespersonId", "Salesperson", "This person is not on the event team."], + ["INVALID_VALUE", "temperature", "Temperature", "Invalid value."], + ["INVALID_VALUE", "status", "Status", "Invalid value."], + ])("%s on %s shows the mapped message under the field", async (code, field, label, text) => { + mocks.updateEventLead.mockRejectedValue(apiError(code, { details: { field } })); + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText(text)).toBeVisible(); + const el = screen.getByLabelText(label); + expect(el).toHaveAttribute("aria-invalid", "true"); + expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent(text); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + expect(memoryRouter.push).not.toHaveBeenCalled(); + }); + + it("INACTIVE_INTEREST shows the mapped message under the interests group", async () => { + mocks.updateEventLead.mockRejectedValue(apiError("INACTIVE_INTEREST", { details: { field: "interestIds" } })); + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("An interest is no longer active.")).toBeVisible(); + const group = screen.getByRole("group", { name: "Interests" }); + expect(group).toHaveAttribute("aria-invalid", "true"); + expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent("An interest is no longer active."); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it("other save errors show a form-level message and stay on the page", async () => { + mocks.updateEventLead.mockRejectedValue(apiError("SOMETHING_ELSE")); + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again."); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + expect(memoryRouter.push).not.toHaveBeenCalled(); + }); + + it("an unknown field in a field error gives a form-level message", async () => { + mocks.updateEventLead.mockRejectedValue(apiError("TOO_LONG", { details: { field: "bogus" } })); + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again."); + }); +}); diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx new file mode 100644 index 0000000..dbccea6 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx @@ -0,0 +1,197 @@ +"use client"; + +import { useEffect, useState, type FormEvent } from "react"; +import { useParams, useRouter } from "next/navigation"; +import Link from "next/link"; +import { Badge } from "@/app/components/ui/badge"; +import { Button } from "@/app/components/ui/button"; +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 { RequireModule } from "@/app/lib/RequireModule"; +import { ApiError } from "@/app/lib/clientApi"; +import { formatDmy } from "@/app/lib/date-input"; +import { getEventLead, listEventLeadInterests, listEventSalespeople, updateEventLead } from "@/app/lib/services/adminEventLeads"; +import type { EventLeadRow, InterestOption, LeadStatus, LeadTemperature, SalespersonOption } from "@/app/lib/types"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +const TEMPERATURES: [LeadTemperature, string][] = [["HOT", "LeadHot"], ["WARM", "LeadWarm"], ["COLD", "LeadCold"]]; +const STATUSES: [LeadStatus, string][] = [["OPEN", "LeadOpen"], ["CONTACTED", "LeadContacted"], ["QUALIFIED", "LeadQualified"], ["WON", "LeadWon"], ["LOST", "LeadLost"]]; +const CODE_MESSAGE: Record = { + TOO_LONG: "LeadErrTooLong", + INVALID_DATE: "LeadErrInvalidDate", + NOT_ON_TEAM: "LeadErrNotOnTeam", + INACTIVE_INTEREST: "LeadErrInactiveInterest", + INVALID_VALUE: "LeadErrInvalidValue", +}; +const FIELDS = ["salespersonId", "temperature", "status", "interestIds", "nextFollowUpDate", "notes"]; +const SELECT_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 TALL = "min-h-11"; + +type Loaded = { lead: EventLeadRow; salespeople: SalespersonOption[]; interests: InterestOption[] }; +type LoadState = "loading" | "notFound" | "error" | Loaded; + +function EventLead() { + const t = useT(); + const router = useRouter(); + const { eventUuid, eventLeadUuid } = useParams<{ eventUuid: string; eventLeadUuid: string }>(); + const [state, setState] = useState("loading"); + const [reloadKey, setReloadKey] = useState(0); + const [salespersonId, setSalespersonId] = useState(""); + const [temperature, setTemperature] = useState(""); + const [status, setStatus] = useState(""); + const [interestIds, setInterestIds] = useState([]); + const [nextFollowUpDate, setNextFollowUpDate] = useState(""); + const [notes, setNotes] = useState(""); + const [fieldErrors, setFieldErrors] = useState>({}); + const [formError, setFormError] = useState(null); + const [busy, setBusy] = useState(false); + const back = `/event-leads/${eventUuid}`; + + useEffect(() => { + let cancelled = false; + Promise.all([getEventLead(eventUuid, eventLeadUuid), listEventSalespeople(eventUuid), listEventLeadInterests()]) + .then(([lead, salespeople, interests]) => { + if (cancelled) return; + setSalespersonId(lead.salesperson ? String(lead.salesperson.id) : ""); + setTemperature(lead.temperature ?? ""); + setStatus(lead.status); + setInterestIds(lead.interests.map((i) => i.id)); + setNextFollowUpDate(lead.nextFollowUpDate ?? ""); + setNotes(lead.notes ?? ""); + setState({ + lead, + // The current salesperson stays selectable even when no longer on the team list. + salespeople: lead.salesperson && !salespeople.some((s) => s.id === lead.salesperson!.id) + ? [...salespeople, { id: lead.salesperson.id, name: lead.salesperson.name, username: "" }] + : salespeople, + // The options list is active-only; an inactive interest on the lead comes from the lead itself. + interests: [...interests, ...lead.interests.filter((i) => !interests.some((o) => o.id === i.id))], + }); + }) + .catch((err) => { + if (cancelled) return; + const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined; + setState(code === "EVENT_LEAD_NOT_FOUND" ? "notFound" : "error"); + }); + return () => { cancelled = true; }; + }, [eventUuid, eventLeadUuid, reloadKey]); + + const backLink = ( + + ); + + if (state === "loading") return ; + if (state === "notFound") return ; + if (state === "error") { + return { setState("loading"); setReloadKey((k) => k + 1); }} />; + } + const { lead, salespeople, interests } = state; + + const fieldProps = (f: string) => ({ + id: `lead-${f}`, + "aria-invalid": fieldErrors[f] ? (true as const) : undefined, + "aria-describedby": fieldErrors[f] ? `lead-${f}-error` : undefined, + }); + const fieldError = (f: string) => + fieldErrors[f] ? : null; + const field = (f: string, label: string, control: React.ReactNode) => ( +
+ + {control} + {fieldError(f)} +
+ ); + + async function onSave(event: FormEvent) { + event.preventDefault(); + setFieldErrors({}); + setFormError(null); + setBusy(true); + try { + await updateEventLead(eventUuid, eventLeadUuid, { + salespersonId: salespersonId ? Number(salespersonId) : null, + temperature: (temperature || null) as LeadTemperature | null, + status: status as LeadStatus, + interestIds, + nextFollowUpDate: nextFollowUpDate || null, + notes: notes.trim() || null, + }); + router.push(back); + } catch (err) { + const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: unknown } } | undefined) : undefined; + const f = data?.details?.field; + const key = data?.code ? CODE_MESSAGE[data.code] : undefined; + if (key && typeof f === "string" && FIELDS.includes(f)) setFieldErrors({ [f]: t(key) }); + else setFormError(t("LeadSaveFailed")); + setBusy(false); + } + } + + const toggleInterest = (id: number) => + setInterestIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id])); + + return ( +
+ + {formError && } +
+
+ {t(lead.leadType === "NEW" ? "LeadNew" : "LeadExisting")} + {lead.mobile &&

{lead.mobile}

} + {lead.email &&

{lead.email}

} + {lead.companyName &&

{lead.companyName}

} + {lead.jobTitle &&

{lead.jobTitle}

} +

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

+
+ + {field("salespersonId", t("LeadSalesperson"), + )} + {field("temperature", t("LeadTemperature"), + )} + {field("status", t("LeadStatus"), + )} + +
+ {t("LeadInterests")} + {interests.map((i) => ( + + ))} + {fieldError("interestIds")} +
+ + {field("nextFollowUpDate", t("LeadNextFollowUp"), + )} + {field("notes", t("LeadNotes"), +