Merge pull request 'feat: admin events with salesperson teams (add-admin-events)' (#5) from add-admin-events into main

This commit was merged in pull request #5.
This commit is contained in:
ngqile committed 2026-11-26 18:37:53 +00:00
commit 5588ade48d
66 files changed
+4143 -2

No files matched your search

+18
View File
@@ -19,9 +19,27 @@ 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');
-- 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;
@@ -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

@@ -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,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,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,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,34 @@ 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",
};
@@ -5,12 +5,13 @@ describe("routeModules", () => {
it("gates /users and /roles by the seeded module name", () => {
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(["/events", "/roles", "/users"]);
});
});
@@ -5,6 +5,7 @@
export const ROUTE_MODULES: Record<string, string> = {
"/users": "BO_USERS",
"/roles": "BO_ROLES",
"/events": "BO_EVENTS",
};
export function requiredModuleFor(pathname: string): string | undefined {
@@ -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");
}
+35
View File
@@ -115,3 +115,38 @@ 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;
}
+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);
}
@@ -32,6 +32,12 @@ 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";
//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,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,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,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,412 @@
package com.solvway.mobile.api.service;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.model.Event;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.dto.admin.AdminEventRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminEventServiceTest {
private static final String PAGE = "/counter/event/findByPropertyAndPageable";
private static final String BY_UUID = "/counter/event/findByUuid/{uuid}";
private static final String SAVE = "/counter/event/save";
private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}";
private static final String REPLACE = "/counter/eventSalesperson/replace";
private static final String USER = "/user/findById/{id}";
private static final String USERS = "/user/findByPropertyAndPageable";
private static final long UUID = 7123456789012345678L;
private RestTemplateCustomUtil rest;
private AdminEventService service;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
service = new AdminEventService(rest, auth);
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setUsername("boss");
caller.setCompanyId(5L);
when(auth.loadUserByToken("tok")).thenReturn(caller);
// default: save echoes, replace echoes an empty list
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
.thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
when(rest.postForEntity(eq(REPLACE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of()));
// default: the event has no team yet (tests that need one stub TEAM themselves)
when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of()));
}
@AfterEach
void close() { http.close(); }
private static Event event() {
Event e = new Event();
e.setId(11L);
e.setUuid(UUID);
e.setName("Old");
e.setLocation("Old place");
e.setDateStart(LocalDateTime.of(2026, 5, 1, 0, 0));
e.setDateEnd(LocalDateTime.of(2026, 5, 2, 23, 59, 59));
e.setUploadFloorPlan("plan.pdf");
e.setUploadLuckyDraw("draw.pdf");
e.setCreateBy("creator");
e.setCreateDateTime(LocalDateTime.of(2026, 1, 1, 8, 0));
return e;
}
private void stubFind(Event e) {
when(rest.getForEntity(eq(BY_UUID), any(ParameterizedTypeReference.class), eq(UUID)))
.thenReturn(e == null ? ResponseEntity.ok().build() : ResponseEntity.ok(e));
}
private void stubUser(long id, String type, boolean enabled) {
Map<String, Object> u = new HashMap<>();
u.put("id", id);
u.put("name", "User " + id);
u.put("username", "u" + id);
u.put("type", type);
u.put("enabled", enabled);
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u));
}
private static AdminEventRequest req(String name, String loc, String start, String end, List<Long> team) {
return new AdminEventRequest(name, loc, start, end, null, team);
}
private static void assertCoded(Runnable r, HttpStatus status, String code, String field) {
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(status);
assertThat(e.getCode()).isEqualTo(code);
// the portal forwards only code, errors (string list) and details (flat object) from a ProblemDetail
if (field != null) assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", field);
});
}
@Test
void create_allMissingFieldsAreListedInErrors() {
assertThatThrownBy(() -> service.create(req("N", " ", null, "", null)))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD");
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("location", "startDate", "endDate"));
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", "location");
});
}
private void assertRefusedWithoutSave(AdminEventRequest r, String code, String field) {
assertCoded(() -> service.create(r), HttpStatus.BAD_REQUEST, code, field);
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
verify(rest, never()).postForEntity(eq(REPLACE), any(ParameterizedTypeReference.class), any());
}
private Event savedEvent() {
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture());
return (Event) c.getValue();
}
private Map<String, Object> replaceBody() {
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(REPLACE), any(ParameterizedTypeReference.class), c.capture());
return (Map<String, Object>) c.getValue();
}
@Test
void list_mapsParamsAndReturnsUuidAsString() {
AtomicReference<Object> sent = new AtomicReference<>();
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> {
sent.set(i.getArgument(2));
return ResponseEntity.ok(new AdminEventService.EventPage(List.of(event()), 41, 3, 2, 20));
});
Map<String, Object> out = service.list(" food ", "N", 2, 20, "startDate", "desc");
Map<String, Object> body = (Map<String, Object>) sent.get();
assertThat((Map<String, Object>) body.get("property")).containsEntry("name", "food").containsEntry("enabled", "N");
Map<String, Object> pageable = (Map<String, Object>) body.get("pageableRest");
assertThat(pageable).containsEntry("number", 2).containsEntry("size", 20);
assertThat((List<Map<String, Object>>) pageable.get("sorts")).containsExactly(Map.of("direction", "DESC", "property", "dateStart"));
assertThat(out).containsEntry("totalElements", 41L).containsEntry("totalPages", 3).containsEntry("number", 2).containsEntry("size", 20);
Map<String, Object> row = ((List<Map<String, Object>>) out.get("content")).get(0);
assertThat(row).containsExactlyInAnyOrderEntriesOf(Map.of("uuid", "7123456789012345678", "name", "Old", "location", "Old place",
"startDate", "2026-05-01", "endDate", "2026-05-02", "enabled", true));
}
@Test
void list_nullSortByAndSortDirSendNameAsc() {
AtomicReference<Object> sent = new AtomicReference<>();
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> {
sent.set(i.getArgument(2));
return ResponseEntity.ok(new AdminEventService.EventPage(List.of(), 0, 0, 0, 20));
});
service.list(null, null, 0, 20, null, null);
Map<String, Object> pageable = (Map<String, Object>) ((Map<String, Object>) sent.get()).get("pageableRest");
assertThat((List<Map<String, Object>>) pageable.get("sorts")).containsExactly(Map.of("direction", "ASC", "property", "name"));
}
@Test
void list_nullQAndEnabledSendEmptyFilters() {
AtomicReference<Object> sent = new AtomicReference<>();
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> {
sent.set(i.getArgument(2));
return ResponseEntity.ok(new AdminEventService.EventPage(List.of(), 0, 0, 0, 20));
});
service.list(null, null, 0, 20, null, null);
assertThat((Map<String, Object>) ((Map<String, Object>) sent.get()).get("property"))
.containsEntry("name", "").containsEntry("enabled", "");
}
@Test
void list_nullContentFromCounterGivesEmptyContent() {
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
.thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(null, 0, 0, 0, 20)));
assertThat((List<?>) service.list(null, null, 0, 20, null, null).get("content")).isEmpty();
}
@Test
void list_defaultsToNameAscAndUnknownSortFallsBackToName() {
AtomicReference<Object> sent = new AtomicReference<>();
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> {
sent.set(i.getArgument(2));
return ResponseEntity.ok(new AdminEventService.EventPage(List.of(), 0, 0, 0, 20));
});
service.list(null, null, 0, 20, "bogus", null);
Map<String, Object> pageable = (Map<String, Object>) ((Map<String, Object>) sent.get()).get("pageableRest");
assertThat((List<Map<String, Object>>) pageable.get("sorts")).containsExactly(Map.of("direction", "ASC", "property", "name"));
}
@Test
void get_returnsDetailWithTeamIncludingDeactivatedAndMissingMembers() {
stubFind(event());
when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), eq(UUID))).thenReturn(ResponseEntity.ok(
List.of(Map.of("userId", 1), Map.of("userId", 2), Map.of("userId", 3))));
stubUser(1, "A", true);
stubUser(2, "A", false);
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(3L))).thenReturn(ResponseEntity.ok().build());
Map<String, Object> out = service.get(String.valueOf(UUID));
assertThat(out).containsEntry("uuid", "7123456789012345678").containsEntry("enabled", true);
List<Map<String, Object>> team = (List<Map<String, Object>>) out.get("team");
assertThat(team).hasSize(3);
assertThat(team.get(0)).containsEntry("id", 1L).containsEntry("username", "u1").containsEntry("enabled", true);
assertThat(team.get(1)).containsEntry("id", 2L).containsEntry("enabled", false);
assertThat(team.get(2)).containsEntry("id", 3L).containsEntry("enabled", false);
}
@Test
void get_unknownOrNonNumericUuidIs404() {
stubFind(null);
assertCoded(() -> service.get(String.valueOf(UUID)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null);
assertCoded(() -> service.get("abc"), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null);
}
@Test
void create_savesEnabledEventWithWholeDaysAndReplacesTeamForCallerCompany() {
stubUser(1, "A", true);
stubUser(2, "A", true);
Map<String, Object> out = service.create(req(" KL Food Fair 2027 ", " MITEC ", "2027-01-15", "2027-01-17", List.of(1L, 2L, 1L)));
Event saved = savedEvent();
assertThat(saved.getName()).isEqualTo("KL Food Fair 2027");
assertThat(saved.getLocation()).isEqualTo("MITEC");
assertThat(saved.getDateStart()).isEqualTo(LocalDateTime.of(2027, 1, 15, 0, 0, 0));
assertThat(saved.getDateEnd()).isEqualTo(LocalDateTime.of(2027, 1, 17, 23, 59, 59));
assertThat(saved.getEnabled()).isEqualTo(GeneralEnum.FlagYesNo.Y);
assertThat(saved.getCreateBy()).isEqualTo("boss");
assertThat(saved.getDoneBy()).isEqualTo("boss");
Map<String, Object> replace = replaceBody();
assertThat(replace).containsEntry("eventUuid", saved.getUuid()).containsEntry("companyId", 5L).containsEntry("doneBy", "boss");
assertThat((List<Long>) replace.get("userIds")).containsExactly(1L, 2L);
assertThat(out).containsEntry("uuid", String.valueOf(saved.getUuid())).containsEntry("startDate", "2027-01-15");
verify(rest, org.mockito.Mockito.times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(1L));
}
@Test
void create_oneDayEventAndNullTeam() {
service.create(req("Pop-up", "KLCC", "2027-02-01", "2027-02-01", null));
Event saved = savedEvent();
assertThat(saved.getDateStart()).isEqualTo(LocalDateTime.of(2027, 2, 1, 0, 0, 0));
assertThat(saved.getDateEnd()).isEqualTo(LocalDateTime.of(2027, 2, 1, 23, 59, 59));
assertThat((List<Long>) replaceBody().get("userIds")).isEmpty();
}
@Test
void create_ignoresEnabledFromRequest() {
service.create(new AdminEventRequest("A", "B", "2027-02-01", "2027-02-01", false, null));
assertThat(savedEvent().getEnabled()).isEqualTo(GeneralEnum.FlagYesNo.Y);
}
@Test
void create_missingFieldsAreRefusedAndNamed() {
assertRefusedWithoutSave(req(null, "L", "2027-01-01", "2027-01-02", null), "REQUIRED_FIELD", "name");
assertRefusedWithoutSave(req("N", " ", "2027-01-01", "2027-01-02", null), "REQUIRED_FIELD", "location");
assertRefusedWithoutSave(req("N", "L", null, "2027-01-02", null), "REQUIRED_FIELD", "startDate");
assertRefusedWithoutSave(req("N", "L", "2027-01-01", " ", null), "REQUIRED_FIELD", "endDate");
}
@Test
void create_nameOf100CharsAfterTrimIsAccepted() {
service.create(req(" " + "n".repeat(100) + " ", "L", "2027-01-01", "2027-01-02", null));
assertThat(savedEvent().getName()).hasSize(100);
}
@Test
void create_nameTooLong() {
assertRefusedWithoutSave(req("n".repeat(101), "L", "2027-01-01", "2027-01-02", null), "TOO_LONG", "name");
}
@Test
void create_locationTooLong() {
assertRefusedWithoutSave(req("N", "l".repeat(201), "2027-01-01", "2027-01-02", null), "TOO_LONG", "location");
}
@Test
void create_badDate() {
assertRefusedWithoutSave(req("N", "L", "15/01/2027", "2027-01-02", null), "INVALID_DATE", "startDate");
assertRefusedWithoutSave(req("N", "L", "2027-01-01", "2027-02-30", null), "INVALID_DATE", "endDate");
}
@Test
void create_endBeforeStart() {
assertRefusedWithoutSave(req("N", "L", "2027-01-02", "2027-01-01", null), "END_BEFORE_START", "endDate");
}
@Test
void create_teamMemberUserDisabledUserOrUnknownIdIsRefusedBeforeSaving() {
stubUser(1, "A", true);
stubUser(2, "M", true);
stubUser(3, "A", false);
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(4L))).thenReturn(ResponseEntity.ok().build());
for (long bad : new long[]{2, 3, 4}) {
assertRefusedWithoutSave(req("N", "L", "2027-01-01", "2027-01-02", List.of(1L, bad)), "UNKNOWN_USER", null);
}
}
@Test
void create_teamReplaceFailureIs502WithEventUuid() {
when(rest.postForEntity(eq(REPLACE), any(ParameterizedTypeReference.class), any())).thenThrow(new IllegalStateException("down"));
assertThatThrownBy(() -> service.create(req("N", "L", "2027-01-01", "2027-01-02", null)))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY);
assertThat(e.getCode()).isEqualTo("TEAM_NOT_SAVED");
Object uuid = ((Map<String, Object>) e.getBody().getProperties().get("details")).get("eventUuid");
assertThat(uuid).isInstanceOf(String.class);
assertThat(e.getReason()).contains((String) uuid);
});
assertThat(savedEvent().getUuid()).isNotZero();
}
@Test
void update_changesOnlyEditableFieldsAndKeepsTheRest() {
stubFind(event());
stubUser(1, "A", true);
AdminEventRequest r = new AdminEventRequest(" New ", " Hall ", "2027-03-01", "2027-03-03", false, List.of(1L));
Map<String, Object> out = service.update(String.valueOf(UUID), r);
Event saved = savedEvent();
assertThat(saved.getId()).isEqualTo(11L);
assertThat(saved.getUuid()).isEqualTo(UUID);
assertThat(saved.getName()).isEqualTo("New");
assertThat(saved.getLocation()).isEqualTo("Hall");
assertThat(saved.getDateStart()).isEqualTo(LocalDateTime.of(2027, 3, 1, 0, 0));
assertThat(saved.getDateEnd()).isEqualTo(LocalDateTime.of(2027, 3, 3, 23, 59, 59));
assertThat(saved.getEnabled()).isEqualTo(GeneralEnum.FlagYesNo.N);
assertThat(saved.getDoneBy()).isEqualTo("boss");
assertThat(saved.getUploadFloorPlan()).isEqualTo("plan.pdf");
assertThat(saved.getUploadLuckyDraw()).isEqualTo("draw.pdf");
assertThat(saved.getCreateBy()).isEqualTo("creator");
assertThat(saved.getCreateDateTime()).isEqualTo(LocalDateTime.of(2026, 1, 1, 8, 0));
assertThat(replaceBody()).containsEntry("eventUuid", UUID).containsEntry("companyId", 5L);
assertThat(out).containsEntry("uuid", "7123456789012345678").containsEntry("enabled", false);
}
@Test
void update_withoutEnabledKeepsStoredStateAndNullTeamLeavesTeamAlone() {
Event e = event();
e.setEnabled(GeneralEnum.FlagYesNo.N);
stubFind(e);
service.update(String.valueOf(UUID), req("New", "Hall", "2027-03-01", "2027-03-03", null));
assertThat(savedEvent().getEnabled()).isEqualTo(GeneralEnum.FlagYesNo.N);
verify(rest, never()).postForEntity(eq(REPLACE), any(ParameterizedTypeReference.class), any());
}
@Test
void update_unknownUuidIs404AndNothingIsSaved() {
stubFind(null);
assertCoded(() -> service.update(String.valueOf(UUID), req("N", "L", "2027-01-01", "2027-01-02", null)),
HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null);
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
}
@Test
void update_badTeamIsRefusedBeforeSaving() {
stubFind(event());
stubUser(2, "A", false);
assertCoded(() -> service.update(String.valueOf(UUID), req("N", "L", "2027-01-01", "2027-01-02", List.of(2L))),
HttpStatus.BAD_REQUEST, "UNKNOWN_USER", null);
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
}
@Test
void update_keepsADeactivatedMemberAlreadyOnTheTeam() {
stubFind(event());
when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), eq(UUID)))
.thenReturn(ResponseEntity.ok(List.of(Map.of("userId", 2))));
stubUser(2, "A", false);
stubUser(3, "A", true);
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
.thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
service.update(String.valueOf(UUID), req("N", "L", "2027-01-01", "2027-01-02", List.of(2L, 3L)));
assertThat(replaceBody()).containsEntry("userIds", List.of(2L, 3L));
}
@Test
void salespersonOptions_onlyEnabledTypeAUsersSortedByName() {
List<Map<String, Object>> users = List.of(
Map.of("id", 1, "name", "Zed", "username", "z", "type", "A", "enabled", true),
Map.of("id", 2, "name", "Off", "username", "o", "type", "A", "enabled", false),
Map.of("id", 3, "name", "Member", "username", "m", "type", "M", "enabled", true),
Map.of("id", 4, "name", "amy", "username", "a", "type", "A", "enabled", true));
when(rest.postForEntity(eq(USERS), any(ParameterizedTypeReference.class), any()))
.thenReturn(ResponseEntity.ok(Map.of("content", users)));
assertThat(service.salespersonOptions()).containsExactly(
Map.of("id", 4L, "name", "amy", "username", "a"), Map.of("id", 1L, "name", "Zed", "username", "z"));
}
}
@@ -0,0 +1,28 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.dto.EventSalespersonReplaceRequest;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.service.EventSalespersonService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/counter/eventSalesperson")
@AllArgsConstructor
@Slf4j
public class EventSalespersonController {
private final EventSalespersonService eventSalespersonService;
@GetMapping("/findByEventUuid/{eventUuid}")
public List<EventSalesperson> findByEventUuid(@PathVariable("eventUuid") long eventUuid) {
return eventSalespersonService.findByEventUuid(eventUuid);
}
@PostMapping("/replace")
public List<EventSalesperson> replace(@RequestBody EventSalespersonReplaceRequest body) {
return eventSalespersonService.replace(body.eventUuid(), body.companyId(), body.userIds(), body.doneBy());
}
}
@@ -0,0 +1,8 @@
package com.solvway.services.counter.dto;
public record EventSalespersonReplaceRequest(
long eventUuid,
long companyId,
java.util.List<Long> userIds,
String doneBy
) {}
@@ -0,0 +1,24 @@
package com.solvway.services.counter.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@Table(name = "event_salesperson", uniqueConstraints = @UniqueConstraint(columnNames = {"event_uuid", "user_id"}))
public class EventSalesperson {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private long companyId;
private long eventUuid;
private long userId;
@Column(updatable = false)
private String createBy;
@Column(updatable = false)
private LocalDateTime createDateTime = LocalDateTime.now();
}
@@ -0,0 +1,19 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.EventSalesperson;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface EventSalespersonRepository extends JpaRepository<EventSalesperson, Long> {
List<EventSalesperson> findByEventUuid(long eventUuid);
@Modifying
@Query("delete from EventSalesperson e where e.eventUuid = :eventUuid")
void deleteByEventUuid(@Param("eventUuid") long eventUuid);
}
@@ -0,0 +1,51 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.repo.EventSalespersonRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Service
@Slf4j
@AllArgsConstructor
public class EventSalespersonService {
private final EventSalespersonRepository eventSalespersonRepository;
public List<EventSalesperson> findByEventUuid(long eventUuid) {
return eventSalespersonRepository.findByEventUuid(eventUuid);
}
@Transactional
public List<EventSalesperson> replace(long eventUuid, long companyId, List<Long> userIds, String doneBy) {
eventSalespersonRepository.deleteByEventUuid(eventUuid);
List<Long> effective = userIds == null ? List.of() : userIds;
List<Long> distinct = effective.stream()
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
List<EventSalesperson> rows = distinct.stream()
.map(userId -> {
EventSalesperson e = new EventSalesperson();
e.setCompanyId(companyId);
e.setEventUuid(eventUuid);
e.setUserId(userId);
e.setCreateBy(doneBy);
return e;
})
.collect(Collectors.toList());
if (rows.isEmpty()) {
return List.of();
}
return eventSalespersonRepository.saveAll(rows);
}
}
@@ -0,0 +1,75 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.dto.EventSalespersonReplaceRequest;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.service.EventSalespersonService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* EventSalespersonController delegates to service and returns results.
*/
@ExtendWith(MockitoExtension.class)
class EventSalespersonControllerTest {
private static final long EVENT_UUID = 100L;
private static final long COMPANY_ID = 42L;
private static final String DONE_BY = "admin";
@Mock private EventSalespersonService eventSalespersonService;
private EventSalespersonController controller;
@BeforeEach
void setUp() {
controller = new EventSalespersonController(eventSalespersonService);
}
@Test
void findByEventUuidDelegatesToService() {
EventSalesperson row = makeSalesperson(1L, EVENT_UUID, COMPANY_ID, 10L);
when(eventSalespersonService.findByEventUuid(EVENT_UUID)).thenReturn(List.of(row));
List<EventSalesperson> result = controller.findByEventUuid(EVENT_UUID);
assertThat(result).hasSize(1).first().isSameAs(row);
verify(eventSalespersonService).findByEventUuid(EVENT_UUID);
}
@Test
void replacePassesBodyFieldsAndReturnsServiceResult() {
EventSalesperson row = makeSalesperson(1L, EVENT_UUID, COMPANY_ID, 10L);
EventSalespersonReplaceRequest body = new EventSalespersonReplaceRequest(
EVENT_UUID, COMPANY_ID, List.of(10L), DONE_BY);
when(eventSalespersonService.replace(eq(EVENT_UUID), eq(COMPANY_ID), eq(List.of(10L)), eq(DONE_BY)))
.thenReturn(List.of(row));
List<EventSalesperson> result = controller.replace(body);
assertThat(result).hasSize(1).first().isSameAs(row);
verify(eventSalespersonService).replace(EVENT_UUID, COMPANY_ID, List.of(10L), DONE_BY);
}
private static EventSalesperson makeSalesperson(Long id, long eventUuid, long companyId, long userId) {
EventSalesperson e = new EventSalesperson();
e.setId(id);
e.setEventUuid(eventUuid);
e.setCompanyId(companyId);
e.setUserId(userId);
e.setCreateBy("admin");
e.setCreateDateTime(LocalDateTime.now());
return e;
}
}
@@ -0,0 +1,223 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.repo.EventSalespersonRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
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.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* EventSalespersonService.replace() — delete-old, save-distinct, collapse-duplicates.
*/
@ExtendWith(MockitoExtension.class)
class EventSalespersonServiceReplaceTest {
private static final long EVENT_UUID = 100L;
private static final long COMPANY_ID = 42L;
private static final String DONE_BY = "admin";
@Mock private EventSalespersonRepository repository;
private EventSalespersonService service;
@BeforeEach
void setUp() throws Exception {
service = new EventSalespersonService(repository);
}
// --- Test 1: replace deletes existing rows before saving (InOrder) ---
@Test
void replaceDeletesBeforeSaving() {
EventSalesperson row = makeSalesperson(1L, EVENT_UUID, COMPANY_ID, 10L, "admin");
when(repository.saveAll(any())).thenReturn(List.of(row));
service.replace(EVENT_UUID, COMPANY_ID, List.of(10L), DONE_BY);
org.mockito.InOrder inOrder = inOrder(repository);
inOrder.verify(repository).deleteByEventUuid(EVENT_UUID);
inOrder.verify(repository).saveAll(any());
}
// --- Test 2: saves one row per distinct user id ---
@Test
void replaceSavesOneRowPerDistinctId() {
when(repository.saveAll(any()))
.thenAnswer(inv -> {
List<EventSalesperson> args = inv.getArgument(0);
return args.stream()
.map(e -> {
EventSalesperson copy = new EventSalesperson();
copy.setId(e.getUserId());
copy.setEventUuid(EVENT_UUID);
copy.setCompanyId(COMPANY_ID);
copy.setUserId(e.getUserId());
copy.setCreateBy(DONE_BY);
copy.setCreateDateTime(e.getCreateDateTime());
return copy;
})
.toList();
});
List<EventSalesperson> result = service.replace(EVENT_UUID, COMPANY_ID, List.of(10L, 20L), DONE_BY);
ArgumentCaptor<List<EventSalesperson>> captor = ArgumentCaptor.forClass(List.class);
verify(repository).saveAll(captor.capture());
assertThat(captor.getValue()).hasSize(2);
assertThat(result).hasSize(2);
}
// --- Test 3: collapses duplicate user ids ---
@Test
void replaceCollapsesDuplicateIds() {
when(repository.saveAll(any()))
.thenAnswer(inv -> {
List<EventSalesperson> args = inv.getArgument(0);
return args.stream()
.map(e -> {
EventSalesperson copy = new EventSalesperson();
copy.setId(1L);
copy.setEventUuid(EVENT_UUID);
copy.setCompanyId(COMPANY_ID);
copy.setUserId(e.getUserId());
copy.setCreateBy(DONE_BY);
copy.setCreateDateTime(e.getCreateDateTime());
return copy;
})
.toList();
});
List<EventSalesperson> result = service.replace(EVENT_UUID, COMPANY_ID, List.of(10L, 10L, 10L), DONE_BY);
ArgumentCaptor<List<EventSalesperson>> captor = ArgumentCaptor.forClass(List.class);
verify(repository).saveAll(captor.capture());
assertThat(captor.getValue()).hasSize(1);
assertThat(result).hasSize(1);
}
// --- Test 4: null or empty list deletes and saves nothing ---
@Test
void replaceWithEmptyListDeletesAndSavesNothing() {
service.replace(EVENT_UUID, COMPANY_ID, Collections.emptyList(), DONE_BY);
verify(repository).deleteByEventUuid(EVENT_UUID);
verify(repository, never()).saveAll(any());
}
// --- Test 5: replace method carries @Transactional ---
@Test
void replaceMethodHasTransactionalAnnotation() throws Exception {
Method replaceMethod = EventSalespersonService.class.getDeclaredMethod(
"replace", long.class, long.class, List.class, String.class);
assertThat(replaceMethod.isAnnotationPresent(org.springframework.transaction.annotation.Transactional.class))
.isTrue();
}
// --- Test 6: findByEventUuid returns repository rows ---
@Test
void findByEventUuidReturnsRepositoryRows() {
EventSalesperson row = makeSalesperson(1L, EVENT_UUID, COMPANY_ID, 10L, "admin");
when(repository.findByEventUuid(EVENT_UUID)).thenReturn(List.of(row));
List<EventSalesperson> result = service.findByEventUuid(EVENT_UUID);
assertThat(result).hasSize(1).first().isSameAs(row);
}
// --- Test 7: deleteByEventUuid carries a @Query whose value starts with "delete" ---
@Test
void deleteByEventUuidHasDeleteQuery() throws Exception {
Method deleteMethod = EventSalespersonRepository.class
.getDeclaredMethod("deleteByEventUuid", long.class);
assertThat(deleteMethod.isAnnotationPresent(Modifying.class)).isTrue();
Query queryAnn = deleteMethod.getAnnotation(Query.class);
assertThat(queryAnn)
.as("deleteByEventUuid must carry @Query to avoid Hibernate derived-delete flush-order issue")
.isNotNull();
assertThat(queryAnn.value())
.as("@Query value must start with 'delete' so Hibernate runs it immediately, not after inserts")
.startsWith("delete");
}
// --- Test 8: replace with null userIds deletes existing rows and saves nothing ---
@Test
void replaceWithNullUserIds() {
service.replace(EVENT_UUID, COMPANY_ID, null, DONE_BY);
verify(repository).deleteByEventUuid(EVENT_UUID);
verify(repository, never()).saveAll(any());
}
// --- Test 9: replace with [5, null, 5, 6] saves exactly users 5 and 6 ---
@Test
void replaceWithNullEntriesInList() {
when(repository.saveAll(any()))
.thenAnswer(inv -> {
List<EventSalesperson> args = inv.getArgument(0);
return args.stream()
.map(e -> {
EventSalesperson copy = new EventSalesperson();
copy.setId(1L);
copy.setEventUuid(EVENT_UUID);
copy.setCompanyId(COMPANY_ID);
copy.setUserId(e.getUserId());
copy.setCreateBy(DONE_BY);
copy.setCreateDateTime(e.getCreateDateTime());
return copy;
})
.toList();
});
List<EventSalesperson> result = service.replace(EVENT_UUID, COMPANY_ID, Arrays.asList(5L, null, 5L, 6L), DONE_BY);
ArgumentCaptor<List<EventSalesperson>> captor = ArgumentCaptor.forClass(List.class);
verify(repository).saveAll(captor.capture());
List<EventSalesperson> saved = captor.getValue();
assertThat(saved).hasSize(2);
assertThat(saved.get(0).getUserId()).isEqualTo(5L);
assertThat(saved.get(1).getUserId()).isEqualTo(6L);
assertThat(result).hasSize(2);
}
// --- Test 10: createBy column has updatable = false ---
@Test
void createByHasUpdatableFalse() throws Exception {
jakarta.persistence.Column colAnn = EventSalesperson.class
.getDeclaredField("createBy")
.getAnnotation(jakarta.persistence.Column.class);
assertThat(colAnn)
.as("createBy must have @Column(updatable = false) to prevent accidental overwrites")
.isNotNull();
assertThat(colAnn.updatable()).isFalse();
}
private static EventSalesperson makeSalesperson(Long id, long eventUuid, long companyId, long userId, String createBy) {
EventSalesperson e = new EventSalesperson();
e.setId(id);
e.setEventUuid(eventUuid);
e.setCompanyId(companyId);
e.setUserId(userId);
e.setCreateBy(createBy);
e.setCreateDateTime(LocalDateTime.now());
return e;
}
}