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/.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..ad327db --- /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; its Snowflake `uuid` is generated in `mobile-api` by the shared core `Event` model and kept by `services-counter`. + +### 4. Validation lives in `mobile-api` + +`services-counter` accepts anything, so `AdminEventService` validates (required, lengths, end not before start, parseable dates) and answers 400 with a code per field (`REQUIRED_FIELD`, `TOO_LONG`, `END_BEFORE_START`, `INVALID_DATE`) and the field name. The portal also checks before submitting, but the API is the authority. + +### 5. Search is by name + +`findByPropertyAndPageable` ANDs `name` and `location`, so one search box cannot match either. The list searches by name, which is what staff look for. `ponytail:` adding an OR search needs a `services-counter` query change; add it if location search is asked for. + +### 6. Event team in `services-counter` + +New table `service-counter`.`event_salesperson` (`id`, `company_id NOT NULL`, `event_uuid`, `user_id`, `create_by`, `create_date_time`; unique `(event_uuid, user_id)`; index on `event_uuid`), an `EventSalesperson` entity and two endpoints: + +- `GET /counter/eventSalesperson/findByEventUuid/{eventUuid}`: the team rows. +- `POST /counter/eventSalesperson/replace` with `{eventUuid, companyId, userIds, doneBy}`: deletes the event's rows and inserts the new set in one transaction. + +The team lives next to `event` and `event_lead` (change 4) in the same schema, so change 4's salesperson check and listings are plain lookups. `user_id` points at `service-system`.`user` across schemas, so there is no foreign key; `mobile-api` checks each id before saving: it must be an admin user (`type A`) and enabled. `company_id` is the logged-in admin's company, never from the request. + +The event payload carries `salespersonIds` on create and update and returns `team: [{id, name, username, enabled}]` on get. `mobile-api` resolves names with one `services-system` user lookup per team member. + +`ponytail:` one lookup per member is fine for event-sized teams; batch it if teams grow past a few dozen. + +### 7. Team picker options + +`GET /api/admin/events/salesperson-options` (`BO_EVENTS`) returns active admin users as `{id, name, username}`. It reuses the admin user lookup from change 2 but needs only `BO_EVENTS`, so an events admin does not need the Users module to staff an event. Any active admin user can be on a team; roles are admin-defined, so there is no fixed "Sales" role to filter on. + +### 8. Create is two calls + +Create saves the event, then replaces the team. If the team call fails, the event exists with no team and the API answers 502 with code `TEAM_NOT_SAVED` and the event's uuid; the portal opens the event's edit page with that message so the admin can save the team again. + +Alternative: one `services-counter` endpoint that creates both in a transaction. Rejected for now: it changes the existing event save path, which also feeds the current-event cache. + +### 9. Date picker + +Port babyboo's `app/components/ui/calendar.tsx` and `date-picker.tsx` (with their tests), adding `react-day-picker` 10.0.1, the version babyboo uses (it depends on `date-fns` itself, so no direct `date-fns` dependency). Required by the native-date-input ban; change 4 reuses the picker on phones. + +### 10. Module + +`BO_EVENTS` (id 40100000, parent 40000000, url `/events`, icon `CalendarDays`, area BO, type M). `/events` joins the portal's route-module map. Every events endpoint, including salesperson options, declares `BO_EVENTS`. + +## Risks / Trade-offs + +- [Snowflake uuid rounded in the browser] → Sent as a string end to end; a test asserts the JSON type. +- [Team saved separately from the event on create] → Rare partial failure is reported with the event's uuid and fixed by saving again (decision 8). +- [Team rows point at users in another schema] → Checked on write; a deactivated member stays visible and marked inactive rather than vanishing. +- [Server time zone] → Dates are whole days computed in `mobile-api`; containers run in the same zone as the database. Revisit at the Kubernetes change. +- [Overlapping enabled events make `findCurrentEvent` pick one for the member app] → Accepted; Co-Lite's lead capture picks the event explicitly. + +## Migration Plan + +Additive SQL in `sql/` of this change: +1. `01-event-salesperson.sql`: create `service-counter`.`event_salesperson`. +2. `02-bo-events-module.sql`: insert the `BO_EVENTS` module row in `service-system`. + +Mirrored in `local/seed/03-colite.sql`. Rollback: `sql/99-rollback.sql` drops the table and deletes the module row and its `modules_roles` rows. diff --git a/openspec/changes/add-admin-events/proposal.md b/openspec/changes/add-admin-events/proposal.md new file mode 100644 index 0000000..158f742 --- /dev/null +++ b/openspec/changes/add-admin-events/proposal.md @@ -0,0 +1,35 @@ +# Proposal + +## Why + +Lead capture (change 4) records every lead against an event, so staff need to create and maintain events before go-live. Tastefully's event screens live in the Thymeleaf backoffice, which Co-Lite never deploys, and `mobile-api` only reads the current event. This change adds an Events screen to the admin portal. See `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md` (Admin portal, screen 4). + +## What Changes + +- **Admin portal Events screens**: a paged list (search by name, filter by enabled), a create page and an edit page. Desktop-first, like Users and Roles. +- **`mobile-api` gains `/api/admin/events`**: list, get, create and update, guarded by a new `BO_EVENTS` module. They call the existing `services-counter` event endpoints (`findByPropertyAndPageable`, `findByUuid`, `save`); the `event` table does not change. +- **Event fields kept** from Tastefully: name, location, start date, end date, enabled. Tastefully's backoffice rules carry over: name and location required, both dates required, end date not before start date, dates are whole days, new events start enabled. +- **Event team**: each event has a team of salespeople (active admin users), chosen on create and edit and stored in a new `services-counter` table `event_salesperson`. Change 4 limits a lead's salesperson to the event's team. +- **Not kept**: the four Tastefully upload fields (floor plan, stage activities, lucky draw, taste rewards). Their columns stay in the table and are left untouched on update. +- **No delete**, as in Tastefully. Leads will reference events, so an event is disabled instead. +- **Back-office module** `BO_EVENTS` (`/events`) added to `service-system`.`module`; SQL in this change folder, mirrored in `local/seed/`. +- **Date picker**: the portal forbids native date inputs (an existing test), so babyboo's `DatePicker` and `Calendar` components are ported, adding `react-day-picker`. Change 4 reuses them for the follow-up date. + +Not in this change: event booths, products, receipts, lucky draw and the other Tastefully event sub-screens; event company scoping (the design keeps `user` as the only existing table that gains `company_id`). + +## Capabilities + +### New Capabilities +- `admin-events`: managing events in the admin portal (list, search, create, edit, enable and disable) and the rules an event must satisfy. + +### Modified Capabilities +None. + +## Impact + +- `solvway-admin-portal`: new `app/events/**` pages, `app/api/events/**` route handlers, an events service, the ported date picker and calendar, `/events` in the route-module map. New dependency `react-day-picker`. +- `solvway-mobile-api`: new `AdminEventController`, `AdminEventService`, DTOs and counter endpoint constants. +- `solvway-services-counter`: `EventSalesperson` entity and team endpoints. +- Database: new table `service-counter`.`event_salesperson` and one new `service-system`.`module` row. Additive only. +- `local/seed/03-colite.sql`: mirrors both. +- No change to the gateway or the `event` table. 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..4cfbed5 --- /dev/null +++ b/openspec/changes/add-admin-events/specs/admin-events/spec.md @@ -0,0 +1,95 @@ +# Spec Delta + +## Purpose + +Admins with the Events module create and maintain the events that leads are captured at, including each event's team of salespeople. + +## ADDED Requirements + +### Requirement: Event list + +The system SHALL let an admin with `BO_EVENTS` list events, paginated on the server, searchable by name, filterable by enabled state, and sortable by name, start date and end date. Each row SHALL show name, location, start date, end date and whether the event is enabled. + +#### Scenario: Search by name + +- **GIVEN** events `KL Food Fair 2027` and `Penang Expo` +- **WHEN** an admin with `BO_EVENTS` searches for `food` +- **THEN** the list shows `KL Food Fair 2027` and not `Penang Expo` + +#### Scenario: Disabled filter + +- **GIVEN** an enabled event and a disabled event +- **WHEN** the admin filters by disabled +- **THEN** only the disabled event is listed + +#### Scenario: No module + +- **WHEN** an admin without `BO_EVENTS` opens the Events page or calls an events endpoint +- **THEN** the page shows not-authorised and the endpoint responds 403 + +### Requirement: Create event + +The system SHALL let an admin with `BO_EVENTS` create an event with a name (required, at most 100 characters), a location (required, at most 200 characters), a start date and an end date (both required, whole days). The end date SHALL NOT be before the start date. The event SHALL start on the start date at 00:00:00 and end on the end date at 23:59:59. A new event SHALL be enabled. Events MAY overlap. + +#### Scenario: New event + +- **WHEN** an admin creates `KL Food Fair 2027` at `MITEC` from 2027-01-15 to 2027-01-17 +- **THEN** the event is saved as enabled, starting 2027-01-15 00:00:00 and ending 2027-01-17 23:59:59 +- **AND** it appears in the event list + +#### Scenario: Missing fields + +- **WHEN** an admin submits the form without a name, location, start date or end date +- **THEN** the save is refused and each missing field is named + +#### Scenario: End before start + +- **WHEN** an admin submits an end date earlier than the start date +- **THEN** the save is refused with a message on the end date + +#### Scenario: One-day event + +- **WHEN** the start date and the end date are the same day +- **THEN** the event is saved and lasts that whole day + +### Requirement: Edit event + +The system SHALL let an admin with `BO_EVENTS` change an event's name, location, start date, end date and enabled state, with the same rules as create. Editing SHALL NOT change any other stored event data. Events SHALL NOT be deletable; an event that should no longer be used is disabled. + +#### Scenario: Disable + +- **WHEN** an admin disables an event +- **THEN** the event shows as disabled in the list and its other details are unchanged + +#### Scenario: Unknown event + +- **WHEN** an admin opens or saves an event id that does not exist +- **THEN** the system responds not found + +### Requirement: Event team + +The system SHALL let an admin with `BO_EVENTS` choose, on create and on edit, the event's team: zero or more active admin users who work the event as salespeople. A user SHALL appear at most once on a team. Saving SHALL replace the team with the chosen set. Team membership SHALL belong to the admin's company. Removing someone from the team SHALL NOT change anything already recorded against them. + +#### Scenario: Team on create + +- **WHEN** an admin creates an event with `sales1` and `sales2` on the team +- **THEN** opening the event shows `sales1` and `sales2` as its team + +#### Scenario: Change team + +- **GIVEN** an event whose team is `sales1` and `sales2` +- **WHEN** an admin saves it with `sales2` and `sales3` +- **THEN** the team is `sales2` and `sales3` + +#### Scenario: Only active admin users + +- **WHEN** an admin opens the team picker +- **THEN** it offers active admin users only, never members or deactivated users +- **AND** a request adding a member, a deactivated user or an unknown user to the team is refused + +#### Scenario: Deactivated member stays visible + +- **GIVEN** `sales1` is on an event's team +- **WHEN** `sales1` is deactivated +- **THEN** the event still lists `sales1` on its team, marked inactive, until an admin removes them +- **AND** saving the event with `sales1` still on the team succeeds 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 new file mode 100644 index 0000000..22319f2 --- /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 + +- [x] 1.1 Write `sql/01-event-salesperson.sql` (`service-counter`.`event_salesperson`: `id` bigint auto-increment PK, `company_id` bigint NOT NULL, `event_uuid` bigint NOT NULL, `user_id` bigint NOT NULL, `create_by` varchar(255), `create_date_time` datetime default now; unique `(event_uuid, user_id)`, index `event_uuid`), `sql/02-bo-events-module.sql` (`40100000 BO_EVENTS` 'Events', area BO, type M, parent 40000000, url `/events`, icon `CalendarDays`) and `sql/99-rollback.sql`. Mirror into `local/seed/03-colite.sql`. Verify: `docker compose -f local/docker-compose.yml down -v && local/up.sh` exits 0, then a read-only SELECT shows the table and the module row. + - Scope: `openspec/changes/add-admin-events/sql/**`, `local/seed/**` + +## 2. services-counter event team + +- [x] 2.1 Add `EventSalesperson` entity and repository, and `EventSalespersonController` with `GET /counter/eventSalesperson/findByEventUuid/{eventUuid}` and `POST /counter/eventSalesperson/replace` (`{eventUuid, companyId, userIds, doneBy}`; delete the event's rows and insert the set in one transaction; duplicate ids collapse to one row). Tests first: replace then find returns the new set; replacing with an empty list clears it; a failure midway leaves the old set. Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`. + - Scope: `solvway-services-counter/src/**` + +## 3. mobile-api events + +- [x] 3.1 Add `AdminEventController` and `AdminEventService` under `/api/admin/events`, all `@AdminModule("BO_EVENTS")`: `GET /events` (paged; `q` searches name; `enabled` Y/N filter; sort by name, startDate, endDate), `GET /events/{uuid}` (with `team`), `POST /events`, `PUT /events/{uuid}`, `GET /events/salesperson-options` (active admin users `{id, name, username}`). Per design: uuid as a JSON string, dates as `YYYY-MM-DD` mapped to 00:00:00 and 23:59:59, update patches the stored event so upload fields and `createBy` survive, validation codes `REQUIRED_FIELD` / `TOO_LONG` / `END_BEFORE_START` / `INVALID_DATE` with the field name, team ids must be enabled type-A users (else 400 `UNKNOWN_USER`), `company_id` from the caller, partial create answers 502 `TEAM_NOT_SAVED` with the uuid, unknown uuid 404. Tests first for each `admin-events` scenario that the API decides, including an exact-JSON test that `uuid` is a string. Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`. + - Scope: `solvway-mobile-api/src/**/controller/admin/**`, `solvway-mobile-api/src/**/service/AdminEvent*`, `solvway-mobile-api/src/**/dto/admin/**`, `solvway-mobile-api/src/**/constant/api/**`, matching tests + +## 4. Admin portal + +- [x] 4.1 Port babyboo's `calendar.tsx` and `date-picker.tsx` (and their tests) into `app/components/ui/`, with their helpers `app/lib/date-input.ts` (and test), `test/pickDate.ts` and the four `Ui*` i18n keys, adding `react-day-picker` 10.0.1 to `package.json` (`npm install`, commit the lockfile; it brings `date-fns` itself). Verify: `npm run lint && npx tsc --noEmit && npx vitest run` exit 0. + - Scope: `solvway-admin-portal/app/components/ui/**`, `solvway-admin-portal/app/lib/date-input*`, `solvway-admin-portal/test/pickDate.ts`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`, `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json` +- [x] 4.2 Add the Events screens on the Users pattern: `app/events/page.tsx` (list: search, enabled filter, sortable name/start/end, columns name, location, start, end, enabled; row Edit), `app/events/new/page.tsx`, `app/events/[uuid]/page.tsx`, an `EventForm` (name, location, start and end `DatePicker`, enabled on edit only, team multi-select from salesperson-options with inactive members shown marked), route handlers `app/api/events/**`, `app/lib/services/adminEvents.ts`, types, i18n defaults, and `/events` → `BO_EVENTS` in `routeModules`. Form checks required fields and end not before start before submitting; API errors show on the field. `TEAM_NOT_SAVED` lands on the edit page with its message. Tests first (vitest) for each portal-visible scenario. Verify: `npm run lint && npx tsc --noEmit && npx vitest run && npm run build` exit 0. + - Scope: `solvway-admin-portal/app/**` + +## 5. End-to-end check + +- [x] 5.1 Rebuild the stack and drive the portal with Playwright: grant `BO_EVENTS` to a role, create an event with a two-person team, the missing-field and end-before-start errors, edit dates and team, disable it, search and filter the list, and a user without `BO_EVENTS` gets not-authorised. Screenshots in `verification/`. Only local dev data. Verify: each scenario observed as specified, `local/smoke.sh` prints `smoke: OK`. + - Scope: `openspec/changes/add-admin-events/verification/**` + +## Workflow follow-up + +- Code review, PR to `main`, merge, then archive this change. diff --git a/openspec/changes/add-admin-events/verification/01-grant-bo-events.png b/openspec/changes/add-admin-events/verification/01-grant-bo-events.png new file mode 100644 index 0000000..908fa68 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/01-grant-bo-events.png differ diff --git a/openspec/changes/add-admin-events/verification/02-missing-fields.png b/openspec/changes/add-admin-events/verification/02-missing-fields.png new file mode 100644 index 0000000..e49b6f1 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/02-missing-fields.png differ diff --git a/openspec/changes/add-admin-events/verification/03-end-before-start.png b/openspec/changes/add-admin-events/verification/03-end-before-start.png new file mode 100644 index 0000000..b6ca40a Binary files /dev/null and b/openspec/changes/add-admin-events/verification/03-end-before-start.png differ diff --git a/openspec/changes/add-admin-events/verification/03a-end-calendar-blocks-before-start.png b/openspec/changes/add-admin-events/verification/03a-end-calendar-blocks-before-start.png new file mode 100644 index 0000000..75925d7 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/03a-end-calendar-blocks-before-start.png differ diff --git a/openspec/changes/add-admin-events/verification/04-create-filled.png b/openspec/changes/add-admin-events/verification/04-create-filled.png new file mode 100644 index 0000000..a69be86 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/04-create-filled.png differ diff --git a/openspec/changes/add-admin-events/verification/05-created.png b/openspec/changes/add-admin-events/verification/05-created.png new file mode 100644 index 0000000..bb451c0 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/05-created.png differ diff --git a/openspec/changes/add-admin-events/verification/06-edited-dates-team.png b/openspec/changes/add-admin-events/verification/06-edited-dates-team.png new file mode 100644 index 0000000..8e11ff1 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/06-edited-dates-team.png differ diff --git a/openspec/changes/add-admin-events/verification/07-disabled.png b/openspec/changes/add-admin-events/verification/07-disabled.png new file mode 100644 index 0000000..469d783 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/07-disabled.png differ diff --git a/openspec/changes/add-admin-events/verification/08-list.png b/openspec/changes/add-admin-events/verification/08-list.png new file mode 100644 index 0000000..ce55370 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/08-list.png differ diff --git a/openspec/changes/add-admin-events/verification/09-search-food.png b/openspec/changes/add-admin-events/verification/09-search-food.png new file mode 100644 index 0000000..745d71e Binary files /dev/null and b/openspec/changes/add-admin-events/verification/09-search-food.png differ diff --git a/openspec/changes/add-admin-events/verification/10-filter-disabled.png b/openspec/changes/add-admin-events/verification/10-filter-disabled.png new file mode 100644 index 0000000..abdcb1b Binary files /dev/null and b/openspec/changes/add-admin-events/verification/10-filter-disabled.png differ diff --git a/openspec/changes/add-admin-events/verification/11-inactive-member-shown.png b/openspec/changes/add-admin-events/verification/11-inactive-member-shown.png new file mode 100644 index 0000000..47af7e4 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/11-inactive-member-shown.png differ diff --git a/openspec/changes/add-admin-events/verification/12-no-module-not-authorised.png b/openspec/changes/add-admin-events/verification/12-no-module-not-authorised.png new file mode 100644 index 0000000..855ffd1 Binary files /dev/null and b/openspec/changes/add-admin-events/verification/12-no-module-not-authorised.png differ diff --git a/solvway-admin-portal/app/api/events/[uuid]/route.test.ts b/solvway-admin-portal/app/api/events/[uuid]/route.test.ts new file mode 100644 index 0000000..d0ab34f --- /dev/null +++ b/solvway-admin-portal/app/api/events/[uuid]/route.test.ts @@ -0,0 +1,67 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET, PUT } from "./route"; + +function ctx(uuid: string) { + return { params: Promise.resolve({ uuid }) }; +} +function getReq() { + return new Request("http://localhost/api/events/abc-123") as unknown as Parameters[0]; +} +function putReq(body: unknown) { + return new Request("http://localhost/api/events/abc-123", { + method: "PUT", + body: JSON.stringify(body), + }) as unknown as Parameters[0]; +} + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset(); +}); + +describe("GET /api/events/[uuid]", () => { + it("returns 401 when there is no session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await GET(getReq(), ctx("abc-123")); + expect(res.status).toBe(401); + }); + + it("forwards to GET /api/admin/events/{uuid}", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc-123" } }); + await GET(getReq(), ctx("abc-123")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/abc-123", { token: "jwt-abc" }); + }); + + it("encodes special characters in uuid", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "encoded" } }); + await GET(getReq(), ctx("some:uuid/with-slashes")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/some%3Auuid%2Fwith-slashes", { token: "jwt-abc" }); + }); +}); + +describe("PUT /api/events/[uuid]", () => { + it("returns 401 when there is no session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await PUT(putReq({ name: "Updated" }), ctx("abc-123")); + expect(res.status).toBe(401); + }); + + it("forwards the body to PUT /api/admin/events/{uuid}", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + const body = { name: "Updated", location: "New Place", startDate: "2025-02-01", endDate: "2025-02-02", enabled: true, salespersonIds: [3] }; + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc-123", ...body } }); + await PUT(putReq(body), ctx("abc-123")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/abc-123", { + method: "PUT", + body, + token: "jwt-abc", + }); + }); +}); diff --git a/solvway-admin-portal/app/api/events/[uuid]/route.ts b/solvway-admin-portal/app/api/events/[uuid]/route.ts new file mode 100644 index 0000000..ab0d531 --- /dev/null +++ b/solvway-admin-portal/app/api/events/[uuid]/route.ts @@ -0,0 +1,29 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +type Ctx = { params: Promise<{ uuid: string }> }; + +export async function GET(_req: NextRequest, { params }: Ctx) { + const token = await getToken(); + if (!token) return unauthorized(); + const { uuid } = await params; + const result = await callMobileApi>(`/api/admin/events/${encodeURIComponent(uuid)}`, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} + +export async function PUT(req: NextRequest, { params }: Ctx) { + const token = await getToken(); + if (!token) return unauthorized(); + const { uuid } = await params; + const body = await req.json().catch(() => ({})); + const result = await callMobileApi>(`/api/admin/events/${encodeURIComponent(uuid)}`, { + method: "PUT", + body, + token, + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/events/route.test.ts b/solvway-admin-portal/app/api/events/route.test.ts new file mode 100644 index 0000000..d3b1a9c --- /dev/null +++ b/solvway-admin-portal/app/api/events/route.test.ts @@ -0,0 +1,99 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ + callMobileApi: vi.fn(), + getToken: vi.fn(), +})); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET, POST } from "./route"; + +function getReq(query = "") { + return new Request(`http://localhost/api/events${query}`) as unknown as Parameters[0]; +} +function postReq(body: unknown) { + return new Request("http://localhost/api/events", { + method: "POST", + body: JSON.stringify(body), + }) as unknown as Parameters[0]; +} + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset(); +}); + +describe("GET /api/events", () => { + it("returns 401 when there is no session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await GET(getReq()); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("forwards q/page/size/sortBy/sortDir to /api/admin/events", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } }); + await GET(getReq("?q=event1&page=1&size=10&sortBy=name&sortDir=asc")); + expect(mocks.callMobileApi).toHaveBeenCalledWith( + "/api/admin/events?q=event1&page=1&size=10&sortBy=name&sortDir=asc", + { token: "jwt-abc" }, + ); + }); + + it("forwards enabled=Y/N to /api/admin/events", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } }); + await GET(getReq("?enabled=Y&page=0&size=20")); + expect(mocks.callMobileApi).toHaveBeenCalledWith( + "/api/admin/events?enabled=Y&page=0&size=20", + { token: "jwt-abc" }, + ); + }); + + it("returns 400 when enabled is not Y or N", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + const res = await GET(getReq("?enabled=true")); + expect(res.status).toBe(400); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("returns 400 when enabled is false", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + const res = await GET(getReq("?enabled=false")); + expect(res.status).toBe(400); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("uses default page=0 and size=20 when absent", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } }); + await GET(getReq("")); + expect(mocks.callMobileApi).toHaveBeenCalledWith( + "/api/admin/events?page=0&size=20", + { token: "jwt-abc" }, + ); + }); +}); + +describe("POST /api/events", () => { + it("returns 401 when there is no session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await POST(postReq({ name: "Event", location: "Place", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, salespersonIds: [] })); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("forwards the body to POST /api/admin/events", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + const body = { name: "Event", location: "Place", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, salespersonIds: [1, 2] }; + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc123", ...body } }); + await POST(postReq(body)); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events", { + method: "POST", + body, + token: "jwt-abc", + }); + }); +}); diff --git a/solvway-admin-portal/app/api/events/route.ts b/solvway-admin-portal/app/api/events/route.ts new file mode 100644 index 0000000..dae3a6a --- /dev/null +++ b/solvway-admin-portal/app/api/events/route.ts @@ -0,0 +1,44 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute"; + +export async function GET(req: NextRequest) { + const token = await getToken(); + if (!token) return unauthorized(); + + const params = new URL(req.url).searchParams; + const qs = new URLSearchParams(); + const q = params.get("q"); + if (q) qs.set("q", q); + const enabled = params.get("enabled"); + if (enabled) { + if (enabled !== "Y" && enabled !== "N") return badRequest("enabled must be Y or N."); + qs.set("enabled", enabled); + } + qs.set("page", params.get("page") ?? "0"); + qs.set("size", params.get("size") ?? "20"); + const sortBy = params.get("sortBy"); + if (sortBy) { + qs.set("sortBy", sortBy); + const sortDir = params.get("sortDir"); + if (sortDir) qs.set("sortDir", sortDir); + } + + const result = await callMobileApi>(`/api/admin/events?${qs.toString()}`, { + token, + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} + +export async function POST(req: NextRequest) { + const token = await getToken(); + if (!token) return unauthorized(); + + const body = await req.json().catch(() => ({})); + + const result = await callMobileApi>("/api/admin/events", { method: "POST", body, token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/events/salesperson-options/route.test.ts b/solvway-admin-portal/app/api/events/salesperson-options/route.test.ts new file mode 100644 index 0000000..5066394 --- /dev/null +++ b/solvway-admin-portal/app/api/events/salesperson-options/route.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ + callMobileApi: vi.fn(), + getToken: vi.fn(), +})); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET } from "./route"; + +function getReq() { + return new Request("http://localhost/api/events/salesperson-options") as unknown as Parameters[0]; +} + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset(); +}); + +describe("GET /api/events/salesperson-options", () => { + it("returns 401 when there is no session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await GET(getReq()); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("forwards to GET /api/admin/events/salesperson-options", async () => { + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: [{ id: 1, name: "Jane", username: "jane.doe" }] }); + await GET(getReq()); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/salesperson-options", { token: "jwt-abc" }); + }); +}); diff --git a/solvway-admin-portal/app/api/events/salesperson-options/route.ts b/solvway-admin-portal/app/api/events/salesperson-options/route.ts new file mode 100644 index 0000000..97ce01c --- /dev/null +++ b/solvway-admin-portal/app/api/events/salesperson-options/route.ts @@ -0,0 +1,13 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +export async function GET(req: NextRequest) { + const token = await getToken(); + if (!token) return unauthorized(); + + const result = await callMobileApi>("/api/admin/events/salesperson-options", { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/components/app/icon-map.events.test.tsx b/solvway-admin-portal/app/components/app/icon-map.events.test.tsx new file mode 100644 index 0000000..034f3dc --- /dev/null +++ b/solvway-admin-portal/app/components/app/icon-map.events.test.tsx @@ -0,0 +1,13 @@ +import { render } from "@testing-library/react"; +import { describe, it, expect } from "vitest"; +import { iconFor } from "./icon-map"; + +// add-admin-events: BO_EVENTS seed icon_name = 'CalendarDays'. +describe("iconFor — Events", () => { + it("resolves CalendarDays to a real (non-fallback) icon", () => { + const Icon = iconFor("CalendarDays"); + const { container } = render(