From 246fec3c7be0953ea0bbd4ed2a404c08f637ac9b Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 23:19:39 +0800 Subject: [PATCH 01/11] docs(openspec): propose add-admin-events Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-admin-events/.openspec.yaml | 2 + openspec/changes/add-admin-events/design.md | 90 ++++++++++++++++++ openspec/changes/add-admin-events/proposal.md | 33 +++++++ .../specs/admin-events/spec.md | 94 +++++++++++++++++++ openspec/changes/add-admin-events/tasks.md | 34 +++++++ 5 files changed, 253 insertions(+) create mode 100644 openspec/changes/add-admin-events/.openspec.yaml create mode 100644 openspec/changes/add-admin-events/design.md create mode 100644 openspec/changes/add-admin-events/proposal.md create mode 100644 openspec/changes/add-admin-events/specs/admin-events/spec.md create mode 100644 openspec/changes/add-admin-events/tasks.md diff --git a/openspec/changes/add-admin-events/.openspec.yaml b/openspec/changes/add-admin-events/.openspec.yaml new file mode 100644 index 0000000..7ed429c --- /dev/null +++ b/openspec/changes/add-admin-events/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-26 diff --git a/openspec/changes/add-admin-events/design.md b/openspec/changes/add-admin-events/design.md new file mode 100644 index 0000000..a151749 --- /dev/null +++ b/openspec/changes/add-admin-events/design.md @@ -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 and leaves `uuid` for `services-counter` to generate. + +### 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 and `date-fns` ^4.4.0, the versions babyboo uses. 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. diff --git a/openspec/changes/add-admin-events/proposal.md b/openspec/changes/add-admin-events/proposal.md new file mode 100644 index 0000000..faae25e --- /dev/null +++ b/openspec/changes/add-admin-events/proposal.md @@ -0,0 +1,33 @@ +# 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`); `services-counter` and its schema do 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. +- **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` and `date-fns`. 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 dependencies `react-day-picker` and `date-fns`. +- `solvway-mobile-api`: new `AdminEventController`, `AdminEventService`, DTOs and counter endpoint constants. +- Database `service-system`: one new `module` row. Additive only. +- `local/seed/03-colite.sql`: mirrors the module row. +- No change to `services-counter`, the gateway, or the `event` table. diff --git a/openspec/changes/add-admin-events/specs/admin-events/spec.md b/openspec/changes/add-admin-events/specs/admin-events/spec.md new file mode 100644 index 0000000..263169a --- /dev/null +++ b/openspec/changes/add-admin-events/specs/admin-events/spec.md @@ -0,0 +1,94 @@ +# 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 naming a member, a deactivated user or an unknown user 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 diff --git a/openspec/changes/add-admin-events/tasks.md b/openspec/changes/add-admin-events/tasks.md new file mode 100644 index 0000000..0b6673c --- /dev/null +++ b/openspec/changes/add-admin-events/tasks.md @@ -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 + +- [ ] 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 + +- [ ] 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 + +- [ ] 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 + +- [ ] 4.1 Port babyboo's `calendar.tsx` and `date-picker.tsx` (and their tests) into `app/components/ui/`, adding `react-day-picker` 10.0.1 and `date-fns` ^4.4.0 to `package.json` (`npm install`, commit the lockfile). Verify: `npm run lint && npx tsc --noEmit && npx vitest run` exit 0. + - Scope: `solvway-admin-portal/app/components/ui/**`, `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json` +- [ ] 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 + +- [ ] 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. -- 2.54.1 From 814c51da3d5009af22275849721cea81c833faf1 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 23:23:34 +0800 Subject: [PATCH 02/11] feat(db): event_salesperson table and BO_EVENTS module Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 18 ++++++++++++++++++ .../sql/01-event-salesperson.sql | 16 ++++++++++++++++ .../sql/02-bo-events-module.sql | 6 ++++++ .../add-admin-events/sql/99-rollback.sql | 7 +++++++ openspec/changes/add-admin-events/tasks.md | 2 +- 5 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/add-admin-events/sql/01-event-salesperson.sql create mode 100644 openspec/changes/add-admin-events/sql/02-bo-events-module.sql create mode 100644 openspec/changes/add-admin-events/sql/99-rollback.sql diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 400988b..2197a4a 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -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; diff --git a/openspec/changes/add-admin-events/sql/01-event-salesperson.sql b/openspec/changes/add-admin-events/sql/01-event-salesperson.sql new file mode 100644 index 0000000..ce9c6ed --- /dev/null +++ b/openspec/changes/add-admin-events/sql/01-event-salesperson.sql @@ -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; diff --git a/openspec/changes/add-admin-events/sql/02-bo-events-module.sql b/openspec/changes/add-admin-events/sql/02-bo-events-module.sql new file mode 100644 index 0000000..c48d8eb --- /dev/null +++ b/openspec/changes/add-admin-events/sql/02-bo-events-module.sql @@ -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'); diff --git a/openspec/changes/add-admin-events/sql/99-rollback.sql b/openspec/changes/add-admin-events/sql/99-rollback.sql new file mode 100644 index 0000000..ee78248 --- /dev/null +++ b/openspec/changes/add-admin-events/sql/99-rollback.sql @@ -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`; diff --git a/openspec/changes/add-admin-events/tasks.md b/openspec/changes/add-admin-events/tasks.md index 0b6673c..ecdef3b 100644 --- a/openspec/changes/add-admin-events/tasks.md +++ b/openspec/changes/add-admin-events/tasks.md @@ -4,7 +4,7 @@ Babyboo source: `~/Projects/babyboo` (read only). Tastefully backoffice rules: ` ## 1. Database -- [ ] 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. +- [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 -- 2.54.1 From 70e0651a75df0de1fa8fe8ce0e2f592b580bab5a Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 23:57:50 +0800 Subject: [PATCH 03/11] feat(services-counter): store each event's team of salespeople GET /counter/eventSalesperson/findByEventUuid/{eventUuid} and POST /counter/eventSalesperson/replace (bulk delete then insert, one transaction). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-admin-events/tasks.md | 2 +- .../EventSalespersonController.java | 28 +++ .../dto/EventSalespersonReplaceRequest.java | 8 + .../counter/model/EventSalesperson.java | 24 ++ .../repo/EventSalespersonRepository.java | 19 ++ .../service/EventSalespersonService.java | 51 ++++ .../EventSalespersonControllerTest.java | 75 ++++++ .../EventSalespersonServiceReplaceTest.java | 223 ++++++++++++++++++ 8 files changed, 429 insertions(+), 1 deletion(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventSalespersonController.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventSalespersonReplaceRequest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventSalesperson.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventSalespersonService.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventSalespersonControllerTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventSalespersonServiceReplaceTest.java diff --git a/openspec/changes/add-admin-events/tasks.md b/openspec/changes/add-admin-events/tasks.md index ecdef3b..3fe56c1 100644 --- a/openspec/changes/add-admin-events/tasks.md +++ b/openspec/changes/add-admin-events/tasks.md @@ -9,7 +9,7 @@ Babyboo source: `~/Projects/babyboo` (read only). Tastefully backoffice rules: ` ## 2. services-counter event team -- [ ] 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`. +- [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 diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventSalespersonController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventSalespersonController.java new file mode 100644 index 0000000..16efe57 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventSalespersonController.java @@ -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 findByEventUuid(@PathVariable("eventUuid") long eventUuid) { + return eventSalespersonService.findByEventUuid(eventUuid); + } + + @PostMapping("/replace") + public List replace(@RequestBody EventSalespersonReplaceRequest body) { + return eventSalespersonService.replace(body.eventUuid(), body.companyId(), body.userIds(), body.doneBy()); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventSalespersonReplaceRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventSalespersonReplaceRequest.java new file mode 100644 index 0000000..3eca8e1 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventSalespersonReplaceRequest.java @@ -0,0 +1,8 @@ +package com.solvway.services.counter.dto; + +public record EventSalespersonReplaceRequest( + long eventUuid, + long companyId, + java.util.List userIds, + String doneBy +) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventSalesperson.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventSalesperson.java new file mode 100644 index 0000000..17bd6db --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventSalesperson.java @@ -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(); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java new file mode 100644 index 0000000..de84937 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java @@ -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 { + List findByEventUuid(long eventUuid); + + @Modifying + @Query("delete from EventSalesperson e where e.eventUuid = :eventUuid") + void deleteByEventUuid(@Param("eventUuid") long eventUuid); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventSalespersonService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventSalespersonService.java new file mode 100644 index 0000000..9c71c6a --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventSalespersonService.java @@ -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 findByEventUuid(long eventUuid) { + return eventSalespersonRepository.findByEventUuid(eventUuid); + } + + @Transactional + public List replace(long eventUuid, long companyId, List userIds, String doneBy) { + eventSalespersonRepository.deleteByEventUuid(eventUuid); + + List effective = userIds == null ? List.of() : userIds; + List distinct = effective.stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + + List 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); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventSalespersonControllerTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventSalespersonControllerTest.java new file mode 100644 index 0000000..71f2a5c --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventSalespersonControllerTest.java @@ -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 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 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; + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventSalespersonServiceReplaceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventSalespersonServiceReplaceTest.java new file mode 100644 index 0000000..0f6b313 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventSalespersonServiceReplaceTest.java @@ -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 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 result = service.replace(EVENT_UUID, COMPANY_ID, List.of(10L, 20L), DONE_BY); + + ArgumentCaptor> 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 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 result = service.replace(EVENT_UUID, COMPANY_ID, List.of(10L, 10L, 10L), DONE_BY); + + ArgumentCaptor> 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 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 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 result = service.replace(EVENT_UUID, COMPANY_ID, Arrays.asList(5L, null, 5L, 6L), DONE_BY); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); + verify(repository).saveAll(captor.capture()); + List 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; + } +} -- 2.54.1 From 1fa7c60feeb7f31c8c59d828a7dedb5ac11fbb8c Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 00:18:32 +0800 Subject: [PATCH 04/11] feat(mobile-api): admin events API with salesperson teams /api/admin/events list, get, create, update and salesperson-options, all behind BO_EVENTS. Whole-day dates, uuid as a string, team ids checked before saving. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-admin-events/design.md | 2 +- openspec/changes/add-admin-events/tasks.md | 2 +- .../api/RestApiCounterServiceConstants.java | 6 + .../admin/AdminEventController.java | 56 +++ .../api/dto/admin/AdminEventRequest.java | 9 + .../mobile/api/service/AdminEventService.java | 257 ++++++++++++ .../admin/AdminEventControllerTest.java | 100 +++++ .../api/service/AdminEventServiceTest.java | 384 ++++++++++++++++++ 8 files changed, 814 insertions(+), 2 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceTest.java diff --git a/openspec/changes/add-admin-events/design.md b/openspec/changes/add-admin-events/design.md index a151749..69b41a6 100644 --- a/openspec/changes/add-admin-events/design.md +++ b/openspec/changes/add-admin-events/design.md @@ -32,7 +32,7 @@ The admin API takes and returns `startDate` and `endDate` as plain dates. `mobil ### 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 and leaves `uuid` for `services-counter` to generate. +`/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` diff --git a/openspec/changes/add-admin-events/tasks.md b/openspec/changes/add-admin-events/tasks.md index 3fe56c1..604a0ab 100644 --- a/openspec/changes/add-admin-events/tasks.md +++ b/openspec/changes/add-admin-events/tasks.md @@ -14,7 +14,7 @@ Babyboo source: `~/Projects/babyboo` (read only). Tastefully backoffice rules: ` ## 3. mobile-api events -- [ ] 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`. +- [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 diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index 2158682..a793e2e 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -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}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventController.java new file mode 100644 index 0000000..665d3b0 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventController.java @@ -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> 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>> salespersonOptions() { + return ResponseEntity.ok(adminEventService.salespersonOptions()); + } + @AppAuth + @AdminModule("BO_EVENTS") + @GetMapping("/events/{uuid}") + public ResponseEntity> getByUuid(@PathVariable String uuid) { + return ResponseEntity.ok(adminEventService.get(uuid)); + } + @AppAuth + @AdminModule("BO_EVENTS") + @PostMapping("/events") + public ResponseEntity> create(@RequestBody AdminEventRequest request) { + return ResponseEntity.ok(adminEventService.create(request)); + } + @AppAuth + @AdminModule("BO_EVENTS") + @PutMapping("/events/{uuid}") + public ResponseEntity> update(@PathVariable String uuid, @RequestBody AdminEventRequest request) { + return ResponseEntity.ok(adminEventService.update(uuid, request)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java new file mode 100644 index 0000000..158fc3e --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java @@ -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 salespersonIds) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java new file mode 100644 index 0000000..a9c7a21 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java @@ -0,0 +1,257 @@ +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 = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference PAGE = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; + private static final Map 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 content, long totalElements, int totalPages, int number, int size) {} + + public Map list(String q, String enabled, int page, int size, String sortBy, String sortDir) { + Map property = new LinkedHashMap<>(); + property.put("name", q == null ? "" : q.trim()); + property.put("enabled", "Y".equals(enabled) || "N".equals(enabled) ? enabled : ""); + Map sort = Map.of("direction", "desc".equalsIgnoreCase(sortDir) ? "DESC" : "ASC", + "property", sortBy == null ? "name" : SORTS.getOrDefault(sortBy, "name")); + Map 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 get(String uuid) { + Event event = load(uuid); + Map out = row(event); + List> team = new ArrayList<>(); + for (Long id : teamIds(event.getUuid())) { + Map user = user(id); + Map 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 create(AdminEventRequest r) { + Fields f = validate(r); + User caller = caller(); + List team = checkedTeam(r.salespersonIds()); + 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 update(String uuid, AdminEventRequest r) { + Fields f = validate(r); + User caller = caller(); + Event event = load(uuid); + List team = r.salespersonIds() == null ? null : checkedTeam(r.salespersonIds()); + 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> salespersonOptions() { + Map 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 body = restTemplateUtil.postForEntity( + url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request).getBody(); + List> all = body == null || body.get("content") == null ? List.of() : (List>) 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 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 in = new LinkedHashMap<>(); + in.put("name", r.name()); + in.put("location", r.location()); + in.put("startDate", r.startDate()); + in.put("endDate", r.endDate()); + List 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("fields", 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 must be an enabled admin user. One services-system lookup per id. */ + private List checkedTeam(List ids) { + List team = ids == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(ids)); + for (Long id : team) { + if (id == null || !isActiveAdmin(user(id))) { + throw error(HttpStatus.BAD_REQUEST, "Unknown or inactive admin user " + id, "UNKNOWN_USER", "salespersonIds"); + } + } + return team; + } + + private static boolean isActiveAdmin(Map user) { + return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled")); + } + + private Map user(Long id) { + return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody(); + } + + private List teamIds(long eventUuid) { + List> rows = restTemplateUtil.getForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID), MAP_LIST, eventUuid).getBody(); + return rows == null ? List.of() : rows.stream().map(m -> ((Number) m.get("userId")).longValue()).toList(); + } + + /** 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 userIds, User caller) { + Map 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("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 row(Event e) { + Map m = new LinkedHashMap<>(); + m.put("uuid", String.valueOf(e.getUuid())); + m.put("name", e.getName()); + m.put("location", e.getLocation()); + m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString()); + m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString()); + 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 on the ProblemDetail body next to code, so the portal can mark the failing input. */ + 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("field", field); + return e; + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventControllerTest.java new file mode 100644 index 0000000..d1423a0 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventControllerTest.java @@ -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 row() { + Map m = new LinkedHashMap<>(); + m.put("uuid", "7123456789012345678"); + m.put("name", "Fair"); + return m; + } + + @Test + void everyHandlerIsAuthenticatedAndGuardedByBoEvents() { + List 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 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))); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceTest.java new file mode 100644 index 0000000..f256b06 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceTest.java @@ -0,0 +1,384 @@ +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 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())); + } + + @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 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 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); + if (field != null) assertThat(e.getBody().getProperties()).containsEntry("field", field); + }); + } + + 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 c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture()); + return (Event) c.getValue(); + } + + private Map replaceBody() { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(REPLACE), any(ParameterizedTypeReference.class), c.capture()); + return (Map) c.getValue(); + } + + @Test + void list_mapsParamsAndReturnsUuidAsString() { + AtomicReference 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 out = service.list(" food ", "N", 2, 20, "startDate", "desc"); + + Map body = (Map) sent.get(); + assertThat((Map) body.get("property")).containsEntry("name", "food").containsEntry("enabled", "N"); + Map pageable = (Map) body.get("pageableRest"); + assertThat(pageable).containsEntry("number", 2).containsEntry("size", 20); + assertThat((List>) 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 row = ((List>) 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 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 pageable = (Map) ((Map) sent.get()).get("pageableRest"); + assertThat((List>) pageable.get("sorts")).containsExactly(Map.of("direction", "ASC", "property", "name")); + } + + @Test + void list_nullQAndEnabledSendEmptyFilters() { + AtomicReference 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) ((Map) 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 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 pageable = (Map) ((Map) sent.get()).get("pageableRest"); + assertThat((List>) 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 out = service.get(String.valueOf(UUID)); + + assertThat(out).containsEntry("uuid", "7123456789012345678").containsEntry("enabled", true); + List> team = (List>) 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 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 replace = replaceBody(); + assertThat(replace).containsEntry("eventUuid", saved.getUuid()).containsEntry("companyId", 5L).containsEntry("doneBy", "boss"); + assertThat((List) 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) 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 = e.getBody().getProperties().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 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 salespersonOptions_onlyEnabledTypeAUsersSortedByName() { + List> 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")); + } +} -- 2.54.1 From c908fbe9fcdbc611a42c3af1171776e6857cbca1 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 00:23:56 +0800 Subject: [PATCH 05/11] feat(admin-portal): port babyboo's date picker and calendar Adds react-day-picker 10.0.1 (it brings date-fns). The portal bans native date inputs, and the events and leads forms need a date field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-admin-events/design.md | 2 +- openspec/changes/add-admin-events/proposal.md | 14 +- openspec/changes/add-admin-events/tasks.md | 4 +- .../app/components/ui/calendar.test.tsx | 23 +++ .../app/components/ui/calendar.tsx | 21 +++ .../app/components/ui/date-picker.test.tsx | 122 ++++++++++++++++ .../app/components/ui/date-picker.tsx | 138 ++++++++++++++++++ .../app/lib/date-input.test.ts | 24 +++ solvway-admin-portal/app/lib/date-input.ts | 24 +++ .../app/lib/i18n/defaultMessages.ts | 4 + solvway-admin-portal/package-lock.json | 43 ++++++ solvway-admin-portal/package.json | 1 + solvway-admin-portal/test/pickDate.ts | 32 ++++ 13 files changed, 443 insertions(+), 9 deletions(-) create mode 100644 solvway-admin-portal/app/components/ui/calendar.test.tsx create mode 100644 solvway-admin-portal/app/components/ui/calendar.tsx create mode 100644 solvway-admin-portal/app/components/ui/date-picker.test.tsx create mode 100644 solvway-admin-portal/app/components/ui/date-picker.tsx create mode 100644 solvway-admin-portal/app/lib/date-input.test.ts create mode 100644 solvway-admin-portal/app/lib/date-input.ts create mode 100644 solvway-admin-portal/test/pickDate.ts diff --git a/openspec/changes/add-admin-events/design.md b/openspec/changes/add-admin-events/design.md index 69b41a6..ad327db 100644 --- a/openspec/changes/add-admin-events/design.md +++ b/openspec/changes/add-admin-events/design.md @@ -67,7 +67,7 @@ Alternative: one `services-counter` endpoint that creates both in a transaction. ### 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 and `date-fns` ^4.4.0, the versions babyboo uses. Required by the native-date-input ban; change 4 reuses the picker on phones. +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 diff --git a/openspec/changes/add-admin-events/proposal.md b/openspec/changes/add-admin-events/proposal.md index faae25e..158f742 100644 --- a/openspec/changes/add-admin-events/proposal.md +++ b/openspec/changes/add-admin-events/proposal.md @@ -7,12 +7,13 @@ Lead capture (change 4) records every lead against an event, so staff need to cr ## 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`); `services-counter` and its schema do not change. +- **`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` and `date-fns`. Change 4 reuses them for the follow-up date. +- **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`). @@ -26,8 +27,9 @@ 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 dependencies `react-day-picker` and `date-fns`. +- `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. -- Database `service-system`: one new `module` row. Additive only. -- `local/seed/03-colite.sql`: mirrors the module row. -- No change to `services-counter`, the gateway, or the `event` table. +- `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. diff --git a/openspec/changes/add-admin-events/tasks.md b/openspec/changes/add-admin-events/tasks.md index 604a0ab..46c3130 100644 --- a/openspec/changes/add-admin-events/tasks.md +++ b/openspec/changes/add-admin-events/tasks.md @@ -19,8 +19,8 @@ Babyboo source: `~/Projects/babyboo` (read only). Tastefully backoffice rules: ` ## 4. Admin portal -- [ ] 4.1 Port babyboo's `calendar.tsx` and `date-picker.tsx` (and their tests) into `app/components/ui/`, adding `react-day-picker` 10.0.1 and `date-fns` ^4.4.0 to `package.json` (`npm install`, commit the lockfile). Verify: `npm run lint && npx tsc --noEmit && npx vitest run` exit 0. - - Scope: `solvway-admin-portal/app/components/ui/**`, `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json` +- [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` - [ ] 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/**` diff --git a/solvway-admin-portal/app/components/ui/calendar.test.tsx b/solvway-admin-portal/app/components/ui/calendar.test.tsx new file mode 100644 index 0000000..26e41f4 --- /dev/null +++ b/solvway-admin-portal/app/components/ui/calendar.test.tsx @@ -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( + , + ); + 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( + , + ); + const cell = container.querySelector('[data-day="2026-10-09"]')!; + expect(cell).toHaveClass("rdp-today", "rdp-selected", "rdp-range_middle"); + }); +}); diff --git a/solvway-admin-portal/app/components/ui/calendar.tsx b/solvway-admin-portal/app/components/ui/calendar.tsx new file mode 100644 index 0000000..e8e0064 --- /dev/null +++ b/solvway-admin-portal/app/components/ui/calendar.tsx @@ -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) { + return ( + + ) +} + +export { Calendar } diff --git a/solvway-admin-portal/app/components/ui/date-picker.test.tsx b/solvway-admin-portal/app/components/ui/date-picker.test.tsx new file mode 100644 index 0000000..1b55864 --- /dev/null +++ b/solvway-admin-portal/app/components/ui/date-picker.test.tsx @@ -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 ( + <> + { setValue(v); props.onChange?.(v); }} /> + + + ); +} + +describe("DatePicker", () => { + it("opens the calendar from the keyboard", () => { + render(); + 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(); + 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(); + expect(() => pickDate("Expiry date", "2026-09-01")).toThrow(/not an enabled day/); + }); + + it("opens the calendar when the box is clicked", () => { + render(); + fireEvent.click(screen.getByLabelText("Expiry date")); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + }); + + it("ignores typing", () => { + const onChange = vi.fn(); + render(); + 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(); + 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(); + fireEvent.click(screen.getByLabelText("Expiry date")); + fireEvent.click(screen.getByRole("button", { name: "Clear" })); + expect(onChange).toHaveBeenLastCalledWith(""); + unmount(); + render( {}} />); + 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(); + 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(); + 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(); + 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(); + 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