Compare commits

..
Author SHA1 Message Date
ngqileandClaude Opus 5.5 8ce641ea86 docs: correct interest storage comment and record event scoping gap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 14:21:20 +08:00
ngqileandClaude Opus 5.5 fad639d690 test(admin-portal): wait for picker cards before asserting
The picker tests waited only for the load call, then read the cards
before they rendered, which failed intermittently in the full suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 14:16:56 +08:00
ngqileandClaude Opus 5.5 29f5c6f094 docs(openspec): tick browser check for add-event-lead-capture
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 14:10:29 +08:00
ngqileandClaude Opus 5.5 adaca0a4eb feat(admin-portal): event lead edit page
Edits salesperson, temperature, status, interests, follow-up date and
notes. An off-team current salesperson and an inactive interest already
on the lead stay selectable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 13:51:03 +08:00
ngqileandClaude Opus 5.5 7fe8dcc8a5 feat(admin-portal): two-step event lead key-in form
Step 1 matches on mobile or email and offers each candidate (or opens an
already-captured one). Step 2 captures a new or picked lead with
salesperson, temperature, status, interests and follow-up date. A picked
lead only gets contact values that are its own, so no two people merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 13:31:29 +08:00
ngqileandClaude Opus 5.5 94e1e7fdde feat(admin-portal): event picker and event leads listing
Picker lists events with those running today first. The listing filters
by salesperson, temperature, status, interest and lead type, with a
table at md and up and tappable cards on phones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 13:09:55 +08:00
ngqileandClaude Opus 5.5 90f25debc2 feat(admin-portal): event leads data layer
One proxy route for /api/admin/event-leads (dot segments rejected),
service, types, and /event-leads gated by BO_EVENT_LEADS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 12:20:47 +08:00
ngqileandClaude Opus 5.5 18672ba173 feat(admin-portal): interests screen
Lists, adds, renames, orders and activates/deactivates interests,
gated by BO_INTERESTS. API errors map to field messages under Name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 12:18:21 +08:00
ngqileandClaude Opus 5.5 fe9d9bd38d feat(mobile-api): event leads API with phone normalisation and team rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 11:37:27 +08:00
ngqileandClaude Opus 5.5 5d768b1566 feat(mobile-api): admin interests API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 11:20:10 +08:00
ngqileandClaude Opus 5.5 48507979bd feat(services-counter): capture, match, list and edit event leads
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 11:13:49 +08:00
ngqileandClaude Opus 5.5 b75d636886 feat(services-counter): store each company's interest list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 10:09:56 +08:00
ngqileandClaude Opus 5.5 4c853c428e feat(db): lead, event_lead and interest tables with their modules
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 09:42:24 +08:00
ngqileandClaude Opus 5.5 3fc0510615 docs(openspec): propose add-event-lead-capture
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 09:33:21 +08:00
ngqile 66581f1944 Merge pull request 'docs(openspec): archive add-admin-events' (#6) from archive-add-admin-events into main 2026-11-26 18:38:20 +00:00
ngqileandClaude Opus 5.5 846a08da57 docs(openspec): archive add-admin-events
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 02:38:12 +08:00
ngqile 5588ade48d Merge pull request 'feat: admin events with salesperson teams (add-admin-events)' (#5) from add-admin-events into main 2026-11-26 18:37:53 +00:00
ngqileandClaude Opus 5.5 4e77440709 docs(openspec): add-admin-events browser verification
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 02:32:51 +08:00
ngqileandClaude Opus 5.5 82d47f4023 fix(admin-portal): show the CalendarDays icon for the Events menu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 02:32:50 +08:00
ngqileandClaude Opus 5.5 b6671280fa docs(openspec): tick add-admin-events task 4.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 02:18:27 +08:00
ngqileandClaude Opus 5.5 c57aa3e7cc feat(admin-portal): events list, create and edit screens with team picker
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 02:18:20 +08:00
ngqileandClaude Opus 5.5 33f1e7a505 fix(mobile-api): keep a deactivated member already on an event's team
Only users being added must be active admins; someone already on the team stays
until an admin removes them, so an unrelated event edit no longer fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 01:48:35 +08:00
ngqileandClaude Opus 5.5 2efdcba1ae fix(mobile-api): event errors use the portal's details/errors contract
The portal forwards only code, errors and flat details from a ProblemDetail, so
the failing field and the TEAM_NOT_SAVED event uuid move into details and the
missing-field list into errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 00:25:55 +08:00
ngqileandClaude Opus 5.5 c908fbe9fc feat(admin-portal): port babyboo's date picker and calendar
Adds react-day-picker 10.0.1 (it brings date-fns). The portal bans native date
inputs, and the events and leads forms need a date field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 00:23:56 +08:00
ngqileandClaude Opus 5.5 1fa7c60fee feat(mobile-api): admin events API with salesperson teams
/api/admin/events list, get, create, update and salesperson-options, all behind
BO_EVENTS. Whole-day dates, uuid as a string, team ids checked before saving.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 00:18:32 +08:00
ngqileandClaude Opus 5.5 70e0651a75 feat(services-counter): store each event's team of salespeople
GET /counter/eventSalesperson/findByEventUuid/{eventUuid} and
POST /counter/eventSalesperson/replace (bulk delete then insert, one transaction).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 23:57:50 +08:00
ngqileandClaude Opus 5.5 814c51da3d feat(db): event_salesperson table and BO_EVENTS module
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 23:23:34 +08:00
ngqileandClaude Opus 5.5 246fec3c7b docs(openspec): propose add-admin-events
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 23:19:39 +08:00
ngqile dfed2919a0 Merge pull request 'docs(openspec): archive add-admin-auth-users-roles' (#4) from archive-add-admin-auth-users-roles into main 2026-11-26 14:41:05 +00:00
138 changed files with 11465 additions and 3 deletions

No files matched your search

+83
View File
@@ -19,9 +19,92 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic
(40700000, 'BO_USERS', 'Users', 'BO', 'M', 40000000, '/users', 'UserCog'),
(40800000, 'BO_ROLES', 'Roles', 'BO', 'M', 40000000, '/roles', 'ShieldCheck');
-- add-admin-events/sql/02-bo-events-module.sql
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`)
VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 1,
'Y', 'Y', 'A', 'seed', NOW(), 'seed', 1);
INSERT INTO `users_roles` (`user_id`, `role_id`) VALUES (1, 1);
-- add-admin-events/sql/01-event-salesperson.sql
USE `service-counter`;
CREATE TABLE `event_salesperson` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_uuid` bigint NOT NULL,
`user_id` bigint NOT NULL,
`create_by` varchar(255) DEFAULT NULL,
`create_date_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
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`.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-26
@@ -0,0 +1,90 @@
# Design
## Context
- `services-counter` owns the `event` table (schema `service-counter`) and exposes `/counter/event/findByPropertyAndPageable`, `/findByUuid/{uuid}` and `/save`, reached through the gateway. `save` is a full-entity JPA save with no validation; it also refreshes the current-event cache. `findByPropertyAndPageable` ANDs its filters: `name` and `location` are `LIKE %v%`, `enabled` is `Y`/`N`, and sorting comes from `pageableRest.sorts`.
- `event.uuid` is a Snowflake `bigint` (about 19 digits). That is larger than a JavaScript number can hold exactly.
- `mobile-api` already reads `findCurrentEvent` and `findByUuid` for the member app. The admin layer from change 2 (`@AdminModule`, `AppAccessAspect`, `AdminUserService`, `CodedResponseStatusException`) is in place.
- The portal's Users pages (list with `DataTable`, `FilterPanel`, `useListFilters`; `new` and `[id]` pages around a form component) are the pattern for list, create and edit. `app/no-native-date-inputs.test.ts` forbids native date inputs.
- Tastefully's backoffice event rules (`EventController` add and edit): name, location, start and end required; dates parsed as days, start at start of day, end at 23:59:59; end not before start; enabled only on edit.
## Goals / Non-Goals
**Goals:**
- Events list, create, edit with the backoffice rules pinned by tests before the screens are built.
- An event team that change 4 can read to restrict a lead's salesperson.
**Non-Goals:**
- Booths, products, receipts, lucky draw, uploads.
- Restricting the lead salesperson to the team: that rule lands with lead capture in change 4. This change stores and edits the team.
## Decisions
### 1. Event API uses the uuid, sent as a string
`/api/admin/events/{uuid}` and every event payload carry `uuid` as a JSON string, and `mobile-api` parses it back to `long`. Change 4's `event_lead` references `event_uuid`, so the uuid is the stable key. Sending it as a number would round it in the browser.
Alternative: use the numeric `id`. Rejected: `services-counter` has no `findById` for events, and leads key on the uuid.
### 2. Dates travel as `YYYY-MM-DD`
The admin API takes and returns `startDate` and `endDate` as plain dates. `mobile-api` turns them into `dateStart = day 00:00:00` and `dateEnd = day 23:59:59` for `services-counter`, and turns stored values back into dates. This matches the backoffice and keeps time zones out of the browser.
### 3. Update reads, patches and saves the stored event
`/counter/event/save` is a full-entity save, so update loads the event with `findByUuid`, sets only name, location, dates, enabled and `doneBy`, and sends the whole stored event back. The upload fields, `createBy` and `createDateTime` survive untouched. Create sends a new event with `createBy` and `doneBy` set to the admin's username; its Snowflake `uuid` is generated in `mobile-api` by the shared core `Event` model and kept by `services-counter`.
### 4. Validation lives in `mobile-api`
`services-counter` accepts anything, so `AdminEventService` validates (required, lengths, end not before start, parseable dates) and answers 400 with a code per field (`REQUIRED_FIELD`, `TOO_LONG`, `END_BEFORE_START`, `INVALID_DATE`) and the field name. The portal also checks before submitting, but the API is the authority.
### 5. Search is by name
`findByPropertyAndPageable` ANDs `name` and `location`, so one search box cannot match either. The list searches by name, which is what staff look for. `ponytail:` adding an OR search needs a `services-counter` query change; add it if location search is asked for.
### 6. Event team in `services-counter`
New table `service-counter`.`event_salesperson` (`id`, `company_id NOT NULL`, `event_uuid`, `user_id`, `create_by`, `create_date_time`; unique `(event_uuid, user_id)`; index on `event_uuid`), an `EventSalesperson` entity and two endpoints:
- `GET /counter/eventSalesperson/findByEventUuid/{eventUuid}`: the team rows.
- `POST /counter/eventSalesperson/replace` with `{eventUuid, companyId, userIds, doneBy}`: deletes the event's rows and inserts the new set in one transaction.
The team lives next to `event` and `event_lead` (change 4) in the same schema, so change 4's salesperson check and listings are plain lookups. `user_id` points at `service-system`.`user` across schemas, so there is no foreign key; `mobile-api` checks each id before saving: it must be an admin user (`type A`) and enabled. `company_id` is the logged-in admin's company, never from the request.
The event payload carries `salespersonIds` on create and update and returns `team: [{id, name, username, enabled}]` on get. `mobile-api` resolves names with one `services-system` user lookup per team member.
`ponytail:` one lookup per member is fine for event-sized teams; batch it if teams grow past a few dozen.
### 7. Team picker options
`GET /api/admin/events/salesperson-options` (`BO_EVENTS`) returns active admin users as `{id, name, username}`. It reuses the admin user lookup from change 2 but needs only `BO_EVENTS`, so an events admin does not need the Users module to staff an event. Any active admin user can be on a team; roles are admin-defined, so there is no fixed "Sales" role to filter on.
### 8. Create is two calls
Create saves the event, then replaces the team. If the team call fails, the event exists with no team and the API answers 502 with code `TEAM_NOT_SAVED` and the event's uuid; the portal opens the event's edit page with that message so the admin can save the team again.
Alternative: one `services-counter` endpoint that creates both in a transaction. Rejected for now: it changes the existing event save path, which also feeds the current-event cache.
### 9. Date picker
Port babyboo's `app/components/ui/calendar.tsx` and `date-picker.tsx` (with their tests), adding `react-day-picker` 10.0.1, the version babyboo uses (it depends on `date-fns` itself, so no direct `date-fns` dependency). Required by the native-date-input ban; change 4 reuses the picker on phones.
### 10. Module
`BO_EVENTS` (id 40100000, parent 40000000, url `/events`, icon `CalendarDays`, area BO, type M). `/events` joins the portal's route-module map. Every events endpoint, including salesperson options, declares `BO_EVENTS`.
## Risks / Trade-offs
- [Snowflake uuid rounded in the browser] → Sent as a string end to end; a test asserts the JSON type.
- [Team saved separately from the event on create] → Rare partial failure is reported with the event's uuid and fixed by saving again (decision 8).
- [Team rows point at users in another schema] → Checked on write; a deactivated member stays visible and marked inactive rather than vanishing.
- [Server time zone] → Dates are whole days computed in `mobile-api`; containers run in the same zone as the database. Revisit at the Kubernetes change.
- [Overlapping enabled events make `findCurrentEvent` pick one for the member app] → Accepted; Co-Lite's lead capture picks the event explicitly.
## Migration Plan
Additive SQL in `sql/` of this change:
1. `01-event-salesperson.sql`: create `service-counter`.`event_salesperson`.
2. `02-bo-events-module.sql`: insert the `BO_EVENTS` module row in `service-system`.
Mirrored in `local/seed/03-colite.sql`. Rollback: `sql/99-rollback.sql` drops the table and deletes the module row and its `modules_roles` rows.
@@ -0,0 +1,35 @@
# Proposal
## Why
Lead capture (change 4) records every lead against an event, so staff need to create and maintain events before go-live. Tastefully's event screens live in the Thymeleaf backoffice, which Co-Lite never deploys, and `mobile-api` only reads the current event. This change adds an Events screen to the admin portal. See `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md` (Admin portal, screen 4).
## What Changes
- **Admin portal Events screens**: a paged list (search by name, filter by enabled), a create page and an edit page. Desktop-first, like Users and Roles.
- **`mobile-api` gains `/api/admin/events`**: list, get, create and update, guarded by a new `BO_EVENTS` module. They call the existing `services-counter` event endpoints (`findByPropertyAndPageable`, `findByUuid`, `save`); the `event` table does not change.
- **Event fields kept** from Tastefully: name, location, start date, end date, enabled. Tastefully's backoffice rules carry over: name and location required, both dates required, end date not before start date, dates are whole days, new events start enabled.
- **Event team**: each event has a team of salespeople (active admin users), chosen on create and edit and stored in a new `services-counter` table `event_salesperson`. Change 4 limits a lead's salesperson to the event's team.
- **Not kept**: the four Tastefully upload fields (floor plan, stage activities, lucky draw, taste rewards). Their columns stay in the table and are left untouched on update.
- **No delete**, as in Tastefully. Leads will reference events, so an event is disabled instead.
- **Back-office module** `BO_EVENTS` (`/events`) added to `service-system`.`module`; SQL in this change folder, mirrored in `local/seed/`.
- **Date picker**: the portal forbids native date inputs (an existing test), so babyboo's `DatePicker` and `Calendar` components are ported, adding `react-day-picker`. Change 4 reuses them for the follow-up date.
Not in this change: event booths, products, receipts, lucky draw and the other Tastefully event sub-screens; event company scoping (the design keeps `user` as the only existing table that gains `company_id`).
## Capabilities
### New Capabilities
- `admin-events`: managing events in the admin portal (list, search, create, edit, enable and disable) and the rules an event must satisfy.
### Modified Capabilities
None.
## Impact
- `solvway-admin-portal`: new `app/events/**` pages, `app/api/events/**` route handlers, an events service, the ported date picker and calendar, `/events` in the route-module map. New dependency `react-day-picker`.
- `solvway-mobile-api`: new `AdminEventController`, `AdminEventService`, DTOs and counter endpoint constants.
- `solvway-services-counter`: `EventSalesperson` entity and team endpoints.
- Database: new table `service-counter`.`event_salesperson` and one new `service-system`.`module` row. Additive only.
- `local/seed/03-colite.sql`: mirrors both.
- No change to the gateway or the `event` table.
@@ -0,0 +1,95 @@
# Spec Delta
## Purpose
Admins with the Events module create and maintain the events that leads are captured at, including each event's team of salespeople.
## ADDED 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,16 @@
-- Co-Lite change 3: each event's team of salespeople.
-- Target: `service-counter`. Additive only. Run once.
-- user_id points at `service-system`.`user` (another schema), so there is no foreign key; mobile-api checks it on write.
USE `service-counter`;
CREATE TABLE `event_salesperson` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_uuid` bigint NOT NULL,
`user_id` bigint NOT NULL,
`create_by` varchar(255) DEFAULT NULL,
`create_date_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_event_salesperson_event_user` (`event_uuid`, `user_id`),
KEY `idx_event_salesperson_event` (`event_uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -0,0 +1,6 @@
-- Co-Lite change 3: Events back-office module (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
(40100000, 'BO_EVENTS', 'Events', 'BO', 'M', 40000000, '/events', 'CalendarDays');
@@ -0,0 +1,7 @@
-- Rollback for add-admin-events. Drops the team table and the Events module with its grants.
USE `service-system`;
DELETE FROM `modules_roles` WHERE `module_id` = 40100000;
DELETE FROM `module` WHERE `id` = 40100000;
USE `service-counter`;
DROP TABLE IF EXISTS `event_salesperson`;
@@ -0,0 +1,34 @@
# Tasks
Babyboo source: `~/Projects/babyboo` (read only). Tastefully backoffice rules: `~/Projects/tastefully/solvway-backoffice/.../controller/EventController.java` (add and edit). All tasks run serially.
## 1. Database
- [x] 1.1 Write `sql/01-event-salesperson.sql` (`service-counter`.`event_salesperson`: `id` bigint auto-increment PK, `company_id` bigint NOT NULL, `event_uuid` bigint NOT NULL, `user_id` bigint NOT NULL, `create_by` varchar(255), `create_date_time` datetime default now; unique `(event_uuid, user_id)`, index `event_uuid`), `sql/02-bo-events-module.sql` (`40100000 BO_EVENTS` 'Events', area BO, type M, parent 40000000, url `/events`, icon `CalendarDays`) and `sql/99-rollback.sql`. Mirror into `local/seed/03-colite.sql`. Verify: `docker compose -f local/docker-compose.yml down -v && local/up.sh` exits 0, then a read-only SELECT shows the table and the module row.
- Scope: `openspec/changes/add-admin-events/sql/**`, `local/seed/**`
## 2. services-counter event team
- [x] 2.1 Add `EventSalesperson` entity and repository, and `EventSalespersonController` with `GET /counter/eventSalesperson/findByEventUuid/{eventUuid}` and `POST /counter/eventSalesperson/replace` (`{eventUuid, companyId, userIds, doneBy}`; delete the event's rows and insert the set in one transaction; duplicate ids collapse to one row). Tests first: replace then find returns the new set; replacing with an empty list clears it; a failure midway leaves the old set. Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`.
- Scope: `solvway-services-counter/src/**`
## 3. mobile-api events
- [x] 3.1 Add `AdminEventController` and `AdminEventService` under `/api/admin/events`, all `@AdminModule("BO_EVENTS")`: `GET /events` (paged; `q` searches name; `enabled` Y/N filter; sort by name, startDate, endDate), `GET /events/{uuid}` (with `team`), `POST /events`, `PUT /events/{uuid}`, `GET /events/salesperson-options` (active admin users `{id, name, username}`). Per design: uuid as a JSON string, dates as `YYYY-MM-DD` mapped to 00:00:00 and 23:59:59, update patches the stored event so upload fields and `createBy` survive, validation codes `REQUIRED_FIELD` / `TOO_LONG` / `END_BEFORE_START` / `INVALID_DATE` with the field name, team ids must be enabled type-A users (else 400 `UNKNOWN_USER`), `company_id` from the caller, partial create answers 502 `TEAM_NOT_SAVED` with the uuid, unknown uuid 404. Tests first for each `admin-events` scenario that the API decides, including an exact-JSON test that `uuid` is a string. Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`.
- Scope: `solvway-mobile-api/src/**/controller/admin/**`, `solvway-mobile-api/src/**/service/AdminEvent*`, `solvway-mobile-api/src/**/dto/admin/**`, `solvway-mobile-api/src/**/constant/api/**`, matching tests
## 4. Admin portal
- [x] 4.1 Port babyboo's `calendar.tsx` and `date-picker.tsx` (and their tests) into `app/components/ui/`, with their helpers `app/lib/date-input.ts` (and test), `test/pickDate.ts` and the four `Ui*` i18n keys, adding `react-day-picker` 10.0.1 to `package.json` (`npm install`, commit the lockfile; it brings `date-fns` itself). Verify: `npm run lint && npx tsc --noEmit && npx vitest run` exit 0.
- Scope: `solvway-admin-portal/app/components/ui/**`, `solvway-admin-portal/app/lib/date-input*`, `solvway-admin-portal/test/pickDate.ts`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`, `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`
- [x] 4.2 Add the Events screens on the Users pattern: `app/events/page.tsx` (list: search, enabled filter, sortable name/start/end, columns name, location, start, end, enabled; row Edit), `app/events/new/page.tsx`, `app/events/[uuid]/page.tsx`, an `EventForm` (name, location, start and end `DatePicker`, enabled on edit only, team multi-select from salesperson-options with inactive members shown marked), route handlers `app/api/events/**`, `app/lib/services/adminEvents.ts`, types, i18n defaults, and `/events` → `BO_EVENTS` in `routeModules`. Form checks required fields and end not before start before submitting; API errors show on the field. `TEAM_NOT_SAVED` lands on the edit page with its message. Tests first (vitest) for each portal-visible scenario. Verify: `npm run lint && npx tsc --noEmit && npx vitest run && npm run build` exit 0.
- Scope: `solvway-admin-portal/app/**`
## 5. End-to-end check
- [x] 5.1 Rebuild the stack and drive the portal with Playwright: grant `BO_EVENTS` to a role, create an event with a two-person team, the missing-field and end-before-start errors, edit dates and team, disable it, search and filter the list, and a user without `BO_EVENTS` gets not-authorised. Screenshots in `verification/`. Only local dev data. Verify: each scenario observed as specified, `local/smoke.sh` prints `smoke: OK`.
- Scope: `openspec/changes/add-admin-events/verification/**`
## Workflow follow-up
- Code review, PR to `main`, merge, then archive this change.
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+95
View File
@@ -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,67 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, PUT } from "./route";
function ctx(uuid: string) {
return { params: Promise.resolve({ uuid }) };
}
function getReq() {
return new Request("http://localhost/api/events/abc-123") as unknown as Parameters<typeof GET>[0];
}
function putReq(body: unknown) {
return new Request("http://localhost/api/events/abc-123", {
method: "PUT",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof PUT>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/events/[uuid]", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq(), ctx("abc-123"));
expect(res.status).toBe(401);
});
it("forwards to GET /api/admin/events/{uuid}", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc-123" } });
await GET(getReq(), ctx("abc-123"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/abc-123", { token: "jwt-abc" });
});
it("encodes special characters in uuid", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "encoded" } });
await GET(getReq(), ctx("some:uuid/with-slashes"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/some%3Auuid%2Fwith-slashes", { token: "jwt-abc" });
});
});
describe("PUT /api/events/[uuid]", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await PUT(putReq({ name: "Updated" }), ctx("abc-123"));
expect(res.status).toBe(401);
});
it("forwards the body to PUT /api/admin/events/{uuid}", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const body = { name: "Updated", location: "New Place", startDate: "2025-02-01", endDate: "2025-02-02", enabled: true, salespersonIds: [3] };
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc-123", ...body } });
await PUT(putReq(body), ctx("abc-123"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/abc-123", {
method: "PUT",
body,
token: "jwt-abc",
});
});
});
@@ -0,0 +1,29 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
type Ctx = { params: Promise<{ uuid: string }> };
export async function GET(_req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { uuid } = await params;
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/${encodeURIComponent(uuid)}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function PUT(req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { uuid } = await params;
const body = await req.json().catch(() => ({}));
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/${encodeURIComponent(uuid)}`, {
method: "PUT",
body,
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,99 @@
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(query = "") {
return new Request(`http://localhost/api/events${query}`) as unknown as Parameters<typeof GET>[0];
}
function postReq(body: unknown) {
return new Request("http://localhost/api/events", {
method: "POST",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/events", () => {
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 q/page/size/sortBy/sortDir to /api/admin/events", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
await GET(getReq("?q=event1&page=1&size=10&sortBy=name&sortDir=asc"));
expect(mocks.callMobileApi).toHaveBeenCalledWith(
"/api/admin/events?q=event1&page=1&size=10&sortBy=name&sortDir=asc",
{ token: "jwt-abc" },
);
});
it("forwards enabled=Y/N to /api/admin/events", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
await GET(getReq("?enabled=Y&page=0&size=20"));
expect(mocks.callMobileApi).toHaveBeenCalledWith(
"/api/admin/events?enabled=Y&page=0&size=20",
{ token: "jwt-abc" },
);
});
it("returns 400 when enabled is not Y or N", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await GET(getReq("?enabled=true"));
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("returns 400 when enabled is false", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await GET(getReq("?enabled=false"));
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("uses default page=0 and size=20 when absent", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
await GET(getReq(""));
expect(mocks.callMobileApi).toHaveBeenCalledWith(
"/api/admin/events?page=0&size=20",
{ token: "jwt-abc" },
);
});
});
describe("POST /api/events", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq({ name: "Event", location: "Place", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, salespersonIds: [] }));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the body to POST /api/admin/events", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const body = { name: "Event", location: "Place", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, salespersonIds: [1, 2] };
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc123", ...body } });
await POST(postReq(body));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events", {
method: "POST",
body,
token: "jwt-abc",
});
});
});
@@ -0,0 +1,44 @@
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";
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const params = new URL(req.url).searchParams;
const qs = new URLSearchParams();
const q = params.get("q");
if (q) qs.set("q", q);
const enabled = params.get("enabled");
if (enabled) {
if (enabled !== "Y" && enabled !== "N") return badRequest("enabled must be Y or N.");
qs.set("enabled", enabled);
}
qs.set("page", params.get("page") ?? "0");
qs.set("size", params.get("size") ?? "20");
const sortBy = params.get("sortBy");
if (sortBy) {
qs.set("sortBy", sortBy);
const sortDir = params.get("sortDir");
if (sortDir) qs.set("sortDir", sortDir);
}
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events?${qs.toString()}`, {
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 result = await callMobileApi<Record<string, unknown>>("/api/admin/events", { method: "POST", body, token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,35 @@
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 } from "./route";
function getReq() {
return new Request("http://localhost/api/events/salesperson-options") as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/events/salesperson-options", () => {
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/events/salesperson-options", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [{ id: 1, name: "Jane", username: "jane.doe" }] });
await GET(getReq());
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/salesperson-options", { token: "jwt-abc" });
});
});
@@ -0,0 +1,13 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<Record<string, unknown>>("/api/admin/events/salesperson-options", { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -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,13 @@
import { render } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { iconFor } from "./icon-map";
// add-admin-events: BO_EVENTS seed icon_name = 'CalendarDays'.
describe("iconFor — Events", () => {
it("resolves CalendarDays to a real (non-fallback) icon", () => {
const Icon = iconFor("CalendarDays");
const { container } = render(<Icon aria-hidden="true" />);
expect(container.querySelector("svg")).not.toBeNull();
expect(container.querySelector("svg.lucide-circle")).toBeNull();
});
});
@@ -1,4 +1,4 @@
import { Activity, ArrowDownToLine, ArrowLeftRight, BarChart2, Bell, Box, Calendar, Circle, ClipboardList, Coins, CreditCard, FileText, GalleryHorizontalEnd, Gift, History, LayoutDashboard, Languages, Layers, Mail, Megaphone, Menu, MessagesSquare, Network, Package, Settings, Shield, ShieldCheck, ShoppingCart, SlidersHorizontal, Star, Store, Tags, ScrollText, Undo2, UserCheck, UserCog, Users, Wallet, Warehouse, Wrench } from "lucide-react";
import { Activity, ArrowDownToLine, ArrowLeftRight, BarChart2, Bell, Box, Calendar, CalendarDays, Circle, ClipboardList, Coins, CreditCard, FileText, GalleryHorizontalEnd, Gift, History, LayoutDashboard, Languages, Layers, Mail, Megaphone, Menu, MessagesSquare, Network, Package, Settings, Shield, ShieldCheck, ShoppingCart, SlidersHorizontal, Star, Store, Tags, ScrollText, Undo2, UserCheck, UserCog, Users, Wallet, Warehouse, Wrench } from "lucide-react";
import type { LucideIcon } from "lucide-react";
// Maps the aclMenu tree's `iconName` (a plain string served by
@@ -43,6 +43,8 @@ const ICONS: Record<string, LucideIcon> = {
// Events module (add-event-module-pickup-e1, E1):
// Events page seed icon.
Calendar,
// add-admin-events: BO_EVENTS seed icon_name = 'CalendarDays'.
CalendarDays,
// POS counter-sales module (add-event-pos-counter-sales):
// POS page seed icon (sql/02-seed-bo-module-pos.sql icon_name = 'ShoppingCart').
ShoppingCart,
@@ -0,0 +1,568 @@
import { 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(() => ({
listSalespersonOptions: vi.fn(),
}));
vi.mock("@/app/lib/services/adminEvents", () => ({
listSalespersonOptions: mocks.listSalespersonOptions,
}));
import { EventForm } from "./EventForm";
import { pickDate } from "@/test/pickDate";
const SALESPEOPLE = [
{ id: 1, name: "Alice", username: "alice.smith" },
{ id: 2, name: "Bob", username: "bob.jones" },
{ id: 3, name: "Charlie", username: "charlie.brown" },
];
beforeEach(() => {
mocks.listSalespersonOptions.mockReset().mockResolvedValue(SALESPEOPLE);
});
async function waitForOptions() {
await waitFor(() => expect(screen.getByText("Alice (alice.smith)")).toBeInTheDocument());
}
describe("EventForm", () => {
it("renders all fields on the create form", async () => {
render(<EventForm onSubmit={vi.fn()} />);
await waitForOptions();
expect(screen.getByLabelText("Name")).toBeInTheDocument();
expect(screen.getByLabelText("Location")).toBeInTheDocument();
expect(screen.getByLabelText("Start date")).toBeInTheDocument();
expect(screen.getByLabelText("End date")).toBeInTheDocument();
expect(screen.getByRole("checkbox", { name: "Alice (alice.smith)" })).toBeInTheDocument();
expect(screen.getByRole("checkbox", { name: "Bob (bob.jones)" })).toBeInTheDocument();
expect(screen.getByRole("checkbox", { name: "Charlie (charlie.brown)" })).toBeInTheDocument();
// Enabled switch must NOT be present on create form.
expect(screen.queryByLabelText("Enabled")).not.toBeInTheDocument();
});
it("renders the Enabled switch on the edit form", async () => {
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
}}
onSubmit={vi.fn()}
/>,
);
await waitForOptions();
expect(screen.getByLabelText("Enabled")).toBeInTheDocument();
});
it("prefills from initial on edit form", async () => {
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: false,
}}
onSubmit={vi.fn()}
/>,
);
await waitForOptions();
expect(screen.getByLabelText("Name")).toHaveValue("Conference");
expect(screen.getByLabelText("Location")).toHaveValue("Convention Center");
});
it("blocks submit and shows errors when required fields are missing", async () => {
const onSubmit = vi.fn();
render(<EventForm onSubmit={onSubmit} />);
await waitForOptions();
await userEvent.click(screen.getByRole("button", { name: /create/i }));
expect(await screen.findByText("Name is required.")).toBeInTheDocument();
expect(await screen.findByText("Location is required.")).toBeInTheDocument();
expect(await screen.findByText("Start date is required.")).toBeInTheDocument();
expect(await screen.findByText("End date is required.")).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
});
it("blocks submit when end date is before start date", async () => {
const onSubmit = vi.fn();
// Start with valid dates, then make start after end.
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
}}
onSubmit={onSubmit}
/>,
);
await waitForOptions();
// Change start to 2025-06-10, which is after the existing end 2025-06-03.
pickDate("Start date", "2025-06-10");
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
expect(await screen.findByText("End date must not be before start date.")).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
});
it("shows name-too-long validation error", async () => {
const onSubmit = vi.fn();
render(<EventForm onSubmit={onSubmit} />);
await waitForOptions();
// Name > 100 chars
await userEvent.type(screen.getByLabelText("Name"), "a".repeat(101));
await userEvent.type(screen.getByLabelText("Location"), "Somewhere");
// Set dates via initial + changing end to be before start doesn't help for name length.
// We need to get dates past the required check. Use an initial with valid dates,
// make name too long, clear name, type long name, and save.
render(
<EventForm
initial={{
uuid: "e1",
name: "a".repeat(101),
location: "Somewhere",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
}}
onSubmit={onSubmit}
/>,
);
await waitForOptions();
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
expect(await screen.findByText("Name must be 100 characters or fewer.")).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
});
it("shows location-too-long validation error", async () => {
const onSubmit = vi.fn();
render(
<EventForm
initial={{
uuid: "e1",
name: "Event",
location: "x".repeat(201),
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
}}
onSubmit={onSubmit}
/>,
);
await waitForOptions();
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
expect(await screen.findByText("Location must be 200 characters or fewer.")).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
});
it("builds the correct payload on create", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<EventForm onSubmit={onSubmit} submitLabel="Create" />);
await waitForOptions();
await userEvent.type(screen.getByLabelText("Name"), "Conference");
await userEvent.type(screen.getByLabelText("Location"), "Convention Center");
// Pick dates through the calendar
pickDate("Start date", "2025-06-01");
pickDate("End date", "2025-06-03");
await userEvent.click(screen.getByRole("checkbox", { name: "Alice (alice.smith)" }));
await userEvent.click(screen.getByRole("checkbox", { name: "Bob (bob.jones)" }));
await userEvent.click(screen.getByRole("button", { name: /create/i }));
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
salespersonIds: [1, 2],
}),
);
});
it("builds the correct payload on edit (includes enabled)", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
team: [],
}}
onSubmit={onSubmit}
submitLabel="Edit"
/>,
);
await waitForOptions();
// Toggle the enabled switch off.
await userEvent.click(screen.getByRole("switch", { name: "Enabled" }));
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: false,
salespersonIds: [],
}),
);
});
it("submits a one-day event when start equals end", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<EventForm onSubmit={onSubmit} submitLabel="Create" />);
await waitForOptions();
await userEvent.type(screen.getByLabelText("Name"), "Workshop");
await userEvent.type(screen.getByLabelText("Location"), "Room 1");
pickDate("Start date", "2025-07-01");
pickDate("End date", "2025-07-01");
await userEvent.click(screen.getByRole("button", { name: /create/i }));
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
name: "Workshop",
location: "Room 1",
startDate: "2025-07-01",
endDate: "2025-07-01",
salespersonIds: [],
}),
);
});
it("unchecking an inactive member removes it from salespersonIds", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
team: [
{ id: 1, name: "Alice", username: "alice.smith", enabled: true },
{ id: 99, name: "Deactivated", username: "old.user", enabled: false },
],
}}
onSubmit={onSubmit}
submitLabel="Edit"
/>,
);
await waitForOptions();
// Both should be checked initially.
expect(screen.getByRole("checkbox", { name: "Alice (alice.smith)" })).toBeChecked();
expect(screen.getByRole("checkbox", { name: "Deactivated (old.user)" })).toBeChecked();
// Uncheck the inactive member, keep Alice.
await userEvent.click(screen.getByRole("checkbox", { name: "Deactivated (old.user)" }));
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
salespersonIds: [1],
}),
);
});
it("shows username or id for inactive member with null name", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
team: [
{ id: 5, name: null, username: null, enabled: false },
{ id: 6, name: "Ghost", username: null, enabled: false },
],
}}
onSubmit={onSubmit}
submitLabel="Edit"
/>,
);
await waitForOptions();
// Member with null name and null username should show id.
expect(screen.getByRole("checkbox", { name: "5" })).toBeChecked();
// Member with name but null username should show just name.
expect(screen.getByRole("checkbox", { name: "Ghost" })).toBeChecked();
});
it("builds the correct payload on edit with team", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
team: [
{ id: 1, name: "Alice", username: "alice.smith", enabled: true },
{ id: 99, name: "Deactivated", username: "old.user", enabled: false },
],
}}
onSubmit={onSubmit}
submitLabel="Edit"
/>,
);
await waitForOptions();
// Alice should be checked, deactivated member should be checked with "Inactive" marker.
expect(screen.getByRole("checkbox", { name: "Alice (alice.smith)" })).toBeChecked();
expect(screen.getByRole("checkbox", { name: "Deactivated (old.user)" })).toBeChecked();
expect(screen.getByText(/Inactive/)).toBeInTheDocument();
// Uncheck Alice, keep deactivated member
await userEvent.click(screen.getByRole("checkbox", { name: "Alice (alice.smith)" }));
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
name: "Conference",
location: "Convention Center",
startDate: "2025-06-01",
endDate: "2025-06-03",
enabled: true,
salespersonIds: [99],
}),
);
});
it("shows an API REQUIRED_FIELD error under each listed field", async () => {
class ApiError extends Error {
status: number;
data?: unknown;
constructor(message: string, status: number, data?: unknown) {
super(message);
this.name = "ApiError";
this.status = status;
this.data = data;
}
}
const onSubmit = vi.fn().mockRejectedValue(
new ApiError("Validation failed", 422, {
errors: ["location", "startDate"],
}),
);
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "",
startDate: "",
endDate: "2025-06-03",
enabled: true,
}}
onSubmit={onSubmit}
submitLabel="Edit"
/>,
);
await waitForOptions();
// Pre-fill all required fields so client-side validation passes,
// but the API returns REQUIRED_FIELD errors for location and startDate.
await userEvent.type(screen.getByLabelText("Name"), "X");
await userEvent.type(screen.getByLabelText("Location"), "Somewhere");
pickDate("Start date", "2025-06-01");
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
// Each field listed in errors[] gets the required message.
expect(await screen.findByText("Location is required.")).toBeInTheDocument();
expect(await screen.findByText("Start date is required.")).toBeInTheDocument();
expect(screen.getByLabelText("Location")).toHaveAttribute("aria-invalid", "true");
expect(screen.getByLabelText("Start date")).toHaveAttribute("aria-invalid", "true");
expect(onSubmit).toHaveBeenCalledTimes(1);
});
it("shows a team error from the API under the Team list, and an unknown missing field at the top", async () => {
class ApiError extends Error {
status: number;
data?: unknown;
constructor(message: string, status: number, data?: unknown) {
super(message);
this.name = "ApiError";
this.status = status;
this.data = data;
}
}
const onSubmit = vi
.fn()
.mockRejectedValueOnce(new ApiError("Unknown or inactive admin user 7", 400, { code: "UNKNOWN_USER", details: { field: "salespersonIds" } }))
.mockRejectedValueOnce(new ApiError("Required: venue", 400, { code: "REQUIRED_FIELD", errors: ["venue"], details: { field: "venue" } }));
render(
<EventForm
initial={{ uuid: "e1", name: "Conference", location: "Hall", startDate: "2025-06-01", endDate: "2025-06-03", enabled: true }}
onSubmit={onSubmit}
submitLabel="Edit"
/>,
);
await waitForOptions();
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
const team = screen.getByRole("group", { name: "Team" });
expect(await within(team).findByText("Unknown or inactive admin user 7")).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
expect(await screen.findByText("Required: venue")).toBeInTheDocument();
expect(within(team).queryByText("Required: venue")).not.toBeInTheDocument();
});
it("shows an API field error under the correct field", async () => {
class ApiError extends Error {
status: number;
data?: unknown;
constructor(message: string, status: number, data?: unknown) {
super(message);
this.name = "ApiError";
this.status = status;
this.data = data;
}
}
const onSubmit = vi.fn().mockRejectedValue(
new ApiError("Validation failed", 422, {
details: { field: "name" },
errors: ["location", "startDate"],
}),
);
render(
<EventForm
initial={{
uuid: "e1",
name: "Conference",
location: "",
startDate: "",
endDate: "2025-06-03",
enabled: true,
}}
onSubmit={onSubmit}
submitLabel="Edit"
/>,
);
await waitForOptions();
// Pre-fill required fields so only the API error shows.
await userEvent.type(screen.getByLabelText("Name"), "X");
await userEvent.type(screen.getByLabelText("Location"), "Somewhere");
pickDate("Start date", "2025-06-01");
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
// errors[] takes priority over details.field, so location and startDate get the errors.
expect(await screen.findByText("Location is required.")).toBeInTheDocument();
expect(await screen.findByText("Start date is required.")).toBeInTheDocument();
expect(onSubmit).toHaveBeenCalledTimes(1);
// The error should be under the listed fields (aria-invalid=true).
expect(screen.getByLabelText("Location")).toHaveAttribute("aria-invalid", "true");
expect(screen.getByLabelText("Start date")).toHaveAttribute("aria-invalid", "true");
});
it("shows a general error at the top when onSubmit throws a non-field API error", async () => {
class ApiError extends Error {
status: number;
data?: unknown;
constructor(message: string, status: number, data?: unknown) {
super(message);
this.name = "ApiError";
this.status = status;
this.data = data;
}
}
const onSubmit = vi.fn().mockRejectedValue(new ApiError("Network error", 500));
render(<EventForm onSubmit={onSubmit} />);
await waitForOptions();
await userEvent.type(screen.getByLabelText("Name"), "Event");
await userEvent.type(screen.getByLabelText("Location"), "Here");
pickDate("Start date", "2025-06-01");
pickDate("End date", "2025-06-03");
await userEvent.click(screen.getByRole("button", { name: /create/i }));
expect(await screen.findByText("Network error")).toBeInTheDocument();
// onSubmit was called (it IS the mock).
expect(onSubmit).toHaveBeenCalledTimes(1);
});
it("disables submit while saving", async () => {
let resolveSubmit!: () => void;
const onSubmit = vi.fn(
() =>
new Promise<void>((resolve) => {
resolveSubmit = resolve;
}),
);
render(<EventForm onSubmit={onSubmit} />);
await waitForOptions();
await userEvent.type(screen.getByLabelText("Name"), "Event");
await userEvent.type(screen.getByLabelText("Location"), "Here");
pickDate("Start date", "2025-06-01");
pickDate("End date", "2025-06-03");
await userEvent.click(screen.getByRole("button", { name: /create/i }));
await waitFor(() => expect(screen.getByRole("button", { name: /create/i })).toBeDisabled());
resolveSubmit();
});
});
@@ -0,0 +1,300 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Switch } from "@/app/components/ui/switch";
import { DatePicker } from "@/app/components/ui/date-picker";
import { ErrorState } from "@/app/components/ui/states";
import { listSalespersonOptions } from "@/app/lib/services/adminEvents";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { AdminEvent, AdminEventPayload, SalespersonOption } from "@/app/lib/types";
import type { ApiError } from "@/app/lib/clientApi";
interface SalespersonOptionExtended extends SalespersonOption {
active: boolean;
}
export interface EventFormProps {
initial?: AdminEvent;
onSubmit: (payload: AdminEventPayload) => Promise<void>;
submitLabel?: string;
}
/** Missing-field codes the API lists in errors[], mapped to the message shown under that field. */
const REQUIRED_MESSAGE: Record<string, string> = {
name: "EvtNameRequired",
location: "EvtLocationRequired",
startDate: "EvtStartRequired",
endDate: "EvtEndRequired",
};
/** Fields the form can show an API error under; anything else goes to the top of the form. */
const FIELD_ERROR_SLOTS = ["name", "location", "startDate", "endDate", "salespersonIds"];
export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
const t = useT();
const [name, setName] = useState(initial?.name ?? "");
const [location, setLocation] = useState(initial?.location ?? "");
const [startDate, setStartDate] = useState(initial?.startDate ?? "");
const [endDate, setEndDate] = useState(initial?.endDate ?? "");
const [enabled, setEnabled] = useState(initial?.enabled ?? true);
const [optionList, setOptionList] = useState<SalespersonOptionExtended[]>([]);
const [loadingPickers, setLoadingPickers] = useState(true);
const [pickersError, setPickersError] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- loading/picker reset is the actual synchronization; initial is in the deps below.
setLoadingPickers(true);
setPickersError(null);
listSalespersonOptions()
.then((opts) => {
if (cancelled) return;
const activeOpts = opts.map((o) => ({ ...o, active: true } as SalespersonOptionExtended));
// Merge deactivated team members from initial.
const activeIds = new Set(activeOpts.map((o) => o.id));
if (initial?.team) {
for (const m of initial.team) {
if (m.id != null && !activeIds.has(m.id)) {
activeOpts.push({
id: m.id as number,
name: m.name ?? "",
username: m.username ?? "",
active: false,
});
}
}
}
setOptionList(activeOpts);
})
.catch((err: unknown) => {
if (!cancelled) {
setPickersError(err instanceof Error ? err.message : "SetupLoadOptionsFailed");
}
})
.finally(() => {
if (!cancelled) setLoadingPickers(false);
});
return () => {
cancelled = true;
};
}, [initial]);
// Build the set of initially selected team member IDs.
// Members from initial.team that are also in the active options → checked.
// Members from initial.team that are NOT in the options (deactivated) → still shown, checked, with "Inactive" marker.
const [selectedIds, setSelectedIds] = useState<Set<number>>(() => {
if (!initial?.team) return new Set<number>();
return new Set(initial.team.map((m) => m.id).filter((id): id is number => id != null));
});
function toggleSalesperson(id: number) {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const trimmedName = name.trim();
const trimmedLocation = location.trim();
const errors: Record<string, string> = {};
if (!trimmedName) errors.name = t("EvtNameRequired");
if (!trimmedLocation) errors.location = t("EvtLocationRequired");
if (!startDate) errors.startDate = t("EvtStartRequired");
if (!endDate) errors.endDate = t("EvtEndRequired");
if (endDate && startDate && endDate < startDate) errors.endDate = t("EvtEndBeforeStart");
if (trimmedName.length > 100) errors.name = t("EvtNameTooLong");
if (trimmedLocation.length > 200) errors.location = t("EvtLocationTooLong");
setFieldErrors(errors);
if (Object.keys(errors).length > 0) return;
setFormError(null);
setSaving(true);
try {
const payload: AdminEventPayload = {
name: trimmedName,
location: trimmedLocation,
startDate,
endDate,
salespersonIds: Array.from(selectedIds).filter((id): id is number => id != null),
};
// `enabled` is only sent on edit (when initial exists).
if (initial) {
payload.enabled = enabled;
}
await onSubmit(payload);
} catch (err) {
if (err instanceof Error && "status" in err && "data" in err) {
// The API sends errors[] (every missing field) and details.field (the failing field).
const data = (err as ApiError).data as { errors?: unknown; details?: { field?: unknown } } | undefined;
const missing = (Array.isArray(data?.errors) ? data.errors : []).filter((f): f is string => typeof f === "string" && Object.hasOwn(REQUIRED_MESSAGE, f));
const field = data?.details?.field;
if (missing.length > 0) {
setFieldErrors(Object.fromEntries(missing.map((f) => [f, t(REQUIRED_MESSAGE[f])])));
return;
}
if (typeof field === "string" && FIELD_ERROR_SLOTS.includes(field)) {
setFieldErrors({ [field]: err.message });
return;
}
}
setFormError(err instanceof Error ? err.message : "EvtSaveFailed");
} finally {
setSaving(false);
}
}
const label = submitLabel ?? (initial ? t("Edit") : t("Create"));
return (
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
{formError && <ErrorState message={t(formError)} />}
{pickersError && <ErrorState message={t(pickersError)} />}
<div className="space-y-1.5">
<Label htmlFor="evt-name">{t("Name")}</Label>
<Input
id="evt-name"
required
value={name}
onChange={(e) => setName(e.target.value)}
disabled={saving}
aria-invalid={!!fieldErrors.name}
/>
{fieldErrors.name && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.name}
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="evt-location">{t("Location")}</Label>
<Input
id="evt-location"
required
value={location}
onChange={(e) => setLocation(e.target.value)}
disabled={saving}
aria-invalid={!!fieldErrors.location}
/>
{fieldErrors.location && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.location}
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="evt-start">{t("EvtStartDate")}</Label>
<DatePicker
id="evt-start"
value={startDate}
onChange={setStartDate}
aria-label={t("EvtStartDate")}
required
disabled={saving}
aria-invalid={!!fieldErrors.startDate}
/>
{fieldErrors.startDate && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.startDate}
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="evt-end">{t("EvtEndDate")}</Label>
<DatePicker
id="evt-end"
value={endDate}
onChange={setEndDate}
aria-label={t("EvtEndDate")}
required
disabled={saving}
min={startDate}
aria-invalid={!!fieldErrors.endDate}
/>
{fieldErrors.endDate && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.endDate}
</p>
)}
</div>
{initial && (
<div className="space-y-1.5">
<div className="flex items-center gap-2">
<Switch
id="evt-enabled"
checked={enabled}
onCheckedChange={setEnabled}
disabled={saving}
/>
<Label htmlFor="evt-enabled">{t("Enabled")}</Label>
</div>
</div>
)}
<fieldset className="space-y-1.5">
<legend className="text-sm font-medium">{t("EvtTeamLabel")}</legend>
{fieldErrors.salespersonIds && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.salespersonIds}
</p>
)}
<div className="max-h-48 space-y-1 overflow-y-auto rounded-md border p-2">
{loadingPickers ? (
<p className="text-sm text-muted-foreground">{t("Loading")}</p>
) : (
optionList.map((opt) => {
const name = opt.name ?? "";
const username = opt.username ?? "";
const displayName = name || username || String(opt.id);
const displayUsername = name ? username : undefined;
return (
<div key={opt.id} className="flex items-center gap-2">
<Checkbox
id={`salesperson-${opt.id}`}
checked={selectedIds.has(opt.id)}
disabled={saving}
onCheckedChange={() => toggleSalesperson(opt.id)}
aria-label={displayUsername ? `${displayName} (${displayUsername})` : displayName}
/>
<Label htmlFor={`salesperson-${opt.id}`}>
{displayName}
{displayUsername && ` (${displayUsername})`}
{!opt.active && (
<span className="ml-1 text-xs text-muted-foreground">
({t("EvtInactiveMember")})
</span>
)}
</Label>
</div>
);
})
)}
</div>
</fieldset>
<Button type="submit" disabled={saving}>
{label}
</Button>
</form>
);
}
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { render } from "@testing-library/react";
import { Calendar } from "./calendar";
describe("Calendar", () => {
it("marks today, and only today, with rdp-today", () => {
const { container } = render(
<Calendar mode="single" today={new Date(2026, 9, 9)} defaultMonth={new Date(2026, 9, 1)} />,
);
const marked = Array.from(container.querySelectorAll(".rdp-today"));
expect(marked).toHaveLength(1);
expect(marked[0]).toBe(container.querySelector('[data-day="2026-10-09"]'));
});
it("keeps the today marker on a day in the middle of a selected range", () => {
const { container } = render(
<Calendar mode="range" today={new Date(2026, 9, 9)} defaultMonth={new Date(2026, 9, 1)}
selected={{ from: new Date(2026, 9, 7), to: new Date(2026, 9, 11) }} />,
);
const cell = container.querySelector('[data-day="2026-10-09"]')!;
expect(cell).toHaveClass("rdp-today", "rdp-selected", "rdp-range_middle");
});
});
@@ -0,0 +1,21 @@
"use client"
import * as React from "react"
import { DayPicker } from "react-day-picker"
import "react-day-picker/style.css"
import { cn } from "@/app/lib/utils"
/** shadcn-style Calendar on react-day-picker v10, themed by `.admin-calendar` in globals.css. */
function Calendar({ className, captionLayout = "dropdown", ...props }: React.ComponentProps<typeof DayPicker>) {
return (
<DayPicker
data-slot="calendar"
captionLayout={captionLayout}
className={cn("admin-calendar text-sm", className)}
{...props}
/>
)
}
export { Calendar }
@@ -0,0 +1,122 @@
import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { DatePicker } from "./date-picker";
import { pickDate } from "@/test/pickDate";
function Harness(props: { initial?: string; onChange?: (v: string) => void; min?: string; max?: string; disabled?: boolean }) {
const [value, setValue] = useState(props.initial ?? "");
return (
<>
<DatePicker aria-label="Expiry date" value={value} min={props.min} max={props.max} disabled={props.disabled}
onChange={(v) => { setValue(v); props.onChange?.(v); }} />
<button type="button" onClick={() => setValue("")}>reset</button>
</>
);
}
describe("DatePicker", () => {
it("opens the calendar from the keyboard", () => {
render(<Harness />);
fireEvent.keyDown(screen.getByLabelText("Expiry date"), { key: "Enter" });
expect(screen.getByRole("dialog")).toBeInTheDocument();
});
it("stays open when the box is clicked again", async () => {
const user = userEvent.setup();
render(<Harness />);
await user.click(screen.getByLabelText("Expiry date"));
await user.click(screen.getByLabelText("Expiry date"));
expect(screen.getByRole("dialog")).toBeInTheDocument();
});
it("the pickDate helper refuses a disabled day instead of silently doing nothing", () => {
render(<Harness initial="2026-09-15" min="2026-09-10" />);
expect(() => pickDate("Expiry date", "2026-09-01")).toThrow(/not an enabled day/);
});
it("opens the calendar when the box is clicked", () => {
render(<Harness />);
fireEvent.click(screen.getByLabelText("Expiry date"));
expect(screen.getByRole("dialog")).toBeInTheDocument();
});
it("ignores typing", () => {
const onChange = vi.fn();
render(<Harness onChange={onChange} />);
expect(screen.getByLabelText("Expiry date")).toHaveAttribute("readonly");
fireEvent.change(screen.getByLabelText("Expiry date"), { target: { value: "01/09/2026" } });
expect(onChange).not.toHaveBeenCalled();
expect(screen.getByLabelText("Expiry date")).toHaveValue("");
});
it("picks a date through the helper", () => {
const onChange = vi.fn();
render(<Harness onChange={onChange} />);
pickDate("Expiry date", "2026-09-01");
expect(onChange).toHaveBeenLastCalledWith("2026-09-01");
expect(screen.getByLabelText("Expiry date")).toHaveValue("01/09/2026");
});
it("Clear empties an optional field; a required one has no Clear", () => {
const onChange = vi.fn();
const { unmount } = render(<Harness initial="2026-09-01" onChange={onChange} />);
fireEvent.click(screen.getByLabelText("Expiry date"));
fireEvent.click(screen.getByRole("button", { name: "Clear" }));
expect(onChange).toHaveBeenLastCalledWith("");
unmount();
render(<DatePicker aria-label="Due" required value="2026-09-01" onChange={() => {}} />);
fireEvent.click(screen.getByLabelText("Due"));
expect(screen.queryByRole("button", { name: "Clear" })).not.toBeInTheDocument();
});
it("fills the field from a picked day", async () => {
const onChange = vi.fn();
render(<Harness initial="2026-09-15" onChange={onChange} />);
await userEvent.click(screen.getByRole("button", { name: "Open calendar for Expiry date" }));
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: /September 1st, 2026/ }));
expect(onChange).toHaveBeenLastCalledWith("2026-09-01");
expect(screen.getByLabelText("Expiry date")).toHaveValue("01/09/2026");
});
it("does not wipe the value when the selected day is clicked again", async () => {
const onChange = vi.fn();
render(<Harness initial="2026-09-15" onChange={onChange} />);
await userEvent.click(screen.getByRole("button", { name: "Open calendar for Expiry date" }));
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: /September 15th, 2026/ }));
expect(onChange).not.toHaveBeenCalledWith("");
});
it("disables days outside min and max", async () => {
render(<Harness initial="2026-09-15" min="2026-09-10" max="2026-09-20" />);
await userEvent.click(screen.getByRole("button", { name: "Open calendar for Expiry date" }));
const dialog = screen.getByRole("dialog");
expect(within(dialog).getByRole("button", { name: /September 9th, 2026/ })).toBeDisabled();
expect(within(dialog).getByRole("button", { name: /September 21st, 2026/ })).toBeDisabled();
expect(within(dialog).getByRole("button", { name: /September 10th, 2026/ })).toBeEnabled();
});
it("disables the calendar button when the field is disabled", () => {
render(<Harness disabled />);
expect(screen.getByLabelText("Expiry date")).toBeDisabled();
expect(screen.getByRole("button", { name: "Open calendar for Expiry date" })).toBeDisabled();
});
it("passes id and required to the text box so <Label htmlFor> and native validation keep working", () => {
render(<><label htmlFor="exp">Expiry</label><DatePicker id="exp" required value="" onChange={() => {}} /></>);
expect(screen.getByLabelText("Expiry")).toBeRequired();
});
});
// sales-order-no-contains-search: Input is text-base below md, which cut "DD/MM/YYYY" to "DD/MM/YYY"
// in the 120px range fields at 375px. The box is read-only, so text-sm cannot trigger iOS focus zoom.
describe("DatePicker text size", () => {
it("uses text-sm at every width so the placeholder fits", () => {
render(<Harness />);
const box = screen.getByLabelText("Expiry date");
expect(box).toHaveClass("text-sm");
expect(box).not.toHaveClass("text-base");
});
});
@@ -0,0 +1,138 @@
"use client"
import * as React from "react"
import { CalendarIcon } from "lucide-react"
import type { Matcher } from "react-day-picker"
import { Button } from "@/app/components/ui/button"
import { Calendar } from "@/app/components/ui/calendar"
import { Input } from "@/app/components/ui/input"
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover"
import { dateToIso, formatDmy, isoToDate } from "@/app/lib/date-input"
import { cn } from "@/app/lib/utils"
import { useT } from "@/app/lib/i18n/MessagesProvider"
type DmyInputProps = Omit<React.ComponentProps<"input">, "value" | "onChange" | "type" | "readOnly"> & {
value: string
onOpen: () => void
}
const OPEN_KEYS = new Set(["Enter", " ", "ArrowDown"])
/** Read-only box showing DD/MM/YYYY; the calendar is the only way to change the value. */
function DmyInput({ value, onOpen, placeholder, className, ...props }: DmyInputProps) {
const t = useT()
// text-sm at every width: Input's mobile text-base cut "DD/MM/YYYY" in the 120px range boxes; read-only, so no iOS zoom.
return (
<Input
{...props}
type="text"
readOnly
inputMode="none"
aria-haspopup="dialog"
placeholder={placeholder ?? t("UiDatePlaceholder")}
value={formatDmy(value)}
className={cn("cursor-pointer text-sm", className)}
onClick={props.disabled ? undefined : onOpen}
onKeyDown={(e) => {
if (!props.disabled && OPEN_KEYS.has(e.key)) {
e.preventDefault()
onOpen()
}
}}
/>
)
}
/** Year-dropdown range and disabled days for a min/max pair ("yyyy-MM-dd"). */
function calendarBounds(min?: string, max?: string) {
const minDate = min ? isoToDate(min) : undefined
const maxDate = max ? isoToDate(max) : undefined
const disabled: Matcher[] = []
if (minDate) disabled.push({ before: minDate })
if (maxDate) disabled.push({ after: maxDate })
return {
startMonth: minDate ?? new Date(1920, 0),
endMonth: maxDate ?? new Date(new Date().getFullYear() + 10, 11),
disabled,
}
}
interface DatePickerProps {
value: string
onChange: (iso: string) => void
id?: string
"aria-label"?: string
"aria-labelledby"?: string
"aria-invalid"?: boolean
"aria-describedby"?: string
required?: boolean
disabled?: boolean
min?: string
max?: string
placeholder?: string
className?: string
}
function DatePicker({ value, onChange, required, min, max, className, ...inputProps }: DatePickerProps) {
const t = useT()
const [open, setOpen] = React.useState(false)
const anchorRef = React.useRef<HTMLDivElement>(null)
const selected = isoToDate(value)
const bounds = calendarBounds(min, max)
const label = inputProps["aria-label"]
const labelledby = inputProps["aria-labelledby"]
const buttonId = React.useId()
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverAnchor asChild>
<div ref={anchorRef} data-slot="date-picker" className={cn("relative h-9", className)}>
<DmyInput {...inputProps} required={required} value={value} onOpen={() => setOpen(true)} className="h-full pr-12" />
<PopoverTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
disabled={inputProps.disabled}
id={buttonId}
aria-label={label ? t("UiOpenCalendarFor", { label }) : t("UiOpenCalendar")}
aria-labelledby={!label && labelledby ? `${buttonId} ${labelledby}` : undefined}
className="absolute top-0 right-0 h-full w-9"
>
<CalendarIcon />
</Button>
</PopoverTrigger>
</div>
</PopoverAnchor>
<PopoverContent className="w-auto p-3" align="start" onInteractOutside={(e) => {
// The boxes sit in PopoverAnchor, outside the content, so radix treats a click on them
// as outside and closes; keep it open (the box re-opens, the icon still toggles).
if (anchorRef.current?.contains(e.target as Node)) e.preventDefault()
}}>
<Calendar
mode="single"
selected={selected}
defaultMonth={selected ?? (bounds.endMonth < new Date() ? bounds.endMonth : undefined)}
startMonth={bounds.startMonth}
endMonth={bounds.endMonth}
disabled={bounds.disabled}
onSelect={(d) => {
if (!d) return // clicking the selected day again deselects; keep the value
onChange(dateToIso(d))
setOpen(false)
}}
/>
{!required ? (
<div className="flex justify-end border-t pt-2">
<Button type="button" variant="ghost" size="sm" onClick={() => { onChange(""); setOpen(false) }}>
{t("UiClear")}
</Button>
</div>
) : null}
</PopoverContent>
</Popover>
)
}
export { DatePicker, DmyInput, calendarBounds }
export type { DatePickerProps }
@@ -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,160 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({
getAdminEvent: vi.fn(),
saveAdminEvent: vi.fn(),
useAdminAuth: vi.fn(),
searchParamsGet: vi.fn(),
listSalespersonOptions: vi.fn().mockResolvedValue([]),
}));
vi.mock("@/app/lib/services/adminEvents", () => ({
getAdminEvent: mocks.getAdminEvent,
saveAdminEvent: mocks.saveAdminEvent,
listSalespersonOptions: mocks.listSalespersonOptions,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", () => ({
useParams: () => ({ uuid: "evt-9" }),
useSearchParams: () => ({ get: mocks.searchParamsGet }),
}));
import EditEventPage from "./page";
const EVENT = {
uuid: "evt-9",
name: "Jane",
location: "Place",
startDate: "2025-01-01",
endDate: "2025-01-02",
enabled: true,
team: [],
};
beforeEach(() => {
mocks.getAdminEvent.mockReset();
mocks.saveAdminEvent.mockReset();
mocks.listSalespersonOptions.mockReset().mockResolvedValue([]);
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
mocks.searchParamsGet.mockReset().mockReturnValue(null);
});
describe("EditEventPage", () => {
it("keeps the page header in the loading and not-found states", async () => {
mocks.getAdminEvent.mockReturnValueOnce(new Promise(() => {}));
const { unmount } = render(<EditEventPage />);
expect(screen.getByRole("heading", { level: 1, name: "Edit event" })).toBeInTheDocument();
unmount();
mocks.getAdminEvent.mockRejectedValue(new ApiError("Request failed (404)", 404));
render(<EditEventPage />);
expect(await screen.findByText(/no event found/i)).toBeInTheDocument();
expect(screen.getByRole("heading", { level: 1, name: "Edit event" })).toBeInTheDocument();
});
it("shows a loading state, then prefills the form from getAdminEvent", async () => {
mocks.getAdminEvent.mockResolvedValue(EVENT);
render(<EditEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
expect(mocks.getAdminEvent).toHaveBeenCalledWith("evt-9");
expect(screen.getByLabelText("Location")).toHaveValue("Place");
});
it("shows a not-found state when the event does not exist", async () => {
mocks.getAdminEvent.mockRejectedValue(new ApiError("Request failed (404)", 404));
render(<EditEventPage />);
expect(await screen.findByText(/no event found/i)).toBeInTheDocument();
});
it("shows an error state with retry on a load failure", async () => {
mocks.getAdminEvent.mockRejectedValueOnce(new Error("network down"));
mocks.getAdminEvent.mockResolvedValueOnce(EVENT);
render(<EditEventPage />);
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
});
it("shows the generic error state (not not-found) for a non-404 ApiError", async () => {
mocks.getAdminEvent.mockRejectedValue(new ApiError("Request failed (400)", 400));
render(<EditEventPage />);
await waitFor(() => expect(screen.getByText(/request failed \(400\)/i)).toBeInTheDocument());
expect(screen.queryByText(/no event found/i)).not.toBeInTheDocument();
});
it("submits edits by calling saveAdminEvent with the uuid", async () => {
mocks.getAdminEvent.mockResolvedValue(EVENT);
mocks.saveAdminEvent.mockResolvedValue({ ...EVENT, name: "Janet" });
render(<EditEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
await userEvent.clear(screen.getByLabelText("Name"));
await userEvent.type(screen.getByLabelText("Name"), "Janet");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() =>
expect(mocks.saveAdminEvent).toHaveBeenCalledWith(expect.objectContaining({ name: "Janet", enabled: true }), "evt-9"),
);
});
it("after a successful save shows 'Event saved.', keeps the form, updates the header and clears the team warning", async () => {
mocks.searchParamsGet.mockImplementation((key: string) => (key === "teamNotSaved" ? "1" : null));
mocks.getAdminEvent.mockResolvedValue(EVENT);
mocks.saveAdminEvent.mockResolvedValue({ ...EVENT, name: "Janet" });
render(<EditEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
await userEvent.clear(screen.getByLabelText("Name"));
await userEvent.type(screen.getByLabelText("Name"), "Janet");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("Event saved.")).toBeInTheDocument();
expect(screen.getByLabelText("Name")).toHaveValue("Janet");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Janet");
expect(screen.queryByText(/its team was not/i)).not.toBeInTheDocument();
expect(mocks.getAdminEvent).toHaveBeenCalledTimes(1);
});
it("shows the error and no 'Event saved.' banner when the save fails", async () => {
mocks.getAdminEvent.mockResolvedValue(EVENT);
mocks.saveAdminEvent.mockRejectedValue(new Error("The event could not be saved. Please try again."));
render(<EditEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText(/could not be saved/i)).toBeInTheDocument();
expect(screen.queryByText("Event saved.")).not.toBeInTheDocument();
});
it("shows the created banner when navigated here right after create", async () => {
mocks.searchParamsGet.mockImplementation((key: string) => (key === "created" ? "1" : null));
mocks.getAdminEvent.mockResolvedValue(EVENT);
render(<EditEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
expect(screen.getByText("Event created.")).toBeInTheDocument();
});
it("shows the team-not-saved warning banner", async () => {
mocks.searchParamsGet.mockImplementation((key: string) => (key === "teamNotSaved" ? "1" : null));
mocks.getAdminEvent.mockResolvedValue(EVENT);
render(<EditEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
expect(
screen.getByText("The event was saved but its team was not. Check the team and save again."),
).toBeInTheDocument();
});
it("renders NotAuthorized when the Events module is absent from aclMenu", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<EditEventPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
});
});
@@ -0,0 +1,127 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import { Alert, AlertDescription } from "@/app/components/ui/alert";
import { PageHeader } from "@/app/components/ui/page-header";
import { Skeleton } from "@/app/components/ui/skeleton";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { ApiError } from "@/app/lib/clientApi";
import { getAdminEvent, saveAdminEvent } from "@/app/lib/services/adminEvents";
import { EventForm } from "@/app/components/events/EventForm";
import type { AdminEvent, AdminEventPayload } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
function EditEventPageContent() {
const t = useT();
const { uuid } = useParams<{ uuid: string }>();
const searchParams = useSearchParams();
const [event, setEvent] = useState<AdminEvent | null>(null);
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [successMessage, setSuccessMessage] = useState<string | null>(
searchParams?.get("created") === "1"
? "EvtCreatedBanner"
: null,
);
const [teamNotSaved, setTeamNotSaved] = useState(
searchParams?.get("teamNotSaved") === "1",
);
const retry = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error/notFound ahead of the uuid/reloadKey-triggered fetch below, which is the actual synchronization.
setLoading(true);
setError(null);
setNotFound(false);
getAdminEvent(uuid)
.then((data) => {
if (!cancelled) setEvent(data);
})
.catch((err: unknown) => {
if (cancelled) return;
if (err instanceof ApiError && err.status === 404) {
setNotFound(true);
} else {
setError(err instanceof Error ? err.message : "EvtLoadFailed");
}
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [uuid, reloadKey]);
async function handleSubmit(payload: AdminEventPayload) {
const saved = await saveAdminEvent(payload, uuid);
// The form already holds what was saved; the PUT response has no team, so keep the loaded one.
setEvent((prev) => ({ ...saved, team: prev?.team }));
setSuccessMessage("EvtSaved");
setTeamNotSaved(false);
}
if (loading) {
return (
<>
<PageHeader title={t("EvtEditEvent")} />
<Skeleton className="h-64 w-full" />
</>
);
}
if (notFound) {
return (
<>
<PageHeader title={t("EvtEditEvent")} />
<EmptyState title={t("EvtNotFound", { uuid })} />
</>
);
}
if (error) {
return (
<>
<PageHeader title={t("EvtEditEvent")} />
<ErrorState message={t(error)} onRetry={retry} />
</>
);
}
if (!event) return null;
return (
<div className="space-y-4">
<PageHeader title={t("EvtEditNamed", { name: event.name })} />
{successMessage && (
<Alert>
<AlertDescription>{t(successMessage)}</AlertDescription>
</Alert>
)}
{teamNotSaved && (
<Alert variant="destructive">
<AlertDescription>{t("EvtTeamNotSaved")}</AlertDescription>
</Alert>
)}
<EventForm initial={event} onSubmit={handleSubmit} submitLabel={t("Save")} />
</div>
);
}
export default function EditEventPage() {
return (
<RequireModule pathname="/events">
<EditEventPageContent />
</RequireModule>
);
}
@@ -0,0 +1,81 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
import { pickDate } from "@/test/pickDate";
const mocks = vi.hoisted(() => ({
saveAdminEvent: vi.fn(),
useAdminAuth: vi.fn(),
push: vi.fn(),
}));
vi.mock("@/app/lib/services/adminEvents", () => ({
saveAdminEvent: mocks.saveAdminEvent,
listSalespersonOptions: vi.fn().mockResolvedValue([]),
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mocks.push }) }));
import NewEventPage from "./page";
beforeEach(() => {
mocks.saveAdminEvent.mockReset();
mocks.push.mockReset();
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
});
describe("NewEventPage", () => {
it("renders the title through the shared page header", async () => {
render(<NewEventPage />);
expect(screen.getByRole("heading", { level: 1, name: "New event" })).toBeInTheDocument();
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
});
it("renders an empty EventForm", async () => {
render(<NewEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue(""));
expect(screen.getByLabelText("Location")).toHaveValue("");
});
it("calls saveAdminEvent without a uuid and redirects to the returned event's uuid", async () => {
mocks.saveAdminEvent.mockResolvedValue({ uuid: "evt-42", name: "Jane" });
render(<NewEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Location"), "Place");
await pickDate("Start date", "2025-06-15");
await pickDate("End date", "2025-06-16");
await userEvent.click(screen.getByRole("button", { name: /create/i }));
await waitFor(() => expect(mocks.saveAdminEvent).toHaveBeenCalledTimes(1));
const payload = mocks.saveAdminEvent.mock.calls[0][0];
expect(payload.name).toBe("Jane");
await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/events/evt-42?created=1"));
});
it("when TEAM_NOT_SAVED is returned, redirects with teamNotSaved=1", async () => {
mocks.saveAdminEvent.mockRejectedValue(
new ApiError("Team not saved", 400, {
code: "TEAM_NOT_SAVED",
details: { eventUuid: "evt-99" },
}),
);
render(<NewEventPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Location"), "Place");
await pickDate("Start date", "2025-06-15");
await pickDate("End date", "2025-06-16");
await userEvent.click(screen.getByRole("button", { name: /create/i }));
await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/events/evt-99?teamNotSaved=1"));
});
it("renders NotAuthorized when the Events module is absent from aclMenu", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<NewEventPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
});
});
@@ -0,0 +1,49 @@
"use client";
import { useRouter } from "next/navigation";
import { ApiError } from "@/app/lib/clientApi";
import { ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { PageHeader } from "@/app/components/ui/page-header";
import { EventForm } from "@/app/components/events/EventForm";
import { saveAdminEvent } from "@/app/lib/services/adminEvents";
import type { AdminEventPayload } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
function NewEventPageContent() {
const t = useT();
const router = useRouter();
async function handleSubmit(payload: AdminEventPayload) {
try {
const created = await saveAdminEvent(payload);
if (created.uuid) {
router.push(`/events/${created.uuid}?created=1`);
}
} catch (err) {
if (err instanceof ApiError) {
const data = err.data as { code?: string; details?: { eventUuid?: string } } | undefined;
if (data?.code === "TEAM_NOT_SAVED" && data.details?.eventUuid) {
router.push(`/events/${data.details.eventUuid}?teamNotSaved=1`);
return;
}
}
throw err;
}
}
return (
<>
<PageHeader title={t("EvtNewEvent")} />
<EventForm onSubmit={handleSubmit} submitLabel={t("Create")} />
</>
);
}
export default function NewEventPage() {
return (
<RequireModule pathname="/events">
<NewEventPageContent />
</RequireModule>
);
}
@@ -0,0 +1,174 @@
import { act, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAdminEvents: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminEvents", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminEvents")>()),
listAdminEvents: mocks.listAdminEvents,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import EventsPage from "./page";
beforeEach(() => {
memoryRouter.reset("/events");
mocks.listAdminEvents.mockReset();
mocks.useAdminAuth.mockReset();
mocks.useAdminAuth.mockReturnValue({
loading: false,
hasModule: () => true,
});
});
// unify-admin-listing-toolbar: "Send password reset" sits in the row's ⋯ menu, not as a row button.
async function openResetFromRowMenu() {
await userEvent.click(screen.getAllByRole("button", { name: /more actions for/i })[0]);
await userEvent.click(await screen.findByRole("menuitem", { name: /send password reset/i }));
}
describe("EventsPage filters", () => {
beforeEach(() => mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 }));
it("sends q after the debounce, as page 1, and puts it in the URL", async () => {
const user = userEvent.setup();
render(<EventsPage />);
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalled());
await user.type(screen.getByRole("searchbox", { name: "Event name" }), "jane");
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(expect.objectContaining({ q: "jane", page: 1 })));
expect(memoryRouter.getSearch().get("q")).toBe("jane");
expect(mocks.listAdminEvents.mock.calls.filter((c) => (c[0] as { q?: string }).q).length).toBe(1);
});
it("sends enabled from the Status filter", async () => {
const user = userEvent.setup();
render(<EventsPage />);
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalled());
await user.click(screen.getByRole("combobox", { name: /status filter/i }));
await user.click(await screen.findByRole("option", { name: "Disabled" }));
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(expect.objectContaining({ enabled: "N", page: 1 })));
expect(memoryRouter.getSearch().get("enabled")).toBe("N");
});
it("populates the controls and the request from the URL on mount", async () => {
memoryRouter.reset("/events", "enabled=Y&q=jo");
render(<EventsPage />);
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(expect.objectContaining({ enabled: "Y", q: "jo" })));
expect(screen.getByRole("searchbox", { name: "Event name" })).toHaveValue("jo");
expect(screen.getByRole("combobox", { name: /status filter/i })).toHaveTextContent("Enabled");
});
it("Clear filters empties the URL", async () => {
memoryRouter.reset("/events", "enabled=Y&q=jo");
render(<EventsPage />);
await userEvent.click(await screen.findByRole("button", { name: "Clear filters" }));
await waitFor(() => expect(memoryRouter.getSearch().toString()).toBe(""));
});
});
describe("EventsPage", () => {
it("shows the empty state when there are no events", async () => {
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
render(<EventsPage />);
await waitFor(() => expect(screen.getByText(/no events/i)).toBeInTheDocument());
});
it("shows the error state and lets the user retry on a load failure", async () => {
mocks.listAdminEvents.mockRejectedValueOnce(new Error("network down"));
mocks.listAdminEvents.mockResolvedValueOnce({ items: [], total: 0 });
render(<EventsPage />);
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalledTimes(2));
});
it("links the New event button to the create form", async () => {
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
render(<EventsPage />);
await waitFor(() => expect(screen.getByText(/no events/i)).toBeInTheDocument());
const addEventLink = screen.getByRole("link", { name: /new event/i });
expect(addEventLink).toHaveAttribute("href", "/events/new");
expect(addEventLink).not.toHaveAttribute("aria-disabled");
});
it("links each event row to its edit page", async () => {
mocks.listAdminEvents.mockResolvedValue({
items: [{ uuid: "abc-123", name: "My Event", location: "Hall A", startDate: "2025-06-15", endDate: "2025-06-16", enabled: true, team: [] }],
total: 1,
});
render(<EventsPage />);
const edit = await screen.findByRole("link", { name: "Edit My Event" });
expect(edit).toHaveAttribute("href", "/events/abc-123");
expect(screen.getByRole("link", { name: "My Event" })).toHaveAttribute("href", "/events/abc-123");
});
it("renders NotAuthorized when the Events module is absent from aclMenu", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<EventsPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
});
it("shows a toned status badge under a level-1 heading", async () => {
mocks.listAdminEvents.mockResolvedValue({
items: [
{ uuid: "e1", name: "A", location: "Place", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, team: [] },
{ uuid: "e2", name: "B", location: "Place2", startDate: "2025-02-01", endDate: "2025-02-02", enabled: false, team: [] },
],
total: 2,
});
render(<EventsPage />);
expect(await screen.findByText("Enabled")).toHaveAttribute("data-variant", "positive");
expect(screen.getByText("Disabled")).toHaveAttribute("data-variant", "neutral");
expect(screen.getByRole("heading", { level: 1, name: "Events" })).toBeInTheDocument();
});
it("End column header requests sortBy endDate", async () => {
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
render(<EventsPage />);
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalled());
await userEvent.click(await screen.findByRole("button", { name: /end date/i }));
await waitFor(() =>
expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(
expect.objectContaining({ sortBy: "endDate" }),
),
);
});
it("Start column header requests sortBy startDate", async () => {
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
render(<EventsPage />);
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalled());
await userEvent.click(await screen.findByRole("button", { name: /start date/i }));
await waitFor(() =>
expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(
expect.objectContaining({ sortBy: "startDate" }),
),
);
});
it("Edit action navigates to the edit page", async () => {
mocks.listAdminEvents.mockResolvedValue({
items: [{ uuid: "evt-55", name: "Test Event", location: "Room", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, team: [] }],
total: 1,
});
render(<EventsPage />);
await waitFor(() => expect(screen.getByText("Test Event")).toBeInTheDocument());
await userEvent.click(screen.getAllByRole("button", { name: /more actions for/i })[0]);
await userEvent.click(await screen.findByRole("menuitem", { name: /edit/i }));
expect(memoryRouter.push).toHaveBeenCalledWith("/events/evt-55");
});
});
+174
View File
@@ -0,0 +1,174 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Pencil, 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, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
import { DataTable } from "@/app/components/ui/data-table";
import { PageHeader } from "@/app/components/ui/page-header";
import { RowActions } from "@/app/components/ui/row-actions";
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 { listAdminEvents } from "@/app/lib/services/adminEvents";
import type { AdminEvent } from "@/app/lib/types";
import { useTableSort } from "@/app/lib/hooks/useTableSort";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { formatDmy } from "@/app/lib/date-input";
const DEFAULTS = { q: "", enabled: "" };
export const EVENT_STATUS_FILTER_OPTIONS = [{ value: "Y", label: "Enabled" }, { value: "N", label: "Disabled" }];
function EventsPageContent() {
const t = useT();
const router = useRouter();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
const { sorting, onSortingChange, sortBy, sortDir } = useTableSort();
const [data, setData] = useState<{ items: AdminEvent[]; total: number }>({ items: [], total: 0 });
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
if (pageSize == null) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
setLoading(true);
setError(null);
listAdminEvents({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir })
.then((result) => {
if (!cancelled) setData(result);
})
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : "EvtListLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [filters, page, reloadKey, pageSize, sortBy, sortDir]);
const statusOptions = useMemo(
() => EVENT_STATUS_FILTER_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
[t],
);
const columns = useMemo<ColumnDef<AdminEvent, unknown>[]>(
() => [
{
accessorKey: "name",
header: t("Name"),
cell: ({ row }) => (
<Link href={`/events/${row.original.uuid}`} className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
{row.original.name}
</Link>
),
},
{ accessorKey: "location", header: t("Location"), enableSorting: false },
{
accessorKey: "startDate",
header: t("EvtStartDate"),
cell: ({ row }) => <span>{formatDmy(row.original.startDate)}</span>,
},
{
accessorKey: "endDate",
header: t("EvtEndDate"),
cell: ({ row }) => <span>{formatDmy(row.original.endDate)}</span>,
},
{
accessorKey: "enabled",
header: t("Status"),
enableSorting: false,
cell: ({ row }) => (
<Badge variant={row.original.enabled ? "positive" : "neutral"}>
{row.original.enabled ? t("Enabled") : t("Disabled")}
</Badge>
),
},
{
id: "actions",
enableSorting: false,
header: t("CatActions"),
meta: { numeric: true },
cell: ({ row }) => (
<RowActions
label={row.original.name}
items={[{
label: t("EvtEdit"),
onSelect: () => router.push(`/events/${row.original.uuid}`),
}]}
>
<Button variant="ghost" size="sm" asChild className="h-8 px-2">
<Link href={`/events/${row.original.uuid}`} aria-label={t("EvtEditNamed", { name: row.original.name })}>
<Pencil aria-hidden="true" className="size-3.5" />
</Link>
</Button>
</RowActions>
),
},
],
[t, router],
);
return (
<>
<PageHeader
title={t("BO_EVENTS")}
actions={
<Button asChild>
<Link href="/events/new">
<Plus aria-hidden="true" className="size-4" />
{t("EvtNewEvent")}
</Link>
</Button>
}
/>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
<FilterPanel activeCount={activeCount} onClear={clear}>
<FilterField label={t("EvtEventNameFilter")}>
<FilterSearch className="w-full" aria-label={t("EvtEventNameFilter")} placeholder={t("EvtEventNameFilter")} value={filters.q} onChange={q => set({ q })} />
</FilterField>
<FilterField label={t("EvtStatusFilter")}>
<FilterSelect className="w-full" aria-label={t("EvtStatusFilter")} allLabel={t("AllStatuses")} options={statusOptions} value={filters.enabled} onChange={enabled => set({ enabled })} />
</FilterField>
</FilterPanel>
<DataTable
label={t("BO_EVENTS")}
columns={columns}
data={data.items}
total={data.total}
page={page}
pageSize={pageSize ?? MIN_PAGE_SIZE}
sorting={sorting}
onSortingChange={onSortingChange}
tableRef={tableRef}
onPageChange={setPage}
isLoading={loading}
rowKey={(e) => String(e.uuid)}
empty={<EmptyState title={activeCount > 0 ? t("EvtNoMatch") : t("EvtNoEvents")} />}
/>
</>
);
}
export default function EventsPage() {
return (
<RequireModule pathname="/events">
<EventsPageContent />
</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();
});
});
+284
View File
@@ -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>
);
}
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { dateToIso, formatDmy, isoToDate } from "./date-input";
describe("formatDmy", () => {
it("formats ISO as DD/MM/YYYY", () => {
expect(formatDmy("1990-03-14")).toBe("14/03/1990");
});
it("returns empty for non-ISO input", () => {
expect(formatDmy("")).toBe("");
expect(formatDmy("14/03/1990")).toBe("");
});
});
describe("isoToDate / dateToIso", () => {
it("uses local date parts, not UTC", () => {
const d = isoToDate("1990-03-14")!;
expect([d.getFullYear(), d.getMonth(), d.getDate()]).toEqual([1990, 2, 14]);
expect(dateToIso(new Date(1990, 2, 14, 0, 30))).toBe("1990-03-14");
});
it("isoToDate returns undefined for empty or invalid", () => {
expect(isoToDate("")).toBeUndefined();
expect(isoToDate("1990-02-31")).toBeUndefined();
});
});
@@ -0,0 +1,24 @@
const pad = (n: number) => String(n).padStart(2, "0");
/** Local-midnight Date for y/m/d, or undefined when the parts are not a real calendar day. */
function realDate(y: number, m: number, d: number): Date | undefined {
const dt = new Date(y, m - 1, d);
return dt.getFullYear() === y && dt.getMonth() === m - 1 && dt.getDate() === d ? dt : undefined;
}
/** "yyyy-MM-dd" → "DD/MM/YYYY"; "" for anything else. */
export function formatDmy(iso: string): string {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
return m ? `${m[3]}/${m[2]}/${m[1]}` : "";
}
/** "yyyy-MM-dd" → local-midnight Date; undefined for "" or an impossible date. */
export function isoToDate(iso: string): Date | undefined {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
return m ? realDate(Number(m[1]), Number(m[2]), Number(m[3])) : undefined;
}
/** Date → "yyyy-MM-dd" from LOCAL parts (toISOString would shift the day in UTC+8). */
export function dateToIso(d: Date): string {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
@@ -129,6 +129,10 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
UsrCreatedNoEmail: "User created, but the temporary password email could not be sent. Open the user from the users list and use Send password reset to try again.",
UsrBackToUsers: "Back to users",
AdminPasswordHint: "At least 8 characters, with at least one capital letter and one small letter.",
UiDatePlaceholder: "DD/MM/YYYY",
UiOpenCalendarFor: "Open calendar for {label}",
UiOpenCalendar: "Open calendar",
UiClear: "Clear",
UsrLoadFailed: "Failed to load user",
UsrSaved: "User saved.",
UsrResetSent: "Password reset email sent to {email}.",
@@ -170,4 +174,110 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
RolManageAccess: "Manage access",
RolNoRoles: "No roles found",
No: "No",
// Event form messages
EvtNameRequired: "Name is required.",
EvtLocationRequired: "Location is required.",
EvtStartDate: "Start date",
EvtEndDate: "End date",
EvtStartRequired: "Start date is required.",
EvtEndRequired: "End date is required.",
EvtEndBeforeStart: "End date must not be before start date.",
EvtNameTooLong: "Name must be 100 characters or fewer.",
EvtLocationTooLong: "Location must be 200 characters or fewer.",
EvtSaveFailed: "Failed to save event.",
EvtInactiveMember: "Inactive",
EvtTeamLabel: "Team",
Location: "Location",
Create: "Create",
BO_EVENTS: "Events",
EvtNewEvent: "New event",
EvtEdit: "Edit",
EvtNoEvents: "No events found",
EvtNoMatch: "No events match your filters",
EvtListLoadFailed: "Failed to load events",
EvtLoadFailed: "Failed to load event",
EvtEditEvent: "Edit event",
EvtEditNamed: "Edit {name}",
EvtNotFound: "No event found for \"{uuid}\"",
EvtCreatedBanner: "Event created.",
EvtSaved: "Event saved.",
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,14 +3,17 @@ 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");
expect(requiredModulesFor("/roles")).toEqual(["BO_ROLES"]);
});
it("leaves other routes ungated", () => {
expect(requiredModuleFor("/")).toBeUndefined();
expect(requiredModulesFor("/members")).toBeUndefined();
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/roles", "/users"]);
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/event-leads", "/events", "/interests", "/roles", "/users"]);
});
});
@@ -5,6 +5,9 @@
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,83 @@
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 {
listAdminEvents,
getAdminEvent,
saveAdminEvent,
listSalespersonOptions,
} from "./adminEvents";
import type { AdminEventPayload } from "@/app/lib/types";
beforeEach(() => {
mocks.apiGet.mockReset();
mocks.apiPost.mockReset();
mocks.apiPut.mockReset();
});
describe("listAdminEvents", () => {
it("translates 1-based page to a 0-based query and normalizes the page shape", async () => {
mocks.apiGet.mockResolvedValue({ content: [{ uuid: "e1" }], totalElements: 1 });
const result = await listAdminEvents({ page: 2, pageSize: 20 });
expect(mocks.apiGet).toHaveBeenCalledWith("/api/events?page=1&size=20");
expect(result).toEqual({ items: [{ uuid: "e1" }], total: 1 });
});
it("sends q, enabled, sortBy, sortDir when given", async () => {
mocks.apiGet.mockResolvedValue({ content: [], totalElements: 0 });
await listAdminEvents({ q: "event", enabled: "true", page: 1, pageSize: 20, sortBy: "name", sortDir: "asc" });
expect(mocks.apiGet).toHaveBeenCalledWith("/api/events?q=event&enabled=true&page=0&size=20&sortBy=name&sortDir=asc");
});
});
describe("getAdminEvent", () => {
it("calls GET /api/events/{uuid}", async () => {
mocks.apiGet.mockResolvedValue({ uuid: "abc-123", name: "Event" });
const result = await getAdminEvent("abc-123");
expect(mocks.apiGet).toHaveBeenCalledWith("/api/events/abc-123");
expect(result).toEqual({ uuid: "abc-123", name: "Event" });
});
});
describe("saveAdminEvent", () => {
it("POSTs when no uuid given", async () => {
mocks.apiPost.mockResolvedValue({ uuid: "new-1", name: "New Event" });
const payload: AdminEventPayload = {
name: "New Event",
location: "Place",
startDate: "2025-01-01",
endDate: "2025-01-02",
enabled: true,
salespersonIds: [],
};
const result = await saveAdminEvent(payload);
expect(mocks.apiPost).toHaveBeenCalledWith("/api/events", payload);
expect(result).toEqual({ uuid: "new-1", name: "New Event" });
});
it("PUTs to /api/events/{uuid} when uuid is present", async () => {
mocks.apiPut.mockResolvedValue({ uuid: "existing", name: "Updated" });
const payload: AdminEventPayload = {
name: "Updated",
location: "Place",
startDate: "2025-01-01",
endDate: "2025-01-02",
enabled: true,
salespersonIds: [],
};
const result = await saveAdminEvent(payload, "existing");
expect(mocks.apiPut).toHaveBeenCalledWith("/api/events/existing", payload);
expect(result).toEqual({ uuid: "existing", name: "Updated" });
});
});
describe("listSalespersonOptions", () => {
it("calls GET /api/events/salesperson-options", async () => {
mocks.apiGet.mockResolvedValue([{ id: 1, name: "Jane", username: "jane.doe" }]);
const result = await listSalespersonOptions();
expect(mocks.apiGet).toHaveBeenCalledWith("/api/events/salesperson-options");
expect(result).toEqual([{ id: 1, name: "Jane", username: "jane.doe" }]);
});
});
@@ -0,0 +1,50 @@
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
import type { AdminEvent, AdminEventPayload, SalespersonOption } from "@/app/lib/types";
export interface AdminEventListParams {
q?: string;
enabled?: string;
page: number;
pageSize: number;
sortBy?: string;
sortDir?: "asc" | "desc";
}
export interface AdminEventListResult {
items: AdminEvent[];
total: number;
}
export function normalizeAdminEventPage(raw: unknown): AdminEventListResult {
if (!raw || typeof raw !== "object") return { items: [], total: 0 };
const obj = raw as Record<string, unknown>;
const events = Array.isArray(obj.content) ? (obj.content as AdminEvent[]) : [];
const total = typeof obj.totalElements === "number" ? obj.totalElements : events.length;
return { items: events, total };
}
export async function listAdminEvents(params: AdminEventListParams): Promise<AdminEventListResult> {
const qs = new URLSearchParams();
if (params.q) qs.set("q", params.q);
if (params.enabled) qs.set("enabled", params.enabled);
qs.set("page", String(Math.max(0, params.page - 1)));
qs.set("size", String(params.pageSize));
if (params.sortBy) qs.set("sortBy", params.sortBy);
if (params.sortDir && params.sortBy) qs.set("sortDir", params.sortDir);
const raw = await apiGet<unknown>(`/api/events?${qs.toString()}`);
return normalizeAdminEventPage(raw);
}
export async function getAdminEvent(uuid: string): Promise<AdminEvent> {
return apiGet<AdminEvent>(`/api/events/${uuid}`);
}
export async function saveAdminEvent(payload: AdminEventPayload, uuid?: string): Promise<AdminEvent> {
return uuid
? apiPut<AdminEvent>(`/api/events/${uuid}`, payload)
: apiPost<AdminEvent>("/api/events", payload);
}
export async function listSalespersonOptions(): Promise<SalespersonOption[]> {
return apiGet<SalespersonOption[]>("/api/events/salesperson-options");
}
@@ -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);
}
+118
View File
@@ -115,3 +115,121 @@ export interface ModuleGrantRow {
parentId: number | null;
granted: boolean;
}
/** An event as returned by the mobile admin API and displayed in the portal. */
export interface AdminEvent {
uuid: string;
name: string;
location: string;
startDate: string;
endDate: string;
enabled: boolean;
team?: AdminEventMember[];
}
export interface AdminEventMember {
id: number;
name: string | null;
username: string | null;
enabled: boolean;
}
/** Payload shape for creating/updating an event via the BFF client API. */
export interface AdminEventPayload {
name: string;
location: string;
startDate: string;
endDate: string;
enabled?: boolean;
salespersonIds: number[];
}
/** A salesperson row from the salesperson-options endpoint. */
export interface SalespersonOption {
id: number;
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) => {
+43
View File
@@ -15,6 +15,7 @@
"next": "^16.4.5",
"radix-ui": "^1.6.7",
"react": "^19.2.8",
"react-day-picker": "10.0.1",
"react-dom": "^19.2.8",
"tailwind-merge": "^3.6.0"
},
@@ -513,6 +514,12 @@
"node": ">=20.19.0"
}
},
"node_modules/@date-fns/tz": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.5.0.tgz",
"integrity": "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==",
"license": "MIT"
},
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
@@ -5304,6 +5311,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/date-fns": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz",
"integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -8670,6 +8687,32 @@
"node": ">=0.10.0"
}
},
"node_modules/react-day-picker": {
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-10.0.1.tgz",
"integrity": "sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w==",
"license": "MIT",
"dependencies": {
"@date-fns/tz": "^1.4.1",
"date-fns": "^4.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/gpbl"
},
"peerDependencies": {
"@types/react": ">=16.8.0",
"react": ">=16.8.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/react-dom": {
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
+1
View File
@@ -21,6 +21,7 @@
"next": "^16.4.5",
"radix-ui": "^1.6.7",
"react": "^19.2.8",
"react-day-picker": "10.0.1",
"react-dom": "^19.2.8",
"tailwind-merge": "^3.6.0"
},
+32
View File
@@ -0,0 +1,32 @@
import { fireEvent, screen, within } from "@testing-library/react";
function topPopover() {
const dialogs = screen.getAllByRole("dialog");
return dialogs[dialogs.length - 1];
}
/** Shows `iso`'s month in the popover's first calendar month and clicks the day. */
function clickDay(pop: HTMLElement, iso: string) {
const [month, year] = within(pop).getAllByRole("combobox");
const [y, m] = iso.split("-").map(Number);
fireEvent.change(year, { target: { value: String(y) } });
fireEvent.change(month, { target: { value: String(m - 1) } });
const day = pop.querySelector<HTMLButtonElement>(`[data-day="${iso}"] button`);
// A disabled day ignores the click, so fail loudly instead of letting the test pass vacuously.
if (!day || day.disabled) throw new Error(`pickDate: ${iso} is not an enabled day in the calendar`);
fireEvent.click(day);
}
/** Picks `iso` (yyyy-MM-dd) in the calendar of the date box labelled `label`. */
export function pickDate(label: string | RegExp | HTMLElement, iso: string) {
fireEvent.click(label instanceof HTMLElement ? label : screen.getByLabelText(label));
clickDay(topPopover(), iso);
}
/** Picks the range `from`–`to` in the calendar of the range box labelled `fromLabel`. */
export function pickRange(fromLabel: string | RegExp, from: string, to: string) {
fireEvent.click(screen.getByLabelText(fromLabel));
const pop = topPopover();
clickDay(pop, from);
clickDay(pop, to);
}
+6
View File
@@ -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>
@@ -32,6 +32,20 @@ public class RestApiCounterServiceConstants {
public static final String API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_MEMBER_UUID="/counter/eventRedeemCode/findByMemberUuid/{memberUuid}";
public static final String API_REST_COUNTER_EVENT_FIND_BY_UUID="/counter/event/findByUuid/{uuid}";
//Event admin
public static final String API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE="/counter/event/findByPropertyAndPageable";
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,56 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminEventRequest;
import com.solvway.mobile.api.service.AdminEventService;
import com.solvway.mobile.api.useraccess.AdminModule;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/** Admin events and their salesperson teams. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminEventController {
private final AdminEventService adminEventService;
@AppAuth
@AdminModule("BO_EVENTS")
@GetMapping("/events")
public ResponseEntity<Map<String, Object>> list(@RequestParam(required = false) String q,
@RequestParam(required = false) String enabled,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String sortBy,
@RequestParam(required = false) String sortDir) {
return ResponseEntity.ok(adminEventService.list(q, enabled, page, size, sortBy, sortDir));
}
@AppAuth
@AdminModule("BO_EVENTS")
@GetMapping("/events/salesperson-options")
public ResponseEntity<List<Map<String, Object>>> salespersonOptions() {
return ResponseEntity.ok(adminEventService.salespersonOptions());
}
@AppAuth
@AdminModule("BO_EVENTS")
@GetMapping("/events/{uuid}")
public ResponseEntity<Map<String, Object>> getByUuid(@PathVariable String uuid) {
return ResponseEntity.ok(adminEventService.get(uuid));
}
@AppAuth
@AdminModule("BO_EVENTS")
@PostMapping("/events")
public ResponseEntity<Map<String, Object>> create(@RequestBody AdminEventRequest request) {
return ResponseEntity.ok(adminEventService.create(request));
}
@AppAuth
@AdminModule("BO_EVENTS")
@PutMapping("/events/{uuid}")
public ResponseEntity<Map<String, Object>> update(@PathVariable String uuid, @RequestBody AdminEventRequest request) {
return ResponseEntity.ok(adminEventService.update(uuid, request));
}
}
@@ -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,9 @@
package com.solvway.mobile.api.dto.admin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
/** Create/update body. Dates are kept as text so a malformed date answers INVALID_DATE, not a bind error. enabled is update-only. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List<Long> salespersonIds) {}
@@ -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,260 @@
package com.solvway.mobile.api.service;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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.AdminEventRequest;
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.util.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/**
* Admin events for the portal. The event table lives in services-counter, users in services-system, so this
* validates, maps to and from the counter's Event, and resolves team members through services-system.
* Event uuids are Snowflake values beyond JavaScript's number precision, so they leave here as strings.
*/
@Service
@RequiredArgsConstructor
public class AdminEventService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<EventPage> PAGE = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<Event> EVENT = new ParameterizedTypeReference<>() {};
private static final Map<String, String> SORTS = Map.of("name", "name", "startDate", "dateStart", "endDate", "dateEnd");
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
/** The slice of a Spring Page this service reads. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record EventPage(List<Event> content, long totalElements, int totalPages, int number, int size) {}
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir) {
Map<String, Object> property = new LinkedHashMap<>();
property.put("name", q == null ? "" : q.trim());
property.put("enabled", "Y".equals(enabled) || "N".equals(enabled) ? enabled : "");
Map<String, Object> sort = Map.of("direction", "desc".equalsIgnoreCase(sortDir) ? "DESC" : "ASC",
"property", sortBy == null ? "name" : SORTS.getOrDefault(sortBy, "name"));
Map<String, Object> request = Map.of("property", property,
"pageableRest", Map.of("number", Math.max(page, 0), "size", Math.max(size, 1), "sorts", List.of(sort)));
EventPage p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE), PAGE, request).getBody();
if (p == null) return Map.of("content", List.of(), "totalElements", 0L, "totalPages", 0, "number", 0, "size", Math.max(size, 1));
return Map.of("content", p.content() == null ? List.of() : p.content().stream().map(AdminEventService::row).toList(), "totalElements", p.totalElements(),
"totalPages", p.totalPages(), "number", p.number(), "size", p.size());
}
public Map<String, Object> get(String uuid) {
Event event = load(uuid);
Map<String, Object> out = row(event);
List<Map<String, Object>> team = new ArrayList<>();
for (Long id : teamIds(event.getUuid())) {
Map<String, Object> user = user(id);
Map<String, Object> member = new LinkedHashMap<>();
member.put("id", id);
member.put("name", user == null ? null : user.get("name"));
member.put("username", user == null ? null : user.get("username"));
member.put("enabled", user != null && Boolean.TRUE.equals(user.get("enabled")));
team.add(member);
}
out.put("team", team);
return out;
}
public Map<String, Object> create(AdminEventRequest r) {
Fields f = validate(r);
User caller = caller();
List<Long> team = checkedTeam(r.salespersonIds(), List.of());
Event event = new Event();
apply(event, f);
event.setCreateBy(caller.getUsername());
event.setDoneBy(caller.getUsername());
Event saved = save(event);
replaceTeam(saved.getUuid(), team, caller);
return row(saved);
}
public Map<String, Object> update(String uuid, AdminEventRequest r) {
Fields f = validate(r);
User caller = caller();
Event event = load(uuid);
List<Long> team = r.salespersonIds() == null ? null : checkedTeam(r.salespersonIds(), teamIds(event.getUuid()));
apply(event, f);
if (r.enabled() != null) event.setEnabled(r.enabled() ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N);
event.setDoneBy(caller.getUsername());
Event saved = save(event);
if (team != null) replaceTeam(saved.getUuid(), team, caller);
return row(saved);
}
public List<Map<String, Object>> salespersonOptions() {
Map<String, Object> request = Map.of("property", Map.of("type", "A"),
"pageableRest", Map.of("number", 0, "size", 10000, "sorts", List.of(Map.of("direction", "ASC", "property", "id"))));
Map<String, Object> body = restTemplateUtil.postForEntity(
url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request).getBody();
List<Map<String, Object>> all = body == null || body.get("content") == null ? List.of() : (List<Map<String, Object>>) body.get("content");
// ponytail: loads all admins (staff-sized) like AdminUserService.list; not company-scoped yet.
return all.stream().filter(AdminEventService::isActiveAdmin)
.sorted(Comparator.comparing(m -> String.valueOf(m.get("name")).toLowerCase()))
.map(m -> {
Map<String, Object> o = new LinkedHashMap<>();
o.put("id", ((Number) m.get("id")).longValue());
o.put("name", m.get("name"));
o.put("username", m.get("username"));
return o;
}).toList();
}
private record Fields(String name, String location, LocalDate start, LocalDate end) {}
private static Fields validate(AdminEventRequest r) {
if (r == null) throw error(HttpStatus.BAD_REQUEST, "Name, location, start date and end date are required", "REQUIRED_FIELD", "name");
Map<String, String> in = new LinkedHashMap<>();
in.put("name", r.name());
in.put("location", r.location());
in.put("startDate", r.startDate());
in.put("endDate", r.endDate());
List<String> missing = in.entrySet().stream().filter(e -> !StringUtils.hasText(e.getValue())).map(Map.Entry::getKey).toList();
if (!missing.isEmpty()) {
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: " + String.join(", ", missing), "REQUIRED_FIELD", missing.get(0));
e.getBody().setProperty("errors", missing);
throw e;
}
String name = r.name().trim();
String location = r.location().trim();
if (name.length() > 100) throw error(HttpStatus.BAD_REQUEST, "Name is at most 100 characters", "TOO_LONG", "name");
if (location.length() > 200) throw error(HttpStatus.BAD_REQUEST, "Location is at most 200 characters", "TOO_LONG", "location");
LocalDate start = date(r.startDate(), "startDate");
LocalDate end = date(r.endDate(), "endDate");
if (end.isBefore(start)) throw error(HttpStatus.BAD_REQUEST, "End date is before the start date", "END_BEFORE_START", "endDate");
return new Fields(name, location, start, end);
}
private static LocalDate date(String s, String field) {
try {
return LocalDate.parse(s.trim());
} catch (DateTimeParseException e) {
throw error(HttpStatus.BAD_REQUEST, field + " must be a date as YYYY-MM-DD", "INVALID_DATE", field);
}
}
private static void apply(Event e, Fields f) {
e.setName(f.name());
e.setLocation(f.location());
e.setDateStart(f.start().atStartOfDay());
e.setDateEnd(LocalDateTime.of(f.end(), LocalTime.of(23, 59, 59)));
}
/**
* Duplicates collapse; every id added to the team must be an enabled admin user. Someone already on the team
* stays even if deactivated since, so an unrelated edit does not fail until an admin removes them.
*/
private List<Long> checkedTeam(List<Long> ids, List<Long> current) {
List<Long> team = ids == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(ids));
for (Long id : team) {
if (id == null || !current.contains(id) && !isActiveAdmin(user(id))) {
throw error(HttpStatus.BAD_REQUEST, "Unknown or inactive admin user " + id, "UNKNOWN_USER", "salespersonIds");
}
}
return team;
}
private static boolean isActiveAdmin(Map<String, Object> user) {
return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled"));
}
private Map<String, Object> user(Long id) {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody();
}
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();
}
/** The event already exists when this fails, so the client gets the uuid to retry the team save on. */
private void replaceTeam(long eventUuid, List<Long> userIds, User caller) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("eventUuid", eventUuid);
body.put("companyId", caller.getCompanyId());
body.put("userIds", userIds);
body.put("doneBy", caller.getUsername());
try {
restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_REPLACE), MAP_LIST, body);
} catch (RuntimeException ex) {
CodedResponseStatusException e = error(HttpStatus.BAD_GATEWAY,
"Event " + eventUuid + " was saved but its team was not; save the team again", "TEAM_NOT_SAVED", null);
e.getBody().setProperty("details", Map.of("eventUuid", String.valueOf(eventUuid)));
throw e;
}
}
private Event load(String uuid) {
long id;
try {
id = Long.parseLong(uuid);
} catch (NumberFormatException e) {
throw notFound();
}
Event event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
if (event == null) throw notFound();
return event;
}
private Event save(Event event) {
Event saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SAVE), EVENT, event).getBody();
if (saved == null) throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Event could not be saved", "SAVE_FAILED", null);
return saved;
}
private static Map<String, Object> row(Event 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());
m.put("enabled", e.getEnabled() == GeneralEnum.FlagYesNo.Y);
return m;
}
private User caller() {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
return caller;
}
private String url(String api) {
return restTemplateUtil.getURLforApiService(api);
}
private static CodedResponseStatusException notFound() {
return error(HttpStatus.NOT_FOUND, "Event not found", "EVENT_NOT_FOUND", null);
}
/** field, when given, rides in the ProblemDetail's details (the portal forwards code, errors and flat details only). */
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,100 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminEventRequest;
import com.solvway.mobile.api.service.AdminEventService;
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.ArgumentCaptor;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
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 AdminEventControllerTest {
@Mock private AdminEventService events;
@InjectMocks private AdminEventController controller;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
private static Map<String, Object> row() {
Map<String, Object> m = new LinkedHashMap<>();
m.put("uuid", "7123456789012345678");
m.put("name", "Fair");
return m;
}
@Test
void everyHandlerIsAuthenticatedAndGuardedByBoEvents() {
List<Method> handlers = Arrays.stream(AdminEventController.class.getDeclaredMethods())
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
assertThat(handlers).hasSize(5);
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_EVENTS");
}
}
@Test
void get_uuidIsAJsonString() throws Exception {
when(events.get("7123456789012345678")).thenReturn(row());
mvc.perform(get("/api/admin/events/7123456789012345678")).andExpect(status().isOk())
.andExpect(content().json("{\"uuid\":\"7123456789012345678\",\"name\":\"Fair\"}", true));
}
@Test
void list_passesQueryParamsAndDefaults() throws Exception {
when(events.list(any(), any(), eq(0), eq(20), any(), any())).thenReturn(Map.of("content", List.of(row()), "totalElements", 1));
mvc.perform(get("/api/admin/events").param("q", "food").param("enabled", "Y").param("sortBy", "endDate").param("sortDir", "desc"))
.andExpect(status().isOk())
.andExpect(content().json("{\"content\":[{\"uuid\":\"7123456789012345678\"}],\"totalElements\":1}"));
verify(events).list("food", "Y", 0, 20, "endDate", "desc");
}
@Test
void salespersonOptions_isNotShadowedByTheUuidRoute() throws Exception {
when(events.salespersonOptions()).thenReturn(List.of(Map.of("id", 1, "name", "Amy", "username", "amy")));
mvc.perform(get("/api/admin/events/salesperson-options")).andExpect(status().isOk())
.andExpect(content().json("[{\"id\":1,\"name\":\"Amy\",\"username\":\"amy\"}]"));
}
@Test
void createAndUpdate_bindTheBody() throws Exception {
when(events.create(any())).thenReturn(row());
when(events.update(eq("77"), any())).thenReturn(row());
String body = "{\"name\":\"Fair\",\"location\":\"KL\",\"startDate\":\"2027-01-15\",\"endDate\":\"2027-01-17\",\"enabled\":false,\"salespersonIds\":[1,2],\"extra\":1}";
mvc.perform(post("/api/admin/events").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isOk());
mvc.perform(put("/api/admin/events/77").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isOk());
ArgumentCaptor<AdminEventRequest> c = ArgumentCaptor.forClass(AdminEventRequest.class);
verify(events).create(c.capture());
assertThat(c.getValue()).isEqualTo(new AdminEventRequest("Fair", "KL", "2027-01-15", "2027-01-17", false, List.of(1L, 2L)));
}
}
@@ -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);
}
}
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more