From 3fc05106151f14d3c61a82b3af0aedcbb5cfd5dc Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 09:33:21 +0800 Subject: [PATCH 01/14] docs(openspec): propose add-event-lead-capture Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-event-lead-capture/.openspec.yaml | 2 + .../changes/add-event-lead-capture/design.md | 183 ++++++++++++++++++ .../add-event-lead-capture/proposal.md | 39 ++++ .../specs/event-lead-capture/spec.md | 152 +++++++++++++++ .../specs/lead-interests/spec.md | 34 ++++ .../changes/add-event-lead-capture/tasks.md | 147 ++++++++++++++ 6 files changed, 557 insertions(+) create mode 100644 openspec/changes/add-event-lead-capture/.openspec.yaml create mode 100644 openspec/changes/add-event-lead-capture/design.md create mode 100644 openspec/changes/add-event-lead-capture/proposal.md create mode 100644 openspec/changes/add-event-lead-capture/specs/event-lead-capture/spec.md create mode 100644 openspec/changes/add-event-lead-capture/specs/lead-interests/spec.md create mode 100644 openspec/changes/add-event-lead-capture/tasks.md 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..020c89d --- /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 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. 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/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md new file mode 100644 index 0000000..940c821 --- /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 + +- [ ] 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 + +- [ ] 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`. + +- [ ] 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 + +- [ ] 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`. + +- [ ] 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 + +- [ ] 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`. + +- [ ] 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 + +- [ ] 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`. -- 2.54.1 From 4c853c428e7ed58c284795e3f7185b3f17021d0a Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 09:42:24 +0800 Subject: [PATCH 02/14] feat(db): lead, event_lead and interest tables with their modules Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 65 +++++++++++++++++++ .../sql/01-lead-tables.sql | 64 ++++++++++++++++++ .../sql/02-lead-modules.sql | 7 ++ .../sql/99-rollback.sql | 11 ++++ .../changes/add-event-lead-capture/tasks.md | 2 +- 5 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/add-event-lead-capture/sql/01-lead-tables.sql create mode 100644 openspec/changes/add-event-lead-capture/sql/02-lead-modules.sql create mode 100644 openspec/changes/add-event-lead-capture/sql/99-rollback.sql 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/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 index 940c821..d98dd3b 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -4,7 +4,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial ## 1. Database -- [ ] 1.1 Write the SQL files: +- [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`. -- 2.54.1 From b75d636886de7e9a15795cab92f1e8c7979e4927 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 10:09:56 +0800 Subject: [PATCH 03/14] feat(services-counter): store each company's interest list Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-event-lead-capture/tasks.md | 2 +- .../controller/InterestController.java | 31 ++ .../counter/dto/InterestFindByIdsRequest.java | 8 + .../services/counter/model/Interest.java | 23 ++ .../counter/repo/InterestRepository.java | 17 + .../counter/service/InterestService.java | 69 ++++ .../controller/InterestControllerTest.java | 82 ++++ .../counter/service/InterestServiceTest.java | 367 ++++++++++++++++++ 8 files changed, 598 insertions(+), 1 deletion(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/InterestController.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/InterestFindByIdsRequest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/controller/InterestControllerTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceTest.java diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md index d98dd3b..c81ec37 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -15,7 +15,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial ## 2. services-counter -- [ ] 2.1 Add the interests backend (design decision 8): +- [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. diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/InterestController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/InterestController.java new file mode 100644 index 0000000..040ab0f --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/InterestController.java @@ -0,0 +1,31 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.dto.InterestFindByIdsRequest; +import com.solvway.services.counter.model.Interest; +import com.solvway.services.counter.service.InterestService; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/counter/interest") +@AllArgsConstructor +public class InterestController { + private final InterestService interestService; + + @GetMapping("/findByCompany/{companyId}") + public List findByCompany(@PathVariable("companyId") long companyId) { + return interestService.findByCompany(companyId); + } + + @PostMapping("/save") + public Interest save(@RequestBody Interest interest) { + return interestService.save(interest); + } + + @PostMapping("/findByIds") + public List findByIds(@RequestBody InterestFindByIdsRequest body) { + return interestService.findByIds(body.companyId(), body.ids()); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/InterestFindByIdsRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/InterestFindByIdsRequest.java new file mode 100644 index 0000000..1382a29 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/InterestFindByIdsRequest.java @@ -0,0 +1,8 @@ +package com.solvway.services.counter.dto; + +import java.util.List; + +public record InterestFindByIdsRequest( + long companyId, + List ids +) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java new file mode 100644 index 0000000..caaab7b --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java @@ -0,0 +1,23 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Entity +@Table(name = "interest", uniqueConstraints = @UniqueConstraint(columnNames = {"company_id", "name"})) +public class Interest { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private long companyId; + + private String name; + + private boolean active = true; + + private int sortOrder; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java new file mode 100644 index 0000000..6801136 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java @@ -0,0 +1,17 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.Interest; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; + +@Repository +public interface InterestRepository extends JpaRepository { + List findByCompanyIdOrderBySortOrderAscNameAsc(long companyId); + + boolean existsByCompanyIdAndNameIgnoreCase(long companyId, String name); + + List findByIdInAndCompanyId(Collection ids, long companyId); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java new file mode 100644 index 0000000..150be28 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java @@ -0,0 +1,69 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Interest; +import com.solvway.services.counter.repo.InterestRepository; +import lombok.AllArgsConstructor; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +@Service +@AllArgsConstructor +public class InterestService { + private final InterestRepository interestRepository; + + public List findByCompany(long companyId) { + return interestRepository.findByCompanyIdOrderBySortOrderAscNameAsc(companyId); + } + + @Transactional + public Interest save(Interest interest) { + String name = interest.getName(); + String trimmedName = name != null ? name.trim() : null; + interest.setName(trimmedName); + + // Validate name + if (trimmedName == null || trimmedName.isEmpty()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + } + if (trimmedName.length() > 100) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "TOO_LONG"); + } + + try { + if (interest.getId() == null) { + // Create: check duplicate name for this company + if (interestRepository.existsByCompanyIdAndNameIgnoreCase(interest.getCompanyId(), trimmedName)) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME"); + } + return interestRepository.saveAndFlush(interest); + } else { + // Update: verify the row belongs to this company + Interest existing = interestRepository.findById(interest.getId()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + if (existing.getCompanyId() != interest.getCompanyId()) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND); + } + // Check duplicate name within the same company, excluding this row + if (!existing.getName().equalsIgnoreCase(trimmedName) + && interestRepository.existsByCompanyIdAndNameIgnoreCase(interest.getCompanyId(), trimmedName)) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME"); + } + return interestRepository.saveAndFlush(interest); + } + } catch (DataIntegrityViolationException e) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME"); + } + } + + public List findByIds(long companyId, List ids) { + if (ids == null || ids.isEmpty()) { + return List.of(); + } + return interestRepository.findByIdInAndCompanyId(ids, companyId); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/InterestControllerTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/InterestControllerTest.java new file mode 100644 index 0000000..90b67c5 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/InterestControllerTest.java @@ -0,0 +1,82 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.dto.InterestFindByIdsRequest; +import com.solvway.services.counter.model.Interest; +import com.solvway.services.counter.service.InterestService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * InterestController delegates to service and returns results. + */ +@ExtendWith(MockitoExtension.class) +class InterestControllerTest { + + private static final long COMPANY_A = 1L; + + @Mock + private InterestService interestService; + + private InterestController controller; + + @BeforeEach + void setUp() { + controller = new InterestController(interestService); + } + + @Test + void findByCompanyDelegatesToService() { + Interest row = makeInterest(1L, COMPANY_A, "tech", true, 0); + when(interestService.findByCompany(COMPANY_A)).thenReturn(List.of(row)); + + List result = controller.findByCompany(COMPANY_A); + + assertThat(result).hasSize(1).first().isSameAs(row); + verify(interestService).findByCompany(COMPANY_A); + } + + @Test + void saveDelegatesToService() { + Interest input = makeInterest(null, COMPANY_A, "tech", true, 0); + Interest saved = makeInterest(99L, COMPANY_A, "tech", true, 0); + when(interestService.save(input)).thenReturn(saved); + + Interest result = controller.save(input); + + assertThat(result.getId()).isEqualTo(99L); + verify(interestService).save(input); + } + + @Test + void findByIdsDelegatesToService() { + Interest row = makeInterest(5L, COMPANY_A, "filter", true, 0); + InterestFindByIdsRequest body = new InterestFindByIdsRequest(COMPANY_A, List.of(5L)); + when(interestService.findByIds(COMPANY_A, List.of(5L))).thenReturn(List.of(row)); + + List result = controller.findByIds(body); + + assertThat(result).hasSize(1).first().isSameAs(row); + verify(interestService).findByIds(COMPANY_A, List.of(5L)); + } + + private static Interest makeInterest(Long id, long companyId, String name, boolean active, int sortOrder) { + Interest i = new Interest(); + if (id != null) { + i.setId(id); + } + i.setCompanyId(companyId); + i.setName(name); + i.setActive(active); + i.setSortOrder(sortOrder); + return i; + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceTest.java new file mode 100644 index 0000000..ed7b6d8 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceTest.java @@ -0,0 +1,367 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Interest; +import com.solvway.services.counter.repo.InterestRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.springframework.dao.DataIntegrityViolationException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * InterestService — findByCompany ordering, save create/update/duplicate, findByIds. + */ +@ExtendWith(MockitoExtension.class) +class InterestServiceTest { + + private static final long COMPANY_A = 1L; + private static final long COMPANY_B = 2L; + + @Mock + private InterestRepository repository; + + private InterestService service; + + @BeforeEach + void setUp() { + service = new InterestService(repository); + } + + // --- Test 1: findByCompany orders by sortOrder asc, then name asc --- + @Test + void findByCompanyOrdersBySortOrderThenName() { + Interest b = makeInterest(2L, COMPANY_A, "banana", true, 5); + Interest a = makeInterest(1L, COMPANY_A, "apple", true, 10); + Interest c = makeInterest(3L, COMPANY_A, "apricot", true, 10); + when(repository.findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A)) + .thenReturn(List.of(b, a, c)); + + List result = service.findByCompany(COMPANY_A); + + // Repo method already orders; service passes through + assertThat(result).hasSize(3); + assertThat(result.get(0).getName()).isEqualTo("banana"); + assertThat(result.get(1).getName()).isEqualTo("apple"); + assertThat(result.get(2).getName()).isEqualTo("apricot"); + verify(repository).findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A); + } + + // --- Test 2: save creates a new row (id is null) --- + @Test + void saveCreatesNewRow() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName(" tech "); + input.setActive(true); + input.setSortOrder(0); + when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false); + when(repository.saveAndFlush(any())).thenAnswer(inv -> { + Interest saved = inv.getArgument(0); + saved.setId(99L); + return saved; + }); + + Interest result = service.save(input); + + assertThat(result.getId()).isEqualTo(99L); + assertThat(result.getName()).isEqualTo("tech"); + verify(repository).saveAndFlush(any()); + } + + // --- Test 3: save updates existing row with matching company --- + @Test + void saveUpdatesOwnRow() { + Interest existing = makeInterest(10L, COMPANY_A, "old", true, 1); + when(repository.findById(10L)).thenReturn(Optional.of(existing)); + + Interest input = new Interest(); + input.setId(10L); + input.setCompanyId(COMPANY_A); + input.setName(" new "); + input.setActive(false); + input.setSortOrder(5); + when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "new")).thenReturn(false); + when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); + + Interest result = service.save(input); + + assertThat(result.getName()).isEqualTo("new"); + assertThat(result.isActive()).isFalse(); + assertThat(result.getSortOrder()).isEqualTo(5); + verify(repository).saveAndFlush(any()); + } + + // --- Test 4: save updates other company's row -> 404 --- + @Test + void saveUpdatesOtherCompanyRow() { + Interest existing = makeInterest(10L, COMPANY_B, "other", true, 1); + when(repository.findById(10L)).thenReturn(Optional.of(existing)); + + Interest input = new Interest(); + input.setId(10L); + input.setCompanyId(COMPANY_A); + input.setName(" mine "); + + assertThatThrownBy(() -> service.save(input)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + } + + // --- Test 5: save duplicate name ignoring case in same company -> 409 --- + @Test + void saveDuplicateNameCaseInsensitive() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName(" Tech "); + when(repository.existsByCompanyIdAndNameIgnoreCase(eq(COMPANY_A), any())).thenReturn(true); + + assertThatThrownBy(() -> service.save(input)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("DUPLICATE_NAME"); + } + + // --- Test 6: same name in different company allowed --- + @Test + void sameNameDifferentCompanyAllowed() { + Interest inputA = new Interest(); + inputA.setCompanyId(COMPANY_A); + inputA.setName("tech"); + when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false); + when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); + + Interest inputB = new Interest(); + inputB.setCompanyId(COMPANY_B); + inputB.setName("tech"); + when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_B, "tech")).thenReturn(false); + when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); + + // Company A: no duplicate -> succeeds + service.save(inputA); + // Company B: no duplicate for B -> succeeds + service.save(inputB); + + verify(repository).existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech"); + verify(repository).existsByCompanyIdAndNameIgnoreCase(COMPANY_B, "tech"); + } + + // --- Test 7: updating row with same name unchanged is allowed --- + @Test + void updateWithSameNameUnchanged() { + Interest existing = makeInterest(10L, COMPANY_A, "tech", true, 1); + when(repository.findById(10L)).thenReturn(Optional.of(existing)); + + Interest input = new Interest(); + input.setId(10L); + input.setCompanyId(COMPANY_A); + input.setName("tech"); + when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); + + Interest result = service.save(input); + + assertThat(result.getId()).isEqualTo(10L); + verify(repository).saveAndFlush(any()); + } + + // --- Test 8: update changing name that conflicts with another row -> 409 --- + @Test + void updateNameConflictsWithAnotherRow() { + Interest existing = makeInterest(10L, COMPANY_A, "original", true, 1); + when(repository.findById(10L)).thenReturn(Optional.of(existing)); + + Interest input = new Interest(); + input.setId(10L); + input.setCompanyId(COMPANY_A); + input.setName(" tech "); + when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(true); + + assertThatThrownBy(() -> service.save(input)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("DUPLICATE_NAME"); + } + + // --- Test 9: findByIds with null ids returns empty --- + @Test + void findByIdsWithNullIdsReturnsEmpty() { + List result = service.findByIds(COMPANY_A, null); + + assertThat(result).isEmpty(); + verify(repository, org.mockito.Mockito.never()).findByIdInAndCompanyId(any(), eq(COMPANY_A)); + } + + // --- Test 10: findByIds with empty ids returns empty --- + @Test + void findByIdsWithEmptyIdsReturnsEmpty() { + List result = service.findByIds(COMPANY_A, Collections.emptyList()); + + assertThat(result).isEmpty(); + verify(repository, org.mockito.Mockito.never()).findByIdInAndCompanyId(any(), eq(COMPANY_A)); + } + + // --- Test 11: findByIds returns only company's rows --- + @Test + void findByIdsFiltersByCompany() { + Interest row = makeInterest(5L, COMPANY_A, "filter", true, 0); + when(repository.findByIdInAndCompanyId(List.of(5L), COMPANY_A)) + .thenReturn(List.of(row)); + + List result = service.findByIds(COMPANY_A, List.of(5L)); + + assertThat(result).hasSize(1).first().isSameAs(row); + verify(repository).findByIdInAndCompanyId(List.of(5L), COMPANY_A); + } + + // --- Test 12: findByIds filters by company — row not in company --- + @Test + void findByIdsExcludesOtherCompany() { + Interest row = makeInterest(5L, COMPANY_B, "other", true, 0); + when(repository.findByIdInAndCompanyId(List.of(5L), COMPANY_A)) + .thenReturn(List.of()); + + List result = service.findByIds(COMPANY_A, List.of(5L)); + + assertThat(result).isEmpty(); + verify(repository).findByIdInAndCompanyId(List.of(5L), COMPANY_A); + } + + // --- Test 13: creating interest with active left unset defaults to true --- + @Test + void defaultActiveIsTrue() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName("default"); + // active is left at JVM default (false) + when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "default")).thenReturn(false); + when(repository.saveAndFlush(any())).thenAnswer(inv -> { + Interest saved = inv.getArgument(0); + saved.setId(99L); + return saved; + }); + + Interest result = service.save(input); + + assertThat(result.isActive()).isTrue(); + } + + // --- Test 14: save then find returns saved interest with trimmed name --- + @Test + void saveThenFindByCompanyReturnsTrimmedName() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName(" tech "); + when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false); + when(repository.saveAndFlush(any())).thenAnswer(inv -> { + Interest saved = inv.getArgument(0); + saved.setId(99L); + return saved; + }); + when(repository.findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A)) + .thenAnswer(inv -> List.of(input)); + + service.save(input); + + List found = service.findByCompany(COMPANY_A); + assertThat(found).hasSize(1); + assertThat(found.get(0).getName()).isEqualTo("tech"); + assertThat(found.get(0).getId()).isEqualTo(99L); + } + + // --- Test 15: null name -> 400 REQUIRED_FIELD --- + @Test + void saveNullNameThrows400() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName(null); + + assertThatThrownBy(() -> service.save(input)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.BAD_REQUEST) + .hasMessageContaining("REQUIRED_FIELD"); + } + + // --- Test 16: blank name -> 400 REQUIRED_FIELD --- + @Test + void saveBlankNameThrows400() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName(" "); + + assertThatThrownBy(() -> service.save(input)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.BAD_REQUEST) + .hasMessageContaining("REQUIRED_FIELD"); + } + + // --- Test 17: name over 100 chars after trim -> 400 TOO_LONG --- + @Test + void saveNameTooLongThrows400() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName("a".repeat(101)); + + assertThatThrownBy(() -> service.save(input)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.BAD_REQUEST) + .hasMessageContaining("TOO_LONG"); + } + + // --- Test 18: DataIntegrityViolationException on save -> 409 DUPLICATE_NAME --- + @Test + void saveDataIntegrityViolationReturns409() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName("raced"); + when(repository.existsByCompanyIdAndNameIgnoreCase(eq(COMPANY_A), any())).thenReturn(false); + when(repository.saveAndFlush(any())).thenThrow(new DataIntegrityViolationException("duplicate key")); + + assertThatThrownBy(() -> service.save(input)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("DUPLICATE_NAME"); + } + + // --- Update race: the unique key fires at flush, which must still answer 409 --- + @Test + void updateRaceOnUniqueKeyReturns409() { + Interest existing = makeInterest(10L, COMPANY_A, "original", true, 1); + when(repository.findById(10L)).thenReturn(Optional.of(existing)); + when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false); + when(repository.saveAndFlush(any())).thenThrow(new DataIntegrityViolationException("duplicate key")); + + Interest input = new Interest(); + input.setId(10L); + input.setCompanyId(COMPANY_A); + input.setName("tech"); + + assertThatThrownBy(() -> service.save(input)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("DUPLICATE_NAME"); + } + + private static Interest makeInterest(Long id, long companyId, String name, boolean active, int sortOrder) { + Interest i = new Interest(); + i.setId(id); + i.setCompanyId(companyId); + i.setName(name); + i.setActive(active); + i.setSortOrder(sortOrder); + return i; + } +} -- 2.54.1 From 48507979bd97f1936bcc53a40302f5beaca50282 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 11:13:49 +0800 Subject: [PATCH 04/14] feat(services-counter): capture, match, list and edit event leads Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-event-lead-capture/tasks.md | 2 +- .../controller/EventLeadController.java | 52 +++ .../counter/dto/EventLeadCaptureRequest.java | 23 ++ .../services/counter/dto/EventLeadDetail.java | 25 ++ .../counter/dto/EventLeadSearchRequest.java | 5 + .../counter/dto/EventLeadUpdateRequest.java | 9 + .../services/counter/dto/LeadMatch.java | 5 + .../counter/dto/LeadMatchRequest.java | 4 + .../services/counter/model/EventLead.java | 58 ++++ .../counter/model/EventLeadInterest.java | 24 ++ .../counter/model/EventLeadInterestId.java | 41 +++ .../solvway/services/counter/model/Lead.java | 45 +++ .../repo/EventLeadInterestRepository.java | 24 ++ .../counter/repo/EventLeadRepository.java | 40 +++ .../services/counter/repo/LeadRepository.java | 22 ++ .../counter/service/EventLeadService.java | 191 +++++++++++ .../controller/EventLeadControllerTest.java | 71 +++++ .../counter/model/LeadMappingTest.java | 32 ++ .../service/EventLeadListAndUpdateTest.java | 212 +++++++++++++ .../counter/service/EventLeadServiceTest.java | 299 ++++++++++++++++++ 20 files changed, 1183 insertions(+), 1 deletion(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatch.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterestId.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/Lead.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadInterestRepository.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventLeadControllerTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/model/LeadMappingTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadListAndUpdateTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadServiceTest.java diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md index c81ec37..4cafe19 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -30,7 +30,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial - Scope: `solvway-services-counter/src/**/*Interest*`, plus a `dto/` record if needed. - Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`. -- [ ] 2.2 Add the lead backend (design decisions 3, 6, 7): +- [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`. diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java new file mode 100644 index 0000000..9da6d13 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java @@ -0,0 +1,52 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import com.solvway.services.counter.dto.EventLeadDetail; +import com.solvway.services.counter.dto.EventLeadSearchRequest; +import com.solvway.services.counter.dto.EventLeadUpdateRequest; +import com.solvway.services.counter.dto.LeadMatch; +import com.solvway.services.counter.dto.LeadMatchRequest; +import com.solvway.services.counter.service.EventLeadService; +import lombok.AllArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/counter") +@AllArgsConstructor +public class EventLeadController { + private final EventLeadService eventLeadService; + + @PostMapping("/lead/findMatches") + public List findMatches(@RequestBody LeadMatchRequest req) { + return eventLeadService.findMatches(req); + } + + @PostMapping("/eventLead/capture") + public EventLeadDetail capture(@RequestBody EventLeadCaptureRequest req) { + return eventLeadService.capture(req); + } + + @GetMapping("/eventLead/findByUuid/{companyId}/{eventLeadUuid}") + public EventLeadDetail findByUuid(@PathVariable("companyId") long companyId, + @PathVariable("eventLeadUuid") long eventLeadUuid) { + return eventLeadService.findByUuid(companyId, eventLeadUuid); + } + + @PostMapping("/eventLead/findByEvent") + public Page findByEvent(@RequestBody EventLeadSearchRequest req) { + return eventLeadService.search(req); + } + + @PostMapping("/eventLead/update") + public EventLeadDetail update(@RequestBody EventLeadUpdateRequest req) { + return eventLeadService.update(req); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java new file mode 100644 index 0000000..efd6eff --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java @@ -0,0 +1,23 @@ +package com.solvway.services.counter.dto; + +import java.time.LocalDate; +import java.util.List; + +/** Capture a lead at an event. leadUuid null means a new person. Values arrive validated and normalised by mobile-api. */ +public record EventLeadCaptureRequest( + long companyId, + long eventUuid, + Long leadUuid, + String name, + String mobileE164, + String email, + String companyName, + String jobTitle, + Long salespersonUserId, + String temperature, + String status, + List interestIds, + LocalDate nextFollowUpDate, + String notes, + String doneBy +) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java new file mode 100644 index 0000000..40c6cda --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java @@ -0,0 +1,25 @@ +package com.solvway.services.counter.dto; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +/** An event lead with its lead's contact details and its interest ids. */ +public record EventLeadDetail( + long eventLeadUuid, + long eventUuid, + long leadUuid, + String name, + String mobileE164, + String email, + String companyName, + String jobTitle, + String leadType, + Long salespersonUserId, + String temperature, + String status, + LocalDate nextFollowUpDate, + String notes, + LocalDateTime capturedAt, + List interestIds +) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java new file mode 100644 index 0000000..17ee57e --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java @@ -0,0 +1,5 @@ +package com.solvway.services.counter.dto; + +/** One event's leads, filtered; null or blank filters are ignored. page is 0-based. */ +public record EventLeadSearchRequest(long companyId, long eventUuid, Long salespersonUserId, String temperature, + String status, Long interestId, String leadType, int page, int size) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java new file mode 100644 index 0000000..2bda50a --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java @@ -0,0 +1,9 @@ +package com.solvway.services.counter.dto; + +import java.time.LocalDate; +import java.util.List; + +/** Replaces an event lead's working fields and its interest set. Values arrive validated by mobile-api. */ +public record EventLeadUpdateRequest(long companyId, long eventLeadUuid, Long salespersonUserId, String temperature, + String status, List interestIds, LocalDate nextFollowUpDate, String notes, + String doneBy) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatch.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatch.java new file mode 100644 index 0000000..ae1ba8a --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatch.java @@ -0,0 +1,5 @@ +package com.solvway.services.counter.dto; + +/** A matching lead; eventLeadUuid is set when the lead is already captured at the requested event. */ +public record LeadMatch(long leadUuid, String name, String mobileE164, String email, + String companyName, String jobTitle, Long eventLeadUuid) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java new file mode 100644 index 0000000..5938529 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java @@ -0,0 +1,4 @@ +package com.solvway.services.counter.dto; + +/** Find the company's leads whose mobile or email matches; blank values are ignored. */ +public record LeadMatchRequest(long companyId, long eventUuid, String mobileE164, String email) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java new file mode 100644 index 0000000..82c44b6 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java @@ -0,0 +1,58 @@ +package com.solvway.services.counter.model; + +import com.solvway.core.utils.SnowflakeIdWorker; +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Getter +@Setter +@Entity +@Table(name = "event_lead", uniqueConstraints = { + @UniqueConstraint(columnNames = {"uuid"}), + @UniqueConstraint(columnNames = {"event_uuid", "lead_uuid"}) +}) +public class EventLead { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(updatable = false) + private long uuid = SnowflakeIdWorker.getUUID(); + + private long companyId; + + @Column(name = "event_uuid") + private long eventUuid; + + @Column(name = "lead_uuid") + private long leadUuid; + + + @Column(name = "salesperson_user_id") + private Long salespersonUserId; + + private String leadType; + + private String temperature; + + private String status; + + @Column(name = "next_follow_up_date") + private LocalDate nextFollowUpDate; + + private String notes; + + private String capturedBy; + + @Column(updatable = false) + private LocalDateTime capturedAt = LocalDateTime.now(); + + private String updatedBy; + + private LocalDateTime updatedAt; + +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterest.java new file mode 100644 index 0000000..31e62df --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterest.java @@ -0,0 +1,24 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; +import org.springframework.data.domain.Persistable; + +@Getter +@Setter +@Entity +@Table(name = "event_lead_interest", uniqueConstraints = @UniqueConstraint(columnNames = {"event_lead_id", "interest_id"})) +public class EventLeadInterest implements Persistable { + @EmbeddedId + private EventLeadInterestId id; + + private long companyId; + + /** Rows are only inserted (a set is replaced by a bulk delete first), so saveAll persists without a SELECT per row. */ + @Override + @Transient + public boolean isNew() { + return true; + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterestId.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterestId.java new file mode 100644 index 0000000..e81bbc9 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterestId.java @@ -0,0 +1,41 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import lombok.Getter; +import lombok.Setter; + +import java.io.Serializable; +import java.util.Objects; + +@Getter +@Setter +@Embeddable +public class EventLeadInterestId implements Serializable { + + @Column(name = "event_lead_id") + private long eventLeadId; + + @Column(name = "interest_id") + private long interestId; + + public EventLeadInterestId() {} + + public EventLeadInterestId(long eventLeadId, long interestId) { + this.eventLeadId = eventLeadId; + this.interestId = interestId; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof EventLeadInterestId)) return false; + EventLeadInterestId that = (EventLeadInterestId) o; + return eventLeadId == that.eventLeadId && interestId == that.interestId; + } + + @Override + public int hashCode() { + return Objects.hash(eventLeadId, interestId); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Lead.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Lead.java new file mode 100644 index 0000000..26ba4a2 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Lead.java @@ -0,0 +1,45 @@ +package com.solvway.services.counter.model; + +import com.solvway.core.utils.SnowflakeIdWorker; +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@Entity +@Table(name = "`lead`", uniqueConstraints = @UniqueConstraint(columnNames = {"uuid"})) +public class Lead { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(updatable = false) + private long uuid = SnowflakeIdWorker.getUUID(); + + private long companyId; + + private String name; + + @Column(name = "mobile_e164") + private String mobileE164; + + private String emailNormalised; + + private String companyName; + + private String jobTitle; + + private String notes; + + private String createdBy; + + @Column(updatable = false) + private LocalDateTime createdAt = LocalDateTime.now(); + + private String updatedBy; + + private LocalDateTime updatedAt; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadInterestRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadInterestRepository.java new file mode 100644 index 0000000..dc61804 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadInterestRepository.java @@ -0,0 +1,24 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.EventLeadInterest; +import com.solvway.services.counter.model.EventLeadInterestId; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; + +@Repository +public interface EventLeadInterestRepository extends JpaRepository { + + List findByIdEventLeadId(long eventLeadId); + + List findByIdEventLeadIdIn(Collection eventLeadIds); + + @Modifying + @Query("DELETE FROM EventLeadInterest i WHERE i.id.eventLeadId = :eventLeadId") + void deleteByEventLeadId(@Param("eventLeadId") long eventLeadId); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java new file mode 100644 index 0000000..12cea09 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java @@ -0,0 +1,40 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.EventLead; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +@Repository +public interface EventLeadRepository extends JpaRepository { + + Optional findByEventUuidAndLeadUuid(long eventUuid, long leadUuid); + + List findByEventUuidAndLeadUuidIn(long eventUuid, Collection leadUuids); + + Optional findByUuidAndCompanyId(long uuid, long companyId); + + String SEARCH_WHERE = " WHERE l.uuid = e.leadUuid AND l.companyId = e.companyId" + + " AND e.companyId = :companyId AND e.eventUuid = :eventUuid" + + " AND (:salespersonUserId IS NULL OR e.salespersonUserId = :salespersonUserId)" + + " AND (:temperature IS NULL OR e.temperature = :temperature)" + + " AND (:status IS NULL OR e.status = :status)" + + " AND (:leadType IS NULL OR e.leadType = :leadType)" + + " AND (:interestId IS NULL OR EXISTS (SELECT 1 FROM EventLeadInterest i" + + " WHERE i.id.eventLeadId = e.id AND i.id.interestId = :interestId))"; + + /** Rows are [EventLead, Lead]; the caller supplies the sort through the pageable. */ + @Query(value = "SELECT e, l FROM EventLead e, Lead l" + SEARCH_WHERE, + countQuery = "SELECT COUNT(e) FROM EventLead e, Lead l" + SEARCH_WHERE) + Page search(@Param("companyId") long companyId, @Param("eventUuid") long eventUuid, + @Param("salespersonUserId") Long salespersonUserId, @Param("temperature") String temperature, + @Param("status") String status, @Param("interestId") Long interestId, + @Param("leadType") String leadType, Pageable pageable); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java new file mode 100644 index 0000000..e5f7b48 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java @@ -0,0 +1,22 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.Lead; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface LeadRepository extends JpaRepository { + + /** Leads in the company whose mobile or email equals the given value; a null value matches nothing. Newest first. */ + @Query("SELECT l FROM Lead l WHERE l.companyId = :companyId AND (l.mobileE164 = :mobile OR l.emailNormalised = :email) ORDER BY l.id DESC") + List findMatches(@Param("companyId") long companyId, @Param("mobile") String mobile, + @Param("email") String email, Pageable pageable); + + Optional findByUuidAndCompanyId(long uuid, long companyId); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java new file mode 100644 index 0000000..62f27fb --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java @@ -0,0 +1,191 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import com.solvway.services.counter.dto.EventLeadDetail; +import com.solvway.services.counter.dto.EventLeadSearchRequest; +import com.solvway.services.counter.dto.EventLeadUpdateRequest; +import com.solvway.services.counter.dto.LeadMatch; +import com.solvway.services.counter.dto.LeadMatchRequest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.EventLeadInterest; +import com.solvway.services.counter.model.EventLeadInterestId; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import lombok.AllArgsConstructor; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +/** + * Lead capture at events. Values arrive validated and normalised by mobile-api; this service applies the + * New/Existing rules and keeps the lead, its event lead and its interests in one transaction. + * Never log a lead's name, mobile or email. + */ +@Service +@AllArgsConstructor +public class EventLeadService { + private static final int MAX_MATCHES = 20; + private static final int MAX_PAGE_SIZE = 100; + + private final LeadRepository leadRepository; + private final EventLeadRepository eventLeadRepository; + private final EventLeadInterestRepository eventLeadInterestRepository; + + public List findMatches(LeadMatchRequest req) { + String mobile = blankToNull(req.mobileE164()); + String email = blankToNull(req.email()); + if (mobile == null && email == null) return List.of(); + + List leads = leadRepository.findMatches(req.companyId(), mobile, email, PageRequest.of(0, MAX_MATCHES)); + if (leads.isEmpty()) return List.of(); + Map capturedHere = eventLeadRepository + .findByEventUuidAndLeadUuidIn(req.eventUuid(), leads.stream().map(Lead::getUuid).toList()).stream() + .collect(Collectors.toMap(EventLead::getLeadUuid, EventLead::getUuid)); + return leads.stream() + .map(l -> new LeadMatch(l.getUuid(), l.getName(), l.getMobileE164(), l.getEmailNormalised(), + l.getCompanyName(), l.getJobTitle(), capturedHere.get(l.getUuid()))) + .toList(); + } + + @Transactional + public EventLeadDetail capture(EventLeadCaptureRequest req) { + Lead lead; + String leadType; + if (req.leadUuid() == null) { + lead = new Lead(); + lead.setCompanyId(req.companyId()); + lead.setName(req.name()); + lead.setMobileE164(blankToNull(req.mobileE164())); + lead.setEmailNormalised(blankToNull(req.email())); + lead.setCompanyName(blankToNull(req.companyName())); + lead.setJobTitle(blankToNull(req.jobTitle())); + lead.setCreatedBy(req.doneBy()); + leadType = "NEW"; + } else { + lead = leadRepository.findByUuidAndCompanyId(req.leadUuid(), req.companyId()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND")); + eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid()).ifPresent(existing -> { + ResponseStatusException e = new ResponseStatusException(HttpStatus.CONFLICT, "ALREADY_CAPTURED"); + e.getBody().setProperty("eventLeadUuid", String.valueOf(existing.getUuid())); + throw e; + }); + fillBlank(lead.getName(), req.name(), lead::setName); + fillBlank(lead.getMobileE164(), req.mobileE164(), lead::setMobileE164); + fillBlank(lead.getEmailNormalised(), req.email(), lead::setEmailNormalised); + fillBlank(lead.getCompanyName(), req.companyName(), lead::setCompanyName); + fillBlank(lead.getJobTitle(), req.jobTitle(), lead::setJobTitle); + lead.setUpdatedBy(req.doneBy()); + lead.setUpdatedAt(LocalDateTime.now()); + leadType = "EXISTING"; + } + leadRepository.saveAndFlush(lead); + + EventLead eventLead = new EventLead(); + eventLead.setCompanyId(req.companyId()); + eventLead.setEventUuid(req.eventUuid()); + eventLead.setLeadUuid(lead.getUuid()); + eventLead.setSalespersonUserId(req.salespersonUserId()); + eventLead.setLeadType(leadType); + eventLead.setTemperature(req.temperature()); + eventLead.setStatus(req.status() == null ? "OPEN" : req.status()); + eventLead.setNextFollowUpDate(req.nextFollowUpDate()); + eventLead.setNotes(req.notes()); + eventLead.setCapturedBy(req.doneBy()); + try { + eventLead = eventLeadRepository.saveAndFlush(eventLead); + } catch (DataIntegrityViolationException e) { + // uk_event_lead_event_lead: another capture of the same person at this event won the race. + throw new ResponseStatusException(HttpStatus.CONFLICT, "ALREADY_CAPTURED"); + } + + List interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds()); + return detail(eventLead, lead, interestIds); + } + + public EventLeadDetail findByUuid(long companyId, long eventLeadUuid) { + EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(eventLeadUuid, companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + List interestIds = eventLeadInterestRepository.findByIdEventLeadId(eventLead.getId()).stream() + .map(r -> r.getId().getInterestId()).toList(); + return detail(eventLead, lead, interestIds); + } + + public Page search(EventLeadSearchRequest req) { + Pageable pageable = PageRequest.of(Math.max(req.page(), 0), Math.min(Math.max(req.size(), 1), MAX_PAGE_SIZE), + Sort.by(Sort.Order.desc("capturedAt"), Sort.Order.desc("id"))); + Page rows = eventLeadRepository.search(req.companyId(), req.eventUuid(), req.salespersonUserId(), + blankToNull(req.temperature()), blankToNull(req.status()), req.interestId(), blankToNull(req.leadType()), pageable); + if (rows.isEmpty()) return rows.map(r -> null); + Map> interests = eventLeadInterestRepository + .findByIdEventLeadIdIn(rows.map(r -> ((EventLead) r[0]).getId()).getContent()).stream() + .collect(Collectors.groupingBy(i -> i.getId().getEventLeadId(), + Collectors.mapping(i -> i.getId().getInterestId(), Collectors.toList()))); + return rows.map(r -> { + EventLead e = (EventLead) r[0]; + return detail(e, (Lead) r[1], interests.getOrDefault(e.getId(), List.of())); + }); + } + + @Transactional + public EventLeadDetail update(EventLeadUpdateRequest req) { + EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(req.eventLeadUuid(), req.companyId()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + eventLead.setSalespersonUserId(req.salespersonUserId()); + eventLead.setTemperature(blankToNull(req.temperature())); + if (req.status() != null) eventLead.setStatus(req.status()); + eventLead.setNextFollowUpDate(req.nextFollowUpDate()); + eventLead.setNotes(blankToNull(req.notes())); + eventLead.setUpdatedBy(req.doneBy()); + eventLead.setUpdatedAt(LocalDateTime.now()); + eventLead = eventLeadRepository.saveAndFlush(eventLead); + eventLeadInterestRepository.deleteByEventLeadId(eventLead.getId()); + List interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds()); + Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), req.companyId()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + return detail(eventLead, lead, interestIds); + } + + private List saveInterests(long eventLeadId, long companyId, List requested) { + List ids = requested == null ? List.of() : requested.stream().filter(Objects::nonNull).distinct().toList(); + if (!ids.isEmpty()) { + eventLeadInterestRepository.saveAll(ids.stream().map(id -> { + EventLeadInterest row = new EventLeadInterest(); + row.setId(new EventLeadInterestId(eventLeadId, id)); + row.setCompanyId(companyId); + return row; + }).toList()); + } + return ids; + } + + private static EventLeadDetail detail(EventLead e, Lead l, List interestIds) { + return new EventLeadDetail(e.getUuid(), e.getEventUuid(), l.getUuid(), l.getName(), l.getMobileE164(), + l.getEmailNormalised(), l.getCompanyName(), l.getJobTitle(), e.getLeadType(), e.getSalespersonUserId(), + e.getTemperature(), e.getStatus(), e.getNextFollowUpDate(), e.getNotes(), e.getCapturedAt(), interestIds); + } + + private static void fillBlank(String current, String offered, Consumer setter) { + if (blankToNull(current) == null && blankToNull(offered) != null) setter.accept(offered); + } + + private static String blankToNull(String s) { + return s == null || s.isBlank() ? null : s; + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventLeadControllerTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventLeadControllerTest.java new file mode 100644 index 0000000..841add4 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventLeadControllerTest.java @@ -0,0 +1,71 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import com.solvway.services.counter.dto.EventLeadDetail; +import com.solvway.services.counter.dto.EventLeadSearchRequest; +import com.solvway.services.counter.dto.EventLeadUpdateRequest; +import com.solvway.services.counter.dto.LeadMatch; +import com.solvway.services.counter.dto.LeadMatchRequest; +import com.solvway.services.counter.service.EventLeadService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** EventLeadController delegates to the service and returns its result. */ +@ExtendWith(MockitoExtension.class) +class EventLeadControllerTest { + + @Mock private EventLeadService service; + + @Test + void findMatchesDelegates() { + LeadMatchRequest req = new LeadMatchRequest(42L, 1L, "+60123456789", null); + List out = List.of(new LeadMatch(2L, "Aisyah", "+60123456789", null, null, null, null)); + when(service.findMatches(req)).thenReturn(out); + + assertThat(new EventLeadController(service).findMatches(req)).isSameAs(out); + } + + @Test + void captureReturnsTheCapturedEventLead() { + EventLeadCaptureRequest req = mock(EventLeadCaptureRequest.class); + EventLeadDetail out = mock(EventLeadDetail.class); + when(service.capture(req)).thenReturn(out); + + assertThat(new EventLeadController(service).capture(req)).isSameAs(out); + } + + @Test + void findByUuidDelegates() { + EventLeadDetail out = mock(EventLeadDetail.class); + when(service.findByUuid(42L, 9L)).thenReturn(out); + + assertThat(new EventLeadController(service).findByUuid(42L, 9L)).isSameAs(out); + } + + @Test + void findByEventDelegates() { + EventLeadSearchRequest req = new EventLeadSearchRequest(42L, 1L, null, null, null, null, null, 0, 20); + Page out = Page.empty(); + when(service.search(req)).thenReturn(out); + + assertThat(new EventLeadController(service).findByEvent(req)).isSameAs(out); + } + + @Test + void updateDelegates() { + EventLeadUpdateRequest req = mock(EventLeadUpdateRequest.class); + EventLeadDetail out = mock(EventLeadDetail.class); + when(service.update(req)).thenReturn(out); + + assertThat(new EventLeadController(service).update(req)).isSameAs(out); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/model/LeadMappingTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/model/LeadMappingTest.java new file mode 100644 index 0000000..a9cee1c --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/model/LeadMappingTest.java @@ -0,0 +1,32 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Table; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Lead's column names that the default naming strategy gets wrong: mobileE164 would map to `mobilee164`, + * and LEAD is a MySQL 8 reserved word, so the table name must stay quoted. + */ +class LeadMappingTest { + + @Test + void mobileMapsToMobileE164Column() throws Exception { + Column column = Lead.class.getDeclaredField("mobileE164").getAnnotation(Column.class); + assertThat(column).isNotNull(); + assertThat(column.name()).isEqualTo("mobile_e164"); + } + + @Test + void tableNameIsQuoted() { + assertThat(Lead.class.getAnnotation(Table.class).name()).isEqualTo("`lead`"); + } + + @Test + void eventLeadInterestRowsAreAlwaysInsertedWithoutALookup() { + // Rows are only ever inserted (replacing the set deletes in bulk first), so saveAll must persist, not merge. + assertThat(new EventLeadInterest().isNew()).isTrue(); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadListAndUpdateTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadListAndUpdateTest.java new file mode 100644 index 0000000..863bd9a --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadListAndUpdateTest.java @@ -0,0 +1,212 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.EventLeadDetail; +import com.solvway.services.counter.dto.EventLeadSearchRequest; +import com.solvway.services.counter.dto.EventLeadUpdateRequest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.EventLeadInterest; +import com.solvway.services.counter.model.EventLeadInterestId; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** EventLeadService: the event leads listing and the event lead edit. */ +@ExtendWith(MockitoExtension.class) +class EventLeadListAndUpdateTest { + + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository eventLeadInterestRepository; + + private EventLeadService service; + + @BeforeEach + void setUp() { + service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository); + } + + @Test + void listingPassesEveryFilterAndPagesNewestCaptureFirstWithIdTieBreak() { + when(eventLeadRepository.search(eq(COMPANY), eq(EVENT), eq(11L), eq("HOT"), eq("OPEN"), eq(3L), eq("NEW"), any())) + .thenReturn(Page.empty()); + + service.search(new EventLeadSearchRequest(COMPANY, EVENT, 11L, "HOT", "OPEN", 3L, "NEW", 2, 25)); + + ArgumentCaptor pageable = ArgumentCaptor.forClass(Pageable.class); + verify(eventLeadRepository).search(eq(COMPANY), eq(EVENT), eq(11L), eq("HOT"), eq("OPEN"), eq(3L), eq("NEW"), pageable.capture()); + assertThat(pageable.getValue().getPageNumber()).isEqualTo(2); + assertThat(pageable.getValue().getPageSize()).isEqualTo(25); + assertThat(pageable.getValue().getSort().toString()).isEqualTo("capturedAt: DESC,id: DESC"); + } + + @Test + void blankFiltersAreIgnoredAndPageSizeIsBounded() { + when(eventLeadRepository.search(eq(COMPANY), eq(EVENT), eq(null), eq(null), eq(null), eq(null), eq(null), any())) + .thenReturn(Page.empty()); + + service.search(new EventLeadSearchRequest(COMPANY, EVENT, null, " ", "", null, null, -1, 1000)); + + ArgumentCaptor pageable = ArgumentCaptor.forClass(Pageable.class); + verify(eventLeadRepository).search(eq(COMPANY), eq(EVENT), eq(null), eq(null), eq(null), eq(null), eq(null), pageable.capture()); + assertThat(pageable.getValue().getPageNumber()).isZero(); + assertThat(pageable.getValue().getPageSize()).isEqualTo(100); + } + + @Test + void listingRowsCarryLeadDetailsAndInterestsFetchedInOneQuery() { + EventLead a = eventLead(1L, 501L); + EventLead b = eventLead(2L, 502L); + Lead la = lead(501L, "Aisyah"); + Lead lb = lead(502L, "Ahmad"); + when(eventLeadRepository.search(eq(COMPANY), eq(EVENT), any(), any(), any(), any(), any(), any())) + .thenReturn(new PageImpl<>(List.of(new Object[]{a, la}, new Object[]{b, lb}), PageRequest.of(0, 20), 2)); + when(eventLeadInterestRepository.findByIdEventLeadIdIn(anyCollection())) + .thenReturn(List.of(row(1L, 3L), row(1L, 4L), row(2L, 3L))); + + Page page = service.search(new EventLeadSearchRequest(COMPANY, EVENT, null, null, null, null, null, 0, 20)); + + assertThat(page.getTotalElements()).isEqualTo(2); + assertThat(page.getContent()).extracting(EventLeadDetail::name).containsExactly("Aisyah", "Ahmad"); + assertThat(page.getContent().get(0).interestIds()).containsExactlyInAnyOrder(3L, 4L); + assertThat(page.getContent().get(1).interestIds()).containsExactly(3L); + verify(eventLeadInterestRepository).findByIdEventLeadIdIn(anyCollection()); + } + + @Test + void emptyPageSkipsTheInterestQuery() { + when(eventLeadRepository.search(eq(COMPANY), eq(EVENT), any(), any(), any(), any(), any(), any())).thenReturn(Page.empty()); + + assertThat(service.search(new EventLeadSearchRequest(COMPANY, EVENT, null, null, null, null, null, 0, 20)).getContent()).isEmpty(); + verify(eventLeadInterestRepository, never()).findByIdEventLeadIdIn(anyCollection()); + } + + @Test + void updateReplacesWorkingFieldsAndTheInterestSet() { + EventLead el = eventLead(7L, 501L); + when(eventLeadRepository.findByUuidAndCompanyId(el.getUuid(), COMPANY)).thenReturn(Optional.of(el)); + when(eventLeadRepository.saveAndFlush(el)).thenReturn(el); + when(leadRepository.findByUuidAndCompanyId(501L, COMPANY)).thenReturn(Optional.of(lead(501L, "Aisyah"))); + + EventLeadDetail detail = service.update(new EventLeadUpdateRequest(COMPANY, el.getUuid(), 12L, "COLD", "CONTACTED", + List.of(4L, 4L, 5L), LocalDate.of(2027, 1, 20), "called back", "sales2")); + + assertThat(el.getSalespersonUserId()).isEqualTo(12L); + assertThat(el.getTemperature()).isEqualTo("COLD"); + assertThat(el.getStatus()).isEqualTo("CONTACTED"); + assertThat(el.getNextFollowUpDate()).isEqualTo(LocalDate.of(2027, 1, 20)); + assertThat(el.getNotes()).isEqualTo("called back"); + assertThat(el.getUpdatedBy()).isEqualTo("sales2"); + assertThat(el.getUpdatedAt()).isNotNull(); + assertThat(detail.interestIds()).containsExactlyInAnyOrder(4L, 5L); + + InOrder order = inOrder(eventLeadInterestRepository); + order.verify(eventLeadInterestRepository).deleteByEventLeadId(7L); + @SuppressWarnings("unchecked") + ArgumentCaptor> rows = ArgumentCaptor.forClass(List.class); + order.verify(eventLeadInterestRepository).saveAll(rows.capture()); + assertThat(rows.getValue()).extracting(r -> r.getId().getInterestId()).containsExactlyInAnyOrder(4L, 5L); + } + + @Test + void updateCanClearTemperatureSalespersonAndInterests() { + EventLead el = eventLead(7L, 501L); + el.setTemperature("HOT"); + el.setSalespersonUserId(11L); + when(eventLeadRepository.findByUuidAndCompanyId(el.getUuid(), COMPANY)).thenReturn(Optional.of(el)); + when(eventLeadRepository.saveAndFlush(el)).thenReturn(el); + when(leadRepository.findByUuidAndCompanyId(501L, COMPANY)).thenReturn(Optional.of(lead(501L, "Aisyah"))); + + service.update(new EventLeadUpdateRequest(COMPANY, el.getUuid(), null, null, "OPEN", List.of(), null, null, "sales2")); + + assertThat(el.getTemperature()).isNull(); + assertThat(el.getSalespersonUserId()).isNull(); + verify(eventLeadInterestRepository).deleteByEventLeadId(7L); + verify(eventLeadInterestRepository, never()).saveAll(any()); + } + + @Test + void updateOfUnknownOrOtherCompanyEventLeadIsNotFound() { + when(eventLeadRepository.findByUuidAndCompanyId(9L, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.update(new EventLeadUpdateRequest(COMPANY, 9L, null, null, "OPEN", List.of(), null, null, "x"))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + verify(eventLeadInterestRepository, never()).deleteByEventLeadId(any(Long.class)); + } + + @Test + void updateWithoutStatusKeepsTheCurrentStatus() { + EventLead el = eventLead(7L, 501L); + el.setStatus("WON"); + when(eventLeadRepository.findByUuidAndCompanyId(el.getUuid(), COMPANY)).thenReturn(Optional.of(el)); + when(eventLeadRepository.saveAndFlush(el)).thenReturn(el); + when(leadRepository.findByUuidAndCompanyId(501L, COMPANY)).thenReturn(Optional.of(lead(501L, "Aisyah"))); + + service.update(new EventLeadUpdateRequest(COMPANY, el.getUuid(), null, null, null, List.of(), null, null, "sales2")); + + assertThat(el.getStatus()).isEqualTo("WON"); + } + + @Test + void updateIsOneTransaction() throws Exception { + assertThat(EventLeadService.class.getMethod("update", EventLeadUpdateRequest.class) + .isAnnotationPresent(Transactional.class)).isTrue(); + } + + private static EventLead eventLead(long id, long leadUuid) { + EventLead e = new EventLead(); + e.setId(id); + e.setCompanyId(COMPANY); + e.setEventUuid(EVENT); + e.setLeadUuid(leadUuid); + e.setLeadType("NEW"); + e.setStatus("OPEN"); + return e; + } + + private static Lead lead(long uuid, String name) { + Lead l = new Lead(); + l.setUuid(uuid); + l.setCompanyId(COMPANY); + l.setName(name); + return l; + } + + private static EventLeadInterest row(long eventLeadId, long interestId) { + EventLeadInterest r = new EventLeadInterest(); + r.setId(new EventLeadInterestId(eventLeadId, interestId)); + return r; + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadServiceTest.java new file mode 100644 index 0000000..68e7065 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadServiceTest.java @@ -0,0 +1,299 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import com.solvway.services.counter.dto.EventLeadDetail; +import com.solvway.services.counter.dto.LeadMatch; +import com.solvway.services.counter.dto.LeadMatchRequest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.EventLeadInterest; +import com.solvway.services.counter.model.EventLeadInterestId; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** EventLeadService: matching, capture (NEW / EXISTING, fill blanks only, already captured) and find. */ +@ExtendWith(MockitoExtension.class) +class EventLeadServiceTest { + + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + private static final long LEAD_UUID = 2000L; + private static final String MOBILE = "+60123456789"; + private static final String EMAIL = "aisyah@example.com"; + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository eventLeadInterestRepository; + + private EventLeadService service; + + @BeforeEach + void setUp() { + service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository); + } + + // --- findMatches --- + + @Test + void matchesByMobileOrEmailNewestFirstAtMostTwenty() { + Lead a = lead(LEAD_UUID, "Aisyah", MOBILE, null, null); + when(leadRepository.findMatches(COMPANY, MOBILE, EMAIL, PageRequest.of(0, 20))).thenReturn(List.of(a)); + + List matches = service.findMatches(new LeadMatchRequest(COMPANY, EVENT, MOBILE, EMAIL)); + + assertThat(matches).extracting(LeadMatch::leadUuid).containsExactly(LEAD_UUID); + assertThat(matches.get(0).eventLeadUuid()).isNull(); + } + + @Test + void blankMobileIsNotMatchedOn() { + when(leadRepository.findMatches(eq(COMPANY), eq(null), eq(EMAIL), any())).thenReturn(List.of()); + + service.findMatches(new LeadMatchRequest(COMPANY, EVENT, " ", EMAIL)); + + verify(leadRepository).findMatches(eq(COMPANY), eq(null), eq(EMAIL), any()); + } + + @Test + void blankEmailIsNotMatchedOn() { + when(leadRepository.findMatches(eq(COMPANY), eq(MOBILE), eq(null), any())).thenReturn(List.of()); + + service.findMatches(new LeadMatchRequest(COMPANY, EVENT, MOBILE, "")); + + verify(leadRepository).findMatches(eq(COMPANY), eq(MOBILE), eq(null), any()); + } + + @Test + void bothBlankFindsNothingWithoutQuerying() { + assertThat(service.findMatches(new LeadMatchRequest(COMPANY, EVENT, null, " "))).isEmpty(); + verify(leadRepository, never()).findMatches(anyLong(), any(), any(), any()); + } + + @Test + void matchAlreadyCapturedAtThisEventCarriesItsEventLeadUuid() { + Lead a = lead(LEAD_UUID, "Aisyah", MOBILE, null, null); + Lead b = lead(LEAD_UUID + 1, "Ahmad", MOBILE, null, null); + when(leadRepository.findMatches(eq(COMPANY), eq(MOBILE), eq(null), any())).thenReturn(List.of(a, b)); + EventLead captured = eventLead(LEAD_UUID, "NEW"); + when(eventLeadRepository.findByEventUuidAndLeadUuidIn(eq(EVENT), anyCollection())).thenReturn(List.of(captured)); + + List matches = service.findMatches(new LeadMatchRequest(COMPANY, EVENT, MOBILE, null)); + + assertThat(matches.get(0).eventLeadUuid()).isEqualTo(captured.getUuid()); + assertThat(matches.get(1).eventLeadUuid()).isNull(); + } + + // --- capture --- + + @Test + void newPersonCreatesLeadAndNewEventLeadWithInterests() { + when(leadRepository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); + when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> withId(inv.getArgument(0), 7L)); + + EventLeadDetail detail = service.capture(request(null, "Aisyah", MOBILE, EMAIL, "Acme", List.of(3L, 3L, 4L))); + + ArgumentCaptor lead = ArgumentCaptor.forClass(Lead.class); + verify(leadRepository).saveAndFlush(lead.capture()); + assertThat(lead.getValue().getCompanyId()).isEqualTo(COMPANY); + assertThat(lead.getValue().getName()).isEqualTo("Aisyah"); + assertThat(lead.getValue().getMobileE164()).isEqualTo(MOBILE); + assertThat(lead.getValue().getEmailNormalised()).isEqualTo(EMAIL); + assertThat(lead.getValue().getNotes()).isNull(); + assertThat(detail.leadType()).isEqualTo("NEW"); + assertThat(detail.status()).isEqualTo("OPEN"); + assertThat(detail.leadUuid()).isEqualTo(lead.getValue().getUuid()); + assertThat(detail.interestIds()).containsExactlyInAnyOrder(3L, 4L); + + @SuppressWarnings("unchecked") + ArgumentCaptor> rows = ArgumentCaptor.forClass(List.class); + verify(eventLeadInterestRepository).saveAll(rows.capture()); + assertThat(rows.getValue()).extracting(r -> r.getId().getEventLeadId()).containsOnly(7L); + assertThat(rows.getValue()).extracting(EventLeadInterest::getCompanyId).containsOnly(COMPANY); + } + + @Test + void pickedLeadIsExistingAndOnlyBlankFieldsAreFilled() { + Lead stored = lead(LEAD_UUID, "Aisyah", MOBILE, null, "Acme"); + stored.setNotes("met at expo"); + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.of(stored)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, LEAD_UUID)).thenReturn(Optional.empty()); + when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> withId(inv.getArgument(0), 8L)); + + EventLeadDetail detail = service.capture(request(LEAD_UUID, "Aisyah Binti Ali", "+60199999999", EMAIL, "Other Co", List.of())); + + assertThat(detail.leadType()).isEqualTo("EXISTING"); + assertThat(stored.getName()).isEqualTo("Aisyah"); + assertThat(stored.getMobileE164()).isEqualTo(MOBILE); + assertThat(stored.getEmailNormalised()).isEqualTo(EMAIL); + assertThat(stored.getCompanyName()).isEqualTo("Acme"); + assertThat(stored.getJobTitle()).isEqualTo("Buyer"); + assertThat(stored.getNotes()).isEqualTo("met at expo"); + assertThat(stored.getUpdatedBy()).isEqualTo("sales1"); + verify(leadRepository).saveAndFlush(stored); + verify(eventLeadInterestRepository, never()).saveAll(any()); + } + + @Test + void alreadyCapturedAtThisEventIsRefusedAndNothingIsWritten() { + Lead stored = lead(LEAD_UUID, "Aisyah", MOBILE, null, null); + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.of(stored)); + EventLead already = eventLead(LEAD_UUID, "NEW"); + long capturedUuid = already.getUuid(); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, LEAD_UUID)).thenReturn(Optional.of(already)); + + assertThatThrownBy(() -> service.capture(request(LEAD_UUID, "Aisyah", MOBILE, EMAIL, null, List.of(3L)))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("ALREADY_CAPTURED") + .satisfies(e -> assertThat(((ResponseStatusException) e).getBody().getProperties()) + .containsEntry("eventLeadUuid", String.valueOf(capturedUuid))); + verify(leadRepository, never()).saveAndFlush(any()); + verify(eventLeadRepository, never()).saveAndFlush(any()); + verify(eventLeadInterestRepository, never()).saveAll(any()); + } + + @Test + void concurrentCaptureHittingTheUniqueKeyIsAlreadyCaptured() { + Lead stored = lead(LEAD_UUID, "Aisyah", MOBILE, null, null); + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.of(stored)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, LEAD_UUID)).thenReturn(Optional.empty()); + when(eventLeadRepository.saveAndFlush(any())).thenThrow(new DataIntegrityViolationException("uk_event_lead_event_lead")); + + assertThatThrownBy(() -> service.capture(request(LEAD_UUID, "Aisyah", MOBILE, null, null, List.of()))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("ALREADY_CAPTURED"); + } + + @Test + void leadOfAnotherCompanyIsNotFound() { + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.capture(request(LEAD_UUID, "Aisyah", MOBILE, null, null, List.of()))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + verify(eventLeadRepository, never()).saveAndFlush(any()); + } + + @Test + void captureIsOneTransaction() throws Exception { + assertThat(EventLeadService.class.getMethod("capture", EventLeadCaptureRequest.class) + .isAnnotationPresent(Transactional.class)).isTrue(); + } + + @Test + void mobileAndEmailMatchingDifferentLeadsReturnsBothUnmerged() { + Lead byMobile = lead(LEAD_UUID, "A", MOBILE, null, null); + Lead byEmail = lead(LEAD_UUID + 1, "B", null, "b@example.com", null); + when(leadRepository.findMatches(eq(COMPANY), eq(MOBILE), eq("b@example.com"), any())).thenReturn(List.of(byEmail, byMobile)); + EventLead bHere = eventLead(LEAD_UUID + 1, "NEW"); + when(eventLeadRepository.findByEventUuidAndLeadUuidIn(eq(EVENT), anyCollection())).thenReturn(List.of(bHere)); + + List matches = service.findMatches(new LeadMatchRequest(COMPANY, EVENT, MOBILE, "b@example.com")); + + assertThat(matches).extracting(LeadMatch::name).containsExactly("B", "A"); + assertThat(matches).extracting(LeadMatch::mobileE164).containsExactly(null, MOBILE); + assertThat(matches).extracting(LeadMatch::email).containsExactly("b@example.com", null); + assertThat(matches.get(0).eventLeadUuid()).isEqualTo(bHere.getUuid()); + assertThat(matches.get(1).eventLeadUuid()).isNull(); + } + + @Test + void failureSavingInterestsPropagatesSoTheTransactionRollsBack() { + when(leadRepository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); + when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> withId(inv.getArgument(0), 7L)); + RuntimeException boom = new org.springframework.dao.DataIntegrityViolationException("interest insert failed"); + when(eventLeadInterestRepository.saveAll(any())).thenThrow(boom); + + assertThatThrownBy(() -> service.capture(request(null, "Aisyah", MOBILE, null, null, List.of(3L)))).isSameAs(boom); + } + + // --- findByUuid --- + + @Test + void findByUuidReturnsEventLeadWithLeadAndInterests() { + EventLead el = withId(eventLead(LEAD_UUID, "EXISTING"), 9L); + when(eventLeadRepository.findByUuidAndCompanyId(el.getUuid(), COMPANY)).thenReturn(Optional.of(el)); + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.of(lead(LEAD_UUID, "Aisyah", MOBILE, EMAIL, "Acme"))); + EventLeadInterest row = new EventLeadInterest(); + row.setId(new EventLeadInterestId(9L, 3L)); + when(eventLeadInterestRepository.findByIdEventLeadId(9L)).thenReturn(List.of(row)); + + EventLeadDetail detail = service.findByUuid(COMPANY, el.getUuid()); + + assertThat(detail.name()).isEqualTo("Aisyah"); + assertThat(detail.companyName()).isEqualTo("Acme"); + assertThat(detail.leadType()).isEqualTo("EXISTING"); + assertThat(detail.eventUuid()).isEqualTo(EVENT); + assertThat(detail.interestIds()).containsExactly(3L); + } + + @Test + void findByUuidOfAnotherCompanyIsNotFound() { + when(eventLeadRepository.findByUuidAndCompanyId(5L, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.findByUuid(COMPANY, 5L)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + } + + // --- helpers --- + + private static EventLeadCaptureRequest request(Long leadUuid, String name, String mobile, String email, + String companyName, List interestIds) { + return new EventLeadCaptureRequest(COMPANY, EVENT, leadUuid, name, mobile, email, companyName, "Buyer", + 11L, "HOT", null, interestIds, LocalDate.of(2027, 1, 20), "wants a demo", "sales1"); + } + + private static Lead lead(long uuid, String name, String mobile, String email, String companyName) { + Lead l = new Lead(); + l.setUuid(uuid); + l.setCompanyId(COMPANY); + l.setName(name); + l.setMobileE164(mobile); + l.setEmailNormalised(email); + l.setCompanyName(companyName); + return l; + } + + private static EventLead eventLead(long leadUuid, String type) { + EventLead e = new EventLead(); + e.setCompanyId(COMPANY); + e.setEventUuid(EVENT); + e.setLeadUuid(leadUuid); + e.setLeadType(type); + e.setStatus("OPEN"); + return e; + } + + private static EventLead withId(EventLead e, long id) { + e.setId(id); + return e; + } +} -- 2.54.1 From 5d768b15666a3cac61991298830f3b2f49611f55 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 11:20:10 +0800 Subject: [PATCH 05/14] feat(mobile-api): admin interests API Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-event-lead-capture/tasks.md | 2 +- .../api/RestApiCounterServiceConstants.java | 3 + .../admin/AdminInterestController.java | 47 ++++++ .../api/dto/admin/AdminInterestRequest.java | 4 + .../api/service/AdminInterestService.java | 107 +++++++++++++ .../admin/AdminInterestControllerTest.java | 74 +++++++++ .../api/service/AdminInterestServiceTest.java | 151 ++++++++++++++++++ 7 files changed, 387 insertions(+), 1 deletion(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminInterestController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminInterestRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminInterestControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestServiceTest.java diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md index 4cafe19..7f23722 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -57,7 +57,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial ## 3. mobile-api -- [ ] 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. +- [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`. diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index a793e2e..0fb5b82 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -37,6 +37,9 @@ public class RestApiCounterServiceConstants { public static final String API_REST_COUNTER_EVENT_SAVE="/counter/event/save"; public static final String API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}"; public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace"; + public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}"; + public static final String API_REST_COUNTER_INTEREST_SAVE="/counter/interest/save"; + public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds"; //Event Product public static final String API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID = "/counter/eventProduct/findByEventUuid/{eventUuid}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminInterestController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminInterestController.java new file mode 100644 index 0000000..a2be84d --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminInterestController.java @@ -0,0 +1,47 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminInterestRequest; +import com.solvway.mobile.api.service.AdminInterestService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** Admin interest list. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +public class AdminInterestController { + private final AdminInterestService adminInterestService; + + @AppAuth + @AdminModule("BO_INTERESTS") + @GetMapping("/interests") + public ResponseEntity>> list() { + return ResponseEntity.ok(adminInterestService.list()); + } + + @AppAuth + @AdminModule("BO_INTERESTS") + @PostMapping("/interests") + public ResponseEntity> create(@RequestBody AdminInterestRequest request) { + return ResponseEntity.ok(adminInterestService.create(request)); + } + + @AppAuth + @AdminModule("BO_INTERESTS") + @PutMapping("/interests/{id}") + public ResponseEntity> update(@PathVariable long id, @RequestBody AdminInterestRequest request) { + return ResponseEntity.ok(adminInterestService.update(id, request)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminInterestRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminInterestRequest.java new file mode 100644 index 0000000..bd8ecc7 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminInterestRequest.java @@ -0,0 +1,4 @@ +package com.solvway.mobile.api.dto.admin; + +/** Create (name) or update (any field; omitted fields keep their stored value) an interest. */ +public record AdminInterestRequest(String name, Boolean active, Integer sortOrder) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java new file mode 100644 index 0000000..898dcdc --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java @@ -0,0 +1,107 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminInterestRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** The company's interest list (tags for leads). Company comes from the logged-in admin, never the request. */ +@Service +@RequiredArgsConstructor +public class AdminInterestService { + private static final int NAME_MAX = 100; + private static final ParameterizedTypeReference>> LIST = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + + public List> list() { + return load(caller().getCompanyId()).stream().map(AdminInterestService::row).toList(); + } + + public Map create(AdminInterestRequest r) { + User caller = caller(); + Map body = new LinkedHashMap<>(); + body.put("companyId", caller.getCompanyId()); + body.put("name", checkedName(r.name())); + body.put("active", r.active() == null || r.active()); + body.put("sortOrder", r.sortOrder() == null ? 0 : r.sortOrder()); + return save(body); + } + + public Map update(long id, AdminInterestRequest r) { + User caller = caller(); + Map stored = load(caller.getCompanyId()).stream() + .filter(m -> m.get("id") instanceof Number n && n.longValue() == id).findFirst() + .orElseThrow(() -> error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null)); + Map body = new LinkedHashMap<>(); + body.put("id", id); + body.put("companyId", caller.getCompanyId()); + body.put("name", r.name() == null ? stored.get("name") : checkedName(r.name())); + body.put("active", r.active() == null ? stored.get("active") : r.active()); + body.put("sortOrder", r.sortOrder() == null ? stored.get("sortOrder") : r.sortOrder()); + return save(body); + } + + private Map save(Map body) { + try { + return row(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_SAVE), MAP, body).getBody()); + } catch (HttpClientErrorException.Conflict e) { + throw error(HttpStatus.CONFLICT, "An interest with this name already exists", "DUPLICATE_NAME", "name"); + } + } + + private List> load(long companyId) { + List> rows = restTemplateUtil.getForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), LIST, companyId).getBody(); + return rows == null ? List.of() : rows; + } + + private static String checkedName(String name) { + String n = name == null ? "" : name.trim(); + if (n.isEmpty()) { + CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: name", "REQUIRED_FIELD", "name"); + e.getBody().setProperty("errors", List.of("name")); + throw e; + } + if (n.length() > NAME_MAX) throw error(HttpStatus.BAD_REQUEST, "Name is too long", "TOO_LONG", "name"); + return n; + } + + private static Map row(Map m) { + Map out = new LinkedHashMap<>(); + out.put("id", m.get("id")); + out.put("name", m.get("name")); + out.put("active", m.get("active")); + out.put("sortOrder", m.get("sortOrder")); + return out; + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null); + return caller; + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } + + private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) { + CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code); + if (field != null) e.getBody().setProperty("details", Map.of("field", field)); + return e; + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminInterestControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminInterestControllerTest.java new file mode 100644 index 0000000..ee90782 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminInterestControllerTest.java @@ -0,0 +1,74 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminInterestRequest; +import com.solvway.mobile.api.service.AdminInterestService; +import com.solvway.mobile.api.useraccess.AdminModule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminInterestControllerTest { + + @Mock private AdminInterestService interests; + @InjectMocks private AdminInterestController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void everyHandlerIsAuthenticatedAndGuardedByBoInterests() { + List handlers = Arrays.stream(AdminInterestController.class.getDeclaredMethods()) + .filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList(); + assertThat(handlers).hasSize(3); + for (Method m : handlers) { + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue(); + assertThat(Arrays.asList(m.getAnnotation(AdminModule.class).value())).as(m.getName()).containsExactly("BO_INTERESTS"); + } + } + + @Test + void listReturnsTheInterests() throws Exception { + when(interests.list()).thenReturn(List.of(Map.of("id", 1, "name", "Cookware"))); + mvc.perform(get("/api/admin/interests")).andExpect(status().isOk()) + .andExpect(content().json("[{\"id\":1,\"name\":\"Cookware\"}]")); + } + + @Test + void createAndUpdateBindTheBody() throws Exception { + when(interests.create(new AdminInterestRequest("Cookware", null, null))).thenReturn(Map.of("id", 1)); + mvc.perform(post("/api/admin/interests").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"Cookware\"}")) + .andExpect(status().isOk()); + verify(interests).create(new AdminInterestRequest("Cookware", null, null)); + + when(interests.update(2L, new AdminInterestRequest(null, false, null))).thenReturn(Map.of("id", 2)); + mvc.perform(put("/api/admin/interests/2").contentType(MediaType.APPLICATION_JSON).content("{\"active\":false}")) + .andExpect(status().isOk()); + verify(interests).update(2L, new AdminInterestRequest(null, false, null)); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestServiceTest.java new file mode 100644 index 0000000..d9d37cc --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestServiceTest.java @@ -0,0 +1,151 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminInterestRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminInterestServiceTest { + + private static final String LIST = "/counter/interest/findByCompany/{companyId}"; + private static final String SAVE = "/counter/interest/save"; + + private RestTemplateCustomUtil rest; + private AdminInterestService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + service = new AdminInterestService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + User caller = new User(); + caller.setUsername("boss"); + caller.setCompanyId(5L); + when(auth.loadUserByToken("tok")).thenReturn(caller); + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(i.getArgument(2))); + } + + @AfterEach + void close() { http.close(); } + + private static Map row(long id, String name, boolean active, int sort) { + Map m = new LinkedHashMap<>(); + m.put("id", id); + m.put("companyId", 5); + m.put("name", name); + m.put("active", active); + m.put("sortOrder", sort); + return m; + } + + private void stubList(Map... rows) { + when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(5L))).thenReturn(ResponseEntity.ok(List.of(rows))); + } + + private Map saved() { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture()); + return (Map) c.getValue(); + } + + private static void assertCoded(Runnable r, HttpStatus status, String code, String field) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + if (field != null) assertThat((Map) e.getBody().getProperties().get("details")).containsEntry("field", field); + }); + } + + @Test + void listIsTheCallersCompanyInterests() { + stubList(row(1, "Cookware", true, 0), row(2, "Old", false, 1)); + + assertThat(service.list()).extracting(m -> m.get("name")).containsExactly("Cookware", "Old"); + assertThat(service.list().get(1)).containsEntry("active", false).doesNotContainKey("companyId"); + } + + @Test + void createSendsTrimmedActiveInterestForTheCallersCompany() { + service.create(new AdminInterestRequest(" Kitchen appliances ", null, null)); + + assertThat(saved()).containsEntry("companyId", 5L).containsEntry("name", "Kitchen appliances") + .containsEntry("active", true).containsEntry("sortOrder", 0).doesNotContainKey("id"); + } + + @Test + void nameIsRequired() { + assertCoded(() -> service.create(new AdminInterestRequest(" ", null, null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD", "name"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void nameAtMostHundredCharacters() { + assertCoded(() -> service.create(new AdminInterestRequest("x".repeat(101), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "name"); + service.create(new AdminInterestRequest("x".repeat(100), null, null)); + } + + @Test + void duplicateNameIsAConflictOnTheNameField() { + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, null, null)); + + assertCoded(() -> service.create(new AdminInterestRequest("kitchen APPLIANCES", null, null)), HttpStatus.CONFLICT, "DUPLICATE_NAME", "name"); + } + + @Test + void updateDeactivatesKeepingNameAndOrder() { + stubList(row(2, "Cookware", true, 3)); + + service.update(2L, new AdminInterestRequest(null, false, null)); + + assertThat(saved()).containsEntry("id", 2L).containsEntry("companyId", 5L).containsEntry("name", "Cookware") + .containsEntry("active", false).containsEntry("sortOrder", 3); + } + + @Test + void updateRenamesAndReorders() { + stubList(row(2, "Cookware", true, 3)); + + service.update(2L, new AdminInterestRequest(" Pots ", null, 1)); + + assertThat(saved()).containsEntry("name", "Pots").containsEntry("sortOrder", 1).containsEntry("active", true); + } + + @Test + void updateOfAnInterestNotInTheCallersCompanyIsNotFound() { + stubList(row(2, "Cookware", true, 3)); + + assertCoded(() -> service.update(99L, new AdminInterestRequest("X", true, 0)), HttpStatus.NOT_FOUND, "INTEREST_NOT_FOUND", null); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } +} -- 2.54.1 From fe9d9bd38de056d4aee24d35a6fa6dc6bee9d9fa Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 11:37:27 +0800 Subject: [PATCH 06/14] feat(mobile-api): event leads API with phone normalisation and team rule Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-event-lead-capture/tasks.md | 2 +- solvway-mobile-api/pom.xml | 6 + .../api/RestApiCounterServiceConstants.java | 5 + .../admin/AdminEventLeadController.java | 93 +++ .../admin/AdminEventLeadCaptureRequest.java | 8 + .../admin/AdminEventLeadUpdateRequest.java | 7 + .../api/dto/admin/AdminLeadMatchRequest.java | 4 + .../api/service/AdminEventLeadService.java | 447 +++++++++++++++ .../mobile/api/service/EventLeadContact.java | 38 ++ .../admin/AdminEventLeadControllerTest.java | 111 ++++ .../service/AdminEventLeadServiceTest.java | 536 ++++++++++++++++++ .../api/service/EventLeadContactTest.java | 56 ++ 12 files changed, 1312 insertions(+), 1 deletion(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/EventLeadContact.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/EventLeadContactTest.java diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md index 7f23722..2e9b0f3 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -69,7 +69,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial - 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`. -- [ ] 3.2 Add the event-leads admin API (design decisions 2–7). +- [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` diff --git a/solvway-mobile-api/pom.xml b/solvway-mobile-api/pom.xml index 94b06ab..3e451a0 100644 --- a/solvway-mobile-api/pom.xml +++ b/solvway-mobile-api/pom.xml @@ -61,6 +61,12 @@ org.springframework.boot spring-boot-starter-validation + + + com.googlecode.libphonenumber + libphonenumber + 8.13.55 + org.springframework.boot diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index 0fb5b82..af58433 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -40,6 +40,11 @@ public class RestApiCounterServiceConstants { public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}"; public static final String API_REST_COUNTER_INTEREST_SAVE="/counter/interest/save"; public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds"; + public static final String API_REST_COUNTER_LEAD_FIND_MATCHES="/counter/lead/findMatches"; + public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture"; + public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}"; + public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update"; + public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT="/counter/eventLead/findByEvent"; //Event Product public static final String API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID = "/counter/eventProduct/findByEventUuid/{eventUuid}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java new file mode 100644 index 0000000..6eb3a36 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventLeadController.java @@ -0,0 +1,93 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest; +import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest; +import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest; +import com.solvway.mobile.api.service.AdminEventLeadService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** Event-floor lead capture: events, options, match, capture, listing and edit. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin/event-leads") +@RequiredArgsConstructor +public class AdminEventLeadController { + private final AdminEventLeadService adminEventLeadService; + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @GetMapping("/events") + public ResponseEntity>> events() { + return ResponseEntity.ok(adminEventLeadService.events()); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @GetMapping("/interest-options") + public ResponseEntity>> interestOptions() { + return ResponseEntity.ok(adminEventLeadService.interestOptions()); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @GetMapping("/{eventUuid}/salesperson-options") + public ResponseEntity>> salespersonOptions(@PathVariable String eventUuid) { + return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid)); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @PostMapping("/{eventUuid}/match") + public ResponseEntity> match(@PathVariable String eventUuid, @RequestBody AdminLeadMatchRequest request) { + return ResponseEntity.ok(adminEventLeadService.match(eventUuid, request)); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @PostMapping("/{eventUuid}") + public ResponseEntity> capture(@PathVariable String eventUuid, @RequestBody AdminEventLeadCaptureRequest request) { + return ResponseEntity.ok(adminEventLeadService.capture(eventUuid, request)); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @GetMapping("/{eventUuid}/leads") + public ResponseEntity> list(@PathVariable String eventUuid, + @RequestParam(required = false) Long salespersonId, + @RequestParam(required = false) String temperature, + @RequestParam(required = false) String status, + @RequestParam(required = false) Long interestId, + @RequestParam(required = false) String leadType, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ResponseEntity.ok(adminEventLeadService.list(eventUuid, salespersonId, temperature, status, interestId, leadType, page, size)); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @GetMapping("/{eventUuid}/leads/{eventLeadUuid}") + public ResponseEntity> get(@PathVariable String eventUuid, @PathVariable String eventLeadUuid) { + return ResponseEntity.ok(adminEventLeadService.get(eventUuid, eventLeadUuid)); + } + + @AppAuth + @AdminModule("BO_EVENT_LEADS") + @PutMapping("/{eventUuid}/leads/{eventLeadUuid}") + public ResponseEntity> update(@PathVariable String eventUuid, @PathVariable String eventLeadUuid, + @RequestBody AdminEventLeadUpdateRequest request) { + return ResponseEntity.ok(adminEventLeadService.update(eventUuid, eventLeadUuid, request)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java new file mode 100644 index 0000000..b4f3d34 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadCaptureRequest.java @@ -0,0 +1,8 @@ +package com.solvway.mobile.api.dto.admin; + +import java.util.List; + +/** Step 2 of capture. leadUuid is the picked match as a string, or null for a new person. nextFollowUpDate is YYYY-MM-DD. */ +public record AdminEventLeadCaptureRequest(String leadUuid, String name, String mobile, String email, String companyName, + String jobTitle, Long salespersonId, String temperature, String status, + List interestIds, String nextFollowUpDate, String notes) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java new file mode 100644 index 0000000..42b5a9e --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java @@ -0,0 +1,7 @@ +package com.solvway.mobile.api.dto.admin; + +import java.util.List; + +/** An event lead's working fields. nextFollowUpDate is YYYY-MM-DD; null clears it. */ +public record AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List interestIds, + String nextFollowUpDate, String notes) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java new file mode 100644 index 0000000..df705df --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLeadMatchRequest.java @@ -0,0 +1,4 @@ +package com.solvway.mobile.api.dto.admin; + +/** Step 1 of capture: the mobile and/or email to look up. */ +public record AdminLeadMatchRequest(String mobile, String email) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java new file mode 100644 index 0000000..78df6f5 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -0,0 +1,447 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.model.Event; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest; +import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest; +import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Lead capture at events for the admin portal. Validates and normalises at this boundary; services-counter stores. + * Company comes from the logged-in admin, never the request. Uuids leave as strings (Snowflake longs). + * Never log a lead's name, mobile or email. + */ +@Service +@RequiredArgsConstructor +@SuppressWarnings("unchecked") +public class AdminEventLeadService { + private static final Set TEMPERATURES = Set.of("HOT", "WARM", "COLD"); + private static final Set STATUSES = Set.of("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST"); + private static final Set LEAD_TYPES = Set.of("NEW", "EXISTING"); + private static final int EVENT_PAGE = 100; + private static final ObjectMapper JSON = new ObjectMapper(); + + private static final ParameterizedTypeReference PAGE = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + + // --- options --- + + /** Enabled events, newest start first. ponytail: one page of 100; add paging when a company has more enabled events. */ + public List> events() { + Map request = Map.of("property", Map.of("name", "", "enabled", "Y"), + "pageableRest", Map.of("number", 0, "size", EVENT_PAGE, "sorts", List.of(Map.of("direction", "DESC", "property", "dateStart")))); + AdminEventService.EventPage p = restTemplateUtil.postForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE), PAGE, request).getBody(); + if (p == null || p.content() == null) return List.of(); + return p.content().stream().map(e -> { + Map m = new LinkedHashMap<>(); + m.put("uuid", String.valueOf(e.getUuid())); + m.put("name", e.getName()); + m.put("location", e.getLocation()); + m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString()); + m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString()); + return m; + }).toList(); + } + + public List> interestOptions() { + return interests(caller().getCompanyId()).values().stream().filter(i -> Boolean.TRUE.equals(i.get("active"))).toList(); + } + + public List> salespersonOptions(String eventUuid) { + Event event = loadEvent(eventUuid); + List> out = new ArrayList<>(); + for (Long id : teamIds(event.getUuid())) { + Map u = user(id); + if (isActiveAdmin(u)) out.add(Map.of("id", id, "name", String.valueOf(u.get("name")), "username", String.valueOf(u.get("username")))); + } + return out; + } + + // --- capture --- + + public Map match(String eventUuid, AdminLeadMatchRequest r) { + User caller = caller(); + String mobile = mobile(r.mobile()); + String email = email(r.email()); + if (mobile == null && email == null) throw required(List.of("mobile", "email")); + Event event = loadEvent(eventUuid); + Map out = new LinkedHashMap<>(); + out.put("mobile", mobile); + out.put("email", email); + out.put("candidates", findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream().map(m -> { + Map c = new LinkedHashMap<>(); + c.put("leadUuid", str(m.get("leadUuid"))); + c.put("name", m.get("name")); + c.put("mobile", m.get("mobileE164")); + c.put("email", m.get("email")); + c.put("companyName", m.get("companyName")); + c.put("jobTitle", m.get("jobTitle")); + c.put("eventLeadUuid", str(m.get("eventLeadUuid"))); + return c; + }).toList()); + return out; + } + + public Map capture(String eventUuid, AdminEventLeadCaptureRequest r) { + User caller = caller(); + String name = trimmed(r.name()); + String mobile = mobile(r.mobile()); + String email = email(r.email()); + List missing = new ArrayList<>(); + if (name == null) missing.add("name"); + if (mobile == null && email == null) { missing.add("mobile"); missing.add("email"); } + if (!missing.isEmpty()) throw required(missing); + maxLength("name", name, 100); + maxLength("email", email, 254); + String companyName = maxLength("companyName", trimmed(r.companyName()), 150); + String jobTitle = maxLength("jobTitle", trimmed(r.jobTitle()), 100); + String temperature = oneOf("temperature", r.temperature(), TEMPERATURES); + String status = oneOf("status", r.status(), STATUSES); + LocalDate followUp = date(r.nextFollowUpDate()); + Long leadUuid = r.leadUuid() == null ? null : parseOr(r.leadUuid(), () -> error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null)); + + Event event = loadEvent(eventUuid); + if (event.getEnabled() != GeneralEnum.FlagYesNo.Y) { + throw error(HttpStatus.CONFLICT, "This event is disabled and cannot take new leads", "EVENT_DISABLED", null); + } + if (r.salespersonId() != null) checkOnTeam(event.getUuid(), r.salespersonId()); + Map> known = interests(caller.getCompanyId()); + List interestIds = checkedInterests(known, r.interestIds(), List.of()); + + Map body = new LinkedHashMap<>(); + body.put("companyId", caller.getCompanyId()); + body.put("eventUuid", event.getUuid()); + body.put("leadUuid", leadUuid); + body.put("name", name); + body.put("mobileE164", mobile); + body.put("email", email); + body.put("companyName", companyName); + body.put("jobTitle", jobTitle); + body.put("salespersonUserId", r.salespersonId()); + body.put("temperature", temperature); + body.put("status", status); + body.put("interestIds", interestIds); + body.put("nextFollowUpDate", followUp == null ? null : followUp.toString()); + body.put("notes", trimmed(r.notes())); + body.put("doneBy", caller.getUsername()); + try { + return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_CAPTURE), MAP, body).getBody(), + known, new HashMap<>()); + } catch (HttpClientErrorException.Conflict e) { + Object existing = conflictEventLeadUuid(e); + if (existing == null) existing = findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream() + .filter(m -> Objects.equals(str(m.get("leadUuid")), str(leadUuid))).map(m -> m.get("eventLeadUuid")) + .filter(Objects::nonNull).findFirst().orElse(null); + CodedResponseStatusException ex = new CodedResponseStatusException(HttpStatus.CONFLICT, + "This person is already captured at this event", "ALREADY_CAPTURED"); + if (existing != null) ex.getBody().setProperty("details", Map.of("eventLeadUuid", str(existing))); + throw ex; + } catch (HttpClientErrorException.NotFound e) { + throw error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null); + } + } + + // --- listing and edit --- + + public Map list(String eventUuid, Long salespersonId, String temperature, String status, Long interestId, + String leadType, int page, int size) { + User caller = caller(); + Event event = loadEvent(eventUuid); + Map body = new LinkedHashMap<>(); + body.put("companyId", caller.getCompanyId()); + body.put("eventUuid", event.getUuid()); + body.put("salespersonUserId", salespersonId); + body.put("temperature", oneOf("temperature", temperature, TEMPERATURES)); + body.put("status", oneOf("status", status, STATUSES)); + body.put("interestId", interestId); + body.put("leadType", oneOf("leadType", leadType, LEAD_TYPES)); + body.put("page", Math.max(page, 0)); + body.put("size", size); + Map p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), MAP, body).getBody(); + List> rows = p == null || p.get("content") == null ? List.of() : (List>) p.get("content"); + Map> interests = rows.isEmpty() ? Map.of() : interests(caller.getCompanyId()); + Map> users = new HashMap<>(); + Map out = new LinkedHashMap<>(); + out.put("content", rows.stream().map(row -> view(row, interests, users)).toList()); + out.put("totalElements", p == null ? 0 : p.get("totalElements")); + out.put("totalPages", p == null ? 0 : p.get("totalPages")); + out.put("number", p == null ? 0 : p.get("number")); + out.put("size", p == null ? size : p.get("size")); + return out; + } + + public Map get(String eventUuid, String eventLeadUuid) { + User caller = caller(); + return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId()); + } + + public Map update(String eventUuid, String eventLeadUuid, AdminEventLeadUpdateRequest r) { + User caller = caller(); + String temperature = oneOf("temperature", r.temperature(), TEMPERATURES); + String status = oneOf("status", r.status(), STATUSES); + LocalDate followUp = date(r.nextFollowUpDate()); + Map current = stored(caller.getCompanyId(), eventUuid, eventLeadUuid); + Long currentSalesperson = current.get("salespersonUserId") == null ? null : ((Number) current.get("salespersonUserId")).longValue(); + if (r.salespersonId() != null && !r.salespersonId().equals(currentSalesperson)) { + checkOnTeam(((Number) current.get("eventUuid")).longValue(), r.salespersonId()); + } + Map> known = interests(caller.getCompanyId()); + List interestIds = checkedInterests(known, r.interestIds(), longs(current.get("interestIds"))); + + Map body = new LinkedHashMap<>(); + body.put("companyId", caller.getCompanyId()); + body.put("eventLeadUuid", ((Number) current.get("eventLeadUuid")).longValue()); + body.put("salespersonUserId", r.salespersonId()); + body.put("temperature", temperature); + body.put("status", status); + body.put("interestIds", interestIds); + body.put("nextFollowUpDate", followUp == null ? null : followUp.toString()); + body.put("notes", trimmed(r.notes())); + body.put("doneBy", caller.getUsername()); + return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(), + known, new HashMap<>()); + } + + // --- rules --- + + /** A salesperson newly set must be an active admin on the event's current team. */ + private void checkOnTeam(long eventUuid, long userId) { + if (!teamIds(eventUuid).contains(userId) || !isActiveAdmin(user(userId))) { + throw error(HttpStatus.BAD_REQUEST, "The salesperson must be an active member of the event's team", "NOT_ON_TEAM", "salespersonId"); + } + } + + /** Ids must be the company's interests; one newly added must be active, one already on the lead may stay. */ + private static List checkedInterests(Map> known, List requested, List current) { + List ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList())); + for (Long id : ids) { + Map interest = known.get(id); + if (interest == null) throw error(HttpStatus.BAD_REQUEST, "Unknown interest " + id, "INVALID_VALUE", "interestIds"); + if (!Boolean.TRUE.equals(interest.get("active")) && !current.contains(id)) { + throw error(HttpStatus.BAD_REQUEST, "Interest " + interest.get("name") + " is no longer active", "INACTIVE_INTEREST", "interestIds"); + } + } + return ids; + } + + private Map stored(long companyId, String eventUuid, String eventLeadUuid) { + Event event = loadEvent(eventUuid); + long id = parseOr(eventLeadUuid, AdminEventLeadService::eventLeadNotFound); + Map d; + try { + d = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID), MAP, companyId, id).getBody(); + } catch (HttpClientErrorException.NotFound e) { + throw eventLeadNotFound(); + } + if (d == null || !(d.get("eventUuid") instanceof Number n) || n.longValue() != event.getUuid()) throw eventLeadNotFound(); + return d; + } + + // --- views --- + + private Map view(Map d, long companyId) { + return view(d, interests(companyId), new HashMap<>()); + } + + private Map view(Map d, Map> interests, Map> users) { + Map m = new LinkedHashMap<>(); + m.put("eventLeadUuid", str(d.get("eventLeadUuid"))); + m.put("eventUuid", str(d.get("eventUuid"))); + m.put("leadUuid", str(d.get("leadUuid"))); + m.put("name", d.get("name")); + m.put("mobile", d.get("mobileE164")); + m.put("email", d.get("email")); + m.put("companyName", d.get("companyName")); + m.put("jobTitle", d.get("jobTitle")); + m.put("leadType", d.get("leadType")); + Object sp = d.get("salespersonUserId"); + if (sp instanceof Number n) { + Map u = users.computeIfAbsent(n.longValue(), this::user); + m.put("salesperson", Map.of("id", n.longValue(), "name", u == null ? String.valueOf(n) : String.valueOf(u.get("name")))); + } else { + m.put("salesperson", null); + } + m.put("temperature", d.get("temperature")); + m.put("status", d.get("status")); + m.put("interests", longs(d.get("interestIds")).stream().map(id -> { + Map i = interests.get(id); + return Map.of("id", id, "name", i == null ? String.valueOf(id) : i.get("name"), + "active", i != null && Boolean.TRUE.equals(i.get("active"))); + }).toList()); + m.put("nextFollowUpDate", d.get("nextFollowUpDate")); + m.put("notes", d.get("notes")); + m.put("capturedAt", d.get("capturedAt")); + return m; + } + + // --- lookups --- + + private List> findMatches(long companyId, long eventUuid, String mobile, String email) { + Map body = new LinkedHashMap<>(); + body.put("companyId", companyId); + body.put("eventUuid", eventUuid); + body.put("mobileE164", mobile); + body.put("email", email); + List> rows = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_FIND_MATCHES), MAP_LIST, body).getBody(); + return rows == null ? List.of() : rows; + } + + /** id -> {id, name, active}, in the counter's order (sort order, then name). */ + private Map> interests(long companyId) { + List> rows = restTemplateUtil.getForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId).getBody(); + Map> out = new LinkedHashMap<>(); + if (rows != null) for (Map r : rows) { + long id = ((Number) r.get("id")).longValue(); + out.put(id, Map.of("id", id, "name", String.valueOf(r.get("name")), "active", Boolean.TRUE.equals(r.get("active")))); + } + return out; + } + + private List teamIds(long eventUuid) { + List> rows = restTemplateUtil.getForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID), MAP_LIST, eventUuid).getBody(); + return rows == null ? List.of() : rows.stream().map(m -> ((Number) m.get("userId")).longValue()).toList(); + } + + private Map user(Long id) { + return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody(); + } + + private Event loadEvent(String uuid) { + long id = parseOr(uuid, AdminEventLeadService::eventNotFound); + Event event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody(); + if (event == null) throw eventNotFound(); + return event; + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null); + return caller; + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } + + // --- small helpers --- + + private static Object conflictEventLeadUuid(HttpClientErrorException e) { + try { + return JSON.readValue(e.getResponseBodyAsString(), Map.class).get("eventLeadUuid"); + } catch (Exception ignored) { + return null; + } + } + + private static boolean isActiveAdmin(Map user) { + return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled")); + } + + private static String mobile(String input) { + try { + return EventLeadContact.mobile(input); + } catch (IllegalArgumentException e) { + throw error(HttpStatus.BAD_REQUEST, "Enter a valid mobile number", "INVALID_MOBILE", "mobile"); + } + } + + private static String email(String input) { + try { + return EventLeadContact.email(input); + } catch (IllegalArgumentException e) { + throw error(HttpStatus.BAD_REQUEST, "Enter a valid email address", "INVALID_EMAIL", "email"); + } + } + + private static LocalDate date(String input) { + if (input == null || input.isBlank()) return null; + try { + return LocalDate.parse(input.trim()); + } catch (DateTimeParseException e) { + throw error(HttpStatus.BAD_REQUEST, "Use a date like 2027-01-20", "INVALID_DATE", "nextFollowUpDate"); + } + } + + private static String oneOf(String field, String value, Set allowed) { + if (value == null || value.isBlank()) return null; + if (!allowed.contains(value)) throw error(HttpStatus.BAD_REQUEST, "Unknown " + field + " " + value, "INVALID_VALUE", field); + return value; + } + + private static String maxLength(String field, String value, int max) { + if (value != null && value.length() > max) throw error(HttpStatus.BAD_REQUEST, field + " is too long", "TOO_LONG", field); + return value; + } + + private static String trimmed(String s) { + return s == null || s.isBlank() ? null : s.trim(); + } + + private static long parseOr(String s, java.util.function.Supplier notFound) { + try { + return Long.parseLong(s.trim()); + } catch (RuntimeException e) { + throw notFound.get(); + } + } + + private static List longs(Object list) { + if (!(list instanceof List l)) return List.of(); + return l.stream().filter(Number.class::isInstance).map(o -> ((Number) o).longValue()).toList(); + } + + private static String str(Object o) { + return o == null ? null : String.valueOf(o); + } + + private static CodedResponseStatusException required(List fields) { + CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: " + String.join(", ", fields), "REQUIRED_FIELD", fields.get(0)); + e.getBody().setProperty("errors", fields); + return e; + } + + private static CodedResponseStatusException eventNotFound() { + return error(HttpStatus.NOT_FOUND, "Event not found", "EVENT_NOT_FOUND", null); + } + + private static CodedResponseStatusException eventLeadNotFound() { + return error(HttpStatus.NOT_FOUND, "Event lead not found", "EVENT_LEAD_NOT_FOUND", null); + } + + private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) { + CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code); + if (field != null) e.getBody().setProperty("details", Map.of("field", field)); + return e; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/EventLeadContact.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/EventLeadContact.java new file mode 100644 index 0000000..8a526b8 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/EventLeadContact.java @@ -0,0 +1,38 @@ +package com.solvway.mobile.api.service; + +import com.google.i18n.phonenumbers.NumberParseException; +import com.google.i18n.phonenumbers.PhoneNumberUtil; +import com.google.i18n.phonenumbers.Phonenumber; + +import java.util.Locale; +import java.util.regex.Pattern; + +/** + * Normalises a lead's contact values so the same person always has the same value: mobile numbers to E.164 + * (a number without a country code is Malaysian), emails trimmed and lowercased. Blank input is null; + * anything that is not a valid number or email address throws IllegalArgumentException. + */ +final class EventLeadContact { + private static final PhoneNumberUtil PHONES = PhoneNumberUtil.getInstance(); + private static final Pattern EMAIL = Pattern.compile("[^\\s@]+@[^\\s@]+\\.[^\\s@]+"); + + private EventLeadContact() {} + + static String mobile(String input) { + if (input == null || input.isBlank()) return null; + try { + Phonenumber.PhoneNumber number = PHONES.parse(input.trim(), "MY"); + if (PHONES.isValidNumber(number)) return PHONES.format(number, PhoneNumberUtil.PhoneNumberFormat.E164); + } catch (NumberParseException ignored) { + // falls through to the refusal below + } + throw new IllegalArgumentException("not a valid phone number"); + } + + static String email(String input) { + if (input == null || input.isBlank()) return null; + String email = input.trim().toLowerCase(Locale.ROOT); + if (!EMAIL.matcher(email).matches()) throw new IllegalArgumentException("not an email address"); + return email; + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java new file mode 100644 index 0000000..02117b8 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventLeadControllerTest.java @@ -0,0 +1,111 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest; +import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest; +import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest; +import com.solvway.mobile.api.service.AdminEventLeadService; +import com.solvway.mobile.api.useraccess.AdminModule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminEventLeadControllerTest { + + private static final String EV = "3312726793093644288"; + private static final String EL = "3312853897594494976"; + + @Mock private AdminEventLeadService eventLeads; + @InjectMocks private AdminEventLeadController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void everyHandlerIsAuthenticatedAndGuardedByBoEventLeads() { + List handlers = Arrays.stream(AdminEventLeadController.class.getDeclaredMethods()) + .filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList(); + assertThat(handlers).hasSize(8); + for (Method m : handlers) { + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue(); + assertThat(Arrays.asList(m.getAnnotation(AdminModule.class).value())).as(m.getName()).containsExactly("BO_EVENT_LEADS"); + } + } + + @Test + void optionsEndpoints() throws Exception { + when(eventLeads.events()).thenReturn(List.of(Map.of("uuid", EV, "name", "Fair"))); + mvc.perform(get("/api/admin/event-leads/events")).andExpect(status().isOk()) + .andExpect(content().json("[{\"uuid\":\"" + EV + "\",\"name\":\"Fair\"}]", true)); + when(eventLeads.interestOptions()).thenReturn(List.of(Map.of("id", 3, "name", "Cookware", "active", true))); + mvc.perform(get("/api/admin/event-leads/interest-options")).andExpect(status().isOk()); + when(eventLeads.salespersonOptions(EV)).thenReturn(List.of(Map.of("id", 21, "name", "Sales One", "username", "sales1"))); + mvc.perform(get("/api/admin/event-leads/" + EV + "/salesperson-options")).andExpect(status().isOk()) + .andExpect(content().json("[{\"id\":21,\"username\":\"sales1\"}]")); + } + + @Test + void matchAndCaptureBindTheirBodies() throws Exception { + when(eventLeads.match(EV, new AdminLeadMatchRequest("0123456789", null))).thenReturn(Map.of("candidates", List.of())); + mvc.perform(post("/api/admin/event-leads/" + EV + "/match").contentType(MediaType.APPLICATION_JSON) + .content("{\"mobile\":\"0123456789\"}")).andExpect(status().isOk()); + + AdminEventLeadCaptureRequest req = new AdminEventLeadCaptureRequest(null, "Aisyah", "0123456789", null, null, null, + 21L, "HOT", null, List.of(3L), "2027-01-20", null); + when(eventLeads.capture(EV, req)).thenReturn(Map.of("eventLeadUuid", EL)); + mvc.perform(post("/api/admin/event-leads/" + EV).contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"Aisyah\",\"mobile\":\"0123456789\",\"salespersonId\":21,\"temperature\":\"HOT\",\"interestIds\":[3],\"nextFollowUpDate\":\"2027-01-20\"}")) + .andExpect(status().isOk()).andExpect(content().json("{\"eventLeadUuid\":\"" + EL + "\"}", true)); + } + + @Test + void listPassesFiltersAndPaging() throws Exception { + when(eventLeads.list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25)).thenReturn(Map.of("content", List.of(), "totalElements", 0)); + mvc.perform(get("/api/admin/event-leads/" + EV + "/leads").param("salespersonId", "21").param("temperature", "HOT") + .param("status", "OPEN").param("interestId", "3").param("leadType", "NEW").param("page", "1").param("size", "25")) + .andExpect(status().isOk()); + verify(eventLeads).list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25); + + when(eventLeads.list(EV, null, null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of())); + mvc.perform(get("/api/admin/event-leads/" + EV + "/leads")).andExpect(status().isOk()); + verify(eventLeads).list(EV, null, null, null, null, null, 0, 20); + } + + @Test + void getAndUpdateAnEventLead() throws Exception { + when(eventLeads.get(EV, EL)).thenReturn(Map.of("eventLeadUuid", EL)); + mvc.perform(get("/api/admin/event-leads/" + EV + "/leads/" + EL)).andExpect(status().isOk()); + + AdminEventLeadUpdateRequest req = new AdminEventLeadUpdateRequest(21L, "COLD", "CONTACTED", List.of(3L), "2027-01-20", "call"); + when(eventLeads.update(EV, EL, req)).thenReturn(Map.of("eventLeadUuid", EL)); + mvc.perform(put("/api/admin/event-leads/" + EV + "/leads/" + EL).contentType(MediaType.APPLICATION_JSON) + .content("{\"salespersonId\":21,\"temperature\":\"COLD\",\"status\":\"CONTACTED\",\"interestIds\":[3],\"nextFollowUpDate\":\"2027-01-20\",\"notes\":\"call\"}")) + .andExpect(status().isOk()); + verify(eventLeads).update(EV, EL, req); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java new file mode 100644 index 0000000..830a191 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java @@ -0,0 +1,536 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.model.Event; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest; +import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest; +import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminEventLeadServiceTest { + + private static final String EVENTS = "/counter/event/findByPropertyAndPageable"; + private static final String EVENT = "/counter/event/findByUuid/{uuid}"; + private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}"; + private static final String USER = "/user/findById/{id}"; + private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}"; + private static final String MATCHES = "/counter/lead/findMatches"; + private static final String CAPTURE = "/counter/eventLead/capture"; + private static final String FIND = "/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}"; + private static final String UPDATE = "/counter/eventLead/update"; + private static final String SEARCH = "/counter/eventLead/findByEvent"; + + private static final long EV = 3312726793093644288L; + private static final long EL = 3312853897594494976L; + private static final long LEAD = 3312853897040846848L; + private static final long COMPANY = 5L; + + private RestTemplateCustomUtil rest; + private AdminEventLeadService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + service = new AdminEventLeadService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + User caller = new User(); + caller.setId(21L); + caller.setUsername("sales1"); + caller.setCompanyId(COMPANY); + when(auth.loadUserByToken("tok")).thenReturn(caller); + stubEvent(true); + stubTeam(21L, 22L); + stubUser(21L, "Sales One", true); + stubUser(22L, "Sales Two", true); + stubUser(23L, "Sales Three", true); + stubInterests(interest(3, "Cookware", true), interest(4, "Kitchen appliances", true), interest(5, "Old", false)); + when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(detailFrom((Map) i.getArgument(2)))); + when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(detailFrom((Map) i.getArgument(2)))); + } + + @AfterEach + void close() { http.close(); } + + // --- stubs --- + + private void stubEvent(boolean enabled) { + Event e = new Event(); + e.setUuid(EV); + e.setName("KL Food Fair 2027"); + e.setLocation("MITEC"); + e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0)); + e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + e.setEnabled(enabled ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N); + when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e)); + } + + private void stubTeam(long... userIds) { + List> rows = new java.util.ArrayList<>(); + for (long id : userIds) rows.add(Map.of("userId", id)); + when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(rows)); + } + + private void stubUser(long id, String name, boolean enabled) { + Map u = new HashMap<>(); + u.put("id", id); + u.put("name", name); + u.put("username", "u" + id); + u.put("type", "A"); + u.put("enabled", enabled); + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u)); + } + + private static Map interest(long id, String name, boolean active) { + return Map.of("id", id, "companyId", COMPANY, "name", name, "active", active, "sortOrder", 0); + } + + private void stubInterests(Map... rows) { + when(rest.getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(COMPANY))).thenReturn(ResponseEntity.ok(List.of(rows))); + } + + /** What the counter returns for a capture or update body. */ + private static Map detailFrom(Map body) { + Map d = new LinkedHashMap<>(); + d.put("eventLeadUuid", EL); + d.put("eventUuid", body.getOrDefault("eventUuid", EV)); + d.put("leadUuid", body.get("leadUuid") == null ? LEAD : body.get("leadUuid")); + d.put("name", body.getOrDefault("name", "Aisyah")); + d.put("mobileE164", body.get("mobileE164")); + d.put("email", body.get("email")); + d.put("companyName", body.get("companyName")); + d.put("jobTitle", body.get("jobTitle")); + d.put("leadType", body.get("leadUuid") == null ? "NEW" : "EXISTING"); + d.put("salespersonUserId", body.get("salespersonUserId")); + d.put("temperature", body.get("temperature")); + d.put("status", body.get("status") == null ? "OPEN" : body.get("status")); + d.put("nextFollowUpDate", body.get("nextFollowUpDate") == null ? null : body.get("nextFollowUpDate").toString()); + d.put("notes", body.get("notes")); + d.put("capturedAt", "2027-01-15T10:00:00"); + d.put("interestIds", body.getOrDefault("interestIds", List.of())); + return d; + } + + private void stubStored(long eventUuid, Long salespersonUserId, List interestIds) { + Map d = new LinkedHashMap<>(); + d.put("eventLeadUuid", EL); + d.put("eventUuid", eventUuid); + d.put("leadUuid", LEAD); + d.put("name", "Aisyah"); + d.put("mobileE164", "+60123456789"); + d.put("leadType", "NEW"); + d.put("salespersonUserId", salespersonUserId); + d.put("status", "OPEN"); + d.put("interestIds", interestIds); + when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL))).thenReturn(ResponseEntity.ok(d)); + } + + private static AdminEventLeadCaptureRequest capture(String leadUuid, String name, String mobile, String email) { + return new AdminEventLeadCaptureRequest(leadUuid, name, mobile, email, null, null, null, null, null, List.of(), null, null); + } + + private static AdminEventLeadCaptureRequest captureWith(Long salespersonId, String temperature, String status, List interests, String followUp) { + return new AdminEventLeadCaptureRequest(null, "Aisyah", "0123456789", null, null, null, salespersonId, temperature, status, interests, followUp, null); + } + + private Map sent(String api) { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture()); + return (Map) c.getValue(); + } + + private void assertNothingSent(String api) { + verify(rest, never()).postForEntity(eq(api), any(ParameterizedTypeReference.class), any()); + } + + private static void assertCoded(Runnable r, HttpStatus status, String code, String field) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + if (field != null) assertThat((Map) e.getBody().getProperties().get("details")).containsEntry("field", field); + }); + } + + // --- events and options --- + + @Test + void eventsAreTheEnabledOnesNewestFirst() { + Event e = new Event(); + e.setUuid(EV); + e.setName("KL Food Fair 2027"); + e.setLocation("MITEC"); + e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0)); + e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(e), 1, 1, 0, 100))); + + List> events = service.events(); + + assertThat(events).containsExactly(Map.of("uuid", String.valueOf(EV), "name", "KL Food Fair 2027", "location", "MITEC", + "startDate", "2027-01-15", "endDate", "2027-01-17")); + Map body = sent(EVENTS); + assertThat((Map) body.get("property")).containsEntry("enabled", "Y"); + Map pageable = (Map) body.get("pageableRest"); + assertThat(pageable).containsEntry("size", 100); + assertThat((List>) pageable.get("sorts")).containsExactly(Map.of("direction", "DESC", "property", "dateStart")); + } + + @Test + void eventWithEmptyFieldsStillListsWithNulls() { + Event e = new Event(); + e.setUuid(EV); + when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(e), 1, 1, 0, 100))); + + Map row = service.events().get(0); + + assertThat(row).containsEntry("uuid", String.valueOf(EV)).containsEntry("name", null) + .containsEntry("location", null).containsEntry("startDate", null).containsEntry("endDate", null); + } + + @Test + void emailLongerThanTheColumnIsTooLong() { + String email = "a".repeat(250) + "@x.co"; + assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", null, email)), HttpStatus.BAD_REQUEST, "TOO_LONG", "email"); + assertNothingSent(CAPTURE); + } + + @Test + void captureReadsTheInterestListOnce() { + service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(3L), null)); + + verify(rest, org.mockito.Mockito.times(1)).getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(COMPANY)); + } + + @Test + void interestOptionsAreActiveOnly() { + assertThat(service.interestOptions()).extracting(m -> m.get("name")).containsExactly("Cookware", "Kitchen appliances"); + } + + @Test + void salespersonOptionsAreTheActiveTeam() { + stubTeam(21L, 22L, 23L); + stubUser(23L, "Sales Three", false); + + assertThat(service.salespersonOptions(String.valueOf(EV))).extracting(m -> m.get("id")).containsExactly(21L, 22L); + } + + // --- normalisation and validation --- + + @Test + void matchNormalisesBothValuesAndReturnsCandidates() { + Map m = new LinkedHashMap<>(); + m.put("leadUuid", LEAD); + m.put("name", "Aisyah"); + m.put("mobileE164", "+60123456789"); + m.put("email", null); + m.put("companyName", "Acme"); + m.put("jobTitle", null); + m.put("eventLeadUuid", EL); + when(rest.postForEntity(eq(MATCHES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(m))); + + Map out = service.match(String.valueOf(EV), new AdminLeadMatchRequest("012-345 6789", " Aisyah@Example.COM ")); + + assertThat(out).containsEntry("mobile", "+60123456789").containsEntry("email", "aisyah@example.com"); + assertThat(sent(MATCHES)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV) + .containsEntry("mobileE164", "+60123456789").containsEntry("email", "aisyah@example.com"); + Map candidate = ((List>) out.get("candidates")).get(0); + assertThat(candidate).containsEntry("leadUuid", String.valueOf(LEAD)).containsEntry("eventLeadUuid", String.valueOf(EL)) + .containsEntry("mobile", "+60123456789").containsEntry("companyName", "Acme"); + } + + @Test + void matchWithNeitherValueNamesBothFields() { + assertThatThrownBy(() -> service.match(String.valueOf(EV), new AdminLeadMatchRequest(" ", null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD"); + assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("mobile", "email")); + }); + } + + @Test + void captureNormalisesAndSendsTheCallersCompanyAndUsername() { + Map out = service.capture(String.valueOf(EV), capture(null, " Aisyah ", "+60 12-345 6789", " Aisyah@Example.COM ")); + + Map body = sent(CAPTURE); + assertThat(body).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("name", "Aisyah") + .containsEntry("mobileE164", "+60123456789").containsEntry("email", "aisyah@example.com") + .containsEntry("doneBy", "sales1").containsEntry("leadUuid", null); + assertThat(out).containsEntry("eventLeadUuid", String.valueOf(EL)).containsEntry("leadUuid", String.valueOf(LEAD)) + .containsEntry("eventUuid", String.valueOf(EV)).containsEntry("leadType", "NEW").containsEntry("mobile", "+60123456789"); + } + + @Test + void neitherMobileNorEmailIsRefusedNamingBoth() { + assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "", " "))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD"); + assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("mobile", "email")); + }); + assertNothingSent(CAPTURE); + } + + @Test + void missingNameAndContactAreAllNamed() { + assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(null, " ", null, null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> + assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("name", "mobile", "email"))); + } + + @Test + void invalidMobileIsRefusedOnTheMobileField() { + assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "12345", null)), HttpStatus.BAD_REQUEST, "INVALID_MOBILE", "mobile"); + assertNothingSent(CAPTURE); + } + + @Test + void invalidEmailIsRefusedOnTheEmailField() { + assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", null, "aisyah@")), HttpStatus.BAD_REQUEST, "INVALID_EMAIL", "email"); + } + + @Test + void tooLongValuesAreRefused() { + assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "x".repeat(101), "0123456789", null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "name"); + assertCoded(() -> service.capture(String.valueOf(EV), new AdminEventLeadCaptureRequest(null, "A", "0123456789", null, + "x".repeat(151), null, null, null, null, List.of(), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "companyName"); + assertCoded(() -> service.capture(String.valueOf(EV), new AdminEventLeadCaptureRequest(null, "A", "0123456789", null, + null, "x".repeat(101), null, null, null, List.of(), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "jobTitle"); + } + + @Test + void temperatureStatusAndDateMustBeKnownValues() { + assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, "WARMISH", null, List.of(), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "temperature"); + assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, "DONE", List.of(), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "status"); + assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(), "20/01/2027")), HttpStatus.BAD_REQUEST, "INVALID_DATE", "nextFollowUpDate"); + } + + @Test + void workingFieldsAreSentWhenValid() { + service.capture(String.valueOf(EV), captureWith(22L, "HOT", "CONTACTED", List.of(3L, 4L), "2027-01-20")); + + assertThat(sent(CAPTURE)).containsEntry("salespersonUserId", 22L).containsEntry("temperature", "HOT") + .containsEntry("status", "CONTACTED").containsEntry("interestIds", List.of(3L, 4L)) + .containsEntry("nextFollowUpDate", "2027-01-20"); + } + + // --- events open for capture --- + + @Test + void disabledEventRefusesCapture() { + stubEvent(false); + + assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "0123456789", null)), HttpStatus.CONFLICT, "EVENT_DISABLED", null); + assertNothingSent(CAPTURE); + } + + @Test + void unknownEventIsNotFound() { + when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(1L))).thenReturn(ResponseEntity.ok().build()); + + assertCoded(() -> service.capture("1", capture(null, "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null); + assertCoded(() -> service.list("not-a-number", null, null, null, null, null, 0, 20), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null); + } + + // --- salesperson from the team --- + + @Test + void outsiderSalespersonIsRefused() { + assertCoded(() -> service.capture(String.valueOf(EV), captureWith(23L, null, null, List.of(), null)), HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId"); + assertNothingSent(CAPTURE); + } + + @Test + void deactivatedTeamMemberCannotBeNewlyAssigned() { + stubUser(22L, "Sales Two", false); + + assertCoded(() -> service.capture(String.valueOf(EV), captureWith(22L, null, null, List.of(), null)), HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId"); + } + + @Test + void salespersonAlreadySetStaysAllowedAfterLeavingTheTeam() { + stubStored(EV, 23L, List.of()); + + service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(23L, null, "CONTACTED", List.of(), null, null)); + + assertThat(sent(UPDATE)).containsEntry("salespersonUserId", 23L).containsEntry("status", "CONTACTED") + .containsEntry("companyId", COMPANY).containsEntry("eventLeadUuid", EL).containsEntry("doneBy", "sales1"); + } + + @Test + void changingToAnOutsiderOnEditIsRefused() { + stubStored(EV, 21L, List.of()); + + assertCoded(() -> service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(23L, null, "OPEN", List.of(), null, null)), + HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId"); + assertNothingSent(UPDATE); + } + + // --- interests --- + + @Test + void inactiveInterestCannotBeAddedAtCapture() { + assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(5L), null)), HttpStatus.BAD_REQUEST, "INACTIVE_INTEREST", "interestIds"); + } + + @Test + void anotherCompanysInterestIsRefused() { + assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(99L), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "interestIds"); + } + + @Test + void inactiveInterestAlreadyOnTheLeadIsKeptOnEdit() { + stubStored(EV, null, List.of(5L)); + + service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(null, null, "CONTACTED", List.of(5L, 3L), null, null)); + + assertThat(sent(UPDATE)).containsEntry("interestIds", List.of(5L, 3L)); + } + + // --- already captured --- + + @Test + void alreadyCapturedCarriesTheExistingEventLeadUuid() { + byte[] body = ("{\"status\":409,\"detail\":\"ALREADY_CAPTURED\",\"eventLeadUuid\":\"" + EL + "\"}").getBytes(StandardCharsets.UTF_8); + when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any())) + .thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, body, StandardCharsets.UTF_8)); + + assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getCode()).isEqualTo("ALREADY_CAPTURED"); + assertThat((Map) e.getBody().getProperties().get("details")).containsEntry("eventLeadUuid", String.valueOf(EL)); + }); + } + + @Test + void alreadyCapturedByARaceFindsTheEventLeadThroughMatching() { + when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any())) + .thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, "{\"status\":409}".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)); + Map m = new HashMap<>(); + m.put("leadUuid", LEAD); + m.put("eventLeadUuid", EL); + when(rest.postForEntity(eq(MATCHES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(m))); + + assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> + assertThat((Map) e.getBody().getProperties().get("details")).containsEntry("eventLeadUuid", String.valueOf(EL))); + } + + @Test + void pickedLeadOfAnotherCompanyIsNotFound() { + when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any())) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", null, null, null)); + + assertCoded(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null); + assertCoded(() -> service.capture(String.valueOf(EV), capture("abc", "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null); + } + + // --- listing, get, update --- + + @Test + void listingSendsFiltersAndNamesSalespeopleAndInterests() { + Map row = new LinkedHashMap<>(); + row.put("eventLeadUuid", EL); + row.put("eventUuid", EV); + row.put("leadUuid", LEAD); + row.put("name", "Aisyah"); + row.put("mobileE164", "+60123456789"); + row.put("leadType", "EXISTING"); + row.put("salespersonUserId", 22L); + row.put("temperature", "HOT"); + row.put("status", "OPEN"); + row.put("nextFollowUpDate", "2027-01-20"); + row.put("interestIds", List.of(3, 5)); + when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(row), "totalElements", 1, "totalPages", 1, "number", 0, "size", 20))); + + Map out = service.list(String.valueOf(EV), 22L, "HOT", "OPEN", 3L, "EXISTING", 0, 20); + + assertThat(sent(SEARCH)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserId", 22L) + .containsEntry("temperature", "HOT").containsEntry("status", "OPEN").containsEntry("interestId", 3L) + .containsEntry("leadType", "EXISTING").containsEntry("page", 0).containsEntry("size", 20); + assertThat(out).containsEntry("totalElements", 1); + Map first = ((List>) out.get("content")).get(0); + assertThat(first).containsEntry("eventLeadUuid", String.valueOf(EL)).containsEntry("mobile", "+60123456789") + .containsEntry("salesperson", Map.of("id", 22L, "name", "Sales Two")).containsEntry("nextFollowUpDate", "2027-01-20"); + assertThat((List>) first.get("interests")).containsExactly( + Map.of("id", 3L, "name", "Cookware", "active", true), Map.of("id", 5L, "name", "Old", "active", false)); + } + + @Test + void eventLeadOfAnotherEventIsNotFound() { + stubStored(EV + 1, null, List.of()); + + assertCoded(() -> service.get(String.valueOf(EV), String.valueOf(EL)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null); + assertCoded(() -> service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(null, null, "OPEN", List.of(), null, null)), + HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null); + assertNothingSent(UPDATE); + } + + @Test + void unknownEventLeadIsNotFound() { + when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL))) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", null, null, null)); + + assertCoded(() -> service.get(String.valueOf(EV), String.valueOf(EL)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null); + } + + @Test + void getShowsSalespersonAndInterestsByName() { + stubStored(EV, 21L, List.of(4L)); + + Map out = service.get(String.valueOf(EV), String.valueOf(EL)); + + assertThat(out).containsEntry("salesperson", Map.of("id", 21L, "name", "Sales One")) + .containsEntry("name", "Aisyah").containsEntry("leadType", "NEW"); + assertThat((List>) out.get("interests")).containsExactly(Map.of("id", 4L, "name", "Kitchen appliances", "active", true)); + } + + @Test + void updateWorksALead() { + stubStored(EV, null, List.of()); + + Map out = service.update(String.valueOf(EV), String.valueOf(EL), + new AdminEventLeadUpdateRequest(21L, "HOT", "CONTACTED", List.of(3L), "2027-01-20", " call back ")); + + assertThat(sent(UPDATE)).containsEntry("temperature", "HOT").containsEntry("status", "CONTACTED") + .containsEntry("nextFollowUpDate", "2027-01-20").containsEntry("notes", "call back").containsEntry("interestIds", List.of(3L)); + assertThat(out).containsEntry("status", "CONTACTED").containsEntry("temperature", "HOT"); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/EventLeadContactTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/EventLeadContactTest.java new file mode 100644 index 0000000..6b28c98 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/EventLeadContactTest.java @@ -0,0 +1,56 @@ +package com.solvway.mobile.api.service; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Mobile numbers become E.164 (Malaysia by default) and emails are trimmed and lowercased, so one person is one value. */ +class EventLeadContactTest { + + @ParameterizedTest + @ValueSource(strings = {"012-345 6789", "0123456789", "+60 12-345 6789", "60123456789", " +60123456789 ", "(012) 345-6789"}) + void malaysianFormatsAreOneNumber(String input) { + assertThat(EventLeadContact.mobile(input)).isEqualTo("+60123456789"); + } + + @ParameterizedTest + @ValueSource(strings = {"+65 9123 4567", "+6591234567"}) + void foreignNumbersKeepTheirCountryCode(String input) { + assertThat(EventLeadContact.mobile(input)).isEqualTo("+6591234567"); + } + + @ParameterizedTest + @ValueSource(strings = {"12345", "abc", "0123", "+60 1"}) + void invalidNumbersAreRefused(String input) { + assertThatThrownBy(() -> EventLeadContact.mobile(input)).isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {" "}) + void blankMobileIsNull(String input) { + assertThat(EventLeadContact.mobile(input)).isNull(); + } + + @ParameterizedTest + @ValueSource(strings = {" Aisyah@Example.COM ", "aisyah@example.com", "AISYAH@EXAMPLE.COM"}) + void emailIsTrimmedAndLowercased(String input) { + assertThat(EventLeadContact.email(input)).isEqualTo("aisyah@example.com"); + } + + @ParameterizedTest + @ValueSource(strings = {"aisyah", "aisyah@", "@example.com", "a b@example.com", "a@b@example.com", "aisyah@example"}) + void invalidEmailsAreRefused(String input) { + assertThatThrownBy(() -> EventLeadContact.email(input)).isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {" "}) + void blankEmailIsNull(String input) { + assertThat(EventLeadContact.email(input)).isNull(); + } +} -- 2.54.1 From 18672ba17331185bbf34707d5aad5c034c1e8794 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 12:18:21 +0800 Subject: [PATCH 07/14] feat(admin-portal): interests screen Lists, adds, renames, orders and activates/deactivates interests, gated by BO_INTERESTS. API errors map to field messages under Name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-event-lead-capture/tasks.md | 2 +- .../app/api/interests/[id]/route.test.ts | 106 +++++++ .../app/api/interests/[id]/route.ts | 35 +++ .../app/api/interests/route.test.ts | 105 +++++++ .../app/api/interests/route.ts | 33 ++ .../app/interests/page.test.tsx | 260 ++++++++++++++++ solvway-admin-portal/app/interests/page.tsx | 284 ++++++++++++++++++ .../app/lib/i18n/defaultMessages.ts | 21 ++ .../app/lib/routeModules.test.ts | 3 +- solvway-admin-portal/app/lib/routeModules.ts | 1 + .../app/lib/services/adminInterests.test.ts | 35 +++ .../app/lib/services/adminInterests.ts | 12 + solvway-admin-portal/app/lib/types.ts | 9 + .../app/listing-page-size.test.ts | 3 +- 14 files changed, 906 insertions(+), 3 deletions(-) create mode 100644 solvway-admin-portal/app/api/interests/[id]/route.test.ts create mode 100644 solvway-admin-portal/app/api/interests/[id]/route.ts create mode 100644 solvway-admin-portal/app/api/interests/route.test.ts create mode 100644 solvway-admin-portal/app/api/interests/route.ts create mode 100644 solvway-admin-portal/app/interests/page.test.tsx create mode 100644 solvway-admin-portal/app/interests/page.tsx create mode 100644 solvway-admin-portal/app/lib/services/adminInterests.test.ts create mode 100644 solvway-admin-portal/app/lib/services/adminInterests.ts diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md index 2e9b0f3..d5fd4d5 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -102,7 +102,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial ## 4. Admin portal -- [ ] 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`. +- [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/**` 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/interests/page.test.tsx b/solvway-admin-portal/app/interests/page.test.tsx new file mode 100644 index 0000000..38d30e3 --- /dev/null +++ b/solvway-admin-portal/app/interests/page.test.tsx @@ -0,0 +1,260 @@ +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ + listAdminInterests: vi.fn(), + apiGet: vi.fn(), + apiPost: vi.fn(), + apiPut: vi.fn(), + useAdminAuth: vi.fn(), +})); +vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ + ApiError: (await importOriginal()).ApiError, + apiGet: mocks.apiGet, + apiPost: mocks.apiPost, + apiPut: mocks.apiPut, +})); +vi.mock("@/app/lib/services/adminInterests", async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, listAdminInterests: mocks.listAdminInterests }; +}); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); + +import InterestsPage from "./page"; +import { ApiError } from "@/app/lib/clientApi"; + +beforeEach(() => { + mocks.listAdminInterests.mockReset(); + mocks.apiGet.mockReset(); + mocks.apiPost.mockReset(); + mocks.apiPut.mockReset(); + mocks.useAdminAuth.mockReset(); + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true }); +}); + +describe("InterestsPage", () => { + it("renders an empty table with no interests", async () => { + mocks.listAdminInterests.mockResolvedValue([]); + render(); + await waitFor(() => expect(screen.getByRole("table")).toBeInTheDocument()); + expect(screen.getByText(/no interests/i)).toBeInTheDocument(); + }); + + it("renders rows with name, order, and status badge", async () => { + mocks.listAdminInterests.mockResolvedValue([ + { id: 1, name: "Workshop", active: true, sortOrder: 1 }, + { id: 2, name: "Webinar", active: false, sortOrder: 2 }, + ]); + render(); + await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument()); + const row1 = screen.getByText("Workshop").closest("tr")!; + expect(within(row1).getByText("1")).toBeInTheDocument(); + expect(within(row1).getByText("Active")).toBeInTheDocument(); + + const row2 = screen.getByText("Webinar").closest("tr")!; + expect(within(row2).getByText("2")).toBeInTheDocument(); + expect(within(row2).getByText("Inactive")).toBeInTheDocument(); + }); + + it("posts trimmed name on create", async () => { + mocks.listAdminInterests.mockResolvedValue([]); + mocks.apiPost.mockResolvedValue({ id: 1, name: "New Interest", active: true, sortOrder: 0 }); + render(); + await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument()); + + await userEvent.click(screen.getByRole("button", { name: /Add interest/i })); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + await userEvent.type(screen.getByLabelText(/Name/i), " New Interest "); + await userEvent.click(screen.getByRole("button", { name: /Save/i })); + + await waitFor(() => + expect(mocks.apiPost).toHaveBeenCalledWith("/api/interests", { + name: "New Interest", + active: true, + sortOrder: 0, + }), + ); + }); + + it("blocks submit when name is empty", async () => { + mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]); + render(); + await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument()); + + await userEvent.click(screen.getByRole("button", { name: /Add interest/i })); + await userEvent.click(screen.getByRole("button", { name: /Save/i })); + + expect(screen.getByText(/Name is required/i)).toBeInTheDocument(); + expect(mocks.apiPost).not.toHaveBeenCalled(); + }); + + it("shows an unexpected save error at form level", async () => { + mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]); + mocks.apiPost.mockRejectedValue(new Error("An interest with this name already exists.")); + render(); + await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument()); + + await userEvent.click(screen.getByRole("button", { name: /Add interest/i })); + await userEvent.type(screen.getByLabelText(/Name/i), "Existing"); + await userEvent.click(screen.getByRole("button", { name: /Save/i })); + + expect(await screen.findByText(/An interest with this name already exists/i)).toBeInTheDocument(); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + }); + + it("deactivates interest via PUT { active: false }", async () => { + mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]); + mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop", active: false, sortOrder: 1 }); + render(); + await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument()); + + const row = screen.getByText("Workshop").closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: /Deactivate/i })); + + await waitFor(() => + expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", expect.objectContaining({ active: false })), + ); + }); + + it("activates interest via PUT { active: true }", async () => { + mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: false, sortOrder: 1 }]); + mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop", active: true, sortOrder: 1 }); + render(); + await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument()); + + const row = screen.getByText("Workshop").closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: /Activate/i })); + + await waitFor(() => + expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", expect.objectContaining({ active: true })), + ); + }); + + it("edit dialog: name field, order number input, PUTs on save", async () => { + mocks.listAdminInterests.mockResolvedValue([ + { id: 1, name: "Workshop", active: true, sortOrder: 5 }, + ]); + mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop Edited", active: true, sortOrder: 10 }); + render(); + await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument()); + + const row = screen.getByText("Workshop").closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: /Edit/i })); + + expect(screen.getByRole("dialog")).toBeInTheDocument(); + expect(screen.getByLabelText(/Name/i)).toHaveValue("Workshop"); + expect(screen.getByLabelText(/Order/i)).toHaveValue(5); + + await userEvent.clear(screen.getByLabelText(/Name/i)); + await userEvent.type(screen.getByLabelText(/Name/i), "Workshop Edited"); + await userEvent.clear(screen.getByLabelText(/Order/i)); + await userEvent.type(screen.getByLabelText(/Order/i), "10"); + await userEvent.click(screen.getByRole("button", { name: /Save/i })); + + await waitFor(() => + expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", { + id: 1, + name: "Workshop Edited", + sortOrder: 10, + }), + ); + }); + + it("shows NotAuthorized when the module is missing", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false }); + render(); + await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument()); + expect(screen.getByText(/not authorised/i)).toBeInTheDocument(); + }); + + it("shows IntDuplicateName under Name when API returns DUPLICATE_NAME error", async () => { + mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]); + const dupErr = new ApiError("Conflict", 409, { code: "DUPLICATE_NAME", details: { field: "name" } }); + mocks.apiPost.mockRejectedValue(dupErr); + render(); + await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument()); + + await userEvent.click(screen.getByRole("button", { name: /Add interest/i })); + await userEvent.type(screen.getByLabelText(/Name/i), "Existing"); + await userEvent.click(screen.getByRole("button", { name: /Save/i })); + + // The field error for DUPLICATE_NAME should appear under the Name input + const nameInput = screen.getByLabelText(/Name/i); + const nameField = nameInput.closest(".space-y-1\\.5")!; + await waitFor(() => { + expect(nameField.querySelector('[role="alert"]')?.textContent).toContain("An interest with this name already exists."); + }); + }); + + it("shows IntNameTooLong under Name when API returns TOO_LONG error", async () => { + mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]); + const tooLongErr = new ApiError("Name is too long.", 422, { code: "TOO_LONG", details: { field: "name" } }); + mocks.apiPost.mockRejectedValue(tooLongErr); + render(); + await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument()); + + await userEvent.click(screen.getByRole("button", { name: /Add interest/i })); + await userEvent.type(screen.getByLabelText(/Name/i), "A name that is way too long to be valid for an interest"); + await userEvent.click(screen.getByRole("button", { name: /Save/i })); + + const nameInput = screen.getByLabelText(/Name/i); + const nameField = nameInput.closest(".space-y-1\\.5")!; + await waitFor(() => { + expect(nameField.querySelector('[role="alert"]')?.textContent).toContain("Name must be 100 characters or fewer."); + }); + }); + + it("submits successfully with a 100-character name", async () => { + // maxLength={100} on the input prevents typing 101+ chars. + // The handleSubmit guard (trimmed.length > 100) is defense-in-depth. + // We verify the boundary works by submitting exactly 100 characters. + mocks.listAdminInterests.mockResolvedValue([]); + render(); + await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument()); + + await userEvent.click(screen.getByRole("button", { name: /Add interest/i })); + await userEvent.type(screen.getByLabelText(/Name/i), "A".repeat(100)); + await userEvent.click(screen.getByRole("button", { name: /Save/i })); + await waitFor(() => + expect(mocks.apiPost).toHaveBeenCalledWith("/api/interests", expect.objectContaining({ name: "A".repeat(100) })), + ); + }); + + it("shows activate/deactivate failure error on the page", async () => { + mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]); + mocks.apiPut.mockRejectedValue(new ApiError("Network error", 0)); + render(); + await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument()); + + const row = screen.getByText("Workshop").closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: /Deactivate/i })); + + expect(await screen.findByText("Failed to deactivate interest.")).toBeInTheDocument(); + }); + + it("shows activate failure on the page", async () => { + mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: false, sortOrder: 1 }]); + mocks.apiPut.mockRejectedValue(new ApiError("Network error", 0)); + render(); + await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument()); + + const row = screen.getByText("Workshop").closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: /^Activate$/i })); + + expect(await screen.findByText("Failed to activate interest.")).toBeInTheDocument(); + }); + + it("blocks a name over 100 characters before submit", async () => { + mocks.listAdminInterests.mockResolvedValue([]); + render(); + await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument()); + + await userEvent.click(screen.getByRole("button", { name: /Add interest/i })); + fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: "A".repeat(101) } }); + await userEvent.click(screen.getByRole("button", { name: /Save/i })); + + expect(await screen.findByText("Name must be 100 characters or fewer.")).toBeInTheDocument(); + expect(mocks.apiPost).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/interests/page.tsx b/solvway-admin-portal/app/interests/page.tsx new file mode 100644 index 0000000..7949586 --- /dev/null +++ b/solvway-admin-portal/app/interests/page.tsx @@ -0,0 +1,284 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react"; +import { Plus } from "lucide-react"; +import type { ColumnDef } from "@tanstack/react-table"; +import { Button } from "@/app/components/ui/button"; +import { Input } from "@/app/components/ui/input"; +import { Label } from "@/app/components/ui/label"; +import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; +import { DataTable } from "@/app/components/ui/data-table"; +import { PageHeader } from "@/app/components/ui/page-header"; +import { EmptyState, ErrorState } from "@/app/components/ui/states"; +import { Badge } from "@/app/components/ui/badge"; +import { RequireModule } from "@/app/lib/RequireModule"; +import { listAdminInterests, saveAdminInterest } from "@/app/lib/services/adminInterests"; +import type { AdminInterestEntity } from "@/app/lib/types"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +interface FormState { + id?: number; + name: string; + sortOrder?: number; +} + +const EMPTY_FORM: FormState = { name: "", sortOrder: 0 }; + +function InterestFormDialog({ + initial, + onClose, + onSaved, +}: { + initial: FormState; + onClose: () => void; + onSaved: () => void; +}) { + const t = useT(); + const [form, setForm] = useState(initial); + const [saving, setSaving] = useState(false); + const [fieldErrors, setFieldErrors] = useState>({}); + const [formError, setFormError] = useState(null); + + async function handleSubmit(event: FormEvent) { + event.preventDefault(); + const trimmed = form.name.trim(); + + const errors: Record = {}; + if (!trimmed) errors.name = t("IntNameRequired"); + else if (trimmed.length > 100) errors.name = t("IntNameTooLong"); + setFieldErrors(errors); + if (Object.keys(errors).length > 0) return; + + setFormError(null); + setSaving(true); + try { + if (form.id) { + // Edit: only send name and sortOrder + await saveAdminInterest({ id: form.id, name: trimmed, sortOrder: form.sortOrder }); + } else { + // Create: send active=true and sortOrder + await saveAdminInterest({ name: trimmed, active: true, sortOrder: form.sortOrder ?? 0 }); + } + onSaved(); + onClose(); + } catch (err) { + if (err instanceof Error && "status" in err && "data" in err) { + const apiErr = err as Error & { status?: number; data?: unknown }; + const code = (apiErr.data as { code?: string } | undefined)?.code; + if (code === "DUPLICATE_NAME") { + setFieldErrors({ name: t("IntDuplicateName") }); + } else if (code === "TOO_LONG") { + setFieldErrors({ name: t("IntNameTooLong") }); + } else if (code === "REQUIRED_FIELD") { + setFieldErrors({ name: t("IntNameRequired") }); + } else { + setFormError(err.message || "IntSaveFailed"); + } + } else { + setFormError(err instanceof Error ? err.message : "IntSaveFailed"); + } + } finally { + setSaving(false); + } + } + + return ( + !open && onClose()}> + + + {form.id ? t("IntEditInterest") : t("IntAddInterest")} + + {formError && ( +
+ {t(formError)} +
+ )} +
+
+ + setForm((f) => ({ ...f, name: e.target.value }))} + disabled={saving} + aria-invalid={!!fieldErrors.name} + aria-describedby={fieldErrors.name ? "interest-name-error" : undefined} + /> + {fieldErrors.name && ( + + )} +
+
+ + setForm((f) => ({ ...f, sortOrder: parseInt(e.target.value, 10) || 0 }))} + disabled={saving} + /> +
+ + + +
+
+
+ ); +} + +function InterestsPageContent() { + const t = useT(); + const [interests, setInterests] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [reloadKey, setReloadKey] = useState(0); + const [dialog, setDialog] = useState(null); + + const refetch = useCallback(() => setReloadKey((k) => k + 1), []); + + useEffect(() => { + let cancelled = false; + // eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the reloadKey-triggered fetch below. + setLoading(true); + setError(null); + listAdminInterests() + .then((result) => { + if (!cancelled) setInterests(result); + }) + .catch((err: unknown) => { + if (!cancelled) setError(err instanceof Error ? err.message : "IntLoadFailed"); + }) + .finally(() => { + if (!cancelled) setLoading(false); + }); + return () => { + cancelled = true; + }; + }, [reloadKey]); + + const columns = useMemo[]>( + () => [ + { + accessorKey: "name", + header: t("IntColInterest"), + cell: ({ row }) =>
{row.original.name}
, + }, + { + accessorKey: "sortOrder", + header: t("IntColOrder"), + cell: ({ row }) =>
{row.original.sortOrder ?? 0}
, + }, + { + accessorKey: "active", + header: t("IntColStatus"), + cell: ({ row }) => ( + + {row.original.active ? t("IntActive") : t("IntInactive")} + + ), + }, + { + id: "actions", + header: t("CatActions"), + cell: ({ row }) => ( +
+ + {row.original.active ? ( + + ) : ( + + )} +
+ ), + }, + ], + [t, refetch], + ); + + return ( + <> + setDialog(EMPTY_FORM)}> +