# 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 filters on `company_id`, which comes from the logged-in admin and never from the request. **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 a `findByIds` used by the listing. ### 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.