Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ce641ea86 | ||
|
|
fad639d690 | ||
|
|
29f5c6f094 | ||
|
|
adaca0a4eb | ||
|
|
7fe8dcc8a5 | ||
|
|
94e1e7fdde | ||
|
|
90f25debc2 | ||
|
|
18672ba173 | ||
|
|
fe9d9bd38d | ||
|
|
5d768b1566 | ||
|
|
48507979bd | ||
|
|
b75d636886 | ||
|
|
4c853c428e | ||
|
|
3fc0510615 | ||
|
|
66581f1944 | ||
|
|
846a08da57 | ||
|
|
5588ade48d |
No files matched your search
@@ -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;
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-27
|
||||
@@ -0,0 +1,183 @@
|
||||
# Design
|
||||
|
||||
## Context
|
||||
|
||||
- Change 3 added events (`service-counter`.`event`, Snowflake `uuid`) and each event's team (`event_salesperson`). It also added `/api/admin/events` in `mobile-api` and the portal Events screens. The uuid travels as a JSON string, dates as `YYYY-MM-DD`, and errors as a ProblemDetail with `code`, `errors[]` and a flat `details` object. The portal forwards only those fields.
|
||||
- `services-counter` models generate uuids with `SnowflakeIdWorker.getUUID()` from core-libs.
|
||||
- `mobile-api` knows the logged-in admin's `companyId` (`AdminAuthenticationService`), and change 3 already writes it onto team rows.
|
||||
- The portal's `DataTable` has no phone layout. The Users and Events pages use it with `FilterPanel` and `useListFilters`. The date picker from change 3 works on touch.
|
||||
- Nothing in the repo parses phone numbers. `services-system` already has the `company` table and `user.company_id` (change 2).
|
||||
- Back-office modules in use: 40000000 root, 40100000 `BO_EVENTS`, 40700000 `BO_USERS`, 40800000 `BO_ROLES`. The icon map already has `ClipboardList` and `Tags`.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Capture a lead at an event in seconds on a phone, with New/Existing decided by the rules in the foundation design.
|
||||
- One event's leads listed, filtered and edited on the floor.
|
||||
- An interest list to tag leads.
|
||||
|
||||
**Non-Goals:**
|
||||
- Lead Listing, lead detail, lead field edits after capture, and CSV exports. These are in 4b.
|
||||
- Merging leads, per-salesperson visibility, visitor self-registration, and an audit log beyond `updated_by` and `updated_at`.
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. Tables (schema `service-counter`)
|
||||
|
||||
- **`lead`**
|
||||
- Columns: `id` PK, `uuid` bigint unique, `company_id` NOT NULL, `name` varchar(100) NOT NULL, `mobile_e164` varchar(20) NULL, `email_normalised` varchar(254) NULL, `company_name` varchar(150), `job_title` varchar(100), `notes` text, `created_by`, `created_at`, `updated_by`, `updated_at`.
|
||||
- Indexes, not unique: `(company_id, mobile_e164)` and `(company_id, email_normalised)`.
|
||||
- **`event_lead`**
|
||||
- Columns: `id` PK, `uuid` bigint unique, `company_id` NOT NULL, `event_uuid`, `lead_uuid`, `salesperson_user_id` NULL, `lead_type` varchar(8) (`NEW`/`EXISTING`), `temperature` varchar(4) NULL (`HOT`/`WARM`/`COLD`), `status` varchar(10) NOT NULL default `OPEN` (`OPEN`/`CONTACTED`/`QUALIFIED`/`WON`/`LOST`), `next_follow_up_date` date NULL, `notes` text, `captured_by`, `captured_at`, `updated_by`, `updated_at`.
|
||||
- Unique `(event_uuid, lead_uuid)`; index `(company_id, event_uuid)`.
|
||||
- **`interest`**
|
||||
- Columns: `id` PK, `company_id` NOT NULL, `name` varchar(100) NOT NULL, `active` bit NOT NULL default 1, `sort_order` int NOT NULL default 0.
|
||||
- Unique `(company_id, name)`.
|
||||
- **`event_lead_interest`**
|
||||
- Columns: `event_lead_id`, `interest_id`, `company_id` NOT NULL.
|
||||
- PK `(event_lead_id, interest_id)`.
|
||||
|
||||
`user_id` and `event_uuid` cross into other tables without foreign keys, like `event_salesperson`. Every query on the new tables filters on `company_id`, which comes from the logged-in admin and never from the request. `ponytail:` the change-3 `event` table has no `company_id`, so event lookups are not company-scoped; add it with the multi-company move.
|
||||
|
||||
**Calls I made:**
|
||||
- Name is required: a lead with no name cannot be followed up.
|
||||
- Temperature is optional, because it is often unknown at capture.
|
||||
- Status defaults to `OPEN`.
|
||||
|
||||
### 2. Normalisation and validation in `mobile-api`
|
||||
|
||||
Validation lives at the boundary, as in change 3. `services-counter` stores what it is given.
|
||||
|
||||
- **Mobile:** `PhoneNumberUtil.parse(input, "MY")`. It must be a valid number, then it is formatted as E.164. `012-345 6789`, `0123456789`, `+60 12-345 6789` and `60123456789` all become `+60123456789`.
|
||||
- Invalid input answers 400 `INVALID_MOBILE` with `details.field = mobile`.
|
||||
- **Dependency:** `com.googlecode.libphonenumber:libphonenumber`, latest 8.x, pinned in `solvway-mobile-api/pom.xml`. Justification: nothing in the repo parses phone numbers, and getting it wrong creates duplicate leads (an anti-goal in the foundation design).
|
||||
- **Email:** trimmed and lowercased. It must look like `x@y.z` (one `@`, a dot after it, no spaces), or the answer is 400 `INVALID_EMAIL`.
|
||||
- **Required fields:**
|
||||
- At least one of mobile or email, else `REQUIRED_FIELD` with `errors: ["mobile","email"]`.
|
||||
- Name, else `REQUIRED_FIELD` with `errors: ["name"]`.
|
||||
- **Lengths:** as in the tables, else `TOO_LONG` with the field.
|
||||
- **Enum values:** temperature and status must be in their lists, else `INVALID_VALUE` with the field.
|
||||
|
||||
### 3. Capture is two steps; the write is one transaction
|
||||
|
||||
1. **Match.** `POST /api/admin/event-leads/{eventUuid}/match` with `{mobile, email}` normalises both values and returns `{mobile, email, candidates}`.
|
||||
- Each candidate is `{leadUuid, name, mobile, email, companyName, eventLeadUuid}`. `eventLeadUuid` is set when that lead is already captured at this event.
|
||||
- The candidates are the company's leads matching either value (`services-counter` `POST /counter/lead/findMatches`), at most 20, newest first.
|
||||
2. **Capture.** `POST /api/admin/event-leads/{eventUuid}` with the lead fields, `leadUuid` (null for a new person), `salespersonId`, `temperature`, `status`, `interestIds`, `nextFollowUpDate` and `notes`.
|
||||
- `mobile-api` validates and normalises, checks the event (decision 5) and the salesperson (decision 4), then calls `services-counter` `POST /counter/eventLead/capture`.
|
||||
- That endpoint runs one `@Transactional` method:
|
||||
- **`leadUuid` null:** insert a new `lead`; the event lead is `NEW`.
|
||||
- **`leadUuid` set:** load that lead in the same company, else 404 `LEAD_NOT_FOUND`. Fill only its null or blank fields, never overwrite. The event lead is `EXISTING`.
|
||||
- In both cases it inserts the `event_lead` and its interests.
|
||||
- The lead and its event lead are saved together or not at all, unlike change 3's two-call create.
|
||||
- **Already captured:** if the lead is already at this event (checked first, and enforced by the unique key for races), the answer is 409 `ALREADY_CAPTURED` with `details.eventLeadUuid`. The portal opens that event lead.
|
||||
- **NEW versus EXISTING:** follows the foundation rules. A lead picked from the candidates existed before this capture, so it is `EXISTING`. "Different person" sends `leadUuid` null, so it is `NEW`, even when the value matches another lead.
|
||||
|
||||
**Why two steps:** staff must see the candidates before the system decides. A single call cannot ask "which one is this?".
|
||||
|
||||
`ponytail:` two staff capturing the same new person at the same moment can create two leads with the same mobile. That is allowed by design (non-unique index) and is fixed later by merge, which is not in phase 1.
|
||||
|
||||
### 4. Salesperson must be on the event's team
|
||||
|
||||
`salespersonId` is optional.
|
||||
|
||||
- **A new or changed value** must be an id on the event's current team (`/counter/eventSalesperson/findByEventUuid`) that is also an enabled admin user. Otherwise the answer is 400 `NOT_ON_TEAM` with `details.field = salespersonId`.
|
||||
- **An unchanged value** passes even if that person has since left the team or been deactivated. This mirrors change 3's team rule.
|
||||
- **Options:** `GET /api/admin/event-leads/{eventUuid}/salesperson-options` returns the active team members.
|
||||
- **Default on capture:** the form preselects the capturing user if they are on the team.
|
||||
|
||||
### 5. Events open for capture
|
||||
|
||||
The event picker and capture accept enabled events only. `GET /api/admin/event-leads/events` returns enabled events as `{uuid, name, location, startDate, endDate}`, sorted by start date descending. It uses `findByPropertyAndPageable` with `enabled=Y` and a page size of 100.
|
||||
|
||||
- `ponytail:` one page of 100 events; add paging when a company has more enabled events than that.
|
||||
- **Disabled events:** capture to a disabled event answers 409 `EVENT_DISABLED`. Listing and editing that event's leads still work, through a direct link from the listing URL.
|
||||
- **Unknown event:** answers 404.
|
||||
|
||||
### 6. Listing
|
||||
|
||||
`GET /api/admin/event-leads/{eventUuid}/leads` takes `page`, `size`, `salespersonId`, `temperature`, `status`, `interestId` and `leadType`. It is sorted by `captured_at` descending, with `id` descending as a tie-breaker. That way, rows that tie on the sort column cannot repeat or go missing across pages, as change 3's review found for events.
|
||||
|
||||
- **Backend:** `services-counter` `POST /counter/eventLead/findByEvent` runs one JPQL query joining `event_lead` and `lead`, with optional filters. The interest filter is an `exists` subquery. Interest ids for the page are fetched in one `in` query, not one per row.
|
||||
- **Salesperson names:** resolved in `mobile-api` with one `services-system` user lookup per distinct salesperson on the page.
|
||||
- **Each row:** `{eventLeadUuid, leadUuid, name, mobile, email, leadType, salesperson: {id, name}, temperature, status, interests: [{id, name}], nextFollowUpDate}`.
|
||||
|
||||
### 7. Event lead edit
|
||||
|
||||
- **Read:** `GET /api/admin/event-leads/{eventUuid}/leads/{eventLeadUuid}` returns the row, plus the lead's company name, job title and the event lead's notes. The lead's own fields are shown read-only; editing them is in 4b.
|
||||
- **Update:** `PUT` takes `salespersonId`, `temperature`, `status`, `interestIds`, `nextFollowUpDate` and `notes`. `services-counter` `POST /counter/eventLead/update` replaces those fields and the interest set in one transaction and sets `updated_by` and `updated_at`.
|
||||
- **Not found:** an event lead that is unknown or belongs to another event answers 404.
|
||||
|
||||
### 8. Interests
|
||||
|
||||
**Admin screen:** `/api/admin/interests` (`BO_INTERESTS`).
|
||||
|
||||
- **List:** active and inactive interests, ordered by sort order, then name.
|
||||
- **Create** with name.
|
||||
- **Update:** name, active, sort order.
|
||||
|
||||
**Rules:**
|
||||
- Name is required, at most 100 characters, and unique in the company, case-insensitive. A duplicate answers 409 `DUPLICATE_NAME`.
|
||||
- There is no delete. An interest is deactivated, so past tags keep their name.
|
||||
|
||||
**Capture form options:** `GET /api/admin/event-leads/interest-options` (`BO_EVENT_LEADS`) returns active interests. An inactive interest already on an event lead still shows on that lead and can be removed, but cannot be newly added (`INACTIVE_INTEREST`).
|
||||
|
||||
**Backend:** `services-counter` provides `/counter/interest/findByCompany/{companyId}`, `/counter/interest/save`, and `findByIds` (unused in phase 1: `mobile-api` reads the whole company list once per request).
|
||||
|
||||
### 9. Modules and access
|
||||
|
||||
Module rows:
|
||||
- `40200000 BO_EVENT_LEADS`: 'Event leads', url `/event-leads`, icon `ClipboardList`.
|
||||
- `40300000 BO_INTERESTS`: 'Interests', url `/interests`, icon `Tags`.
|
||||
|
||||
Both are area BO, type M, parent 40000000. Every endpoint carries `@AppAuth` and `@AdminModule`. All staff with `BO_EVENT_LEADS` see all of the company's leads, as the foundation design says.
|
||||
|
||||
`BO_EVENT_LEADS` covers viewing, capturing and editing event leads. The foundation design's separate "edit leads" permission is for the lead record itself, so it comes with lead edits in 4b.
|
||||
|
||||
### 10. Portal screens
|
||||
|
||||
The event-floor screens are responsive down to 360 px. Interests is desktop-first.
|
||||
|
||||
- **`/event-leads`: event picker.** Enabled events as tappable cards, with today's running events first.
|
||||
- **`/event-leads/[eventUuid]`: listing.**
|
||||
- Above `md`: `DataTable`.
|
||||
- Below `md`: a card list showing name, mobile, NEW/EXISTING badge, temperature, status and next follow-up. Same data and paging.
|
||||
- Filters in `FilterPanel`, plus an "Add lead" button.
|
||||
- **`/event-leads/[eventUuid]/new`: key-in form.**
|
||||
- **Step 1:**
|
||||
- Mobile is `type="tel"`, `inputMode="tel"`, `autoComplete="tel"`; email is `type="email"`.
|
||||
- "Check" calls match.
|
||||
- With no candidates, step 2 opens as a new person.
|
||||
- With candidates, each shows as a card with "This person" or, if already captured here, "Open". Below them is "Different person".
|
||||
- **Step 2:**
|
||||
- Fields: name, company, job title, salesperson (team), temperature, interests (checkboxes), next follow-up (date picker), notes.
|
||||
- Matched lead values are prefilled and read-only where they already exist.
|
||||
- **Layout:** single column, touch targets of at least 44 px.
|
||||
- **`/event-leads/[eventUuid]/[eventLeadUuid]`: edit page.** The lead's details read-only, the editable fields from decision 7, and the same layout.
|
||||
- **`/interests`:** a table with add, rename, active toggle and sort order.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **The same person typed in two formats:** E.164 normalisation via libphonenumber, with a test table of Malaysian formats.
|
||||
- **Two leads for one person through concurrent capture or "different person":** allowed by design; merge is later.
|
||||
- **Lead and event lead saved separately:** they are not. One transaction in `services-counter` (decision 3).
|
||||
- **Listing N+1:**
|
||||
- Interests are fetched in one batch per page.
|
||||
- Salesperson names use one lookup per distinct salesperson on the page (bounded by team size). `ponytail:` batch the lookup if teams grow large.
|
||||
- **Leads hold customer PII:**
|
||||
- Names, mobiles and emails are never logged.
|
||||
- Every query is filtered by the caller's company.
|
||||
- Local seeds carry no lead data.
|
||||
- **New dependency:** libphonenumber, pure Java with no transitive dependencies.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
Additive SQL in `sql/` of this change:
|
||||
1. `01-lead-tables.sql`: `lead`, `event_lead`, `interest`, `event_lead_interest` in `service-counter`.
|
||||
2. `02-lead-modules.sql`: the `BO_EVENT_LEADS` and `BO_INTERESTS` module rows.
|
||||
|
||||
These are mirrored in `local/seed/03-colite.sql`. To roll back, `sql/99-rollback.sql` drops the four tables and deletes the two module rows and their `modules_roles` rows.
|
||||
|
||||
## Open Questions
|
||||
|
||||
None blocking. 4b covers the lead record edits and exports.
|
||||
@@ -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.
|
||||
@@ -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`
|
||||
@@ -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
|
||||
@@ -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;
|
||||
@@ -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');
|
||||
@@ -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`;
|
||||
@@ -0,0 +1,147 @@
|
||||
# Tasks
|
||||
|
||||
Design: `design.md` (decision numbers below refer to it). Every task runs serially, and each task touches either a hotspot (SQL, `pom.xml`) or files the next task builds on. Every task is TDD: tests first, run red, then implement.
|
||||
|
||||
## 1. Database
|
||||
|
||||
- [x] 1.1 Write the SQL files:
|
||||
- `sql/01-lead-tables.sql`: the four tables exactly as in design decision 1, with engine InnoDB and charset utf8mb4.
|
||||
- `sql/02-lead-modules.sql`: two module rows, `40200000 BO_EVENT_LEADS` 'Event leads' `/event-leads` `ClipboardList` and `40300000 BO_INTERESTS` 'Interests' `/interests` `Tags`. Both are area BO, type M, parent 40000000.
|
||||
- `sql/99-rollback.sql`.
|
||||
|
||||
Mirror the tables and module rows into `local/seed/03-colite.sql`. Seed no lead data.
|
||||
- Scope: `openspec/changes/add-event-lead-capture/sql/**`, `local/seed/**`
|
||||
- Verify: `docker compose -f local/docker-compose.yml down -v && local/up.sh` exits 0, then a read-only SELECT shows the four tables and both module rows.
|
||||
|
||||
## 2. services-counter
|
||||
|
||||
- [x] 2.1 Add the interests backend (design decision 8):
|
||||
- `Interest` entity and repository.
|
||||
- `GET /counter/interest/findByCompany/{companyId}`, ordered by sort order then name.
|
||||
- `POST /counter/interest/save`, which creates or updates by id within the company.
|
||||
- `POST /counter/interest/findByIds` with `{companyId, ids}`.
|
||||
|
||||
Tests first:
|
||||
- ordering;
|
||||
- save then find;
|
||||
- a duplicate name in the same company (case-insensitive) is refused;
|
||||
- the same name in another company is allowed;
|
||||
- `findByIds` ignores other companies' ids.
|
||||
- Scope: `solvway-services-counter/src/**/*Interest*`, plus a `dto/` record if needed.
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`.
|
||||
|
||||
- [x] 2.2 Add the lead backend (design decisions 3, 6, 7):
|
||||
- `Lead`, `EventLead` and `EventLeadInterest` entities and repositories. Uuids come from `SnowflakeIdWorker.getUUID()`.
|
||||
- `EventLeadController` and service:
|
||||
- `POST /counter/lead/findMatches` with `{companyId, mobileE164, email}`: leads matching either value in the company, at most 20, newest first. Each match carries the `eventLeadUuid` when the lead is already captured at the given `eventUuid`.
|
||||
- `POST /counter/eventLead/capture`: one `@Transactional` method.
|
||||
- With `leadUuid` null, insert a new lead and mark the event lead NEW.
|
||||
- With `leadUuid` set, load the lead in the company and fill only its blank fields; mark the event lead EXISTING.
|
||||
- Already at the event: 409 `ALREADY_CAPTURED` with the `eventLeadUuid`. A lead from another company: 404.
|
||||
- `GET /counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}`.
|
||||
- `POST /counter/eventLead/update`: replaces salesperson, temperature, status, follow-up, notes and the interest set in one transaction.
|
||||
- `POST /counter/eventLead/findByEvent`: paged, with optional filters on salesperson, temperature, status, interest (an `exists` subquery) and lead type. Sorted by `captured_at` desc, then `id` desc. Interest ids for the page come from one `in` query.
|
||||
|
||||
Tests first, for each of these:
|
||||
- New capture.
|
||||
- Existing capture fills only blanks, never overwriting stored values.
|
||||
- A duplicate capture at the same event is refused and nothing is written.
|
||||
- A failure inserting interests rolls back the lead and the event lead.
|
||||
- Matching by mobile only, by email only, and both values matching different leads.
|
||||
- Company isolation in match, capture, find and listing.
|
||||
- Each listing filter.
|
||||
- Paging order with equal `captured_at`.
|
||||
- Update replaces the interest set.
|
||||
- Scope: `solvway-services-counter/src/**/*Lead*`, plus `dto/` records if needed.
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`.
|
||||
|
||||
## 3. mobile-api
|
||||
|
||||
- [x] 3.1 Add the interests admin API (design decision 8). `AdminInterestController` with `GET`, `POST` and `PUT /api/admin/interests`, all `@AppAuth @AdminModule("BO_INTERESTS")`. The company id comes from the caller.
|
||||
|
||||
Validation:
|
||||
- Name is required, else `REQUIRED_FIELD`.
|
||||
- At most 100 characters, else `TOO_LONG`.
|
||||
- A duplicate answers 409 `DUPLICATE_NAME`.
|
||||
- Errors use the `details` and `errors` contract from change 3.
|
||||
|
||||
Tests first, for each `lead-interests` scenario the API decides.
|
||||
- Scope: `solvway-mobile-api/src/**/*Interest*`, `solvway-mobile-api/src/main/java/**/constants/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`.
|
||||
|
||||
- [x] 3.2 Add the event-leads admin API (design decisions 2–7).
|
||||
- Add `com.googlecode.libphonenumber:libphonenumber` (latest 8.x, exact version) to `solvway-mobile-api/pom.xml`.
|
||||
- `AdminEventLeadController` and `AdminEventLeadService` under `/api/admin/event-leads`, all `@AppAuth @AdminModule("BO_EVENT_LEADS")`:
|
||||
- `GET /events`
|
||||
- `GET /interest-options`
|
||||
- `GET /{eventUuid}/salesperson-options`
|
||||
- `POST /{eventUuid}/match`
|
||||
- `POST /{eventUuid}` (capture)
|
||||
- `GET /{eventUuid}/leads`
|
||||
- `GET /{eventUuid}/leads/{eventLeadUuid}`
|
||||
- `PUT /{eventUuid}/leads/{eventLeadUuid}`
|
||||
- Uuids are JSON strings. Dates are `YYYY-MM-DD`.
|
||||
- Codes:
|
||||
- `REQUIRED_FIELD`, `TOO_LONG`, `INVALID_MOBILE`, `INVALID_EMAIL`, `INVALID_VALUE`;
|
||||
- `NOT_ON_TEAM` (salesperson rule, decision 4);
|
||||
- `INACTIVE_INTEREST`;
|
||||
- `EVENT_DISABLED` (409);
|
||||
- `ALREADY_CAPTURED` (409, `details.eventLeadUuid`);
|
||||
- 404 for an unknown event or event lead.
|
||||
- Never log a lead's name, mobile or email.
|
||||
|
||||
Tests first:
|
||||
- A table test of the Malaysian mobile formats in the spec, plus invalid input.
|
||||
- Email normalisation.
|
||||
- Each `event-lead-capture` scenario the API decides.
|
||||
- The salesperson keep-existing rule.
|
||||
- The inactive-interest keep rule.
|
||||
- An exact-JSON test that uuids are strings.
|
||||
- Scope: `solvway-mobile-api/pom.xml`, `solvway-mobile-api/src/**/*EventLead*`, `solvway-mobile-api/src/main/java/**/constants/**`, `solvway-mobile-api/src/main/java/**/dto/admin/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`.
|
||||
|
||||
## 4. Admin portal
|
||||
|
||||
- [x] 4.1 Add the Interests screen (`app/interests/page.tsx`, desktop-first, following the Roles page pattern). It provides a table with add, rename, active toggle and sort order. It needs route handlers `app/api/interests/**`, a service, types, `Int*` i18n keys and `/interests` mapped to `BO_INTERESTS` in `routeModules`.
|
||||
|
||||
Tests first (vitest), for each portal-visible `lead-interests` scenario.
|
||||
- Scope: `solvway-admin-portal/app/interests/**`, `solvway-admin-portal/app/api/interests/**`, `solvway-admin-portal/app/lib/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`.
|
||||
|
||||
- [x] 4.2 Add the event-floor screens (design decision 10):
|
||||
- Pages:
|
||||
- `app/event-leads/page.tsx`: event picker.
|
||||
- `app/event-leads/[eventUuid]/page.tsx`: listing. `DataTable` at `md` and up; a card list below `md`, with filters.
|
||||
- `app/event-leads/[eventUuid]/new/page.tsx`: two-step key-in form. Step 1 is match, with candidate cards and "This person", "Open" and "Different person". Step 2 is the details.
|
||||
- `app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx`: edit.
|
||||
- `ALREADY_CAPTURED` opens the existing event lead.
|
||||
- Supporting code:
|
||||
- route handlers `app/api/event-leads/**`;
|
||||
- service, types, `Lead*` i18n keys;
|
||||
- `/event-leads` mapped to `BO_EVENT_LEADS`.
|
||||
- Mobile input attributes: `type="tel"`, `inputMode="tel"` and `autoComplete="tel"`.
|
||||
- Touch targets of at least 44 px.
|
||||
- Reuse the change-3 `DatePicker` for the follow-up date.
|
||||
|
||||
Tests first (vitest), for each portal-visible `event-lead-capture` scenario. They include the match step's three outcomes, and the card list rendering below `md` (assert the card markup is present, not the layout).
|
||||
- Scope: `solvway-admin-portal/app/event-leads/**`, `solvway-admin-portal/app/api/event-leads/**`, `solvway-admin-portal/app/components/event-leads/**`, `solvway-admin-portal/app/lib/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`.
|
||||
|
||||
## 5. Verification
|
||||
|
||||
- [x] 5.1 Rebuild the stack and drive the portal with Playwright, using only local dev data and test leads made up for this check.
|
||||
- At desktop width:
|
||||
- Grant `BO_EVENT_LEADS` and `BO_INTERESTS` to a role.
|
||||
- Add interests, try a duplicate, and deactivate one.
|
||||
- Capture a NEW lead.
|
||||
- Capture the same mobile in another format at another event. It shows as a match; pick it, and it is EXISTING with its blanks filled.
|
||||
- Capture a different person with the same mobile.
|
||||
- Show the already-captured block.
|
||||
- Show that an outsider salesperson is refused.
|
||||
- Show the invalid mobile and missing contact errors.
|
||||
- Filter the listing, and edit status, temperature and follow-up.
|
||||
- At 360×780: the event picker, listing cards, key-in form and edit page.
|
||||
- A user without the modules gets not-authorised.
|
||||
|
||||
Screenshots go in `verification/`.
|
||||
- Verify: each scenario observed as specified, and `local/smoke.sh` prints `smoke: OK`.
|
||||
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 56 KiB |
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 56 KiB |
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 75 KiB After Width: | Height: | Size: 75 KiB |
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,95 @@
|
||||
# admin-events Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Admins with the Events module create and maintain the events that leads are captured at, including each event's team of salespeople.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Event list
|
||||
|
||||
The system SHALL let an admin with `BO_EVENTS` list events, paginated on the server, searchable by name, filterable by enabled state, and sortable by name, start date and end date. Each row SHALL show name, location, start date, end date and whether the event is enabled.
|
||||
|
||||
#### Scenario: Search by name
|
||||
|
||||
- **GIVEN** events `KL Food Fair 2027` and `Penang Expo`
|
||||
- **WHEN** an admin with `BO_EVENTS` searches for `food`
|
||||
- **THEN** the list shows `KL Food Fair 2027` and not `Penang Expo`
|
||||
|
||||
#### Scenario: Disabled filter
|
||||
|
||||
- **GIVEN** an enabled event and a disabled event
|
||||
- **WHEN** the admin filters by disabled
|
||||
- **THEN** only the disabled event is listed
|
||||
|
||||
#### Scenario: No module
|
||||
|
||||
- **WHEN** an admin without `BO_EVENTS` opens the Events page or calls an events endpoint
|
||||
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||
|
||||
### Requirement: Create event
|
||||
|
||||
The system SHALL let an admin with `BO_EVENTS` create an event with a name (required, at most 100 characters), a location (required, at most 200 characters), a start date and an end date (both required, whole days). The end date SHALL NOT be before the start date. The event SHALL start on the start date at 00:00:00 and end on the end date at 23:59:59. A new event SHALL be enabled. Events MAY overlap.
|
||||
|
||||
#### Scenario: New event
|
||||
|
||||
- **WHEN** an admin creates `KL Food Fair 2027` at `MITEC` from 2027-01-15 to 2027-01-17
|
||||
- **THEN** the event is saved as enabled, starting 2027-01-15 00:00:00 and ending 2027-01-17 23:59:59
|
||||
- **AND** it appears in the event list
|
||||
|
||||
#### Scenario: Missing fields
|
||||
|
||||
- **WHEN** an admin submits the form without a name, location, start date or end date
|
||||
- **THEN** the save is refused and each missing field is named
|
||||
|
||||
#### Scenario: End before start
|
||||
|
||||
- **WHEN** an admin submits an end date earlier than the start date
|
||||
- **THEN** the save is refused with a message on the end date
|
||||
|
||||
#### Scenario: One-day event
|
||||
|
||||
- **WHEN** the start date and the end date are the same day
|
||||
- **THEN** the event is saved and lasts that whole day
|
||||
|
||||
### Requirement: Edit event
|
||||
|
||||
The system SHALL let an admin with `BO_EVENTS` change an event's name, location, start date, end date and enabled state, with the same rules as create. Editing SHALL NOT change any other stored event data. Events SHALL NOT be deletable; an event that should no longer be used is disabled.
|
||||
|
||||
#### Scenario: Disable
|
||||
|
||||
- **WHEN** an admin disables an event
|
||||
- **THEN** the event shows as disabled in the list and its other details are unchanged
|
||||
|
||||
#### Scenario: Unknown event
|
||||
|
||||
- **WHEN** an admin opens or saves an event id that does not exist
|
||||
- **THEN** the system responds not found
|
||||
|
||||
### Requirement: Event team
|
||||
|
||||
The system SHALL let an admin with `BO_EVENTS` choose, on create and on edit, the event's team: zero or more active admin users who work the event as salespeople. A user SHALL appear at most once on a team. Saving SHALL replace the team with the chosen set. Team membership SHALL belong to the admin's company. Removing someone from the team SHALL NOT change anything already recorded against them.
|
||||
|
||||
#### Scenario: Team on create
|
||||
|
||||
- **WHEN** an admin creates an event with `sales1` and `sales2` on the team
|
||||
- **THEN** opening the event shows `sales1` and `sales2` as its team
|
||||
|
||||
#### Scenario: Change team
|
||||
|
||||
- **GIVEN** an event whose team is `sales1` and `sales2`
|
||||
- **WHEN** an admin saves it with `sales2` and `sales3`
|
||||
- **THEN** the team is `sales2` and `sales3`
|
||||
|
||||
#### Scenario: Only active admin users
|
||||
|
||||
- **WHEN** an admin opens the team picker
|
||||
- **THEN** it offers active admin users only, never members or deactivated users
|
||||
- **AND** a request adding a member, a deactivated user or an unknown user to the team is refused
|
||||
|
||||
#### Scenario: Deactivated member stays visible
|
||||
|
||||
- **GIVEN** `sales1` is on an event's team
|
||||
- **WHEN** `sales1` is deactivated
|
||||
- **THEN** the event still lists `sales1` on its team, marked inactive, until an admin removes them
|
||||
- **AND** saving the event with `sales1` still on the team succeeds
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET, POST, PUT } from "./route";
|
||||
|
||||
type Req = Parameters<typeof GET>[0];
|
||||
const ctx = (...path: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
const req = (url: string, init?: RequestInit) => new Request(`http://localhost${url}`, init) as unknown as Req;
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } });
|
||||
});
|
||||
|
||||
describe("/api/event-leads/[...path]", () => {
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await GET(req("/api/event-leads/events"), ctx("events"));
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards GET with the query string", async () => {
|
||||
const res = await GET(req("/api/event-leads/9/leads?status=OPEN&page=0&size=20"), ctx("9", "leads"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/leads?status=OPEN&page=0&size=20", { token: "jwt-abc" });
|
||||
});
|
||||
|
||||
it("forwards POST and PUT bodies", async () => {
|
||||
await POST(req("/api/event-leads/9/match", { method: "POST", body: JSON.stringify({ mobile: "0123" }) }), ctx("9", "match"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/match", { method: "POST", body: { mobile: "0123" }, token: "jwt-abc" });
|
||||
await PUT(req("/api/event-leads/9/leads/7", { method: "PUT", body: JSON.stringify({ status: "WON" }) }), ctx("9", "leads", "7"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/leads/7", { method: "PUT", body: { status: "WON" }, token: "jwt-abc" });
|
||||
});
|
||||
|
||||
it("rejects dot segments so the proxy cannot leave /api/admin/event-leads", async () => {
|
||||
const res = await GET(req("/api/event-leads/x"), ctx("..", "users"));
|
||||
expect(res.status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("encodes path segments", async () => {
|
||||
await GET(req("/api/event-leads/a"), ctx("a/b"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/a%2Fb", { token: "jwt-abc" });
|
||||
});
|
||||
|
||||
it("passes upstream 409 with code and details", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({
|
||||
ok: false, error: "Already captured", status: 409, code: "ALREADY_CAPTURED", details: { eventLeadUuid: "55" },
|
||||
});
|
||||
const res = await POST(req("/api/event-leads/9", { method: "POST", body: "{}" }), ctx("9"));
|
||||
expect(res.status).toBe(409);
|
||||
const json = (await res.json()) as Record<string, unknown>;
|
||||
expect(json.code).toBe("ALREADY_CAPTURED");
|
||||
expect(json.details).toEqual({ eventLeadUuid: "55" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// One proxy for every /api/admin/event-leads endpoint; mobile-api owns validation and the BO_EVENT_LEADS guard.
|
||||
type Ctx = { params: Promise<{ path: string[] }> };
|
||||
|
||||
async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "PUT") {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path } = await params;
|
||||
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||
const target = `/api/admin/event-leads/${path.map(encodeURIComponent).join("/")}${new URL(req.url).search}`;
|
||||
const result = method
|
||||
? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token })
|
||||
: await callMobileApi<unknown>(target, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx);
|
||||
export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST");
|
||||
export const PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT");
|
||||
@@ -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<typeof PUT>[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<string, unknown>).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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
expect(json.error).toBe("Not authorized");
|
||||
expect(json.code).toBe("NOT_AUTHORIZED");
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> = {};
|
||||
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<AdminInterestEntity>(
|
||||
`/api/admin/interests/${encodeURIComponent(id)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
body: payload,
|
||||
token,
|
||||
},
|
||||
);
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -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<typeof GET>[0];
|
||||
}
|
||||
function postReq(body: unknown) {
|
||||
return new Request("http://localhost/api/interests", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}) as unknown as Parameters<typeof POST>[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<string, unknown>).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<string, unknown>;
|
||||
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<string, unknown>).code).toBe("NOT_AUTHORIZED");
|
||||
});
|
||||
});
|
||||
@@ -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<AdminInterestEntity[]>("/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<AdminInterestEntity>).name?.trim();
|
||||
if (!name) {
|
||||
return badRequest("Name is required.", { code: "REQUIRED_FIELD", details: { field: "name" } });
|
||||
}
|
||||
const result = await callMobileApi<AdminInterestEntity>(
|
||||
"/api/admin/interests",
|
||||
{
|
||||
method: "POST",
|
||||
body: { name, active: (body as Partial<AdminInterestEntity>).active, sortOrder: (body as Partial<AdminInterestEntity>).sortOrder },
|
||||
token,
|
||||
},
|
||||
);
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getEventLead: vi.fn(),
|
||||
updateEventLead: vi.fn(),
|
||||
listEventSalespeople: vi.fn(),
|
||||
listEventLeadInterests: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
getEventLead: mocks.getEventLead,
|
||||
updateEventLead: mocks.updateEventLead,
|
||||
listEventSalespeople: mocks.listEventSalespeople,
|
||||
listEventLeadInterests: mocks.listEventLeadInterests,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => ({
|
||||
...(await import("@/test/memoryRouter")).navigationMock,
|
||||
useParams: () => ({ eventUuid: "evt-1", eventLeadUuid: "el-1" }),
|
||||
}));
|
||||
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventLeadPage from "./page";
|
||||
|
||||
const SERVER_MSG = "Server says: internal detail xyz";
|
||||
const apiError = (code: string, extra: { details?: Record<string, unknown> } = {}, status = 400) =>
|
||||
new ApiError(SERVER_MSG, status, { code, errors: [], details: {}, ...extra });
|
||||
|
||||
const LEAD = {
|
||||
eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "l-1",
|
||||
name: "Ann Lead", mobile: "+6591111111", email: "ann@x.com", companyName: "Acme", jobTitle: "CEO",
|
||||
leadType: "NEW", salesperson: { id: 7, name: "Jane Sales" }, temperature: "WARM", status: "CONTACTED",
|
||||
interests: [{ id: 1, name: "Product A", active: true }, { id: 2, name: "Product B", active: false }],
|
||||
nextFollowUpDate: "2026-12-01", notes: "Call back", capturedAt: "2026-11-20T09:30:00Z",
|
||||
};
|
||||
const PAYLOAD = { salespersonId: 7, temperature: "WARM", status: "CONTACTED", interestIds: [1, 2], nextFollowUpDate: "2026-12-01", notes: "Call back" };
|
||||
|
||||
async function open(lead: Record<string, unknown> = {}) {
|
||||
mocks.getEventLead.mockResolvedValue({ ...LEAD, ...lead });
|
||||
render(<EventLeadPage />);
|
||||
await screen.findByLabelText("Status");
|
||||
return userEvent.setup();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads/evt-1/el-1");
|
||||
mocks.getEventLead.mockReset();
|
||||
mocks.updateEventLead.mockReset().mockResolvedValue(LEAD);
|
||||
mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 8, name: "Bob Other", username: "bob" }]);
|
||||
mocks.listEventLeadInterests.mockReset().mockResolvedValue([
|
||||
{ id: 1, name: "Product A", active: true },
|
||||
{ id: 3, name: "Product C", active: true },
|
||||
]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("EventLeadPage", { timeout: 20000 }, () => {
|
||||
it("renders NotAuthorized when the module is absent", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EventLeadPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the lead contact read-only with type badge and captured date", async () => {
|
||||
await open();
|
||||
expect(screen.getByText("Ann Lead")).toBeVisible();
|
||||
expect(screen.getByText("+6591111111")).toBeVisible();
|
||||
expect(screen.getByText("ann@x.com")).toBeVisible();
|
||||
expect(screen.getByText("Acme")).toBeVisible();
|
||||
expect(screen.getByText("CEO")).toBeVisible();
|
||||
expect(screen.getByText("New")).toBeVisible();
|
||||
expect(screen.getByText(/20\/11\/2026/)).toBeVisible();
|
||||
expect(screen.queryByLabelText("Name")).toBeNull();
|
||||
expect(screen.queryByLabelText("Mobile")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the Existing badge for an existing lead", async () => {
|
||||
await open({ leadType: "EXISTING" });
|
||||
expect(screen.getByText("Existing")).toBeVisible();
|
||||
});
|
||||
|
||||
it("prefills the editable fields from the event lead", async () => {
|
||||
await open();
|
||||
expect(screen.getByLabelText("Salesperson")).toHaveValue("7");
|
||||
expect(screen.getByLabelText("Temperature")).toHaveValue("WARM");
|
||||
expect(screen.getByLabelText("Status")).toHaveValue("CONTACTED");
|
||||
expect(screen.getByLabelText("Product A")).toBeChecked();
|
||||
expect(screen.getByLabelText("Next follow-up")).toHaveValue("01/12/2026");
|
||||
expect(screen.getByLabelText("Notes")).toHaveValue("Call back");
|
||||
});
|
||||
|
||||
it("keeps the current salesperson selectable when not on the event team list", async () => {
|
||||
await open();
|
||||
const select = screen.getByLabelText("Salesperson");
|
||||
expect(within(select).getByRole("option", { name: "Jane Sales" })).toBeInTheDocument();
|
||||
expect(within(select).getByRole("option", { name: "Bob Other" })).toBeInTheDocument();
|
||||
expect(within(select).getByRole("option", { name: "None" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists an inactive interest already on the lead (not in the options list) as checked, once", async () => {
|
||||
await open();
|
||||
expect(screen.getByLabelText("Product A")).toBeChecked();
|
||||
expect(screen.getByLabelText("Product B")).toBeChecked();
|
||||
expect(screen.getByLabelText("Product C")).not.toBeChecked();
|
||||
expect(screen.getAllByLabelText("Product A")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("unchecking the inactive interest saves interestIds without it", async () => {
|
||||
const user = await open();
|
||||
await user.click(screen.getByLabelText("Product B"));
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", { ...PAYLOAD, interestIds: [1] });
|
||||
});
|
||||
|
||||
it("saves unchanged values with all six fields, then goes back to the list", async () => {
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", PAYLOAD);
|
||||
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1"));
|
||||
});
|
||||
|
||||
it("saves edited values", async () => {
|
||||
const user = await open();
|
||||
await user.selectOptions(screen.getByLabelText("Salesperson"), "8");
|
||||
await user.selectOptions(screen.getByLabelText("Temperature"), "HOT");
|
||||
await user.selectOptions(screen.getByLabelText("Status"), "WON");
|
||||
await user.click(screen.getByLabelText("Product B"));
|
||||
await user.click(screen.getByLabelText("Product C"));
|
||||
pickDate("Next follow-up", "2026-12-05");
|
||||
const notes = screen.getByLabelText("Notes");
|
||||
await user.clear(notes);
|
||||
await user.type(notes, "Signed");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", {
|
||||
salespersonId: 8, temperature: "HOT", status: "WON", interestIds: [1, 3], nextFollowUpDate: "2026-12-05", notes: "Signed",
|
||||
});
|
||||
});
|
||||
|
||||
it("sends null for emptied fields", async () => {
|
||||
const user = await open();
|
||||
await user.selectOptions(screen.getByLabelText("Salesperson"), "");
|
||||
await user.selectOptions(screen.getByLabelText("Temperature"), "");
|
||||
await user.clear(screen.getByLabelText("Notes"));
|
||||
await user.click(screen.getByLabelText("Product A"));
|
||||
await user.click(screen.getByLabelText("Product B"));
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", {
|
||||
salespersonId: null, temperature: null, status: "CONTACTED", interestIds: [], nextFollowUpDate: "2026-12-01", notes: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("has a Back link to the event's leads", async () => {
|
||||
await open();
|
||||
expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/event-leads/evt-1");
|
||||
});
|
||||
|
||||
it("uses touch targets of at least 44px", async () => {
|
||||
await open();
|
||||
for (const label of ["Salesperson", "Temperature", "Status"]) expect(screen.getByLabelText(label)).toHaveClass("min-h-11");
|
||||
expect(screen.getByLabelText("Product A").closest("label")).toHaveClass("min-h-11");
|
||||
expect(screen.getByRole("button", { name: "Save" })).toHaveClass("min-h-11");
|
||||
expect(screen.getByRole("link", { name: "Back" })).toHaveClass("min-h-11");
|
||||
});
|
||||
|
||||
it("shows a not-found state with a Back link for EVENT_LEAD_NOT_FOUND", async () => {
|
||||
mocks.getEventLead.mockRejectedValue(apiError("EVENT_LEAD_NOT_FOUND", {}, 404));
|
||||
render(<EventLeadPage />);
|
||||
expect(await screen.findByText("Lead not found")).toBeVisible();
|
||||
expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/event-leads/evt-1");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Save" })).toBeNull();
|
||||
});
|
||||
|
||||
it("shows an error with retry for other load failures, and retry reloads", async () => {
|
||||
mocks.getEventLead.mockRejectedValueOnce(apiError("BOOM", {}, 500)).mockResolvedValue(LEAD);
|
||||
render(<EventLeadPage />);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the lead");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
await userEvent.setup().click(screen.getByRole("button", { name: "Retry" }));
|
||||
expect(await screen.findByLabelText("Status")).toBeVisible();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["TOO_LONG", "notes", "Notes", "Too long."],
|
||||
["INVALID_DATE", "nextFollowUpDate", "Next follow-up", "Enter a valid date."],
|
||||
["NOT_ON_TEAM", "salespersonId", "Salesperson", "This person is not on the event team."],
|
||||
["INVALID_VALUE", "temperature", "Temperature", "Invalid value."],
|
||||
["INVALID_VALUE", "status", "Status", "Invalid value."],
|
||||
])("%s on %s shows the mapped message under the field", async (code, field, label, text) => {
|
||||
mocks.updateEventLead.mockRejectedValue(apiError(code, { details: { field } }));
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText(text)).toBeVisible();
|
||||
const el = screen.getByLabelText(label);
|
||||
expect(el).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent(text);
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("INACTIVE_INTEREST shows the mapped message under the interests group", async () => {
|
||||
mocks.updateEventLead.mockRejectedValue(apiError("INACTIVE_INTEREST", { details: { field: "interestIds" } }));
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText("An interest is no longer active.")).toBeVisible();
|
||||
const group = screen.getByRole("group", { name: "Interests" });
|
||||
expect(group).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent("An interest is no longer active.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it("other save errors show a form-level message and stay on the page", async () => {
|
||||
mocks.updateEventLead.mockRejectedValue(apiError("SOMETHING_ELSE"));
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("an unknown field in a field error gives a form-level message", async () => {
|
||||
mocks.updateEventLead.mockRejectedValue(apiError("TOO_LONG", { details: { field: "bogus" } }));
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
import { getEventLead, listEventLeadInterests, listEventSalespeople, updateEventLead } from "@/app/lib/services/adminEventLeads";
|
||||
import type { EventLeadRow, InterestOption, LeadStatus, LeadTemperature, SalespersonOption } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const TEMPERATURES: [LeadTemperature, string][] = [["HOT", "LeadHot"], ["WARM", "LeadWarm"], ["COLD", "LeadCold"]];
|
||||
const STATUSES: [LeadStatus, string][] = [["OPEN", "LeadOpen"], ["CONTACTED", "LeadContacted"], ["QUALIFIED", "LeadQualified"], ["WON", "LeadWon"], ["LOST", "LeadLost"]];
|
||||
const CODE_MESSAGE: Record<string, string> = {
|
||||
TOO_LONG: "LeadErrTooLong",
|
||||
INVALID_DATE: "LeadErrInvalidDate",
|
||||
NOT_ON_TEAM: "LeadErrNotOnTeam",
|
||||
INACTIVE_INTEREST: "LeadErrInactiveInterest",
|
||||
INVALID_VALUE: "LeadErrInvalidValue",
|
||||
};
|
||||
const FIELDS = ["salespersonId", "temperature", "status", "interestIds", "nextFollowUpDate", "notes"];
|
||||
const SELECT_CLASS = "min-h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
|
||||
const TALL = "min-h-11";
|
||||
|
||||
type Loaded = { lead: EventLeadRow; salespeople: SalespersonOption[]; interests: InterestOption[] };
|
||||
type LoadState = "loading" | "notFound" | "error" | Loaded;
|
||||
|
||||
function EventLead() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { eventUuid, eventLeadUuid } = useParams<{ eventUuid: string; eventLeadUuid: string }>();
|
||||
const [state, setState] = useState<LoadState>("loading");
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [salespersonId, setSalespersonId] = useState("");
|
||||
const [temperature, setTemperature] = useState("");
|
||||
const [status, setStatus] = useState("");
|
||||
const [interestIds, setInterestIds] = useState<number[]>([]);
|
||||
const [nextFollowUpDate, setNextFollowUpDate] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const back = `/event-leads/${eventUuid}`;
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
Promise.all([getEventLead(eventUuid, eventLeadUuid), listEventSalespeople(eventUuid), listEventLeadInterests()])
|
||||
.then(([lead, salespeople, interests]) => {
|
||||
if (cancelled) return;
|
||||
setSalespersonId(lead.salesperson ? String(lead.salesperson.id) : "");
|
||||
setTemperature(lead.temperature ?? "");
|
||||
setStatus(lead.status);
|
||||
setInterestIds(lead.interests.map((i) => i.id));
|
||||
setNextFollowUpDate(lead.nextFollowUpDate ?? "");
|
||||
setNotes(lead.notes ?? "");
|
||||
setState({
|
||||
lead,
|
||||
// The current salesperson stays selectable even when no longer on the team list.
|
||||
salespeople: lead.salesperson && !salespeople.some((s) => s.id === lead.salesperson!.id)
|
||||
? [...salespeople, { id: lead.salesperson.id, name: lead.salesperson.name, username: "" }]
|
||||
: salespeople,
|
||||
// The options list is active-only; an inactive interest on the lead comes from the lead itself.
|
||||
interests: [...interests, ...lead.interests.filter((i) => !interests.some((o) => o.id === i.id))],
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
if (cancelled) return;
|
||||
const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined;
|
||||
setState(code === "EVENT_LEAD_NOT_FOUND" ? "notFound" : "error");
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, eventLeadUuid, reloadKey]);
|
||||
|
||||
const backLink = (
|
||||
<Button asChild variant="outline" className={TALL}>
|
||||
<Link href={back}>{t("Back")}</Link>
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (state === "loading") return <TableSkeleton rows={4} columns={2} />;
|
||||
if (state === "notFound") return <EmptyState title={t("LeadNotFound")} action={backLink} />;
|
||||
if (state === "error") {
|
||||
return <ErrorState message={t("LeadGetFailed")} onRetry={() => { setState("loading"); setReloadKey((k) => k + 1); }} />;
|
||||
}
|
||||
const { lead, salespeople, interests } = state;
|
||||
|
||||
const fieldProps = (f: string) => ({
|
||||
id: `lead-${f}`,
|
||||
"aria-invalid": fieldErrors[f] ? (true as const) : undefined,
|
||||
"aria-describedby": fieldErrors[f] ? `lead-${f}-error` : undefined,
|
||||
});
|
||||
const fieldError = (f: string) =>
|
||||
fieldErrors[f] ? <p id={`lead-${f}-error`} role="alert" className="text-sm text-destructive">{fieldErrors[f]}</p> : null;
|
||||
const field = (f: string, label: string, control: React.ReactNode) => (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`lead-${f}`}>{label}</Label>
|
||||
{control}
|
||||
{fieldError(f)}
|
||||
</div>
|
||||
);
|
||||
|
||||
async function onSave(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await updateEventLead(eventUuid, eventLeadUuid, {
|
||||
salespersonId: salespersonId ? Number(salespersonId) : null,
|
||||
temperature: (temperature || null) as LeadTemperature | null,
|
||||
status: status as LeadStatus,
|
||||
interestIds,
|
||||
nextFollowUpDate: nextFollowUpDate || null,
|
||||
notes: notes.trim() || null,
|
||||
});
|
||||
router.push(back);
|
||||
} catch (err) {
|
||||
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: unknown } } | undefined) : undefined;
|
||||
const f = data?.details?.field;
|
||||
const key = data?.code ? CODE_MESSAGE[data.code] : undefined;
|
||||
if (key && typeof f === "string" && FIELDS.includes(f)) setFieldErrors({ [f]: t(key) });
|
||||
else setFormError(t("LeadSaveFailed"));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const toggleInterest = (id: number) =>
|
||||
setInterestIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-xl">
|
||||
<PageHeader title={lead.name} />
|
||||
{formError && <ErrorState message={formError} />}
|
||||
<form onSubmit={onSave} className="space-y-4" noValidate>
|
||||
<div className="space-y-1 rounded-lg border p-4">
|
||||
<Badge variant={lead.leadType === "NEW" ? "default" : "secondary"}>{t(lead.leadType === "NEW" ? "LeadNew" : "LeadExisting")}</Badge>
|
||||
{lead.mobile && <p className="text-sm">{lead.mobile}</p>}
|
||||
{lead.email && <p className="text-sm">{lead.email}</p>}
|
||||
{lead.companyName && <p className="text-sm text-muted-foreground">{lead.companyName}</p>}
|
||||
{lead.jobTitle && <p className="text-sm text-muted-foreground">{lead.jobTitle}</p>}
|
||||
<p className="text-sm text-muted-foreground">{t("LeadCaptured")} {formatDmy(lead.capturedAt.slice(0, 10))}</p>
|
||||
</div>
|
||||
|
||||
{field("salespersonId", t("LeadSalesperson"),
|
||||
<select {...fieldProps("salespersonId")} className={SELECT_CLASS} value={salespersonId} onChange={(e) => setSalespersonId(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{salespeople.map((s) => <option key={s.id} value={String(s.id)}>{s.name}</option>)}
|
||||
</select>)}
|
||||
{field("temperature", t("LeadTemperature"),
|
||||
<select {...fieldProps("temperature")} className={SELECT_CLASS} value={temperature} onChange={(e) => setTemperature(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{TEMPERATURES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
{field("status", t("LeadStatus"),
|
||||
<select {...fieldProps("status")} className={SELECT_CLASS} value={status} onChange={(e) => setStatus(e.target.value)} disabled={busy}>
|
||||
{STATUSES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
|
||||
<fieldset {...fieldProps("interestIds")} className="space-y-1">
|
||||
<legend className="mb-1.5 text-sm font-medium">{t("LeadInterests")}</legend>
|
||||
{interests.map((i) => (
|
||||
<label key={i.id} className="flex min-h-11 items-center gap-3 text-sm">
|
||||
<input type="checkbox" className="size-5" checked={interestIds.includes(i.id)} onChange={() => toggleInterest(i.id)} disabled={busy} />
|
||||
{i.name}
|
||||
</label>
|
||||
))}
|
||||
{fieldError("interestIds")}
|
||||
</fieldset>
|
||||
|
||||
{field("nextFollowUpDate", t("LeadNextFollowUp"),
|
||||
<DatePicker {...fieldProps("nextFollowUpDate")} className="h-11" value={nextFollowUpDate} onChange={setNextFollowUpDate} disabled={busy} />)}
|
||||
{field("notes", t("LeadNotes"),
|
||||
<textarea {...fieldProps("notes")} className={`${SELECT_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
|
||||
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row">
|
||||
{backLink}
|
||||
<Button type="submit" className={TALL} disabled={busy}>{t("Save")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventLeadPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<EventLead />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
matchLead: vi.fn(),
|
||||
captureEventLead: vi.fn(),
|
||||
listEventSalespeople: vi.fn(),
|
||||
listEventLeadInterests: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
matchLead: mocks.matchLead,
|
||||
captureEventLead: mocks.captureEventLead,
|
||||
listEventSalespeople: mocks.listEventSalespeople,
|
||||
listEventLeadInterests: mocks.listEventLeadInterests,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => ({
|
||||
...(await import("@/test/memoryRouter")).navigationMock,
|
||||
useParams: () => ({ eventUuid: "evt-1" }),
|
||||
}));
|
||||
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import NewEventLeadPage from "./page";
|
||||
|
||||
const SERVER_MSG = "Server says: internal detail xyz";
|
||||
const apiError = (code: string, extra: { errors?: string[]; details?: Record<string, unknown> } = {}) =>
|
||||
new ApiError(SERVER_MSG, 400, { code, errors: [], details: {}, ...extra });
|
||||
|
||||
const CAPTURED = { leadUuid: "l-1", name: "Ann Captured", mobile: "+6591111111", email: "ann@x.com", companyName: "Acme", jobTitle: "CEO", eventLeadUuid: "el-9" };
|
||||
const FRESH = { leadUuid: "l-2", name: "Bob Fresh", mobile: "+6592222222", email: "bob@x.com", companyName: "Globex", jobTitle: "CTO", eventLeadUuid: null };
|
||||
|
||||
async function toStep1Match(candidates: unknown[], match = { mobile: "+6591234567", email: "a@b.com" }) {
|
||||
mocks.matchLead.mockResolvedValue({ ...match, candidates });
|
||||
const user = userEvent.setup();
|
||||
render(<NewEventLeadPage />);
|
||||
await user.type(screen.getByLabelText("Mobile"), "91234567");
|
||||
await user.type(screen.getByLabelText("Email"), "a@b.com");
|
||||
await user.click(screen.getByRole("button", { name: "Next" }));
|
||||
return user;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads/evt-1/new");
|
||||
mocks.matchLead.mockReset();
|
||||
mocks.captureEventLead.mockReset().mockResolvedValue({ eventLeadUuid: "el-new" });
|
||||
mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 7, name: "Jane Sales", username: "jane" }]);
|
||||
mocks.listEventLeadInterests.mockReset().mockResolvedValue([
|
||||
{ id: 1, name: "Product A", active: true },
|
||||
{ id: 2, name: "Product B", active: false },
|
||||
]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("NewEventLeadPage", { timeout: 20000 }, () => {
|
||||
it("renders NotAuthorized when the module is absent", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<NewEventLeadPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("step 1 has phone-friendly mobile and email inputs of at least 44px", () => {
|
||||
render(<NewEventLeadPage />);
|
||||
const mobile = screen.getByLabelText("Mobile");
|
||||
expect(mobile).toHaveAttribute("type", "tel");
|
||||
expect(mobile).toHaveAttribute("inputmode", "tel");
|
||||
expect(mobile).toHaveAttribute("autocomplete", "tel");
|
||||
expect(mobile).toHaveClass("min-h-11");
|
||||
const email = screen.getByLabelText("Email");
|
||||
expect(email).toHaveAttribute("type", "email");
|
||||
expect(email).toHaveAttribute("autocomplete", "email");
|
||||
expect(email).toHaveClass("min-h-11");
|
||||
expect(screen.getByRole("button", { name: "Next" })).toHaveClass("min-h-11");
|
||||
});
|
||||
|
||||
it("Next calls matchLead with the typed values, null for empty ones", async () => {
|
||||
mocks.matchLead.mockResolvedValue({ mobile: null, email: null, candidates: [] });
|
||||
const user = userEvent.setup();
|
||||
render(<NewEventLeadPage />);
|
||||
await user.type(screen.getByLabelText("Mobile"), "91234567");
|
||||
await user.click(screen.getByRole("button", { name: "Next" }));
|
||||
await waitFor(() => expect(mocks.matchLead).toHaveBeenCalledWith("evt-1", { mobile: "91234567", email: null }));
|
||||
});
|
||||
|
||||
it("shows each candidate as a card; captured ones link to the lead, others offer This person", async () => {
|
||||
await toStep1Match([CAPTURED, FRESH]);
|
||||
const ann = (await screen.findByText("Ann Captured")).closest("li")!;
|
||||
expect(within(ann).getByText("+6591111111")).toBeVisible();
|
||||
expect(within(ann).getByText("ann@x.com")).toBeVisible();
|
||||
expect(within(ann).getByText("Acme")).toBeVisible();
|
||||
expect(within(ann).getByText("Already captured")).toBeVisible();
|
||||
expect(within(ann).getByRole("link", { name: "Open" })).toHaveAttribute("href", "/event-leads/evt-1/el-9");
|
||||
expect(within(ann).queryByRole("button", { name: "This person" })).toBeNull();
|
||||
const bob = screen.getByText("Bob Fresh").closest("li")!;
|
||||
expect(within(bob).getByText("Globex")).toBeVisible();
|
||||
expect(within(bob).getByRole("button", { name: "This person" })).toHaveClass("min-h-11");
|
||||
expect(within(bob).queryByText("Already captured")).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Different person" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("goes straight to step 2 as new, prefilled with the normalised match values, when nothing matches", async () => {
|
||||
await toStep1Match([]);
|
||||
expect(await screen.findByLabelText("Name")).toHaveValue("");
|
||||
expect(screen.getByLabelText("Mobile")).toHaveValue("+6591234567");
|
||||
expect(screen.getByLabelText("Email")).toHaveValue("a@b.com");
|
||||
expect(screen.getByLabelText("Company")).toBeVisible();
|
||||
expect(screen.getByLabelText("Job title")).toBeVisible();
|
||||
});
|
||||
|
||||
it("Different person goes to step 2 as new", async () => {
|
||||
const user = await toStep1Match([FRESH]);
|
||||
await user.click(await screen.findByRole("button", { name: "Different person" }));
|
||||
expect(await screen.findByLabelText("Name")).toHaveValue("");
|
||||
expect(screen.getByLabelText("Mobile")).toHaveValue("+6591234567");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["REQUIRED_FIELD", ["mobile", "email"], "Mobile or email is required.", ["Mobile", "Email"]],
|
||||
["INVALID_MOBILE", [], "Enter a valid mobile number.", ["Mobile"]],
|
||||
["INVALID_EMAIL", [], "Enter a valid email address.", ["Email"]],
|
||||
])("step 1 %s shows the mapped message under the field", async (code, errors, text, labels) => {
|
||||
mocks.matchLead.mockRejectedValue(apiError(code, { errors }));
|
||||
const user = userEvent.setup();
|
||||
render(<NewEventLeadPage />);
|
||||
await user.click(screen.getByRole("button", { name: "Next" }));
|
||||
const msgs = await screen.findAllByText(text);
|
||||
expect(msgs).toHaveLength(labels.length);
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
for (const label of labels) {
|
||||
const input = screen.getByLabelText(label);
|
||||
expect(input).toHaveAttribute("aria-invalid", "true");
|
||||
const described = document.getElementById(input.getAttribute("aria-describedby")!);
|
||||
expect(described).toHaveTextContent(text);
|
||||
}
|
||||
});
|
||||
|
||||
it("This person shows the lead read-only and saves with leadUuid, filling only its blank contact field", async () => {
|
||||
// Matched on mobile; the lead has no email yet, so the entered email fills it.
|
||||
const picked = { ...FRESH, mobile: "+60198887777", email: null };
|
||||
const user = await toStep1Match([picked], { mobile: "+60198887777", email: "a@b.com" });
|
||||
await user.click(await screen.findByRole("button", { name: "This person" }));
|
||||
expect(await screen.findByText("Bob Fresh")).toBeVisible();
|
||||
expect(screen.queryByLabelText("Name")).toBeNull();
|
||||
expect(screen.queryByLabelText("Company")).toBeNull();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1));
|
||||
const [uuid, payload] = mocks.captureEventLead.mock.calls[0];
|
||||
expect(uuid).toBe("evt-1");
|
||||
expect(payload).toMatchObject({ leadUuid: "l-2", name: "Bob Fresh", mobile: "+60198887777", email: "a@b.com", status: "OPEN" });
|
||||
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1"));
|
||||
});
|
||||
|
||||
it("picking one of two people never copies the other person's contact onto it", async () => {
|
||||
// Mobile matched A, email matched B. Picking A must not send B's email (no merge).
|
||||
const a = { ...FRESH, leadUuid: "l-a", name: "Amy Mobile", mobile: "+60198887777", email: null };
|
||||
const b = { ...FRESH, leadUuid: "l-b", name: "Ben Email", mobile: null, email: "a@b.com" };
|
||||
const user = await toStep1Match([a, b], { mobile: "+60198887777", email: "a@b.com" });
|
||||
await user.click((await screen.findAllByRole("button", { name: "This person" }))[0]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.captureEventLead.mock.calls[0][1]).toMatchObject({ leadUuid: "l-a", mobile: "+60198887777", email: null });
|
||||
});
|
||||
|
||||
it("step 2 offers salespeople, interests (active only), temperature and status, and saves a new lead", async () => {
|
||||
const user = await toStep1Match([]);
|
||||
await user.type(await screen.findByLabelText("Name"), "Carl New");
|
||||
await user.type(screen.getByLabelText("Company"), "Initech");
|
||||
await user.type(screen.getByLabelText("Job title"), "COO");
|
||||
await user.type(screen.getByLabelText("Notes"), "Met at booth");
|
||||
expect(screen.getByLabelText("Status")).toHaveValue("OPEN");
|
||||
expect(screen.getByLabelText("Status")).toHaveClass("min-h-11");
|
||||
expect(within(screen.getByLabelText("Temperature")).getByRole("option", { name: "Hot" })).toBeInTheDocument();
|
||||
expect(await screen.findByRole("option", { name: "Jane Sales" })).toBeInTheDocument();
|
||||
await user.selectOptions(screen.getByLabelText("Salesperson"), "7");
|
||||
await user.selectOptions(screen.getByLabelText("Temperature"), "HOT");
|
||||
await user.selectOptions(screen.getByLabelText("Status"), "QUALIFIED");
|
||||
expect(screen.queryByLabelText("Product B")).toBeNull();
|
||||
await user.click(await screen.findByLabelText("Product A"));
|
||||
pickDate("Next follow-up", "2026-12-05");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.captureEventLead).toHaveBeenCalledWith("evt-1", {
|
||||
name: "Carl New",
|
||||
mobile: "+6591234567",
|
||||
email: "a@b.com",
|
||||
companyName: "Initech",
|
||||
jobTitle: "COO",
|
||||
salespersonId: 7,
|
||||
temperature: "HOT",
|
||||
status: "QUALIFIED",
|
||||
interestIds: [1],
|
||||
nextFollowUpDate: "2026-12-05",
|
||||
notes: "Met at booth",
|
||||
});
|
||||
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1"));
|
||||
});
|
||||
|
||||
it("Back returns to step 1", async () => {
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Back" }));
|
||||
expect(await screen.findByRole("button", { name: "Next" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("step 2 REQUIRED_FIELD marks each field in errors[]", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name", "salespersonId"] }));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
const msgs = await screen.findAllByText("This field is required.");
|
||||
expect(msgs).toHaveLength(2);
|
||||
for (const label of ["Name", "Salesperson"]) {
|
||||
const el = screen.getByLabelText(label);
|
||||
expect(el).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent("This field is required.");
|
||||
}
|
||||
expect(screen.getByLabelText("Company")).not.toHaveAttribute("aria-invalid", "true");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["TOO_LONG", "name", "Name", "Too long."],
|
||||
["TOO_LONG", "companyName", "Company", "Too long."],
|
||||
["TOO_LONG", "jobTitle", "Job title", "Too long."],
|
||||
["INVALID_MOBILE", "mobile", "Mobile", "Enter a valid mobile number."],
|
||||
["INVALID_EMAIL", "email", "Email", "Enter a valid email address."],
|
||||
["INVALID_DATE", "nextFollowUpDate", "Next follow-up", "Enter a valid date."],
|
||||
["NOT_ON_TEAM", "salespersonId", "Salesperson", "This person is not on the event team."],
|
||||
["INVALID_VALUE", "temperature", "Temperature", "Invalid value."],
|
||||
["INVALID_VALUE", "status", "Status", "Invalid value."],
|
||||
])("step 2 %s on %s shows the mapped message under the field", async (code, field, label, text) => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError(code, { details: { field } }));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText(text)).toBeVisible();
|
||||
const el = screen.getByLabelText(label);
|
||||
expect(el).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent(text);
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("step 2 INACTIVE_INTEREST shows the mapped message under the interests group", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("INACTIVE_INTEREST", { details: { field: "interestIds" } }));
|
||||
const user = await toStep1Match([]);
|
||||
await screen.findByLabelText("Product A");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText("An interest is no longer active.")).toBeVisible();
|
||||
const group = screen.getByRole("group", { name: "Interests" });
|
||||
expect(group).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent("An interest is no longer active.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it("step 2 ALREADY_CAPTURED navigates to the existing event lead", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("ALREADY_CAPTURED", { details: { eventLeadUuid: "el-77" } }));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1/el-77"));
|
||||
});
|
||||
|
||||
it("step 2 other errors show a form-level message", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("SOMETHING_ELSE"));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("picked lead: a field error for a field not shown on this step still gives a form-level message", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name"] }));
|
||||
const user = await toStep1Match([FRESH]);
|
||||
await user.click(await screen.findByRole("button", { name: "This person" }));
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it("unknown field in a field error gives a form-level message", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("TOO_LONG", { details: { field: "bogus" } }));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
});
|
||||
|
||||
it("Back on the candidate list returns to editable mobile and email", async () => {
|
||||
const user = await toStep1Match([FRESH]);
|
||||
await screen.findByText("Bob Fresh");
|
||||
await user.click(screen.getByRole("button", { name: "Back" }));
|
||||
expect(screen.queryByText("Bob Fresh")).toBeNull();
|
||||
expect(screen.getByLabelText("Mobile")).toHaveValue("91234567");
|
||||
expect(screen.getByRole("button", { name: "Next" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("preselects the capturing user as salesperson when on the team", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true, id: 7 });
|
||||
const user = await toStep1Match([]);
|
||||
await screen.findByRole("option", { name: "Jane Sales" });
|
||||
await waitFor(() => expect(screen.getByLabelText("Salesperson")).toHaveValue("7"));
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledWith("evt-1", expect.objectContaining({ salespersonId: 7 })));
|
||||
});
|
||||
|
||||
it("leaves the salesperson empty when the capturing user is not on the team", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true, id: 99 });
|
||||
await toStep1Match([]);
|
||||
await screen.findByRole("option", { name: "Jane Sales" });
|
||||
expect(screen.getByLabelText("Salesperson")).toHaveValue("");
|
||||
});
|
||||
|
||||
it("keeps the options-load failure visible after matching", async () => {
|
||||
mocks.listEventSalespeople.mockRejectedValue(new Error("boom"));
|
||||
await toStep1Match([]);
|
||||
expect(await screen.findByText("Failed to load salespeople or interests")).toBeVisible();
|
||||
await screen.findByLabelText("Name");
|
||||
expect(screen.getByText("Failed to load salespeople or interests")).toBeVisible();
|
||||
});
|
||||
|
||||
it("step 2 EVENT_DISABLED shows a specific form-level message", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("EVENT_DISABLED"));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("This event is closed for new leads.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it("step 2 ALREADY_CAPTURED without an event lead uuid shows Already captured", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("ALREADY_CAPTURED"));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Already captured");
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { captureEventLead, listEventLeadInterests, listEventSalespeople, matchLead } from "@/app/lib/services/adminEventLeads";
|
||||
import type { InterestOption, LeadCandidate, LeadMatchResult, LeadStatus, LeadTemperature, SalespersonOption } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const TEMPERATURES: [LeadTemperature, string][] = [["HOT", "LeadHot"], ["WARM", "LeadWarm"], ["COLD", "LeadCold"]];
|
||||
const STATUSES: [LeadStatus, string][] = [["OPEN", "LeadOpen"], ["CONTACTED", "LeadContacted"], ["QUALIFIED", "LeadQualified"], ["WON", "LeadWon"], ["LOST", "LeadLost"]];
|
||||
const CODE_MESSAGE: Record<string, string> = {
|
||||
REQUIRED_FIELD: "LeadErrRequired",
|
||||
TOO_LONG: "LeadErrTooLong",
|
||||
INVALID_MOBILE: "LeadErrInvalidMobile",
|
||||
INVALID_EMAIL: "LeadErrInvalidEmail",
|
||||
INVALID_DATE: "LeadErrInvalidDate",
|
||||
NOT_ON_TEAM: "LeadErrNotOnTeam",
|
||||
INACTIVE_INTEREST: "LeadErrInactiveInterest",
|
||||
INVALID_VALUE: "LeadErrInvalidValue",
|
||||
};
|
||||
// Codes that name their field themselves when the server omits details.field.
|
||||
const IMPLIED_FIELD: Record<string, string> = { INVALID_MOBILE: "mobile", INVALID_EMAIL: "email" };
|
||||
const SELECT_CLASS = "min-h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
|
||||
const TALL = "min-h-11";
|
||||
|
||||
type Step = "match" | "details";
|
||||
const STEP1_FIELDS = ["mobile", "email"];
|
||||
const PICKED_FIELDS = ["salespersonId", "temperature", "status", "interestIds", "nextFollowUpDate", "notes"];
|
||||
const NEW_FIELDS = [...PICKED_FIELDS, "name", "mobile", "email", "companyName", "jobTitle"];
|
||||
// Codes that are never tied to a field.
|
||||
const FORM_CODE_MESSAGE: Record<string, string> = { EVENT_DISABLED: "LeadEventDisabled", ALREADY_CAPTURED: "LeadAlreadyCaptured" };
|
||||
|
||||
type Errors = { fields: Record<string, string>; form: string | null; code?: string; details: Record<string, unknown> };
|
||||
|
||||
function readError(err: unknown, t: (k: string) => string, fallbackKey: string, rendered: string[], requiredKey?: string): Errors {
|
||||
const data = err instanceof ApiError ? (err.data as { code?: string; errors?: string[]; details?: Record<string, unknown> } | undefined) : undefined;
|
||||
const code = data?.code;
|
||||
const details = data?.details ?? {};
|
||||
const fields: Record<string, string> = {};
|
||||
let hidden = false; // a named field this step does not render must not make the failure silent
|
||||
const mark = (f: string, key: string) => {
|
||||
if (rendered.includes(f)) fields[f] = t(key);
|
||||
else hidden = true;
|
||||
};
|
||||
if (code === "REQUIRED_FIELD") {
|
||||
for (const f of data?.errors ?? []) mark(f, requiredKey ?? CODE_MESSAGE.REQUIRED_FIELD);
|
||||
} else if (code && CODE_MESSAGE[code]) {
|
||||
const field = typeof details.field === "string" ? details.field : IMPLIED_FIELD[code];
|
||||
if (field) mark(field, CODE_MESSAGE[code]);
|
||||
}
|
||||
const key = (code && FORM_CODE_MESSAGE[code]) || fallbackKey;
|
||||
const form = hidden || !Object.keys(fields).length ? t(key) : null;
|
||||
return { fields, form, code, details };
|
||||
}
|
||||
|
||||
function NewEventLead() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { id: myId } = useAdminAuth();
|
||||
const { eventUuid } = useParams<{ eventUuid: string }>();
|
||||
const [step, setStep] = useState<Step>("match");
|
||||
const [candidates, setCandidates] = useState<LeadCandidate[] | null>(null);
|
||||
const [match, setMatch] = useState<LeadMatchResult | null>(null);
|
||||
const [existing, setExisting] = useState<LeadCandidate | null>(null);
|
||||
const [mobile, setMobile] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [companyName, setCompanyName] = useState("");
|
||||
const [jobTitle, setJobTitle] = useState("");
|
||||
const [salespersonId, setSalespersonId] = useState("");
|
||||
const [temperature, setTemperature] = useState("");
|
||||
const [status, setStatus] = useState<string>("OPEN");
|
||||
const [interestIds, setInterestIds] = useState<number[]>([]);
|
||||
const [nextFollowUpDate, setNextFollowUpDate] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [salespeople, setSalespeople] = useState<SalespersonOption[]>([]);
|
||||
const [interests, setInterests] = useState<InterestOption[]>([]);
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [optionsError, setOptionsError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
Promise.all([listEventSalespeople(eventUuid), listEventLeadInterests()])
|
||||
.then(([s, i]) => {
|
||||
if (cancelled) return;
|
||||
setSalespeople(s);
|
||||
setInterests(i.filter((o) => o.active));
|
||||
if (myId != null && s.some((o) => o.id === myId)) setSalespersonId(String(myId));
|
||||
})
|
||||
.catch(() => { if (!cancelled) setOptionsError(t("LeadOptionsLoadFailed")); });
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, t, myId]);
|
||||
|
||||
const fieldProps = (f: string) => ({
|
||||
id: `lead-${f}`,
|
||||
"aria-invalid": fieldErrors[f] ? (true as const) : undefined,
|
||||
"aria-describedby": fieldErrors[f] ? `lead-${f}-error` : undefined,
|
||||
});
|
||||
const fieldError = (f: string) =>
|
||||
fieldErrors[f] ? <p id={`lead-${f}-error`} role="alert" className="text-sm text-destructive">{fieldErrors[f]}</p> : null;
|
||||
|
||||
function fail(e: Errors) {
|
||||
setFieldErrors(e.fields);
|
||||
setFormError(e.form);
|
||||
}
|
||||
|
||||
async function onMatch(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await matchLead(eventUuid, { mobile: mobile.trim() || null, email: email.trim() || null });
|
||||
setMatch(result);
|
||||
if (result.candidates.length === 0) startDetails(result, null);
|
||||
else setCandidates(result.candidates);
|
||||
} catch (err) {
|
||||
fail(readError(err, t, "LeadMatchFailed", STEP1_FIELDS, "LeadErrRequiredContact"));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function startDetails(result: LeadMatchResult, lead: LeadCandidate | null) {
|
||||
setExisting(lead);
|
||||
setMobile(result.mobile ?? "");
|
||||
setEmail(result.email ?? "");
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
setStep("details");
|
||||
}
|
||||
|
||||
// A picked lead gets an entered contact value only if it is already its own, or fills its blank field and
|
||||
// belongs to no other candidate: copying another person's mobile or email onto it would merge two people.
|
||||
function ownValue(field: "mobile" | "email"): string | null {
|
||||
const value = match?.[field] ?? null;
|
||||
if (!value || !existing) return null;
|
||||
if (existing[field] === value) return value;
|
||||
if (existing[field]) return null;
|
||||
return candidates?.some((c) => c.leadUuid !== existing.leadUuid && c[field] === value) ? null : value;
|
||||
}
|
||||
|
||||
async function onSave(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await captureEventLead(eventUuid, {
|
||||
...(existing
|
||||
? { leadUuid: existing.leadUuid, name: existing.name, mobile: ownValue("mobile"), email: ownValue("email") }
|
||||
: { name: name.trim(), mobile: mobile.trim() || null, email: email.trim() || null, companyName: companyName.trim() || null, jobTitle: jobTitle.trim() || null }),
|
||||
salespersonId: salespersonId ? Number(salespersonId) : null,
|
||||
temperature: (temperature || null) as LeadTemperature | null,
|
||||
status: status as LeadStatus,
|
||||
interestIds,
|
||||
nextFollowUpDate: nextFollowUpDate || null,
|
||||
notes: notes.trim() || null,
|
||||
});
|
||||
router.push(`/event-leads/${eventUuid}`);
|
||||
} catch (err) {
|
||||
const e = readError(err, t, "LeadSaveFailed", existing ? PICKED_FIELDS : NEW_FIELDS);
|
||||
if (e.code === "ALREADY_CAPTURED" && typeof e.details.eventLeadUuid === "string") {
|
||||
router.push(`/event-leads/${eventUuid}/${e.details.eventLeadUuid}`);
|
||||
return;
|
||||
}
|
||||
fail(e);
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const toggleInterest = (id: number) =>
|
||||
setInterestIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
|
||||
|
||||
const field = (f: string, label: string, control: React.ReactNode) => (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`lead-${f}`}>{label}</Label>
|
||||
{control}
|
||||
{fieldError(f)}
|
||||
</div>
|
||||
);
|
||||
const textInput = (f: string, label: string, value: string, set: (v: string) => void, extra: React.ComponentProps<typeof Input> = {}) =>
|
||||
field(f, label, <Input {...fieldProps(f)} className={TALL} value={value} onChange={(e) => set(e.target.value)} disabled={busy} {...extra} />);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-xl">
|
||||
<PageHeader title={t("LeadAddLead")} />
|
||||
{optionsError && <ErrorState message={optionsError} />}
|
||||
{formError && <ErrorState message={formError} />}
|
||||
|
||||
{step === "match" && !candidates && (
|
||||
<form onSubmit={onMatch} className="space-y-4" noValidate>
|
||||
{textInput("mobile", t("LeadMobile"), mobile, setMobile, { type: "tel", inputMode: "tel", autoComplete: "tel" })}
|
||||
{textInput("email", t("Email"), email, setEmail, { type: "email", autoComplete: "email" })}
|
||||
<Button type="submit" className={`${TALL} w-full sm:w-auto`} disabled={busy}>{t("LeadNext")}</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === "match" && candidates && match && (
|
||||
<div className="space-y-4">
|
||||
<ul className="space-y-3">
|
||||
{candidates.map((c) => (
|
||||
<li key={c.leadUuid} className="space-y-2 rounded-lg border p-4">
|
||||
<p className="font-medium">{c.name}</p>
|
||||
{c.mobile && <p className="text-sm">{c.mobile}</p>}
|
||||
{c.email && <p className="text-sm">{c.email}</p>}
|
||||
{c.companyName && <p className="text-sm text-muted-foreground">{c.companyName}</p>}
|
||||
{c.eventLeadUuid ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span className="text-sm font-medium">{t("LeadAlreadyCaptured")}</span>
|
||||
<Button asChild variant="outline" className={TALL}>
|
||||
<Link href={`/event-leads/${eventUuid}/${c.eventLeadUuid}`}>{t("LeadOpen")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button type="button" className={`${TALL} w-full sm:w-auto`} onClick={() => startDetails(match, c)}>{t("LeadThisPerson")}</Button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<Button type="button" variant="outline" className={TALL} onClick={() => startDetails(match, null)}>{t("LeadDifferentPerson")}</Button>
|
||||
<Button type="button" variant="ghost" className={TALL} onClick={() => setCandidates(null)}>{t("Back")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "details" && (
|
||||
<form onSubmit={onSave} className="space-y-4" noValidate>
|
||||
{existing ? (
|
||||
<div className="space-y-1 rounded-lg border p-4">
|
||||
<p className="font-medium">{existing.name}</p>
|
||||
{existing.mobile && <p className="text-sm">{existing.mobile}</p>}
|
||||
{existing.email && <p className="text-sm">{existing.email}</p>}
|
||||
{existing.companyName && <p className="text-sm text-muted-foreground">{existing.companyName}</p>}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{textInput("name", t("LeadName"), name, setName)}
|
||||
{textInput("mobile", t("LeadMobile"), mobile, setMobile, { type: "tel", inputMode: "tel", autoComplete: "tel" })}
|
||||
{textInput("email", t("Email"), email, setEmail, { type: "email", autoComplete: "email" })}
|
||||
{textInput("companyName", t("LeadCompany"), companyName, setCompanyName)}
|
||||
{textInput("jobTitle", t("LeadJobTitle"), jobTitle, setJobTitle)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{field("salespersonId", t("LeadSalesperson"),
|
||||
<select {...fieldProps("salespersonId")} className={SELECT_CLASS} value={salespersonId} onChange={(e) => setSalespersonId(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{salespeople.map((s) => <option key={s.id} value={String(s.id)}>{s.name}</option>)}
|
||||
</select>)}
|
||||
{field("temperature", t("LeadTemperature"),
|
||||
<select {...fieldProps("temperature")} className={SELECT_CLASS} value={temperature} onChange={(e) => setTemperature(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{TEMPERATURES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
{field("status", t("LeadStatus"),
|
||||
<select {...fieldProps("status")} className={SELECT_CLASS} value={status} onChange={(e) => setStatus(e.target.value)} disabled={busy}>
|
||||
{STATUSES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
|
||||
<fieldset {...fieldProps("interestIds")} className="space-y-1">
|
||||
<legend className="mb-1.5 text-sm font-medium">{t("LeadInterests")}</legend>
|
||||
{interests.map((i) => (
|
||||
<label key={i.id} className="flex min-h-11 items-center gap-3 text-sm">
|
||||
<input type="checkbox" className="size-5" checked={interestIds.includes(i.id)} onChange={() => toggleInterest(i.id)} disabled={busy} />
|
||||
{i.name}
|
||||
</label>
|
||||
))}
|
||||
{fieldError("interestIds")}
|
||||
</fieldset>
|
||||
|
||||
{field("nextFollowUpDate", t("LeadNextFollowUp"),
|
||||
<DatePicker {...fieldProps("nextFollowUpDate")} className="h-11" value={nextFollowUpDate} onChange={setNextFollowUpDate} disabled={busy} />)}
|
||||
{field("notes", t("LeadNotes"),
|
||||
<textarea {...fieldProps("notes")} className={`${SELECT_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
|
||||
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row">
|
||||
<Button type="button" variant="outline" className={TALL} onClick={() => { setFieldErrors({}); setFormError(null); setStep("match"); }} disabled={busy}>{t("Back")}</Button>
|
||||
<Button type="submit" className={TALL} disabled={busy}>{t("Save")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function NewEventLeadPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<NewEventLead />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// --- test mocks ---
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listEventLeads: vi.fn(),
|
||||
listEventSalespeople: vi.fn(),
|
||||
listEventLeadInterests: vi.fn(),
|
||||
listEventLeadEvents: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
listEventLeads: mocks.listEventLeads,
|
||||
listEventSalespeople: mocks.listEventSalespeople,
|
||||
listEventLeadInterests: mocks.listEventLeadInterests,
|
||||
listEventLeadEvents: mocks.listEventLeadEvents,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => ({
|
||||
...(await import("@/test/memoryRouter")).navigationMock,
|
||||
useParams: () => ({ eventUuid: "evt-1" }),
|
||||
}));
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventLeadsDetailPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads/evt-1");
|
||||
mocks.listEventLeads.mockReset().mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 1, name: "Jane Sales", username: "jane" }]);
|
||||
mocks.listEventLeadInterests.mockReset().mockResolvedValue([{ id: 1, name: "Product A", active: true }]);
|
||||
mocks.listEventLeadEvents.mockReset().mockResolvedValue([{ uuid: "evt-1", name: "Test Event", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" }]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({
|
||||
loading: false,
|
||||
hasModule: () => true,
|
||||
});
|
||||
});
|
||||
|
||||
describe("EventLeadsDetailPage (listing)", { timeout: 20000 }, () => {
|
||||
|
||||
it("renders NotAuthorized when the EventLeads module is absent", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EventLeadsDetailPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("sends eventUuid and each filter to listEventLeads", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<EventLeadsDetailPage />);
|
||||
|
||||
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalledWith("evt-1", expect.objectContaining({ page: 1, pageSize: expect.any(Number) })));
|
||||
|
||||
// Filter by temperature
|
||||
await user.click(screen.getByRole("combobox", { name: /temperature filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Hot" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ temperature: "HOT", page: 1 })),
|
||||
);
|
||||
|
||||
// Filter by status
|
||||
await user.click(screen.getByRole("combobox", { name: /status filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Won" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ status: "WON", page: 1 })),
|
||||
);
|
||||
|
||||
// Filter by lead type
|
||||
await user.click(screen.getByRole("combobox", { name: /lead type filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "New" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ leadType: "NEW", page: 1 })),
|
||||
);
|
||||
|
||||
// Filter by salesperson
|
||||
await user.click(screen.getByRole("combobox", { name: /salesperson filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Jane Sales" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ salespersonId: "1", page: 1 })),
|
||||
);
|
||||
|
||||
// Filter by interest
|
||||
await user.click(screen.getByRole("combobox", { name: /interest filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Product A" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ interestId: "1", page: 1 })),
|
||||
);
|
||||
});
|
||||
|
||||
it("renders lead cards on mobile view with data-testid", async () => {
|
||||
mocks.listEventLeads.mockResolvedValue({
|
||||
items: [{
|
||||
eventLeadUuid: "el-1",
|
||||
eventUuid: "evt-1",
|
||||
leadUuid: "lead-1",
|
||||
name: "John Doe",
|
||||
mobile: "+60123456789",
|
||||
email: "john@example.com",
|
||||
companyName: "Acme",
|
||||
jobTitle: "Manager",
|
||||
leadType: "NEW",
|
||||
salesperson: { id: 1, name: "Jane Sales" },
|
||||
temperature: "HOT",
|
||||
status: "OPEN",
|
||||
interests: [{ id: 1, name: "Product A", active: true }],
|
||||
nextFollowUpDate: "2025-06-15",
|
||||
notes: null,
|
||||
capturedAt: "2025-06-01",
|
||||
}],
|
||||
total: 1,
|
||||
});
|
||||
render(<EventLeadsDetailPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("lead-card")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("links each lead row/card to its detail page", async () => {
|
||||
mocks.listEventLeads.mockResolvedValue({
|
||||
items: [{
|
||||
eventLeadUuid: "el-1",
|
||||
eventUuid: "evt-1",
|
||||
leadUuid: "lead-1",
|
||||
name: "John Doe",
|
||||
mobile: "+60123456789",
|
||||
email: "john@example.com",
|
||||
companyName: "Acme",
|
||||
jobTitle: "Manager",
|
||||
leadType: "NEW",
|
||||
salesperson: { id: 1, name: "Jane Sales" },
|
||||
temperature: "HOT",
|
||||
status: "OPEN",
|
||||
interests: [{ id: 1, name: "Product A", active: true }],
|
||||
nextFollowUpDate: "2025-06-15",
|
||||
notes: null,
|
||||
capturedAt: "2025-06-01",
|
||||
}],
|
||||
total: 1,
|
||||
});
|
||||
render(<EventLeadsDetailPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
// The lead card is a link to the detail page
|
||||
const card = screen.getByTestId("lead-card");
|
||||
expect(card).toHaveAttribute("href", "/event-leads/evt-1/el-1");
|
||||
});
|
||||
const card = within(screen.getByTestId("lead-card"));
|
||||
for (const text of ["John Doe", "+60123456789", "New", "Hot", "Open"]) expect(card.getByText(text)).toBeInTheDocument();
|
||||
expect(card.getByText(/Next follow-up.*15\/06\/2025/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offers each filter's All choice once", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<EventLeadsDetailPage />);
|
||||
await user.click(screen.getByRole("combobox", { name: /salesperson filter/i }));
|
||||
await screen.findByRole("option", { name: "Jane Sales" });
|
||||
expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["All", "Jane Sales"]);
|
||||
});
|
||||
|
||||
it("falls back to the module title when the event is not in the list", async () => {
|
||||
mocks.listEventLeadEvents.mockResolvedValue([]);
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.getByRole("heading", { level: 1, name: "Event leads" })).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows the Add lead link to /event-leads/{eventUuid}/new", async () => {
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.getByRole("link", { name: /add lead/i })).toHaveAttribute("href", "/event-leads/evt-1/new"));
|
||||
});
|
||||
|
||||
it("renders the header with the event name", async () => {
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.getByRole("heading", { level: 1, name: "Test Event" })).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows the empty state when there are no leads", async () => {
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.queryByText("John Doe")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows the error state and lets the user retry on a load failure", async () => {
|
||||
mocks.listEventLeads.mockRejectedValueOnce(new Error("network down"));
|
||||
mocks.listEventLeads.mockResolvedValueOnce({ items: [], total: 0 });
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
|
||||
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
|
||||
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it("hides the table below md and shows one pager per layout", async () => {
|
||||
mocks.listEventLeads.mockResolvedValue({ items: [], total: 45 });
|
||||
const { container } = render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalled());
|
||||
const table = screen.getByRole("table").closest("div.hidden");
|
||||
expect(table).not.toBeNull();
|
||||
expect(table!.className).toContain("md:block");
|
||||
// DataTable brings its own pager; the phone pager (44px targets) must sit inside the md:hidden card list.
|
||||
expect(container.querySelectorAll('[data-slot="table-pager"]')).toHaveLength(1);
|
||||
const next = screen.getAllByRole("button", { name: /next/i }).find((b) => !b.closest('[data-slot="table-pager"]'));
|
||||
expect(next?.closest(".md\\:hidden")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("labels temperature and status options through i18n keys", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<EventLeadsDetailPage />);
|
||||
await user.click(screen.getByRole("combobox", { name: /temperature filter/i }));
|
||||
expect(await screen.findByRole("option", { name: "Hot" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,317 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { FilterField, FilterPanel, FilterSelect } from "@/app/components/ui/filter-panel";
|
||||
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 { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
||||
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { listEventLeads, listEventSalespeople, listEventLeadInterests, listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
|
||||
import type { EventLeadRow, InterestOption, SalespersonOption } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
|
||||
const DEFAULTS = { salespersonId: "", temperature: "", status: "", interestId: "", leadType: "" };
|
||||
const TEMPERATURE_OPTIONS = [{ value: "HOT", label: "LeadHot" }, { value: "WARM", label: "LeadWarm" }, { value: "COLD", label: "LeadCold" }];
|
||||
const STATUS_OPTIONS = [{ value: "OPEN", label: "LeadOpen" }, { value: "CONTACTED", label: "LeadContacted" }, { value: "QUALIFIED", label: "LeadQualified" }, { value: "WON", label: "LeadWon" }, { value: "LOST", label: "LeadLost" }];
|
||||
const LEAD_TYPE_OPTIONS = [{ value: "NEW", label: "LeadNew" }, { value: "EXISTING", label: "LeadExisting" }];
|
||||
const TEMPERATURE_BADGE = { HOT: "negative", WARM: "warning", COLD: "neutral" } as const;
|
||||
const STATUS_BADGE = { OPEN: "neutral", CONTACTED: "neutral", QUALIFIED: "contrast", WON: "positive", LOST: "negative" } as const;
|
||||
|
||||
function EventLeadsDetailPageContent() {
|
||||
const t = useT();
|
||||
const { eventUuid } = useParams<{ eventUuid: string }>();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const [data, setData] = useState<{ items: EventLeadRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [salespeople, setSalespeople] = useState<SalespersonOption[]>([]);
|
||||
const [interests, setInterests] = useState<InterestOption[]>([]);
|
||||
// undefined while loading; null when the event is unknown or the lookup failed.
|
||||
const [eventName, setEventName] = useState<string | null | undefined>(undefined);
|
||||
|
||||
// Load event name from the events list
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
listEventLeadEvents()
|
||||
.then((events) => {
|
||||
if (!cancelled) {
|
||||
const found = events.find((e) => e.uuid === eventUuid);
|
||||
setEventName(found ? found.name : null);
|
||||
}
|
||||
})
|
||||
.catch(() => { if (!cancelled) setEventName(null); });
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid]);
|
||||
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
// Load lookup options
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
Promise.allSettled([
|
||||
listEventSalespeople(eventUuid),
|
||||
listEventLeadInterests(),
|
||||
]).then(([salesRes, interestRes]) => {
|
||||
if (!cancelled) {
|
||||
if (salesRes.status === "fulfilled") setSalespeople(salesRes.value);
|
||||
if (interestRes.status === "fulfilled") setInterests(interestRes.value);
|
||||
}
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid]);
|
||||
|
||||
// Fetch leads
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the eventUuid/page/reloadKey-triggered fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listEventLeads(eventUuid, { page, pageSize, ...filters })
|
||||
.then((result) => {
|
||||
if (!cancelled) setData(result);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : "LeadListLoadFailed");
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, filters, page, pageSize, reloadKey]);
|
||||
|
||||
const salespersonOptions = useMemo(
|
||||
() => salespeople.map((o) => ({ value: String(o.id), label: o.name })),
|
||||
[salespeople],
|
||||
);
|
||||
|
||||
const interestOptions = useMemo(
|
||||
() => interests.map((o) => ({ value: String(o.id), label: o.name })),
|
||||
[interests],
|
||||
);
|
||||
|
||||
const temperatureOptions = useMemo(
|
||||
() => TEMPERATURE_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
[t],
|
||||
);
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => STATUS_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
[t],
|
||||
);
|
||||
|
||||
const leadTypeOptions = useMemo(
|
||||
() => LEAD_TYPE_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
[t],
|
||||
);
|
||||
|
||||
const columns = useMemo<ColumnDef<EventLeadRow, unknown>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("LeadName"),
|
||||
cell: ({ row }) => (
|
||||
<Link
|
||||
href={`/event-leads/${row.original.eventUuid}/${row.original.eventLeadUuid}`}
|
||||
className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none min-h-11 flex items-center"
|
||||
>
|
||||
{row.original.name}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "mobile",
|
||||
header: t("LeadMobile"),
|
||||
cell: ({ row }) => <span>{row.original.mobile || "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "email",
|
||||
header: t("Email"),
|
||||
cell: ({ row }) => <span>{row.original.email || "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "leadType",
|
||||
header: t("LeadType"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.leadType === "NEW" ? "default" : "secondary"}>
|
||||
{t(row.original.leadType === "NEW" ? "LeadNew" : "LeadExisting")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "salesperson",
|
||||
header: t("LeadSalesperson"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => <span>{row.original.salesperson?.name || "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "temperature",
|
||||
header: t("LeadTemperature"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => {
|
||||
const temp = row.original.temperature;
|
||||
if (!temp) return <span>—</span>;
|
||||
return <Badge variant={TEMPERATURE_BADGE[temp]}>{t(TEMPERATURE_OPTIONS.find((o) => o.value === temp)!.label)}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: t("Status"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.status;
|
||||
return <Badge variant={STATUS_BADGE[s]}>{t(STATUS_OPTIONS.find((o) => o.value === s)!.label)}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "interests",
|
||||
header: t("LeadInterests"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => <span>{row.original.interests.map(i => i.name).join(", ") || "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "nextFollowUpDate",
|
||||
header: t("LeadNextFollowUp"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => <span>{row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}</span>,
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={eventName === undefined ? "…" : (eventName ?? t("BO_EVENT_LEADS"))}
|
||||
actions={
|
||||
<Button asChild>
|
||||
<Link href={`/event-leads/${eventUuid}/new`}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("LeadAddLead")}
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
<FilterPanel activeCount={activeCount} onClear={clear}>
|
||||
<FilterField label={t("LeadSalespersonFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadSalespersonFilter")} allLabel={t("All")} options={salespersonOptions} value={filters.salespersonId} onChange={salespersonId => set({ salespersonId })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LeadTemperatureFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadTemperatureFilter")} allLabel={t("All")} options={temperatureOptions} value={filters.temperature} onChange={temperature => set({ temperature })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LeadStatusFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadStatusFilter")} allLabel={t("All")} options={statusOptions} value={filters.status} onChange={status => set({ status })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LeadInterestFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadInterestFilter")} allLabel={t("All")} options={interestOptions} value={filters.interestId} onChange={interestId => set({ interestId })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LeadLeadTypeFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadLeadTypeFilter")} allLabel={t("All")} options={leadTypeOptions} value={filters.leadType} onChange={leadType => set({ leadType })} />
|
||||
</FilterField>
|
||||
</FilterPanel>
|
||||
|
||||
{/* Desktop table (md+) */}
|
||||
<div className="hidden md:block">
|
||||
<DataTable
|
||||
label={t("BO_EVENT_LEADS")}
|
||||
columns={columns}
|
||||
data={data.items}
|
||||
total={data.total}
|
||||
page={page}
|
||||
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
||||
tableRef={tableRef}
|
||||
onPageChange={setPage}
|
||||
isLoading={loading}
|
||||
rowKey={(e) => String(e.eventLeadUuid)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Mobile cards (below md) */}
|
||||
<div className="md:hidden space-y-3" aria-busy={loading}>
|
||||
{data.items.map((lead) => (
|
||||
<Link
|
||||
key={lead.eventLeadUuid}
|
||||
href={`/event-leads/${lead.eventUuid}/${lead.eventLeadUuid}`}
|
||||
data-testid="lead-card"
|
||||
className={`flex flex-col gap-1 rounded-lg border p-3 transition-colors hover:bg-accent min-h-11${loading ? " opacity-60" : ""}`}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">{lead.name}</span>
|
||||
<Badge variant={lead.leadType === "NEW" ? "default" : "secondary"}>{t(lead.leadType === "NEW" ? "LeadNew" : "LeadExisting")}</Badge>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{lead.mobile || "—"}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{lead.temperature && <Badge variant={TEMPERATURE_BADGE[lead.temperature]} className="shrink-0">{t(TEMPERATURE_OPTIONS.find((o) => o.value === lead.temperature)!.label)}</Badge>}
|
||||
<Badge variant={STATUS_BADGE[lead.status]} className="shrink-0">{t(STATUS_OPTIONS.find((o) => o.value === lead.status)!.label)}</Badge>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t("LeadNextFollowUp")}: {lead.nextFollowUpDate ? formatDmy(lead.nextFollowUpDate) : "—"}
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
{data.items.length === 0 && !loading && (
|
||||
<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />
|
||||
)}
|
||||
{/* Phone pager: 44px targets; DataTable has its own above md */}
|
||||
{data.total > (pageSize ?? MIN_PAGE_SIZE) && (
|
||||
<div className="flex items-center justify-between mt-4">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t("PagerRange", {
|
||||
first: data.total === 0 ? 0 : (page - 1) * (pageSize ?? MIN_PAGE_SIZE) + 1,
|
||||
last: Math.min(page * (pageSize ?? MIN_PAGE_SIZE), data.total),
|
||||
total: data.total,
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage(page - 1)}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t("PagerPrevious")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page * (pageSize ?? MIN_PAGE_SIZE) >= data.total}
|
||||
onClick={() => setPage(page + 1)}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t("PagerNext")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventLeadsDetailPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<EventLeadsDetailPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listEventLeadEvents: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
listEventLeadEvents: mocks.listEventLeadEvents,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventLeadsPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads");
|
||||
mocks.listEventLeadEvents.mockReset();
|
||||
mocks.useAdminAuth.mockReset();
|
||||
mocks.useAdminAuth.mockReturnValue({
|
||||
loading: false,
|
||||
hasModule: () => true,
|
||||
});
|
||||
});
|
||||
|
||||
describe("EventLeadsPage (picker)", () => {
|
||||
it("renders NotAuthorized when the EventLeads module is absent from aclMenu", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EventLeadsPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists events as tappable card links", async () => {
|
||||
mocks.listEventLeadEvents.mockResolvedValue([
|
||||
{ uuid: "evt-1", name: "Event Alpha", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" },
|
||||
{ uuid: "evt-2", name: "Event Beta", location: "Hall B", startDate: "2025-07-01", endDate: "2025-07-02" },
|
||||
]);
|
||||
render(<EventLeadsPage />);
|
||||
|
||||
expect(await screen.findByText("Event Alpha")).toBeInTheDocument();
|
||||
expect(screen.getByText("Event Beta")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: /Event Alpha/ })).toHaveAttribute("href", "/event-leads/evt-1");
|
||||
expect(screen.getByRole("link", { name: /Event Beta/ })).toHaveAttribute("href", "/event-leads/evt-2");
|
||||
});
|
||||
|
||||
it("shows location and dates formatted with formatDmy", async () => {
|
||||
mocks.listEventLeadEvents.mockResolvedValue([
|
||||
{ uuid: "evt-1", name: "Event Alpha", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" },
|
||||
]);
|
||||
render(<EventLeadsPage />);
|
||||
|
||||
expect(await screen.findByText("Hall A")).toBeInTheDocument();
|
||||
expect(screen.getByText(/01\/06\/2025/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/02\/06\/2025/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("puts events running today first", async () => {
|
||||
// Use a date that's "today" relative to the test run
|
||||
const today = new Date();
|
||||
const iso = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
|
||||
mocks.listEventLeadEvents.mockResolvedValue([
|
||||
{ uuid: "evt-far", name: "Far Event", location: "Hall A", startDate: "2099-01-01", endDate: "2099-01-02" },
|
||||
{ uuid: "evt-today", name: "Today Event", location: "Hall B", startDate: iso, endDate: iso },
|
||||
]);
|
||||
render(<EventLeadsPage />);
|
||||
|
||||
await screen.findByText("Today Event");
|
||||
const links = Array.from(screen.getAllByRole("link").filter((l) => l.getAttribute("href")?.startsWith("/event-leads/")));
|
||||
expect(links[0]).toHaveAttribute("href", "/event-leads/evt-today");
|
||||
expect(links[1]).toHaveAttribute("href", "/event-leads/evt-far");
|
||||
});
|
||||
|
||||
it("shows an error state on load failure", async () => {
|
||||
mocks.listEventLeadEvents.mockRejectedValueOnce(new Error("network down"));
|
||||
render(<EventLeadsPage />);
|
||||
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("counts an event that started earlier and ends later as running today", async () => {
|
||||
const d = (offset: number) => {
|
||||
const x = new Date();
|
||||
x.setDate(x.getDate() + offset);
|
||||
return `${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, "0")}-${String(x.getDate()).padStart(2, "0")}`;
|
||||
};
|
||||
mocks.listEventLeadEvents.mockResolvedValue([
|
||||
{ uuid: "evt-later", name: "Later", location: null, startDate: d(5), endDate: d(6) },
|
||||
{ uuid: "evt-running", name: "Running", location: null, startDate: d(-1), endDate: d(1) },
|
||||
]);
|
||||
render(<EventLeadsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Running")).toBeInTheDocument());
|
||||
const links = screen.getAllByRole("link").filter((l) => l.getAttribute("href")?.startsWith("/event-leads/"));
|
||||
expect(links[0]).toHaveAttribute("href", "/event-leads/evt-running");
|
||||
});
|
||||
|
||||
it("retries the load after a failure", async () => {
|
||||
mocks.listEventLeadEvents.mockRejectedValueOnce(new Error("network down"))
|
||||
.mockResolvedValueOnce([{ uuid: "evt-1", name: "Back", location: null, startDate: null, endDate: null }]);
|
||||
render(<EventLeadsPage />);
|
||||
const retry = await screen.findByRole("button", { name: /retry/i });
|
||||
await act(async () => retry.click());
|
||||
expect(await screen.findByText("Back")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Calendar, MapPin } from "lucide-react";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
|
||||
import type { EventLeadEvent } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
|
||||
const isoToday = () => {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
function EventLeadsPageContent() {
|
||||
const t = useT();
|
||||
const [events, setEvents] = useState<EventLeadEvent[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the triggered fetch below, which is the actual synchronization.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listEventLeadEvents()
|
||||
.then((data) => {
|
||||
if (!cancelled) setEvents(data);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : "LeadLoadFailed");
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [reloadKey]);
|
||||
|
||||
const today = isoToday();
|
||||
const sorted = events
|
||||
.slice()
|
||||
.sort((a, b) => {
|
||||
// ISO dates compare as strings; an event runs today when start <= today <= end.
|
||||
const running = (e: EventLeadEvent) => (e.startDate ?? "9") <= today && today <= (e.endDate ?? e.startDate ?? "");
|
||||
return Number(running(b)) - Number(running(a));
|
||||
});
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EVENT_LEADS")} />
|
||||
<ErrorState message={t(error)} onRetry={() => setReloadKey((k) => k + 1)} className="mb-4" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EVENT_LEADS")} />
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<div key={i} className="h-20 animate-pulse rounded-lg bg-muted" />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EVENT_LEADS")} />
|
||||
{sorted.length === 0 ? (
|
||||
<EmptyState title={t("LeadNoEvents")} />
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{sorted.map((evt) => (
|
||||
<Link
|
||||
key={evt.uuid}
|
||||
href={`/event-leads/${evt.uuid}`}
|
||||
className="flex flex-col gap-2 rounded-lg border p-4 transition-colors hover:bg-accent min-h-[8.5rem]"
|
||||
>
|
||||
<h2 className="font-semibold text-lg">{evt.name}</h2>
|
||||
{evt.location && (
|
||||
<div className="flex items-center gap-1 text-sm text-muted-foreground">
|
||||
<MapPin className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
<span>{evt.location}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-1 text-sm text-muted-foreground">
|
||||
<Calendar className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
<span>{evt.startDate ? formatDmy(evt.startDate) : ""} – {evt.endDate ? formatDmy(evt.endDate) : ""}</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventLeadsPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<EventLeadsPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -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<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
apiPut: mocks.apiPut,
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminInterests", async (importOriginal) => {
|
||||
const mod = await importOriginal<typeof import("@/app/lib/services/adminInterests")>();
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<FormState>(initial);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const trimmed = form.name.trim();
|
||||
|
||||
const errors: Record<string, string> = {};
|
||||
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 (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{form.id ? t("IntEditInterest") : t("IntAddInterest")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{formError && (
|
||||
<div className="text-sm text-destructive" role="alert">
|
||||
{t(formError)}
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="interest-name">{t("IntInterestName")}</Label>
|
||||
<Input
|
||||
id="interest-name"
|
||||
required
|
||||
maxLength={100}
|
||||
value={form.name}
|
||||
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.name}
|
||||
aria-describedby={fieldErrors.name ? "interest-name-error" : undefined}
|
||||
/>
|
||||
{fieldErrors.name && (
|
||||
<p id="interest-name-error" role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="interest-order">{t("IntInterestOrder")}</Label>
|
||||
<Input
|
||||
id="interest-order"
|
||||
type="number"
|
||||
min={0}
|
||||
value={form.sortOrder ?? 0}
|
||||
onChange={(e) => setForm((f) => ({ ...f, sortOrder: parseInt(e.target.value, 10) || 0 }))}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function InterestsPageContent() {
|
||||
const t = useT();
|
||||
const [interests, setInterests] = useState<AdminInterestEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [dialog, setDialog] = useState<FormState | null>(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<ColumnDef<AdminInterestEntity, unknown>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("IntColInterest"),
|
||||
cell: ({ row }) => <div>{row.original.name}</div>,
|
||||
},
|
||||
{
|
||||
accessorKey: "sortOrder",
|
||||
header: t("IntColOrder"),
|
||||
cell: ({ row }) => <div>{row.original.sortOrder ?? 0}</div>,
|
||||
},
|
||||
{
|
||||
accessorKey: "active",
|
||||
header: t("IntColStatus"),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.active ? "positive" : "neutral"}>
|
||||
{row.original.active ? t("IntActive") : t("IntInactive")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: t("CatActions"),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
setDialog({
|
||||
id: row.original.id,
|
||||
name: row.original.name ?? "",
|
||||
sortOrder: row.original.sortOrder,
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("Edit")}
|
||||
</Button>
|
||||
{row.original.active ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await saveAdminInterest({ id: row.original.id, active: false });
|
||||
refetch();
|
||||
} catch {
|
||||
setError("IntDeactivateFailed");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t("IntDeactivate")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await saveAdminInterest({ id: row.original.id, active: true });
|
||||
refetch();
|
||||
} catch {
|
||||
setError("IntActivateFailed");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t("IntActivate")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t, refetch],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("BO_INTERESTS")}
|
||||
actions={
|
||||
<Button onClick={() => setDialog(EMPTY_FORM)}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("IntAddInterest")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
<DataTable
|
||||
label={t("BO_INTERESTS")}
|
||||
columns={columns}
|
||||
data={interests}
|
||||
total={interests.length}
|
||||
page={1}
|
||||
pageSize={interests.length || 1}
|
||||
onPageChange={() => {}}
|
||||
isLoading={loading}
|
||||
rowKey={(r) => String(r.id ?? r.name)}
|
||||
empty={<EmptyState title={t("IntNoInterests")} />}
|
||||
/>
|
||||
|
||||
{dialog && (
|
||||
<InterestFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function InterestsPage() {
|
||||
return (
|
||||
<RequireModule pathname="/interests">
|
||||
<InterestsPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -204,4 +204,80 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
EvtTeamNotSaved: "The event was saved but its team was not. Check the team and save again.",
|
||||
EvtEventNameFilter: "Event name",
|
||||
EvtStatusFilter: "Status filter",
|
||||
// Interest (product/service) messages
|
||||
BO_INTERESTS: "Interests",
|
||||
IntAddInterest: "Add interest",
|
||||
IntEditInterest: "Edit interest",
|
||||
IntInterestName: "Name",
|
||||
IntInterestOrder: "Order",
|
||||
IntColInterest: "Name",
|
||||
IntColOrder: "Order",
|
||||
IntColStatus: "Status",
|
||||
IntNoInterests: "No interests found",
|
||||
IntLoadFailed: "Failed to load interests",
|
||||
IntNameRequired: "Name is required.",
|
||||
IntNameTooLong: "Name must be 100 characters or fewer.",
|
||||
IntSaveFailed: "Failed to save interest.",
|
||||
IntDuplicateName: "An interest with this name already exists.",
|
||||
IntActive: "Active",
|
||||
IntInactive: "Inactive",
|
||||
IntActivate: "Activate",
|
||||
IntDeactivate: "Deactivate",
|
||||
IntActivateFailed: "Failed to activate interest.",
|
||||
IntDeactivateFailed: "Failed to deactivate interest.",
|
||||
// Event leads messages
|
||||
BO_EVENT_LEADS: "Event leads",
|
||||
LeadName: "Name",
|
||||
LeadMobile: "Mobile",
|
||||
LeadType: "Lead type",
|
||||
LeadSalesperson: "Salesperson",
|
||||
LeadTemperature: "Temperature",
|
||||
LeadInterests: "Interests",
|
||||
LeadNextFollowUp: "Next follow-up",
|
||||
LeadAddLead: "Add lead",
|
||||
LeadNoEvents: "No events found",
|
||||
LeadNoLeads: "No leads found",
|
||||
LeadNoMatch: "No leads match your filters",
|
||||
LeadLoadFailed: "Failed to load events",
|
||||
LeadListLoadFailed: "Failed to load leads",
|
||||
LeadSalespersonFilter: "Salesperson filter",
|
||||
LeadTemperatureFilter: "Temperature filter",
|
||||
LeadStatusFilter: "Status filter",
|
||||
LeadInterestFilter: "Interest filter",
|
||||
LeadLeadTypeFilter: "Lead type filter",
|
||||
LeadHot: "Hot",
|
||||
LeadWarm: "Warm",
|
||||
LeadCold: "Cold",
|
||||
LeadOpen: "Open",
|
||||
LeadContacted: "Contacted",
|
||||
LeadQualified: "Qualified",
|
||||
LeadWon: "Won",
|
||||
LeadLost: "Lost",
|
||||
LeadNew: "New",
|
||||
LeadExisting: "Existing",
|
||||
LeadCompany: "Company",
|
||||
LeadJobTitle: "Job title",
|
||||
LeadStatus: "Status",
|
||||
LeadNotes: "Notes",
|
||||
LeadNext: "Next",
|
||||
LeadNone: "None",
|
||||
LeadAlreadyCaptured: "Already captured",
|
||||
LeadThisPerson: "This person",
|
||||
LeadDifferentPerson: "Different person",
|
||||
LeadOptionsLoadFailed: "Failed to load salespeople or interests",
|
||||
LeadEventDisabled: "This event is closed for new leads.",
|
||||
LeadSaveFailed: "Could not save the lead. Please try again.",
|
||||
LeadMatchFailed: "Could not look up this contact. Please try again.",
|
||||
LeadErrRequiredContact: "Mobile or email is required.",
|
||||
LeadErrRequired: "This field is required.",
|
||||
LeadErrTooLong: "Too long.",
|
||||
LeadErrInvalidMobile: "Enter a valid mobile number.",
|
||||
LeadErrInvalidEmail: "Enter a valid email address.",
|
||||
LeadErrInvalidDate: "Enter a valid date.",
|
||||
LeadErrNotOnTeam: "This person is not on the event team.",
|
||||
LeadErrInactiveInterest: "An interest is no longer active.",
|
||||
LeadErrInvalidValue: "Invalid value.",
|
||||
LeadCaptured: "Captured",
|
||||
LeadNotFound: "Lead not found",
|
||||
LeadGetFailed: "Failed to load the lead",
|
||||
};
|
||||
@@ -3,6 +3,8 @@ import { ROUTE_MODULES, requiredModuleFor, requiredModulesFor } from "./routeMod
|
||||
|
||||
describe("routeModules", () => {
|
||||
it("gates /users and /roles by the seeded module name", () => {
|
||||
expect(requiredModuleFor("/interests")).toBe("BO_INTERESTS");
|
||||
expect(requiredModuleFor("/event-leads")).toBe("BO_EVENT_LEADS");
|
||||
expect(requiredModuleFor("/users")).toBe("BO_USERS");
|
||||
expect(requiredModuleFor("/roles")).toBe("BO_ROLES");
|
||||
expect(requiredModuleFor("/events")).toBe("BO_EVENTS");
|
||||
@@ -12,6 +14,6 @@ describe("routeModules", () => {
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/events", "/roles", "/users"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/event-leads", "/events", "/interests", "/roles", "/users"]);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,8 @@ export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/users": "BO_USERS",
|
||||
"/roles": "BO_ROLES",
|
||||
"/events": "BO_EVENTS",
|
||||
"/interests": "BO_INTERESTS",
|
||||
"/event-leads": "BO_EVENT_LEADS",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import {
|
||||
captureEventLead,
|
||||
getEventLead,
|
||||
listEventLeadEvents,
|
||||
listEventLeadInterests,
|
||||
listEventLeads,
|
||||
listEventSalespeople,
|
||||
matchLead,
|
||||
updateEventLead,
|
||||
} from "./adminEventLeads";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset();
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiPut.mockReset();
|
||||
});
|
||||
|
||||
describe("adminEventLeads", () => {
|
||||
it("loads events, interest options and the event's salespeople", async () => {
|
||||
mocks.apiGet.mockResolvedValue([]);
|
||||
await listEventLeadEvents();
|
||||
await listEventLeadInterests();
|
||||
await listEventSalespeople("9");
|
||||
expect(mocks.apiGet.mock.calls.map((c) => c[0])).toEqual([
|
||||
"/api/event-leads/events",
|
||||
"/api/event-leads/interest-options",
|
||||
"/api/event-leads/9/salesperson-options",
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists with only the set filters and a 0-based page", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [{ eventLeadUuid: "1" }], totalElements: 41 });
|
||||
const out = await listEventLeads("9", { page: 3, pageSize: 20, status: "OPEN", temperature: "", interestId: "4" });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/event-leads/9/leads?status=OPEN&interestId=4&page=2&size=20");
|
||||
expect(out).toEqual({ items: [{ eventLeadUuid: "1" }], total: 41 });
|
||||
});
|
||||
|
||||
it("treats a malformed page as empty", async () => {
|
||||
mocks.apiGet.mockResolvedValue(null);
|
||||
expect(await listEventLeads("9", { page: 1, pageSize: 20 })).toEqual({ items: [], total: 0 });
|
||||
});
|
||||
|
||||
it("matches, captures, gets and updates under the event", async () => {
|
||||
await matchLead("9", { mobile: "0123", email: null });
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/event-leads/9/match", { mobile: "0123", email: null });
|
||||
await captureEventLead("9", { name: "A", mobile: "0123" });
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/event-leads/9", { name: "A", mobile: "0123" });
|
||||
await getEventLead("9", "7");
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/event-leads/9/leads/7");
|
||||
await updateEventLead("9", "7", { status: "WON" });
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/event-leads/9/leads/7", { status: "WON" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
import type {
|
||||
EventLeadCapturePayload,
|
||||
EventLeadEvent,
|
||||
EventLeadRow,
|
||||
EventLeadUpdatePayload,
|
||||
InterestOption,
|
||||
LeadMatchResult,
|
||||
SalespersonOption,
|
||||
} from "@/app/lib/types";
|
||||
|
||||
const BASE = "/api/event-leads";
|
||||
const FILTERS = ["salespersonId", "temperature", "status", "interestId", "leadType"] as const;
|
||||
|
||||
export type EventLeadFilters = Partial<Record<(typeof FILTERS)[number], string>>;
|
||||
|
||||
export interface EventLeadListParams extends EventLeadFilters {
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export const listEventLeadEvents = () => apiGet<EventLeadEvent[]>(`${BASE}/events`);
|
||||
export const listEventLeadInterests = () => apiGet<InterestOption[]>(`${BASE}/interest-options`);
|
||||
export const listEventSalespeople = (eventUuid: string) =>
|
||||
apiGet<SalespersonOption[]>(`${BASE}/${eventUuid}/salesperson-options`);
|
||||
|
||||
export async function listEventLeads(eventUuid: string, params: EventLeadListParams): Promise<{ items: EventLeadRow[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of FILTERS) if (params[key]) qs.set(key, params[key]);
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: EventLeadRow[]; totalElements?: number } | null>(`${BASE}/${eventUuid}/leads?${qs}`);
|
||||
const items = Array.isArray(raw?.content) ? raw.content : [];
|
||||
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
|
||||
}
|
||||
|
||||
export const matchLead = (eventUuid: string, contact: { mobile: string | null; email: string | null }) =>
|
||||
apiPost<LeadMatchResult>(`${BASE}/${eventUuid}/match`, contact);
|
||||
export const captureEventLead = (eventUuid: string, payload: EventLeadCapturePayload) =>
|
||||
apiPost<EventLeadRow>(`${BASE}/${eventUuid}`, payload);
|
||||
export const getEventLead = (eventUuid: string, eventLeadUuid: string) =>
|
||||
apiGet<EventLeadRow>(`${BASE}/${eventUuid}/leads/${eventLeadUuid}`);
|
||||
export const updateEventLead = (eventUuid: string, eventLeadUuid: string, payload: EventLeadUpdatePayload) =>
|
||||
apiPut<EventLeadRow>(`${BASE}/${eventUuid}/leads/${eventLeadUuid}`, payload);
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import { listAdminInterests, saveAdminInterest } from "./adminInterests";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset();
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiPut.mockReset();
|
||||
});
|
||||
|
||||
describe("listAdminInterests", () => {
|
||||
it("GETs /api/interests", async () => {
|
||||
mocks.apiGet.mockResolvedValue([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]);
|
||||
const result = await listAdminInterests();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/interests");
|
||||
expect(result).toEqual([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveAdminInterest", () => {
|
||||
it("POSTs when id is absent", async () => {
|
||||
mocks.apiPost.mockResolvedValue({ id: 1, name: "New Interest" });
|
||||
await saveAdminInterest({ name: "New Interest", active: true, sortOrder: 5 });
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/interests", { name: "New Interest", active: true, sortOrder: 5 });
|
||||
});
|
||||
|
||||
it("PUTs to /api/interests/{id} when id is present", async () => {
|
||||
mocks.apiPut.mockResolvedValue({ id: 200, name: "Edited Interest", active: false, sortOrder: 10 });
|
||||
await saveAdminInterest({ id: 200, name: "Edited Interest", active: false, sortOrder: 10 });
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/200", { id: 200, name: "Edited Interest", active: false, sortOrder: 10 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
import type { AdminInterestEntity } from "@/app/lib/types";
|
||||
|
||||
export async function listAdminInterests(): Promise<AdminInterestEntity[]> {
|
||||
return apiGet<AdminInterestEntity[]>("/api/interests");
|
||||
}
|
||||
|
||||
export async function saveAdminInterest(payload: AdminInterestEntity): Promise<AdminInterestEntity> {
|
||||
return payload.id
|
||||
? apiPut<AdminInterestEntity>(`/api/interests/${payload.id}`, payload)
|
||||
: apiPost<AdminInterestEntity>("/api/interests", payload);
|
||||
}
|
||||
@@ -150,3 +150,86 @@ export interface SalespersonOption {
|
||||
name: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
/** An interest (product/service) row used to tag leads.
|
||||
* Stored in services-counter (`interest`), served by mobile-api `/api/admin/interests`, sorted by sortOrder. */
|
||||
export interface AdminInterestEntity {
|
||||
id?: number;
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
/** Event-floor lead capture (`/api/admin/event-leads`). All uuids are strings. */
|
||||
export type LeadTemperature = "HOT" | "WARM" | "COLD";
|
||||
export type LeadStatus = "OPEN" | "CONTACTED" | "QUALIFIED" | "WON" | "LOST";
|
||||
export type LeadType = "NEW" | "EXISTING";
|
||||
|
||||
export interface EventLeadEvent {
|
||||
uuid: string;
|
||||
name: string;
|
||||
location: string | null;
|
||||
startDate: string | null;
|
||||
endDate: string | null;
|
||||
}
|
||||
|
||||
export interface InterestOption {
|
||||
id: number;
|
||||
name: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface LeadCandidate {
|
||||
leadUuid: string;
|
||||
name: string;
|
||||
mobile: string | null;
|
||||
email: string | null;
|
||||
companyName: string | null;
|
||||
jobTitle: string | null;
|
||||
/** Set when this lead is already captured at the event. */
|
||||
eventLeadUuid: string | null;
|
||||
}
|
||||
|
||||
export interface LeadMatchResult {
|
||||
mobile: string | null;
|
||||
email: string | null;
|
||||
candidates: LeadCandidate[];
|
||||
}
|
||||
|
||||
export interface EventLeadRow {
|
||||
eventLeadUuid: string;
|
||||
eventUuid: string;
|
||||
leadUuid: string;
|
||||
name: string;
|
||||
mobile: string | null;
|
||||
email: string | null;
|
||||
companyName: string | null;
|
||||
jobTitle: string | null;
|
||||
leadType: LeadType;
|
||||
salesperson: { id: number; name: string } | null;
|
||||
temperature: LeadTemperature | null;
|
||||
status: LeadStatus;
|
||||
interests: InterestOption[];
|
||||
nextFollowUpDate: string | null;
|
||||
notes: string | null;
|
||||
capturedAt: string;
|
||||
}
|
||||
|
||||
export interface EventLeadUpdatePayload {
|
||||
salespersonId?: number | null;
|
||||
temperature?: LeadTemperature | null;
|
||||
status?: LeadStatus;
|
||||
interestIds?: number[];
|
||||
nextFollowUpDate?: string | null;
|
||||
notes?: string | null;
|
||||
}
|
||||
|
||||
export interface EventLeadCapturePayload extends EventLeadUpdatePayload {
|
||||
/** Set to attach an existing lead; omit for a new one. */
|
||||
leadUuid?: string;
|
||||
name?: string;
|
||||
mobile?: string | null;
|
||||
email?: string | null;
|
||||
companyName?: string | null;
|
||||
jobTitle?: string | null;
|
||||
}
|
||||
@@ -7,7 +7,8 @@ import { describe, expect, it } from "vitest";
|
||||
// no PAGE_SIZE of its own.
|
||||
|
||||
// Roles loads every role and has no real paging (its DataTable shows one page of everything).
|
||||
const EXEMPT = new Set(["roles/page.tsx"]);
|
||||
// Interests loads every interest and has no real paging (same pattern).
|
||||
const EXEMPT = new Set(["roles/page.tsx", "interests/page.tsx"]);
|
||||
|
||||
function sources(dir: string): string[] {
|
||||
return readdirSync(dir).flatMap((name) => {
|
||||
|
||||
@@ -61,6 +61,12 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<!-- Lead capture: mobile numbers normalised to E.164 (add-event-lead-capture). -->
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>libphonenumber</artifactId>
|
||||
<version>8.13.55</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
||||
@@ -37,6 +37,14 @@ 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";
|
||||
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}";
|
||||
|
||||
@@ -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<List<Map<String, Object>>> events() {
|
||||
return ResponseEntity.ok(adminEventLeadService.events());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/interest-options")
|
||||
public ResponseEntity<List<Map<String, Object>>> interestOptions() {
|
||||
return ResponseEntity.ok(adminEventLeadService.interestOptions());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/salesperson-options")
|
||||
public ResponseEntity<List<Map<String, Object>>> salespersonOptions(@PathVariable String eventUuid) {
|
||||
return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PostMapping("/{eventUuid}/match")
|
||||
public ResponseEntity<Map<String, Object>> match(@PathVariable String eventUuid, @RequestBody AdminLeadMatchRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.match(eventUuid, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PostMapping("/{eventUuid}")
|
||||
public ResponseEntity<Map<String, Object>> capture(@PathVariable String eventUuid, @RequestBody AdminEventLeadCaptureRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.capture(eventUuid, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/leads")
|
||||
public ResponseEntity<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> update(@PathVariable String eventUuid, @PathVariable String eventLeadUuid,
|
||||
@RequestBody AdminEventLeadUpdateRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.update(eventUuid, eventLeadUuid, request));
|
||||
}
|
||||
}
|
||||
@@ -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<Map<String, Object>>> list() {
|
||||
return ResponseEntity.ok(adminInterestService.list());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@PostMapping("/interests")
|
||||
public ResponseEntity<Map<String, Object>> create(@RequestBody AdminInterestRequest request) {
|
||||
return ResponseEntity.ok(adminInterestService.create(request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@PutMapping("/interests/{id}")
|
||||
public ResponseEntity<Map<String, Object>> update(@PathVariable long id, @RequestBody AdminInterestRequest request) {
|
||||
return ResponseEntity.ok(adminInterestService.update(id, request));
|
||||
}
|
||||
}
|
||||
@@ -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<Long> interestIds, String nextFollowUpDate, String notes) {}
|
||||
@@ -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<Long> interestIds,
|
||||
String nextFollowUpDate, String notes) {}
|
||||
@@ -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) {}
|
||||
@@ -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) {}
|
||||
@@ -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<String> TEMPERATURES = Set.of("HOT", "WARM", "COLD");
|
||||
private static final Set<String> STATUSES = Set.of("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST");
|
||||
private static final Set<String> LEAD_TYPES = Set.of("NEW", "EXISTING");
|
||||
private static final int EVENT_PAGE = 100;
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private static final ParameterizedTypeReference<AdminEventService.EventPage> PAGE = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Event> EVENT = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> 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<Map<String, Object>> events() {
|
||||
Map<String, Object> 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<String, Object> 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<Map<String, Object>> interestOptions() {
|
||||
return interests(caller().getCompanyId()).values().stream().filter(i -> Boolean.TRUE.equals(i.get("active"))).toList();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> salespersonOptions(String eventUuid) {
|
||||
Event event = loadEvent(eventUuid);
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Long id : teamIds(event.getUuid())) {
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> capture(String eventUuid, AdminEventLeadCaptureRequest r) {
|
||||
User caller = caller();
|
||||
String name = trimmed(r.name());
|
||||
String mobile = mobile(r.mobile());
|
||||
String email = email(r.email());
|
||||
List<String> 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<Long, Map<String, Object>> known = interests(caller.getCompanyId());
|
||||
List<Long> interestIds = checkedInterests(known, r.interestIds(), List.of());
|
||||
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), MAP, body).getBody();
|
||||
List<Map<String, Object>> rows = p == null || p.get("content") == null ? List.of() : (List<Map<String, Object>>) p.get("content");
|
||||
Map<Long, Map<String, Object>> interests = rows.isEmpty() ? Map.of() : interests(caller.getCompanyId());
|
||||
Map<Long, Map<String, Object>> users = new HashMap<>();
|
||||
Map<String, Object> 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<String, Object> get(String eventUuid, String eventLeadUuid) {
|
||||
User caller = caller();
|
||||
return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId());
|
||||
}
|
||||
|
||||
public Map<String, Object> 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<String, Object> 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<Long, Map<String, Object>> known = interests(caller.getCompanyId());
|
||||
List<Long> interestIds = checkedInterests(known, r.interestIds(), longs(current.get("interestIds")));
|
||||
|
||||
Map<String, Object> 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<Long> checkedInterests(Map<Long, Map<String, Object>> known, List<Long> requested, List<Long> current) {
|
||||
List<Long> ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList()));
|
||||
for (Long id : ids) {
|
||||
Map<String, Object> 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<String, Object> stored(long companyId, String eventUuid, String eventLeadUuid) {
|
||||
Event event = loadEvent(eventUuid);
|
||||
long id = parseOr(eventLeadUuid, AdminEventLeadService::eventLeadNotFound);
|
||||
Map<String, Object> 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<String, Object> view(Map<String, Object> d, long companyId) {
|
||||
return view(d, interests(companyId), new HashMap<>());
|
||||
}
|
||||
|
||||
private Map<String, Object> view(Map<String, Object> d, Map<Long, Map<String, Object>> interests, Map<Long, Map<String, Object>> users) {
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> i = interests.get(id);
|
||||
return Map.<String, Object>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<Map<String, Object>> findMatches(long companyId, long eventUuid, String mobile, String email) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", companyId);
|
||||
body.put("eventUuid", eventUuid);
|
||||
body.put("mobileE164", mobile);
|
||||
body.put("email", email);
|
||||
List<Map<String, Object>> 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<Long, Map<String, Object>> interests(long companyId) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId).getBody();
|
||||
Map<Long, Map<String, Object>> out = new LinkedHashMap<>();
|
||||
if (rows != null) for (Map<String, Object> 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<Long> teamIds(long eventUuid) {
|
||||
List<Map<String, Object>> 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<String, Object> 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<String, Object> 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<String> 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<CodedResponseStatusException> notFound) {
|
||||
try {
|
||||
return Long.parseLong(s.trim());
|
||||
} catch (RuntimeException e) {
|
||||
throw notFound.get();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Long> 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<String> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<Map<String, Object>>> LIST = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
public List<Map<String, Object>> list() {
|
||||
return load(caller().getCompanyId()).stream().map(AdminInterestService::row).toList();
|
||||
}
|
||||
|
||||
public Map<String, Object> create(AdminInterestRequest r) {
|
||||
User caller = caller();
|
||||
Map<String, Object> 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<String, Object> update(long id, AdminInterestRequest r) {
|
||||
User caller = caller();
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> save(Map<String, Object> 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<Map<String, Object>> load(long companyId) {
|
||||
List<Map<String, Object>> 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<String, Object> row(Map<String, Object> m) {
|
||||
Map<String, Object> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<Method> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Method> 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));
|
||||
}
|
||||
}
|
||||
@@ -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<HttpReqRespUtils> 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<String, Object>) i.getArgument(2))));
|
||||
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(detailFrom((Map<String, Object>) 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<Map<String, Object>> 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<String, Object> 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<String, Object> interest(long id, String name, boolean active) {
|
||||
return Map.of("id", id, "companyId", COMPANY, "name", name, "active", active, "sortOrder", 0);
|
||||
}
|
||||
|
||||
private void stubInterests(Map<String, Object>... 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<String, Object> detailFrom(Map<String, Object> body) {
|
||||
Map<String, Object> 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<Long> interestIds) {
|
||||
Map<String, Object> 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<Long> interests, String followUp) {
|
||||
return new AdminEventLeadCaptureRequest(null, "Aisyah", "0123456789", null, null, null, salespersonId, temperature, status, interests, followUp, null);
|
||||
}
|
||||
|
||||
private Map<String, Object> sent(String api) {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) 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<String, Object>) 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<Map<String, Object>> 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<String, Object> body = sent(EVENTS);
|
||||
assertThat((Map<String, Object>) body.get("property")).containsEntry("enabled", "Y");
|
||||
Map<String, Object> pageable = (Map<String, Object>) body.get("pageableRest");
|
||||
assertThat(pageable).containsEntry("size", 100);
|
||||
assertThat((List<Map<String, Object>>) 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> candidate = ((List<Map<String, Object>>) 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<String, Object> out = service.capture(String.valueOf(EV), capture(null, " Aisyah ", "+60 12-345 6789", " Aisyah@Example.COM "));
|
||||
|
||||
Map<String, Object> 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<String, Object>) 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<String, Object> 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<String, Object>) 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<String, Object> 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<String, Object> 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<String, Object> first = ((List<Map<String, Object>>) 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<Map<String, Object>>) 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<String, Object> 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<Map<String, Object>>) out.get("interests")).containsExactly(Map.of("id", 4L, "name", "Kitchen appliances", "active", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWorksALead() {
|
||||
stubStored(EV, null, List.of());
|
||||
|
||||
Map<String, Object> 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");
|
||||
}
|
||||
}
|
||||
@@ -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<HttpReqRespUtils> 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<String, Object> row(long id, String name, boolean active, int sort) {
|
||||
Map<String, Object> 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<String, Object>... rows) {
|
||||
when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(5L))).thenReturn(ResponseEntity.ok(List.of(rows)));
|
||||
}
|
||||
|
||||
private Map<String, Object> saved() {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) 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<String, Object>) 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());
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<LeadMatch> 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<EventLeadDetail> findByEvent(@RequestBody EventLeadSearchRequest req) {
|
||||
return eventLeadService.search(req);
|
||||
}
|
||||
|
||||
@PostMapping("/eventLead/update")
|
||||
public EventLeadDetail update(@RequestBody EventLeadUpdateRequest req) {
|
||||
return eventLeadService.update(req);
|
||||
}
|
||||
}
|
||||
@@ -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<Interest> 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<Interest> findByIds(@RequestBody InterestFindByIdsRequest body) {
|
||||
return interestService.findByIds(body.companyId(), body.ids());
|
||||
}
|
||||
}
|
||||
@@ -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<Long> interestIds,
|
||||
LocalDate nextFollowUpDate,
|
||||
String notes,
|
||||
String doneBy
|
||||
) {}
|
||||
@@ -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<Long> interestIds
|
||||
) {}
|
||||
@@ -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) {}
|
||||
@@ -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<Long> interestIds, LocalDate nextFollowUpDate, String notes,
|
||||
String doneBy) {}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.solvway.services.counter.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record InterestFindByIdsRequest(
|
||||
long companyId,
|
||||
List<Long> ids
|
||||
) {}
|
||||
@@ -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) {}
|
||||
@@ -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) {}
|
||||
@@ -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;
|
||||
|
||||
}
|
||||
@@ -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<EventLeadInterestId> {
|
||||
@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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<EventLeadInterest, EventLeadInterestId> {
|
||||
|
||||
List<EventLeadInterest> findByIdEventLeadId(long eventLeadId);
|
||||
|
||||
List<EventLeadInterest> findByIdEventLeadIdIn(Collection<Long> eventLeadIds);
|
||||
|
||||
@Modifying
|
||||
@Query("DELETE FROM EventLeadInterest i WHERE i.id.eventLeadId = :eventLeadId")
|
||||
void deleteByEventLeadId(@Param("eventLeadId") long eventLeadId);
|
||||
}
|
||||
@@ -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<EventLead, Long> {
|
||||
|
||||
Optional<EventLead> findByEventUuidAndLeadUuid(long eventUuid, long leadUuid);
|
||||
|
||||
List<EventLead> findByEventUuidAndLeadUuidIn(long eventUuid, Collection<Long> leadUuids);
|
||||
|
||||
Optional<EventLead> 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<Object[]> 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);
|
||||
}
|
||||
@@ -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<Interest, Long> {
|
||||
List<Interest> findByCompanyIdOrderBySortOrderAscNameAsc(long companyId);
|
||||
|
||||
boolean existsByCompanyIdAndNameIgnoreCase(long companyId, String name);
|
||||
|
||||
List<Interest> findByIdInAndCompanyId(Collection<Long> ids, long companyId);
|
||||
}
|
||||
@@ -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<Lead, Long> {
|
||||
|
||||
/** 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<Lead> findMatches(@Param("companyId") long companyId, @Param("mobile") String mobile,
|
||||
@Param("email") String email, Pageable pageable);
|
||||
|
||||
Optional<Lead> findByUuidAndCompanyId(long uuid, long companyId);
|
||||
}
|
||||
@@ -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<LeadMatch> findMatches(LeadMatchRequest req) {
|
||||
String mobile = blankToNull(req.mobileE164());
|
||||
String email = blankToNull(req.email());
|
||||
if (mobile == null && email == null) return List.of();
|
||||
|
||||
List<Lead> leads = leadRepository.findMatches(req.companyId(), mobile, email, PageRequest.of(0, MAX_MATCHES));
|
||||
if (leads.isEmpty()) return List.of();
|
||||
Map<Long, Long> 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<Long> 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<Long> interestIds = eventLeadInterestRepository.findByIdEventLeadId(eventLead.getId()).stream()
|
||||
.map(r -> r.getId().getInterestId()).toList();
|
||||
return detail(eventLead, lead, interestIds);
|
||||
}
|
||||
|
||||
public Page<EventLeadDetail> 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<Object[]> 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<Long, List<Long>> 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<Long> 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<Long> saveInterests(long eventLeadId, long companyId, List<Long> requested) {
|
||||
List<Long> 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<Long> 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<String> setter) {
|
||||
if (blankToNull(current) == null && blankToNull(offered) != null) setter.accept(offered);
|
||||
}
|
||||
|
||||
private static String blankToNull(String s) {
|
||||
return s == null || s.isBlank() ? null : s;
|
||||
}
|
||||
}
|
||||
@@ -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<Interest> 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<Interest> findByIds(long companyId, List<Long> ids) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return interestRepository.findByIdInAndCompanyId(ids, companyId);
|
||||
}
|
||||
}
|
||||
@@ -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<LeadMatch> 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<EventLeadDetail> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Interest> 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<Interest> 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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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> 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> 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<EventLeadDetail> 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<List<EventLeadInterest>> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<LeadMatch> 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<LeadMatch> 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> 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<List<EventLeadInterest>> 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<LeadMatch> 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<Long> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<Interest> 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<Interest> 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<Interest> 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<Interest> 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<Interest> 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<Interest> 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;
|
||||
}
|
||||
}
|
||||