Compare commits
108
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
372ef7a6c6 | ||
|
|
e0ae164a82 | ||
|
|
a02d923f88 | ||
|
|
91675ffb30 | ||
|
|
a84128cb83 | ||
|
|
0710571894 | ||
|
|
37cb996bc0 | ||
|
|
899b25f45d | ||
|
|
2a78ef0a79 | ||
|
|
92a90d5f48 | ||
|
|
c5b64c15d0 | ||
|
|
6eec747757 | ||
|
|
10b32280ad | ||
|
|
cbe48c2db9 | ||
|
|
39139ed7b1 | ||
|
|
5e5762cdcb | ||
|
|
41c616b3f6 | ||
|
|
ff4b12c2e9 | ||
|
|
3ab1a0e0e3 | ||
|
|
5583cf5897 | ||
|
|
03b85737d7 | ||
|
|
9438fd8cf1 | ||
|
|
d532bdcda4 | ||
|
|
c6c220265f | ||
|
|
9163557945 | ||
|
|
2d1513aa80 | ||
|
|
adbbdc6185 | ||
|
|
08c45e9109 | ||
|
|
f13dac58a4 | ||
|
|
eff4899c0d | ||
|
|
1a7c542f5e | ||
|
|
5036196031 | ||
|
|
6ebfbfb1ac | ||
|
|
ffda35b785 | ||
|
|
cf8478d00c | ||
|
|
ab1643e36e | ||
|
|
85b40424ce | ||
|
|
9c9469f5e5 | ||
|
|
0345314c89 | ||
|
|
2842ef423f | ||
|
|
6fbbdaa3c5 | ||
|
|
065a8561e3 | ||
|
|
61d17d5e38 | ||
|
|
a8d42a8a25 | ||
|
|
07c3ecb7ad | ||
|
|
ee5fe6d15b | ||
|
|
db7f218a71 | ||
|
|
0a5d5a229b | ||
|
|
5ffd4176ec | ||
|
|
5eead327a6 | ||
|
|
7ff5c77b78 | ||
|
|
a482a3a6d0 | ||
|
|
8d5f3747bf | ||
|
|
8177c08540 | ||
|
|
044b746f0b | ||
|
|
5b63e19550 | ||
|
|
a2a369aa19 | ||
|
|
6a512bea8e | ||
|
|
05ff2e9b74 | ||
|
|
b6b05f12df | ||
|
|
a1aa906a66 | ||
|
|
998e04b844 | ||
|
|
7d29d89b3f | ||
|
|
3c30e0d629 | ||
|
|
66904869cf | ||
|
|
2c6cf7bdde | ||
|
|
df70306c9a | ||
|
|
869d7d5894 | ||
|
|
c8ffc6aede | ||
|
|
57e187a992 | ||
|
|
ebf5177543 | ||
|
|
f0629192f2 | ||
|
|
bb39e6b805 | ||
|
|
8f80f52c04 | ||
|
|
bb9d4357af | ||
|
|
ec504fd529 | ||
|
|
de2ae63cea | ||
|
|
00ce47bc49 | ||
|
|
b7d9da8ec0 | ||
|
|
5526294e69 | ||
|
|
de007b5328 | ||
|
|
69d3ebc58c | ||
|
|
91a0f339a5 | ||
|
|
118c57c0ea | ||
|
|
a6996841ac | ||
|
|
c9c0745955 | ||
|
|
840b5a3bae | ||
|
|
4243a2d6cd | ||
|
|
628d885261 | ||
|
|
3ed713d2cb | ||
|
|
b070358446 | ||
|
|
cd1034e962 | ||
|
|
bd881ada09 | ||
|
|
e62c83a187 | ||
|
|
4f38f6b167 | ||
|
|
518901a6d8 | ||
|
|
7aa5c4b921 | ||
|
|
81ef54f996 | ||
|
|
7fc3adfe05 | ||
|
|
8a527e9ffe | ||
|
|
adc62ac436 | ||
|
|
1523dc566b | ||
|
|
d715073ab2 | ||
|
|
10f59c5ca8 | ||
|
|
b9912478e0 | ||
|
|
01603e9ece | ||
|
|
9d811df86a | ||
|
|
877a6b07ad |
No files matched your search
@@ -16,5 +16,7 @@
|
|||||||
# Playwright
|
# Playwright
|
||||||
.playwright-mcp/
|
.playwright-mcp/
|
||||||
|
|
||||||
|
solvway-admin-portal/.impeccable/
|
||||||
|
|
||||||
# Build output
|
# Build output
|
||||||
target/
|
target/
|
||||||
@@ -82,6 +82,44 @@ After running `04`, `SELECT LENGTH(password) FROM \`service-system\`.\`user\` WH
|
|||||||
|
|
||||||
`99-rollback.sql` in the same folder undoes the three and deletes the login history.
|
`99-rollback.sql` in the same folder undoes the three and deletes the login history.
|
||||||
|
|
||||||
|
| File | What it does |
|
||||||
|
|---|---|
|
||||||
|
| `openspec/changes/archive/2026-11-30-add-admin-audit-log/sql/01-audit-event.sql` | Creates `service-log`.`audit_event` (the admin audit trail). DDL: run it with a user that may create tables, not the services' user. |
|
||||||
|
| `openspec/changes/archive/2026-11-30-add-admin-audit-log/sql/02-audit-log-module.sql` | Adds the Audit log back-office module (`BO_AUDIT_LOG`). No role gets it; super admins grant it under Roles. |
|
||||||
|
|
||||||
|
`99-rollback.sql` in the same folder undoes the two and deletes the audit trail.
|
||||||
|
|
||||||
|
| File | What it does |
|
||||||
|
|---|---|
|
||||||
|
| `openspec/changes/archive/2026-11-30-add-company-scoping/sql/01-company-code-status.sql` | Gives each company a sign-in code and a status. Company 1 becomes `INS` (code `ins`) and a second company `CV` (code `cv`) is added. DDL. |
|
||||||
|
| `openspec/changes/archive/2026-11-30-add-company-scoping/sql/02-company-columns.sql` | Adds the company to events and emails (existing rows go to INS) and makes interests one list shared by every company. DDL. |
|
||||||
|
| `openspec/changes/archive/2026-11-30-add-company-scoping/sql/03-admin-login-names.sql` | Super admins (role 1) get no company and keep their username. Every other admin moves to INS and is renamed `username@ins`. It stops without changing anything if an admin username already contains `@`. |
|
||||||
|
|
||||||
|
Run the three in order, with a user that may alter tables. File `03` ends every admin session: everyone signs in again, staff with company `ins`. `99-rollback.sql` in the same folder undoes the three. It fails on the username unique key once two companies have a user with the same username; rename one of them first.
|
||||||
|
|
||||||
|
| File | What it does |
|
||||||
|
|---|---|
|
||||||
|
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/01-status-change.sql` | Creates `service-counter`.`event_lead_status_change` (every event-lead status change with its time and user) and an index on `event_lead` for the dashboard. DDL. |
|
||||||
|
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/02-status-change-backfill.sql` | Gives event leads captured before this release a history: OPEN at capture, and the current status at the last update. These times are approximate. Safe to run twice. |
|
||||||
|
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/03-dashboard-module.sql` | Adds the Dashboard back-office module (`BO_DASHBOARD`). No role gets it; super admins grant it under Roles. |
|
||||||
|
|
||||||
|
Run the three in order before the new images go live: the new services-counter writes to the table from `01` on every capture and status edit, and fails without it. `01` needs a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the status history.
|
||||||
|
|
||||||
|
| File | What it does |
|
||||||
|
|---|---|
|
||||||
|
| `openspec/changes/archive/2026-12-01-add-qr-self-registration/sql/01-registration-link.sql` | Creates `service-counter`.`registration_link` (QR registration codes) and adds `source`, `consent_at` and `consent_notice_id` to `event_lead`. Existing event leads become `STAFF`. DDL. |
|
||||||
|
| `openspec/changes/archive/2026-12-01-add-qr-self-registration/sql/02-company-privacy-notice.sql` | Creates `service-system`.`company_privacy_notice` and gives every existing company the default English and Bahasa Malaysia privacy notice, with the company's name filled in. DDL. |
|
||||||
|
|
||||||
|
Run both before the new images go live: the new services-counter reads the new `event_lead` columns on every lead query and fails without them. Both need a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the codes, the notices and the consent records.
|
||||||
|
|
||||||
|
| File | What it does |
|
||||||
|
|---|---|
|
||||||
|
| `openspec/changes/archive/2026-12-01-uppercase-company-codes/sql/01-uppercase-codes.sql` | Turns every company code and every staff login name to capitals (`ins` becomes `INS`, `sales9@cv` becomes `sales9@CV`). Safe to run twice. |
|
||||||
|
|
||||||
|
Run it when the new services-system and mobile-api go live. Staff who are signed in keep working until their session needs a refresh, then sign in again. Sign-in still ignores case, so staff may keep typing `ins` or `cv`. `99-rollback.sql` in the same folder turns codes and login names back to lowercase.
|
||||||
|
|
||||||
|
**Review the privacy notice before go-live.** The seeded text is a starting template written for the PDPA, not legal advice. INS and CV should each have theirs checked; a super admin changes it under **Companies → Privacy notice**. A company with no notice has no working QR codes.
|
||||||
|
|
||||||
**Database user:**
|
**Database user:**
|
||||||
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
|
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
|
||||||
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
|
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
|
||||||
@@ -98,6 +136,7 @@ The services publish and subscribe through Google Pub/Sub. It is not replaced in
|
|||||||
- **Project:** use a Google Cloud project, and give its id as `GCP_PROJECT`.
|
- **Project:** use a Google Cloud project, and give its id as `GCP_PROJECT`.
|
||||||
- **Service account:** create one with the Pub/Sub Publisher and Pub/Sub Subscriber roles, and download a JSON key. Mount the key into every Java image except `api-gateway` (section 7), and set `GCP_CREDENTIAL_FILE=file:/var/secrets/gcp/key.json`.
|
- **Service account:** create one with the Pub/Sub Publisher and Pub/Sub Subscriber roles, and download a JSON key. Mount the key into every Java image except `api-gateway` (section 7), and set `GCP_CREDENTIAL_FILE=file:/var/secrets/gcp/key.json`.
|
||||||
- **Topics and subscriptions:** use `local/pubsub/topics.txt`. Each line is a topic name, optionally followed by a subscription name. Some topics appear on several lines with different subscriptions (e.g. `update-sync-topic`): create each topic once, then every subscription listed for it. Subscriptions use default settings.
|
- **Topics and subscriptions:** use `local/pubsub/topics.txt`. Each line is a topic name, optionally followed by a subscription name. Some topics appear on several lines with different subscriptions (e.g. `update-sync-topic`): create each topic once, then every subscription listed for it. Subscriptions use default settings.
|
||||||
|
- **Audit log:** `audit-event-topic` with `audit-event-subscription` carries admin audit events from mobile-api to service-log. It is in `topics.txt`; service-log also creates both at startup if they are missing. Keep the subscription's default of not retaining acknowledged messages: the events carry admin usernames and IPs. `AUDIT_RETENTION_DAYS` (section 6) must be at least 1, or service-log does not start.
|
||||||
|
|
||||||
## 6. Environment variables
|
## 6. Environment variables
|
||||||
|
|
||||||
@@ -160,6 +199,12 @@ The keys:
|
|||||||
| `JWT_SECRET` | Secret | Same value as `JWT_TOKEN` |
|
| `JWT_SECRET` | Secret | Same value as `JWT_TOKEN` |
|
||||||
| `CUSTOMER_PORTAL_BASE_URL` | Plain | The customer portal is not deployed in phase 1. When unset, it falls back to a Tastefully address that only the member referral link uses, which Co-Lite does not use. Set it once a customer portal exists. |
|
| `CUSTOMER_PORTAL_BASE_URL` | Plain | The customer portal is not deployed in phase 1. When unset, it falls back to a Tastefully address that only the member referral link uses, which Co-Lite does not use. Set it once a customer portal exists. |
|
||||||
|
|
||||||
|
**`service-log`:**
|
||||||
|
|
||||||
|
| Variable | Kind | Value |
|
||||||
|
|---|---|---|
|
||||||
|
| `AUDIT_RETENTION_DAYS` | Plain | Optional (default 730). Admin audit events older than this many days are deleted daily at 03:30. |
|
||||||
|
|
||||||
**`api-gateway`:** only `JWT_TOKEN` (same value as everywhere). No Pub/Sub, Redis or database settings, and no `key.json` mount. It reads its client keys from the mounted `appkeys.json` (section 7).
|
**`api-gateway`:** only `JWT_TOKEN` (same value as everywhere). No Pub/Sub, Redis or database settings, and no `key.json` mount. It reads its client keys from the mounted `appkeys.json` (section 7).
|
||||||
|
|
||||||
**`admin-portal`:**
|
**`admin-portal`:**
|
||||||
@@ -206,6 +251,8 @@ Generate each random value separately, for example with `openssl rand -base64 48
|
|||||||
|
|
||||||
Route `co-lite.containerverse.dev` to the `admin-portal` Service on port 3000, with TLS. Only the admin portal is public: the browser talks to the portal, and the portal talks to `mobile-api` inside the cluster. Do not expose `mobile-api`, `api-gateway` or the services.
|
Route `co-lite.containerverse.dev` to the `admin-portal` Service on port 3000, with TLS. Only the admin portal is public: the browser talks to the portal, and the portal talks to `mobile-api` inside the cluster. Do not expose `mobile-api`, `api-gateway` or the services.
|
||||||
|
|
||||||
|
QR registration pages (`/r/<code>`) are served by the admin portal on the same host, so nothing new is routed. mobile-api rate-limits visitors by the address the portal sends: the last entry of `X-Forwarded-For`, which is the one Traefik adds. That works whether Traefik appends to or replaces the header. If another proxy or load balancer sits in front of Traefik, the last entry is that proxy's address and every visitor shares one limit; the portal's `clientIp` would then have to change (or use the PROXY protocol). If the portal sees no `X-Forwarded-For` and no `X-Real-Ip` at all, every visitor shares the portal pod's limit.
|
||||||
|
|
||||||
## 9. Secret templates
|
## 9. Secret templates
|
||||||
|
|
||||||
There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files.
|
There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files.
|
||||||
@@ -270,6 +317,11 @@ data:
|
|||||||
|
|
||||||
- **No email provider yet.** Staff onboarding does not need one: the admin types each new user's first password, and "Set temporary password" on a user's page unlocks a user who forgot theirs. Both force a password change at the next sign-in. Forgot-password and "Send password reset" still create an email with a temporary password. Nobody receives it, but `service-email` saves every email first, so a super admin (or a role granted Emails) can read it under **Emails** and pass the password on in person. The user must change it at the next sign-in. Grant Emails narrowly: it shows every saved email, including other users' temporary passwords, member email-verification codes, and contact or distributor form submissions with the sender's personal data.
|
- **No email provider yet.** Staff onboarding does not need one: the admin types each new user's first password, and "Set temporary password" on a user's page unlocks a user who forgot theirs. Both force a password change at the next sign-in. Forgot-password and "Send password reset" still create an email with a temporary password. Nobody receives it, but `service-email` saves every email first, so a super admin (or a role granted Emails) can read it under **Emails** and pass the password on in person. The user must change it at the next sign-in. Grant Emails narrowly: it shows every saved email, including other users' temporary passwords, member email-verification codes, and contact or distributor form submissions with the sender's personal data.
|
||||||
- **Sign-in lockout.** 5 failed sign-ins within 15 minutes lock a username, even with the right password, until 15 minutes after the first of those failures, and unknown usernames are counted too. Anyone who knows a username can therefore lock it on purpose. An admin with **Login security** can unlock it at once (Locked tab), and can change the limits there. If every super admin is locked, wait out the period. The lock check fails open: if `service-system` is down, sign-in still works without the lockout.
|
- **Sign-in lockout.** 5 failed sign-ins within 15 minutes lock a username, even with the right password, until 15 minutes after the first of those failures, and unknown usernames are counted too. Anyone who knows a username can therefore lock it on purpose. An admin with **Login security** can unlock it at once (Locked tab), and can change the limits there. If every super admin is locked, wait out the period. The lock check fails open: if `service-system` is down, sign-in still works without the lockout.
|
||||||
|
- **Companies and super admins.** INS and CV each see only their own leads, events, event leads, users, emails, login history and audit log. Staff sign in with their company code, username and password. A super admin leaves Company blank, sees every company (with a company picker in the header), and is the only one who can manage companies, roles, interests, lockout settings and password rules. Changing a company's code renames its staff's sign-in names and signs them out; deactivating a company blocks its staff from signing in. Emails sent from public forms and other system emails have no company, so only super admins see them. Do not give a company's old code to another company while sessions opened under the old code may still be valid: such a session token would resolve to the new company's user of the same name. When in doubt, never reuse a code.
|
||||||
|
- **Lead dashboard.** Users whose role has the Dashboard module see lead captures, wins, conversion and overdue follow-ups on the home page, for this month, last month or a custom range of up to two years in Malaysian time. A lead counts as converted when its status at an event is WON. Wins and days to win come from the status history, which starts with this release; for older leads it is approximate (see section 3).
|
||||||
|
- **QR self-registration.** Visitors scan a code and register themselves as a lead at an event. Each event has an event code, and each team member has a personal code that assigns the visitor to them; staff with Events see and switch them off on the event page, and every staff user finds their own under **My QR codes** in the user menu. Codes work until the event's end date (Malaysian time). A registration never edits an existing lead: differences go into that event lead's notes for staff to check. Each visitor IP may load 120 registration pages in 10 minutes across all events, and submit 60 registrations per event in 10 minutes; there is no CAPTCHA. For a reprintable code with scan counts, paste the code's link into the dynamic-qr console and print that code instead; no visitor data reaches dynamic-qr.
|
||||||
|
- **Gateway paths open to the public registration.** The internal gateway lets a few exact read paths and the registration write through without a user token, so mobile-api can serve visitors who are not signed in. Keep the gateway unexposed (above); the design notes in the change folder list the paths and the risk.
|
||||||
|
- **Time zone.** The Java images run with `TZ=Asia/Kuala_Lumpur` (set in the `docker-java-21` base image), and stored times such as capture, consent and notice times are Malaysian local time. Do not override `TZ` on the services.
|
||||||
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
|
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
|
||||||
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
|
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
|
||||||
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
|
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
|
||||||
|
|||||||
+10
-7
@@ -20,7 +20,7 @@ Source: whiteboard session (transcribed 2026-11-26). Items marked **[?]** were u
|
|||||||
| 2 | Leads module | Assign leads to sales team | ✓ |
|
| 2 | Leads module | Assign leads to sales team | ✓ |
|
||||||
| 3 | Built-in WhatsApp | WhatsApp messaging inside the system | ✓ |
|
| 3 | Built-in WhatsApp | WhatsApp messaging inside the system | ✓ |
|
||||||
| 4 | Home — create event | Create event per lead | not ticked |
|
| 4 | Home — create event | Create event per lead | not ticked |
|
||||||
| 5 | QR | Show event details? / scan QR | ✓ |
|
| 5 | QR | Multi-purpose QR: event details, event check-in, later other uses (see Answered) | ✓ |
|
||||||
| 6 | Voucher | INS own voucher; partner voucher | ✓ |
|
| 6 | Voucher | INS own voucher; partner voucher | ✓ |
|
||||||
| 7 | Event milestone | Track events joined (Achievement Board) | ✓ |
|
| 7 | Event milestone | Track events joined (Achievement Board) | ✓ |
|
||||||
| 8 | Gamification | Experience / service giveaway: (i) Spin & Win, (ii) Blindbox. Prizes: IPTV test kit, Omada, CCTV? | ✓ |
|
| 8 | Gamification | Experience / service giveaway: (i) Spin & Win, (ii) Blindbox. Prizes: IPTV test kit, Omada, CCTV? | ✓ |
|
||||||
@@ -36,16 +36,19 @@ Source: whiteboard session (transcribed 2026-11-26). Items marked **[?]** were u
|
|||||||
|
|
||||||
## Open Questions
|
## Open Questions
|
||||||
|
|
||||||
- "Tastetuny" **[?]** written under the deadline — project or client name?
|
- Gamification prizes: none chosen yet (IPTV test kit, Omada, CCTV were ideas only). To be confirmed.
|
||||||
- QR: should scanning show event details, check the member in, or both?
|
|
||||||
- Gamification prizes: confirm IPTV test kit, Omada, CCTV.
|
## Answered (2026-11-30)
|
||||||
- Who are "INS" and "CV" — the two partnering brands (CV = Containerverse?)?
|
|
||||||
- Left edge of the board was cut off — any missing items?
|
- **"Tastetuny"** on the board is Tastefully, the platform Co-Lite is cloned from.
|
||||||
|
- **QR:** a QR code can carry different purposes: event details, an event check-in, and later other uses. Scanning does what the code is for. This improves on Tastefully's existing QR feature, which is only a starting point.
|
||||||
|
- **INS and CV** are the two companies that will use the system as a test run. Each sees only its own data at go-live; super admins see all (see Tenancy below).
|
||||||
|
- **Left edge of the board:** nothing missing for now.
|
||||||
|
|
||||||
## Decisions (2026-11-26)
|
## Decisions (2026-11-26)
|
||||||
|
|
||||||
- **Base:** Clone of Tastefully (`~/Projects/tastefully`, Solvway platform).
|
- **Base:** Clone of Tastefully (`~/Projects/tastefully`, Solvway platform).
|
||||||
- **Tenancy:** Single company at go-live. No second company planned soon. New tables still carry a company id so a later SaaS move is a migration, not a rebuild.
|
- **Tenancy:** ~~Single company at go-live.~~ Changed 2026-11-30: two companies (INS and CV) at go-live, each seeing only its own data (leads, events, users and the rest). Super admins see every company's data. New tables carry a company id; admin APIs and screens must filter by it.
|
||||||
- **Modules dropped:** MLM modules (bonus, stockist, tree, inventory, related jobs).
|
- **Modules dropped:** MLM modules (bonus, stockist, tree, inventory, related jobs).
|
||||||
- **Admin portal:** Rebuild as a Next.js admin portal, modelled on babyboo's `solvway-admin-portal` (shell, auth, roles, tables). The Tastefully Thymeleaf backoffice is ported over for reference only; it is not deployed or extended.
|
- **Admin portal:** Rebuild as a Next.js admin portal, modelled on babyboo's `solvway-admin-portal` (shell, auth, roles, tables). The Tastefully Thymeleaf backoffice is ported over for reference only; it is not deployed or extended.
|
||||||
- Every admin screen needs a JSON admin API in `mobile-api` (`/api/admin/**`). Tastefully has none today; babyboo's admin controllers for auth, users, roles, audit log and content are adaptable. Events, check-in, rewards and vouchers admin APIs must be built new.
|
- Every admin screen needs a JSON admin API in `mobile-api` (`/api/admin/**`). Tastefully has none today; babyboo's admin controllers for auth, users, roles, audit log and content are adaptable. Events, check-in, rewards and vouchers admin APIs must be built new.
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# Admin Audit Log — Design
|
||||||
|
|
||||||
|
Date: 2026-11-30. Change id: `add-admin-audit-log`.
|
||||||
|
|
||||||
|
## Intent
|
||||||
|
|
||||||
|
Nothing in Co-Lite records who did what in the admin portal. When an admin edits a user, changes a role's grants, edits or exports leads, or opens a saved email (which can hold a temporary password), the only trace is a line in the application log. Sign-ins are the exception: the `login_audit` table covers them (`add-admin-login-security`).
|
||||||
|
|
||||||
|
The user wants an audit trail before go-live (2027-01-15) and a screen to read it. Scope was agreed on 2026-11-30, with lead edits recording field names only, not values.
|
||||||
|
|
||||||
|
Reference: babyboo's `add-portal-audit-log` (archive `2026-11-19`) and `audit-log-readable-actions` (`2026-11-20`). This design ports the admin half of that work, trimmed.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- Record an audit event for every admin write through mobile-api, and for chosen sensitive reads.
|
||||||
|
- Record refused attempts (a missing module grant, for example) when the token is valid, so the actor is known.
|
||||||
|
- Store before/after values only for an allow-list of fields.
|
||||||
|
- Provide an `/audit-log` screen in the admin portal with filters and a detail view, behind its own module.
|
||||||
|
- Delete events after 2 years, automatically.
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- Member and public calls. The customer portal's public lead capture has no actor.
|
||||||
|
- Sign-in, sign-out and own password change. `login_audit` already records these; the audit log neither duplicates nor links to them.
|
||||||
|
- Page views and ordinary reads (the existing response-time log covers traffic).
|
||||||
|
- Reviving or cleaning up the legacy `back_office_access_log`, `/log/save` and similar. They are unused; removing them belongs in a separate change.
|
||||||
|
|
||||||
|
## Anti-goals
|
||||||
|
|
||||||
|
- Any password, token, raw request body, or lead personal data (name, phone, email, notes) in an audit row.
|
||||||
|
- An audit write that slows down or fails the admin's action.
|
||||||
|
- Audit rows that anyone without `BO_AUDIT_LOG` can read.
|
||||||
|
|
||||||
|
## Approaches considered
|
||||||
|
|
||||||
|
- **A. Pub/Sub from mobile-api's `AppAccessAspect` to services-log (chosen).** The aspect already sees every admin call (the user, its `@AdminModule` code, the outcome) and already publishes a `ResponseTime` record per call to services-log over Pub/Sub. One more message type on the same path is the smallest change. It is asynchronous, and losing an event is acceptable.
|
||||||
|
- **B. A synchronous REST call from mobile-api to services-log, like `login_audit`.** Simpler to test, but it adds a network hop to every admin write, and it needs its own error handling.
|
||||||
|
- **C. Explicit calls inside each service method.** Easy to forget on new endpoints. Rejected: the aspect covers new endpoints by default.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### Event table `service-log`.`audit_event`
|
||||||
|
|
||||||
|
| Column | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `id` | PK |
|
||||||
|
| `company_id` | the actor's company (nullable) |
|
||||||
|
| `occurred_at` | server time of the call |
|
||||||
|
| `actor` | admin username |
|
||||||
|
| `module` | the handler's `@AdminModule` code (for example `BO_USERS`) |
|
||||||
|
| `action` | readable action code (see below) |
|
||||||
|
| `http_method`, `path_template` | for example `PUT /api/admin/users/{id}`: the template, never the concrete path or the query |
|
||||||
|
| `target_id` | the record acted on: the first path variable, when there is one |
|
||||||
|
| `outcome`, `http_status` | `SUCCESS` or `FAILURE`, plus the status code |
|
||||||
|
| `client_ip` | forwarded browser IP (nullable) |
|
||||||
|
| `changes` | JSON, nullable: `{field: {before, after}}` for allow-listed fields, or `{fields: [..]}` for lead edits |
|
||||||
|
|
||||||
|
Indexes: `occurred_at`, `(actor, occurred_at)`, `(module, action, occurred_at)`. The DDL and the module row go in the change's `sql/` folder and in `local/seed/03-colite.sql`.
|
||||||
|
|
||||||
|
### What is recorded
|
||||||
|
|
||||||
|
- **Every non-GET handler under `/api/admin/**`,** except:
|
||||||
|
- `AdminAuthController`'s login, logout, refresh, forgot-password and change-password. Sign-in history covers these, or they have no actor.
|
||||||
|
- `first-login` is recorded.
|
||||||
|
- POSTs that only read, marked with `@Audited(skip = true)`. Today that is event-lead `match`.
|
||||||
|
- **Sensitive GETs, marked with `@Audited`:**
|
||||||
|
- the lead export;
|
||||||
|
- the event-lead export;
|
||||||
|
- the email detail (opening an email).
|
||||||
|
- **Refusals:** a valid admin token refused by the access check (missing module, not super admin, pending first login) is recorded as `FAILURE` with the status. Calls without a valid token are not recorded, because there is no actor.
|
||||||
|
|
||||||
|
### Action codes
|
||||||
|
|
||||||
|
`@Audited(action = "...")` names an action explicitly. Without one, the code is derived from the handler: drop an `Admin` prefix and a `Controller` suffix, then convert both parts to UPPER_SNAKE. For example, `AdminUserController.update` becomes `USER_UPDATE`. Explicit names are used where the derived one would be unclear:
|
||||||
|
- `USER_SET_TEMPORARY_PASSWORD`;
|
||||||
|
- `USER_SEND_PASSWORD_RESET`;
|
||||||
|
- `ROLE_SET_MODULES`;
|
||||||
|
- `LEAD_EXPORT`;
|
||||||
|
- `EVENT_LEAD_EXPORT`;
|
||||||
|
- `EMAIL_VIEW`.
|
||||||
|
|
||||||
|
### Before/after (allow-listed)
|
||||||
|
|
||||||
|
The handler's service supplies the values through a small request-scoped holder (babyboo's `AuditChanges`). Nothing is diffed generically from request bodies.
|
||||||
|
|
||||||
|
- **Admin user update and create:** `roles` (role names) and `enabled`.
|
||||||
|
- **Role module grants:** module codes added and removed.
|
||||||
|
- **Lead edit and event-lead edit:** the names of the fields that changed, no values. This was the user's call.
|
||||||
|
- **Login-security settings** (lockout and password rules): the changed setting names with before and after. These are not personal data.
|
||||||
|
|
||||||
|
### Write path
|
||||||
|
|
||||||
|
- After the handler returns or throws, `AppAccessAspect` builds an `AuditEvent` and publishes it to the new Pub/Sub topic `audit-event`. The `AuditEvent` message class lives in core-libs, shared by mobile-api and services-log.
|
||||||
|
- services-log subscribes on `audit-event-log`, which it creates at startup like its existing subscriptions, and saves the event.
|
||||||
|
- A publish failure is logged at WARN and swallowed. The existing response-time publishing is unchanged.
|
||||||
|
|
||||||
|
### Client IP
|
||||||
|
|
||||||
|
- The portal's server-side calls to mobile-api already send `X-Client-Ip` on every request (`app/lib/server/mobileApi.ts`, the last `x-forwarded-for` hop), so the portal needs no change.
|
||||||
|
- mobile-api stores the value for reading only.
|
||||||
|
|
||||||
|
### Retention
|
||||||
|
|
||||||
|
A scheduled purge in services-log deletes events older than `audit.retention-days` (default 730) in batches, modelled on the existing response-time archive scheduler. The setting is an environment variable.
|
||||||
|
|
||||||
|
### Reading
|
||||||
|
|
||||||
|
- services-log gets `POST /log/audit/search`. It takes filters (actor, module, action, outcome, date range) and paging, returns newest first, and caps the page size at 100.
|
||||||
|
- services-log also gets `GET /log/audit/{id}`.
|
||||||
|
- Both are reached through the gateway with the admin's token, like the other services. Only mobile-api holds a gateway key (`docs/deployment.md` section 7).
|
||||||
|
- mobile-api adds `GET /api/admin/audit-log` and `GET /api/admin/audit-log/{id}` under `@AdminModule("BO_AUDIT_LOG")`.
|
||||||
|
|
||||||
|
### Admin portal
|
||||||
|
|
||||||
|
- **`/audit-log`:** a paged list (newest first) with columns time, who, module, action, target, outcome and IP.
|
||||||
|
- **Filters:** who, module (select), action, outcome and From/To date.
|
||||||
|
- **Detail page:** the event, plus a before/after table, or a list of changed field names for lead edits.
|
||||||
|
- **Copy and gating:** all copy goes through `t()`. The page is gated by `RequireModule` and `ROUTE_MODULES`.
|
||||||
|
- **Module row:** `(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText')`. It has no role grants, so only super admins see it until it is granted.
|
||||||
|
|
||||||
|
## My calls (check these)
|
||||||
|
|
||||||
|
- Pub/Sub, asynchronous, best-effort. A lost event is acceptable, as in babyboo.
|
||||||
|
- Reads go through the gateway with the admin's token. babyboo switched to in-cluster calls because other api-key holders existed; Co-Lite has only mobile-api.
|
||||||
|
- `first-login` is recorded and the other auth endpoints are not.
|
||||||
|
- The login-security settings record values, since they are not personal data. User changes record role names and the enabled flag only.
|
||||||
|
- Retention is 730 days, set by environment variable rather than on a screen.
|
||||||
|
- Legacy `/log/save` and the old access-log tables are left alone.
|
||||||
|
|
||||||
|
## Left to the builder
|
||||||
|
|
||||||
|
- The exact JSON shape of `changes`, as long as the detail view can render it.
|
||||||
|
- Column widths, so the list fits at 1280 px without horizontal scrolling (babyboo hit this).
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
# Company Scoping — Design
|
||||||
|
|
||||||
|
Date: 2026-11-30. Change id: `add-company-scoping`.
|
||||||
|
|
||||||
|
## Intent
|
||||||
|
|
||||||
|
Co-Lite goes live on 2027-01-15 with two test-run companies, INS and CV. This replaces the earlier "single company at go-live" decision (`docs/feature-list.md`, Tenancy). Each company's staff must see only their own company's data. One super admin sees and manages everything, including creating companies. More companies will follow, and adding one must need no code change, no deploy and no database work: the super admin creates it on a screen.
|
||||||
|
|
||||||
|
Everything built so far assumes one company. Some of it is already scoped: leads, event leads, interests and event salespersons are queried by the caller's company. The rest is not: users, events, emails, login history and the audit log. The super admin cannot see across companies at all.
|
||||||
|
|
||||||
|
## Decisions taken with the user (2026-11-30)
|
||||||
|
|
||||||
|
- **Separated per company:** leads, event leads, events, users, emails, login history, audit events.
|
||||||
|
- **Shared by all companies:** roles, interests, lockout settings, password rules.
|
||||||
|
- **Super admin:** a super admin can do everything. It sees every company's data, through a company picker and through mixed lists with a Company column. It creates the companies.
|
||||||
|
- A super admin is an account with **no company** that holds the super admin role. There can be more than one (a second one is kept for recovery); only a super admin can create another.
|
||||||
|
- Company staff can never hold the super admin role.
|
||||||
|
- **Sign-in:** the login page asks for **Company** (for example `ins`), **Username** and **Password**. A super admin leaves Company empty. Usernames are unique **within a company**, so INS and CV can each have a `john` (approach B below).
|
||||||
|
- **Editing shared data:** only a super admin edits roles, interests, lockout settings and password rules.
|
||||||
|
- **Leads:** the same phone at two companies is two separate leads, each with its own New/Existing history. This is already how leads work.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- A Companies screen where the super admin creates and edits companies.
|
||||||
|
- Company + username sign-in for company staff; username only (Company empty) for super admins.
|
||||||
|
- Every admin API and screen returns only the caller's company data, unless the caller is the super admin.
|
||||||
|
- The super admin can see all companies at once or pick one, and can create data in a chosen company.
|
||||||
|
- Interests become one shared list.
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- Members and the customer portal. Member accounts and member sign-in are unchanged.
|
||||||
|
- A company admin who manages their own company's roles, interests or settings. These are shared, so only a super admin edits them.
|
||||||
|
- Per-company branding, logos, web addresses or settings.
|
||||||
|
- Moving or splitting existing data between companies beyond the one-time setup below.
|
||||||
|
- Deleting a company. A company can be deactivated.
|
||||||
|
|
||||||
|
## Anti-goals
|
||||||
|
|
||||||
|
- Any path where a company's staff can read or change another company's data: list, detail, export, edit by id, or audit.
|
||||||
|
- A change to how members sign in.
|
||||||
|
- A sign-in answer that reveals whether a company code or a username exists.
|
||||||
|
- A cross-company leak through a shared table (interests, roles) or through the audit log.
|
||||||
|
|
||||||
|
## Approaches considered (for `username@account`)
|
||||||
|
|
||||||
|
- **A. The suffix is part of the stored username** (`john@ins` saved as the username, globally unique). Smallest change; the sign-in path is untouched. A company's code could never change once users exist. Not chosen.
|
||||||
|
- **B. Usernames unique per company; the company is given at sign-in (chosen by the user).** `john` is stored with company INS. Sign-in finds company `ins`, then the user `john` in it. A company's code can change later. It touches the sign-in lookup, the uniqueness rule, token identity, lockout keys and password reset.
|
||||||
|
- **Login page shape (chosen by the user):** a separate Company field, rather than one `john@ins` field or a company dropdown. A dropdown was rejected because the public login page would list every customer company.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### Companies
|
||||||
|
|
||||||
|
- `company` gains `code` (lowercase letters, digits and hyphens, 2 to 20 characters, unique) and `status` (`A` active, `I` inactive). `name` stays.
|
||||||
|
- **Companies screen** `/companies` in the admin portal, **super admin only** (not a grantable module): list, create, edit name, code and status. Changing a code changes every staff sign-in for that company; the screen warns before saving.
|
||||||
|
- An inactive company's staff cannot sign in. Their data is kept and the super admin still sees it.
|
||||||
|
|
||||||
|
### Identity: the login name
|
||||||
|
|
||||||
|
- The login page sends company code, username and password. Internally a staff user's **login name** is `username@code`; a super admin's login name is its plain username (`admin`), and it belongs to no company (`company_id` NULL). The login name is never typed by staff; it is how the system refers to them.
|
||||||
|
- The login name is the one string that identifies a staff user everywhere the system uses a string today:
|
||||||
|
- the JWT subject;
|
||||||
|
- every `findByUsername`-style lookup from a token (mobile-api resolves the caller about 40 times this way);
|
||||||
|
- the lockout key and the `login_audit` username;
|
||||||
|
- the audit event actor;
|
||||||
|
- forgot-password and the temporary-password flows.
|
||||||
|
- **Lookup rule (one place, services-system):** a login name with an `@` splits at the **last** `@` into username and code; the user is found by company code and username, and must be type `A` in an active company. A login name without `@` matches only a user with no company, which is the super admin.
|
||||||
|
- **Uniqueness:** staff usernames are unique per company; the super admin's username is unique among company-less admin users. Member usernames keep their current global uniqueness. The database enforces it (left to the builder: for example a maintained, uniquely indexed `login_name` column, rewritten in one transaction when a company's code changes).
|
||||||
|
- Changing a company's code changes its users' login names. Existing sessions of those users end; they sign in again with the new code.
|
||||||
|
- Sign-in errors stay as they are: a wrong or inactive company, an unknown user and a wrong password all give the same `BAD_LOGIN` answer.
|
||||||
|
- **Forgot password** takes company, username and email, like sign-in. **Email** is unique per company, not across companies, so one person can have an account at INS and at CV.
|
||||||
|
|
||||||
|
### Super admins
|
||||||
|
|
||||||
|
- Cross-company access means: the caller has **no company and holds the super admin role** (role id 1). Both are required.
|
||||||
|
- The role cannot be granted to a user who has a company, and a company-less user must hold it: every other user belongs to a company. The Users screen enforces this, and services-system rejects it too.
|
||||||
|
- A super admin creates another super admin from the Users screen by leaving the company empty.
|
||||||
|
|
||||||
|
### Scoping rule
|
||||||
|
|
||||||
|
- **Company staff:** every admin read, write, export and detail lookup is limited to the caller's company. A record of another company answers 404, as if it did not exist.
|
||||||
|
- **Super admin:** sees all companies by default. Lists take an optional company filter. Creating a company-owned record (user, event, event lead capture) requires a company: the super admin picks one in the form.
|
||||||
|
- Enforcement is server-side in mobile-api's admin services, which already pass the caller's company to services-counter. The portal only reflects it.
|
||||||
|
|
||||||
|
### What is scoped where
|
||||||
|
|
||||||
|
| Data | Today | Change |
|
||||||
|
|---|---|---|
|
||||||
|
| Leads, event leads, event salespersons | scoped by caller company | super admin: all or the picked company |
|
||||||
|
| Interests | per company | **shared**: one list for all companies; editing super admin only |
|
||||||
|
| Events (`event`) | no company | add `company_id`; scope like leads |
|
||||||
|
| Users | no scoping | scope by company; staff manage only their own company's users |
|
||||||
|
| Roles | global | stay shared; editing becomes super admin only |
|
||||||
|
| Emails (`email`) | no company | add `company_id` (the company of the user the email is for); scope; emails with no company are visible to the super admin only |
|
||||||
|
| Login history, locked users | `login_audit.company_id` exists, not used | scope by company; staff with Login security unlock only their own company's users |
|
||||||
|
| Lockout settings, password rules | global | stay shared; editing becomes super admin only |
|
||||||
|
| Audit log | `company_id` stored, not used | scope by company |
|
||||||
|
|
||||||
|
### Interests become shared
|
||||||
|
|
||||||
|
- `interest.company_id` is no longer used for scoping; the unique key moves from `(company_id, name)` to `name`.
|
||||||
|
- Existing interests: at go-live there is one company, so its list becomes the shared list.
|
||||||
|
- Only a super admin adds, renames or deactivates interests. Company staff pick from the list when capturing leads.
|
||||||
|
|
||||||
|
### Which company an audit row belongs to
|
||||||
|
|
||||||
|
- An audit event and a login-history row carry the **actor's** company, as stored today.
|
||||||
|
- A super admin's actions therefore have no company and are visible to super admins only, even when they changed a company's record. Resolving the changed record's company for every audited endpoint is out of scope.
|
||||||
|
- A failed sign-in carries the company when the code matches a company, and none otherwise; rows with no company are visible to super admins only.
|
||||||
|
|
||||||
|
### Admin portal
|
||||||
|
|
||||||
|
- **Header company picker, super admin only:** "All companies", then each company. It sets the company filter for lists and the default company for create forms. Company staff do not see it.
|
||||||
|
- **Lists, super admin with "All companies":** a Company column on users, events, leads, event leads, emails, login history and audit log.
|
||||||
|
- **Create forms, super admin:** a Company field, prefilled from the picker. Company staff never see it.
|
||||||
|
- **Sign-in page:** Company, Username and Password fields. A super admin leaves Company empty. Forgot password asks for the same Company and Username plus the email.
|
||||||
|
- **Users screen:** company staff create users in their own company. A super admin picks the company, or leaves it empty to create another super admin.
|
||||||
|
- **Screens that become super admin only:** Companies, Roles, Interests, and the Login security Settings tab.
|
||||||
|
|
||||||
|
### One-time setup (deploy SQL)
|
||||||
|
|
||||||
|
- Add `code` and `status` to `company`; add `company_id` to `event` and `email`; move the interest unique key; add the user uniqueness change.
|
||||||
|
- Create INS and CV with their codes. The existing company row (id 1, "Co-Lite") becomes INS, so existing local and test data lands there.
|
||||||
|
- The existing super admin account (`admin`) gets `company_id` NULL. Every other existing admin user stays in company 1 (INS).
|
||||||
|
- Existing events and emails get company 1.
|
||||||
|
- Co-Lite is not deployed anywhere yet, so the setup runs on a fresh database. The deploy ends every existing session, because the token identity changes. No existing admin username contains `@`; the deploy SQL checks this and stops if one does.
|
||||||
|
|
||||||
|
## My calls (check these)
|
||||||
|
|
||||||
|
- Another company's record answers 404, not 403, so its existence is not revealed.
|
||||||
|
- Audit and login-history rows belong to the actor's company; a super admin's actions are visible to super admins only.
|
||||||
|
- Email is unique per company; forgot password takes company, username and email.
|
||||||
|
- The existing company becomes INS; CV starts empty.
|
||||||
|
- Inactive companies block their staff's sign-in; there is no delete.
|
||||||
|
- Changing a company's code or deactivating it ends its staff's sessions.
|
||||||
|
|
||||||
|
## Left to the builder
|
||||||
|
|
||||||
|
- How login-name uniqueness is enforced in MySQL (a maintained `login_name` column is one way).
|
||||||
|
- Whether the company code is cached or looked up per request.
|
||||||
|
- Exact column widths for the Company column, and how the picker looks in the header.
|
||||||
|
- Splitting the work into tasks, ordered so that sign-in keeps working at every step.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Lead Dashboard — Design
|
||||||
|
|
||||||
|
Date: 2026-12-01. Status: draft for approval.
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Co-Lite exists to generate leads for INS and CV marketing. Managers need to see which events, salespeople and interests produce leads and which of those leads convert. Today the portal home page is a welcome line, and the system keeps only each event lead's current status, so it cannot say when a lead was won or how long it took.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- A dashboard on the portal home page showing lead capture and conversion for a chosen period.
|
||||||
|
- Record every event-lead status change with its time, so the dashboard can count wins in a period and time to win.
|
||||||
|
- Gate the dashboard with a new ACL module, `BO_DASHBOARD`, assigned to roles like every other module.
|
||||||
|
- Company scoping as everywhere else: staff see their company, super admins see all or the one picked.
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- New lead statuses or a pipeline editor. The existing statuses stay: OPEN, CONTACTED, QUALIFIED, WON, LOST.
|
||||||
|
- Member-app conversion (option 2). It comes later as its own change.
|
||||||
|
- Showing the status timeline on the lead or event-lead screens. The data will exist; a later change can show it.
|
||||||
|
- Excel export of the dashboard.
|
||||||
|
- Demographics (age, gender, state) as in the legacy event statistics: Co-Lite leads carry none of those fields.
|
||||||
|
|
||||||
|
## Anti-goals
|
||||||
|
|
||||||
|
- Numbers that disagree with the Leads and Event Leads listings for the same filter.
|
||||||
|
- SQL built by string replacement (the legacy report service does this; it is an injection risk).
|
||||||
|
- A slow home page: every user lands there after sign-in.
|
||||||
|
|
||||||
|
## Definitions
|
||||||
|
|
||||||
|
- **Capture:** one event lead (a person captured at one event). A person captured at two events is two captures. Conversion is per capture, because the question is which events convert.
|
||||||
|
- **Won:** an event lead whose current status is WON.
|
||||||
|
- **Won in period:** a won event lead whose latest change into WON falls in the period.
|
||||||
|
- **Conversion rate:** of the captures made in the period, the share that are now WON.
|
||||||
|
- **Days to win:** from capture to the latest change into WON, in whole days. Reported as the median.
|
||||||
|
- **Overdue follow-up:** an event lead that is not WON or LOST and whose next follow-up date is before today. This is a current count, not tied to the period.
|
||||||
|
- **Clock:** Asia/Kuala_Lumpur, as in the legacy dashboard.
|
||||||
|
|
||||||
|
## What the dashboard shows
|
||||||
|
|
||||||
|
- **Period:** This month (the default), Last month, or a custom range. A range of up to 62 days is charted by day; a longer one by month (legacy rule).
|
||||||
|
- **Company picker:** the existing picker, for super admins only.
|
||||||
|
- **Tiles:**
|
||||||
|
- Captures.
|
||||||
|
- New leads (lead type NEW).
|
||||||
|
- Won in period.
|
||||||
|
- Conversion rate.
|
||||||
|
- Median days to win.
|
||||||
|
- Overdue follow-ups.
|
||||||
|
- **Funnel:** the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST).
|
||||||
|
- **Trend chart:** captures and wins per day or month.
|
||||||
|
- **By event:** each event with captures in the period.
|
||||||
|
- Columns: event, captures, new, won, conversion rate.
|
||||||
|
- A super admin viewing all companies also gets a Company column.
|
||||||
|
- Each row links to that event's leads.
|
||||||
|
- **By salesperson:** for the period's captures, per salesperson.
|
||||||
|
- Columns: assigned, worked (status beyond OPEN), won, lost, conversion rate, overdue follow-ups.
|
||||||
|
- Captures with no salesperson appear as an "Unassigned" row.
|
||||||
|
- **By interest:** per interest, the captures and wins. A capture with two interests counts under both.
|
||||||
|
- **Phone width:** tiles stack, and the tables become cards, as on the other listings.
|
||||||
|
|
||||||
|
## Status timing
|
||||||
|
|
||||||
|
- **New table** `event_lead_status_change` in services-counter, append-only. Columns:
|
||||||
|
- `id`, `company_id`, `event_lead_id`;
|
||||||
|
- `from_status` (null for the first row), `to_status`;
|
||||||
|
- `changed_at`, `changed_by`.
|
||||||
|
- **Capture** writes the first row: null → initial status, at `captured_at`.
|
||||||
|
- **An edit that changes status** writes one row in the same transaction. An edit that keeps the status writes nothing.
|
||||||
|
- **Backfill** for existing event leads, in the change's SQL:
|
||||||
|
- one row null → OPEN at `captured_at`;
|
||||||
|
- when the current status is not OPEN, a second row OPEN → status at `updated_at`, or at `captured_at` when `updated_at` is null.
|
||||||
|
|
||||||
|
These times are approximate, and the deployment notes say so.
|
||||||
|
|
||||||
|
## Access
|
||||||
|
|
||||||
|
- **New module** `BO_DASHBOARD`, type M, URL `/`, id `40050000`. The sidebar shows a "Dashboard" link.
|
||||||
|
- **The home page** shows the dashboard to users with `BO_DASHBOARD`. Everyone else sees today's welcome, not a not-authorised page, because every user lands at home after sign-in.
|
||||||
|
- **The endpoint** answers 403 without the module.
|
||||||
|
- **Super admins** pass as they do for every module.
|
||||||
|
|
||||||
|
## Approach
|
||||||
|
|
||||||
|
Aggregate in services-counter SQL:
|
||||||
|
- services-counter gets one endpoint, `/counter/dashboard/leads`. It takes `companyId` (null = all), `from`, `to` and the bucket, and runs grouped native queries with bind parameters over `event_lead`, `event_lead_status_change`, `event_lead_interest` and `event`.
|
||||||
|
- mobile-api adds `GET /api/admin/dashboard/leads` under `@AdminModule("BO_DASHBOARD")`. It applies the company scope, resolves salesperson names in one batch call to services-system, and returns one JSON payload.
|
||||||
|
|
||||||
|
Rejected:
|
||||||
|
- **Aggregating in mobile-api from paged listings:** too many calls, and it gets slower as leads grow.
|
||||||
|
- **A separate report service like legacy:** a new deployable for one screen.
|
||||||
|
|
||||||
|
## Portal
|
||||||
|
|
||||||
|
- **Charts:** add `recharts` and copy babyboo's `chart.tsx` wrapper. babyboo already uses both, and the look then matches.
|
||||||
|
- **The funnel and tables** use existing components (Card, Table, data-table).
|
||||||
|
|
||||||
|
## Left to the builder
|
||||||
|
|
||||||
|
- Indexes for the dashboard queries, chosen from EXPLAIN on realistic local data: likely `event_lead(company_id, captured_at)` and `event_lead_status_change(event_lead_id, changed_at)`.
|
||||||
|
- Exact tile layout and copy.
|
||||||
|
- Message keys for every label (English, as for other screens).
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
# QR Self-Registration — Design
|
||||||
|
|
||||||
|
Date: 2026-12-01. Status: draft for approval (owner answers of 2026-12-01 folded in).
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Co-Lite is a lead-generation system for INS and CV. At events, staff type each visitor's details into Event Leads today. A walk-in visitor should instead scan a QR code at the booth or on a salesperson's phone, register themselves in under a minute, and become a lead that staff follow up. That removes typing at a busy booth, captures more visitors, and credits the salesperson who brought the visitor in.
|
||||||
|
|
||||||
|
Decided with the owner on 2026-12-01:
|
||||||
|
- **Who scans:** walk-in visitors with no account register themselves as leads.
|
||||||
|
- **No member app.** Co-Lite is a lead-generation system.
|
||||||
|
- **Codes:** one QR per event (banner) plus a personal QR per salesperson per event. A personal code assigns the lead to that salesperson.
|
||||||
|
- **dynamic-qr:** loose integration only. Co-Lite makes its own registration links and QR images. An admin who wants a repointable printed code with scan statistics pastes the Co-Lite link into the dynamic-qr console and prints that code. No API integration, and no personal data ever reaches dynamic-qr.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- A public, phone-first registration page per event. It shows the event's name, dates and location (the "event details" purpose), a short form, and a thank-you page.
|
||||||
|
- A registration creates or links the lead and creates the event lead, with the same rules as staff capture.
|
||||||
|
- Event banner codes and personal salesperson codes. Staff can show, download, copy and switch off each code.
|
||||||
|
- Consent under Malaysia's PDPA is recorded for every self-registration.
|
||||||
|
- Abuse limits on the public page.
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- A member app, member accounts, check-in for members, rewards or vouchers.
|
||||||
|
- Calling the dynamic-qr API (option 2, later if admins print many codes).
|
||||||
|
- Showing the registration source on the Event Leads and dashboard screens. The data is stored; a later change can show it.
|
||||||
|
- Several languages on the public page. It is English with message keys, so it can be translated later.
|
||||||
|
- Confirmation emails or WhatsApp to the visitor.
|
||||||
|
- Removing the unused customer portal (`solvway-customer-portal`). That is a later clean-up.
|
||||||
|
|
||||||
|
## Anti-goals
|
||||||
|
|
||||||
|
- Revealing whether a person already exists. Every successful registration gets the same thank-you page.
|
||||||
|
- A guessable link, such as an event id in the URL.
|
||||||
|
- A public endpoint that reaches company data beyond one event's name, dates, location and the active interests.
|
||||||
|
|
||||||
|
## Approaches considered (where the public page lives)
|
||||||
|
|
||||||
|
1. **A public route in the admin portal (chosen).** `/r/{token}` is excluded from the admin sign-in guard. The admin portal is already deployed behind Traefik, so there is nothing new to deploy. A separate hostname, for example `join.`, can point at the same app later.
|
||||||
|
2. **The existing customer portal.** It is the untouched Tastefully member portal (login, vouchers, draws). It is not deployed and not built in CI, so it would need a new image, CI step and clean-up for one page.
|
||||||
|
3. **A new small public app.** The cleanest separation, but it is a new deployable for one page.
|
||||||
|
|
||||||
|
## The visitor's flow
|
||||||
|
|
||||||
|
1. The visitor scans a code. It holds `https://<admin portal host>/r/<token>`.
|
||||||
|
2. The page shows the event name, dates and location, then a form:
|
||||||
|
- name (required), mobile, email (at least one of the two), company, job title;
|
||||||
|
- interests (active ones, optional);
|
||||||
|
- a PDPA consent tick box with the company's notice, which must be ticked.
|
||||||
|
3. Submit. The page always shows "Thank you, you're registered for <event>", unless input is invalid (field errors) or the code is not active.
|
||||||
|
4. A code that is unknown, switched off, belongs to an event that is disabled or has ended, or belongs to a salesperson no longer on the team shows "This code is no longer active." It shows no event details.
|
||||||
|
|
||||||
|
## What a registration does
|
||||||
|
|
||||||
|
Normalisation is the same as staff capture (event-lead-capture spec): mobile becomes E.164, email is lower-cased, and the same limits and errors apply. Matching is stricter, because anyone can type someone else's mobile or email into a public form (owner decision 2026-12-01):
|
||||||
|
- **Match by mobile first, then by email.** The match is within the event's company. When the mobile matches one lead and the email another, the mobile match wins. Among several matches on the same key, the newest wins.
|
||||||
|
- **A matched lead is never edited.** The registration links to it as EXISTING. Any submitted value that differs from the lead's is written into the event lead's notes ("Registered by QR with: name …, email …") for staff to review.
|
||||||
|
- **No match** creates a new lead (NEW) with the submitted values.
|
||||||
|
- **Already captured at this event:** nothing changes, with one exception. When the existing event lead has no salesperson and the visitor came through a personal code whose salesperson is still an active team member, that salesperson is assigned. The visitor sees the same thank-you page either way.
|
||||||
|
- **The event lead:**
|
||||||
|
- status OPEN;
|
||||||
|
- salesperson = the code's salesperson when they are still an active user on the event's active team, otherwise none (Unassigned);
|
||||||
|
- the chosen interests;
|
||||||
|
- `source` = `QR`;
|
||||||
|
- `consent_at` = now;
|
||||||
|
- `consent_notice_id` = the notice version shown;
|
||||||
|
- `captured_by` = `qr`.
|
||||||
|
- **Status history:** null → OPEN, by `qr`.
|
||||||
|
|
||||||
|
## Codes and their management
|
||||||
|
|
||||||
|
- **Data:** table `service-counter.registration_link`:
|
||||||
|
- `id`, `company_id`, `event_uuid`, `salesperson_user_id` (NULL for the event code);
|
||||||
|
- `token` (22-character random URL-safe string from 128 random bits, unique);
|
||||||
|
- `enabled`, `created_by`, `created_at`, `updated_by`, `updated_at`.
|
||||||
|
|
||||||
|
One row per event code and per salesperson per event, created on first use.
|
||||||
|
- **Event page** (users with `BO_EVENTS`): a "Registration QR" section with:
|
||||||
|
- the event code: QR image, copy link, download PNG, and an on/off switch;
|
||||||
|
- each active team member's personal code, with the same controls, so admins can print lanyard cards.
|
||||||
|
|
||||||
|
Staff without edit rights (read-only event view) see the codes but not the switch.
|
||||||
|
- **"My QR codes" page** for any signed-in staff user. It lists the events where they are an active team member and the event has not ended, with their personal code each. It is gated `ANY_ADMIN`, and it only ever shows the caller's own codes.
|
||||||
|
- **When a code works:** the code is enabled, the event is enabled, its end date (Malaysia) has not passed, and the event's company has a privacy notice. Visitors can register before the event starts. A personal code whose salesperson has left the team or been deactivated keeps working, and its registrations arrive Unassigned, so printed cards never lose leads.
|
||||||
|
- **Company scope:** as everywhere. Staff see their company's events; super admins see all.
|
||||||
|
|
||||||
|
## Consent (PDPA)
|
||||||
|
|
||||||
|
- **Bilingual notice.** The Personal Data Protection Act 2010 (s.7) requires the notice in Bahasa Malaysia and English. The form shows both, with a required tick box.
|
||||||
|
- **One notice per company, versioned.** Table `service-system.company_privacy_notice`: `id`, `company_id`, `text_en`, `text_ms`, `created_by`, `created_at`. It is append-only, and the newest row is the current notice.
|
||||||
|
- A super admin edits it on the Companies page. Saving adds a new row.
|
||||||
|
- The change's SQL seeds INS and CV with the default below, with the company name filled in.
|
||||||
|
- **What a registration records:** `event_lead.consent_at` and `event_lead.consent_notice_id`, so staff can show exactly what a person agreed to.
|
||||||
|
- **A company with no notice row has no working codes.**
|
||||||
|
- **The default text is a starting template, not legal advice.** INS and CV should have it reviewed before go-live.
|
||||||
|
|
||||||
|
Default notice (English); `{company}` is the company's name:
|
||||||
|
|
||||||
|
> **Privacy notice.** {company} collects the details you enter on this form (your name, mobile number, email, company, job title and interests) to contact you about our products, services and events, including by phone, SMS, WhatsApp and email. Your details are used only by {company} and the service providers who run this system for us, and are not sold to anyone. We keep them for as long as you remain a contact of ours or until you ask us to delete them. You may ask to see or correct your details, or withdraw this consent, at any time by contacting {company}. Giving your details is voluntary, but without them we cannot follow up with you.
|
||||||
|
>
|
||||||
|
> ☐ I agree to {company} using my details as described above.
|
||||||
|
|
||||||
|
Default notice (Bahasa Malaysia):
|
||||||
|
|
||||||
|
> **Notis privasi.** {company} mengumpul butiran yang anda masukkan dalam borang ini (nama, nombor telefon bimbit, e-mel, syarikat, jawatan dan minat anda) untuk menghubungi anda mengenai produk, perkhidmatan dan acara kami, termasuk melalui telefon, SMS, WhatsApp dan e-mel. Butiran anda hanya digunakan oleh {company} dan pembekal perkhidmatan yang mengendalikan sistem ini bagi pihak kami, dan tidak dijual kepada sesiapa. Kami menyimpannya selagi anda kekal sebagai kenalan kami atau sehingga anda meminta kami memadamnya. Anda boleh meminta untuk melihat atau membetulkan butiran anda, atau menarik balik persetujuan ini, pada bila-bila masa dengan menghubungi {company}. Pemberian butiran adalah secara sukarela, tetapi tanpanya kami tidak dapat menghubungi anda.
|
||||||
|
>
|
||||||
|
> ☐ Saya bersetuju {company} menggunakan butiran saya seperti yang diterangkan di atas.
|
||||||
|
|
||||||
|
## Abuse limits
|
||||||
|
|
||||||
|
- Each client IP may submit at most 60 registrations per event per 10 minutes (Redis counter in mobile-api), so a busy booth on shared venue Wi-Fi is not locked out. Over the limit the visitor sees "Too many registrations from this device. Try again later."
|
||||||
|
- The visitor's IP is read the same way the audit log reads the client IP.
|
||||||
|
- The thank-you page has a "Register another person" button for a kiosk tablet at the booth.
|
||||||
|
- The form has a hidden honeypot field. A submission that fills it is answered with the normal thank-you page and saves nothing.
|
||||||
|
- Each IP may make at most 120 page loads (`GET /r/{token}` data) per 10 minutes, to slow token guessing. With 128-bit tokens, guessing is not a practical risk anyway.
|
||||||
|
- `ponytail:` no CAPTCHA. Add one if the limits prove too weak at a real event.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- **Public, mobile-api:** `@AppAuth(skipValidate = true)`; the portal's server sends the api-key.
|
||||||
|
- `GET /api/public/registration/{token}` returns `{eventName, startDate, endDate, location, companyCode, interests:[{id,name}]}`, or 404 `CODE_INACTIVE`.
|
||||||
|
- `POST /api/public/registration/{token}` with `{name, mobile, email, companyName, jobTitle, interestIds, consent, website}` (`website` is the honeypot). It returns 200 `{eventName}`, 400 with field errors, 404 `CODE_INACTIVE`, or 429 `TOO_MANY`.
|
||||||
|
- **Admin, mobile-api:**
|
||||||
|
- `GET /api/admin/events/{uuid}/registration-links` (`BO_EVENTS`) returns the event code and the team members' codes, each `{salesperson|null, token, enabled}`. Missing rows are created.
|
||||||
|
- `PUT /api/admin/events/{uuid}/registration-links/{token}` with `{enabled}` (`BO_EVENTS`, write).
|
||||||
|
- `GET /api/admin/my-registration-links` (`ANY_ADMIN`) returns the caller's own codes for current events.
|
||||||
|
- **services-counter:** endpoints for the link lookup and creation and for the self-registration capture, reusing `EventLeadService.capture` with `source` and `consent_at`.
|
||||||
|
- **Routing:** the portal's server calls mobile-api directly with the api-key it already holds (`MOBILE_API_KEY`), as for every other call. The registration token never goes into the audit log as a target; the event uuid is recorded instead.
|
||||||
|
- **Portal:**
|
||||||
|
- public route `/r/[token]` and its proxy `app/api/public/registration/[token]`, both excluded from the admin auth middleware;
|
||||||
|
- the QR images, rendered in the browser with `qrcode.react` (the library babyboo's portal already uses; one new dependency);
|
||||||
|
- the portal builds the link from its own origin, so no new setting is needed.
|
||||||
|
|
||||||
|
## Data changes
|
||||||
|
|
||||||
|
- New table `registration_link` (above).
|
||||||
|
- `event_lead`: add `source` varchar(8) NOT NULL DEFAULT 'STAFF' (`STAFF` | `QR`), `consent_at` datetime NULL and `consent_notice_id` bigint NULL.
|
||||||
|
- New table `service-system.company_privacy_notice` (above), seeded with the default notice for INS and CV.
|
||||||
|
- Companies page: a "Privacy notice" section (English and Bahasa Malaysia) for super admins.
|
||||||
|
- Nothing is backfilled. Existing event leads are `STAFF`.
|
||||||
|
|
||||||
|
## Calls made (for the owner to check)
|
||||||
|
|
||||||
|
1. The public page lives on the admin portal at `/r/<token>`, not the customer portal.
|
||||||
|
2. Personal codes are per salesperson per event, not one code per person for all events. Each lead then lands at the right event.
|
||||||
|
3. A personal code keeps working after its salesperson leaves the team, but its registrations arrive Unassigned.
|
||||||
|
4. Codes work from creation until the event's end date. There is no "reopen". Extend the event's end date instead.
|
||||||
|
5. The limits: 60 registrations per IP per event and 120 page loads per IP per 10 minutes. There is also a honeypot field, and no CAPTCHA.
|
||||||
|
6. A visitor already captured with no salesperson who scans a personal code is assigned to that salesperson.
|
||||||
|
|
||||||
|
## Left to the builder
|
||||||
|
|
||||||
|
- The exact layout and copy of the public page (mobile first, readable outdoors, large tap targets).
|
||||||
|
- How the portal proxy passes the visitor's IP to mobile-api, matching what the audit log already uses for the client IP.
|
||||||
|
- The PNG download size and file name.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Co-Lite visual foundation — design
|
||||||
|
|
||||||
|
Date: 2026-12-01. Status: direction chosen by the owner; design awaiting approval.
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
The admin portal still wears the inherited babyboo look: brown primary, DM Sans headings, 16px soft corners, a gradient wordmark, and native selects whose option lists cannot be styled (the owner asked why the company picker's options are not rounded). The owner wants a complete revamp before go-live (2027-01-15), and the invitations screens (tasks 5.1–5.3 of `add-event-invitations`) wait on it.
|
||||||
|
|
||||||
|
## Direction
|
||||||
|
|
||||||
|
The owner looked at nine directions on a decision page and chose **the category standard**: a clean SaaS admin, done well, with no brand gimmick. The quality bar is Stripe Dashboard, Linear and Vercel (my call; the owner did not name products). Reference sketch: `solvway-admin-portal/.impeccable/mocks/decision/canon.html` (local only).
|
||||||
|
|
||||||
|
- **Colour:** white ground and white sidebar with a 1px slate border; slate text (#0F172A, muted #64748B); slate-50 surfaces (#F1F5F9); one blue accent (#2563EB) for primary buttons, links, focus rings and the active nav item. Status pills are pastel tints with dark text (green, amber, red, blue, slate).
|
||||||
|
- **Type:** Inter for everything; DM Sans is dropped. Tabular figures for numbers.
|
||||||
|
- **Shape:** 8px card radius, 6px controls, one soft shadow on cards, 1px borders.
|
||||||
|
- **Wordmark:** a small blue square mark plus "Co-Lite" in solid text. The gradient text goes.
|
||||||
|
- **Selects:** every native `<select>` in the portal becomes the shared styled select menu, so open option lists match the rest of the UI.
|
||||||
|
|
||||||
|
## Approaches considered
|
||||||
|
|
||||||
|
1. **Re-theme the tokens and fix the shell (chosen).** The portal already takes every colour from theme tokens (a test enforces it), so changing the token values, the fonts and the radius re-skins every screen at once. Then fix the few places the tokens do not reach: the wordmark, native selects, and shell spacing.
|
||||||
|
2. **Rebuild screen by screen.** Gives more control per screen, but takes weeks, and screens look mixed until the end.
|
||||||
|
3. **Swap in a component kit.** Adds a dependency and churn for no gain: the shadcn-style components are already here.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
In: theme tokens (light and dark), fonts, radius and shadow; app shell (sidebar, header, page header, footer); shared `ui/` components where token changes are not enough; the six files with native selects; removing the gradient wordmark.
|
||||||
|
|
||||||
|
Out (follow-up change on the same tokens): booth screen (My QR codes), public visitor pages (`/r`, `/i`, `/c`), login. Route pills on lead tables arrive with the invitations screens.
|
||||||
|
|
||||||
|
Open after the finish review (for the follow-up change): the header label repeats the page title ("Events" above "New event") and is blank on the dashboard; it should show the real trail or go. Also: tables at 360 px cut off mid-column with no scroll cue; the 12-item sidebar could use quiet group dividers; login comments still describe the old brown and gold panel.
|
||||||
|
|
||||||
|
## Decisions for the owner to check
|
||||||
|
|
||||||
|
- **Dark theme:** keep the existing dark mechanism and re-derive its tokens from the same slate and blue scale. Light stays the default. (PRODUCT.md lists a dark default as undecided.)
|
||||||
|
- **Per-company accent:** not in this change; both companies use the same blue.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
|
||||||
|
- Colours only from theme tokens; the existing rule and its test stay.
|
||||||
|
- No new dependencies: the styled select is already in `app/components/ui/select.tsx` (Radix).
|
||||||
|
- Existing tests that pin the old look (DM Sans on `<html>`, native select interactions) are re-targeted to the new requirements, never weakened.
|
||||||
|
- Verified in Playwright at 1280 and 360 px, light and dark.
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
# topic [subscription] - one per line; created in the Pub/Sub emulator before services start
|
# topic [subscription] - one per line; created in the Pub/Sub emulator before services start
|
||||||
activate-member-topic activate-member-subscription
|
activate-member-topic activate-member-subscription
|
||||||
|
audit-event-topic audit-event-subscription
|
||||||
backoffice-topic backoffice-subscription
|
backoffice-topic backoffice-subscription
|
||||||
batch-transfer-member-topic batch-transfer-member-subscription
|
batch-transfer-member-topic batch-transfer-member-subscription
|
||||||
camunda-new-registration-topic camunda-new-registration-subscription
|
camunda-new-registration-topic camunda-new-registration-subscription
|
||||||
|
|||||||
@@ -151,3 +151,153 @@ WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
|
|||||||
-- add-admin-login-security/sql/03-login-security-module.sql
|
-- add-admin-login-security/sql/03-login-security-module.sql
|
||||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||||
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
|
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
|
||||||
|
|
||||||
|
-- add-admin-audit-log/sql/02-audit-log-module.sql (still USE `service-system` from above)
|
||||||
|
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||||
|
(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText');
|
||||||
|
|
||||||
|
-- add-admin-audit-log/sql/01-audit-event.sql
|
||||||
|
USE `service-log`;
|
||||||
|
CREATE TABLE IF NOT EXISTS `audit_event` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`company_id` bigint NULL,
|
||||||
|
`occurred_at` datetime(6) NOT NULL,
|
||||||
|
`actor` varchar(191) NOT NULL,
|
||||||
|
`module` varchar(64) NULL,
|
||||||
|
`action` varchar(128) NOT NULL,
|
||||||
|
`http_method` varchar(16) NULL,
|
||||||
|
`path_template` varchar(255) NULL,
|
||||||
|
`target_id` varchar(128) NULL,
|
||||||
|
`outcome` varchar(16) NOT NULL COMMENT 'SUCCESS | FAILURE',
|
||||||
|
`http_status` int NULL,
|
||||||
|
`client_ip` varchar(64) NULL,
|
||||||
|
`changes` text NULL COMMENT 'JSON: allow-listed before/after, or changed field names',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_audit_event_occurred_at` (`occurred_at`),
|
||||||
|
KEY `idx_audit_event_actor` (`actor`, `occurred_at`),
|
||||||
|
KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- add-company-scoping/sql/01-company-code-status.sql
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
ALTER TABLE `company`
|
||||||
|
ADD COLUMN `code` varchar(20) NULL AFTER `name`,
|
||||||
|
ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`;
|
||||||
|
|
||||||
|
UPDATE `company` SET `name` = 'INS', `code` = 'INS' WHERE `id` = 1;
|
||||||
|
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'CV', 'A');
|
||||||
|
|
||||||
|
ALTER TABLE `company`
|
||||||
|
MODIFY COLUMN `code` varchar(20) NOT NULL,
|
||||||
|
ADD UNIQUE KEY `uk_company_code` (`code`);
|
||||||
|
|
||||||
|
-- add-company-scoping/sql/02-company-columns.sql
|
||||||
|
USE `service-counter`;
|
||||||
|
|
||||||
|
ALTER TABLE `event` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_event_company` (`company_id`);
|
||||||
|
UPDATE `event` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||||
|
|
||||||
|
ALTER TABLE `interest`
|
||||||
|
DROP INDEX `uk_interest_company_name`,
|
||||||
|
MODIFY COLUMN `company_id` bigint NULL,
|
||||||
|
ADD UNIQUE KEY `uk_interest_name` (`name`);
|
||||||
|
|
||||||
|
USE `service-email`;
|
||||||
|
|
||||||
|
ALTER TABLE `email` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_email_company` (`company_id`);
|
||||||
|
UPDATE `email` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||||
|
|
||||||
|
-- add-company-scoping/sql/03-admin-login-names.sql
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
DROP PROCEDURE IF EXISTS `colite_check_admin_usernames`;
|
||||||
|
DELIMITER //
|
||||||
|
CREATE PROCEDURE `colite_check_admin_usernames`()
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM `user` WHERE `type` = 'A' AND `username` LIKE '%@%') THEN
|
||||||
|
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An admin username contains @; rename it before running this script';
|
||||||
|
END IF;
|
||||||
|
END //
|
||||||
|
DELIMITER ;
|
||||||
|
CALL `colite_check_admin_usernames`();
|
||||||
|
DROP PROCEDURE `colite_check_admin_usernames`;
|
||||||
|
|
||||||
|
UPDATE `user` u SET u.`company_id` = NULL
|
||||||
|
WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||||
|
|
||||||
|
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@INS')
|
||||||
|
WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||||
|
|
||||||
|
-- add-lead-dashboard/sql/01-status-change.sql (02 backfill has nothing to do on an empty volume)
|
||||||
|
USE `service-counter`;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `event_lead_status_change` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`company_id` bigint NOT NULL,
|
||||||
|
`event_lead_id` bigint NOT NULL,
|
||||||
|
`from_status` varchar(10) NULL,
|
||||||
|
`to_status` varchar(10) NOT NULL,
|
||||||
|
`changed_at` datetime NOT NULL,
|
||||||
|
`changed_by` varchar(255) NULL,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_elsc_event_lead` (`event_lead_id`, `changed_at`),
|
||||||
|
KEY `idx_elsc_company_to_changed` (`company_id`, `to_status`, `changed_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- Dashboard capture query: captures by company and capture time.
|
||||||
|
ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_captured` (`company_id`, `captured_at`);
|
||||||
|
|
||||||
|
-- add-lead-dashboard/sql/03-dashboard-module.sql
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||||
|
(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard');
|
||||||
|
|
||||||
|
-- add-qr-self-registration/sql/01-registration-link.sql
|
||||||
|
USE `service-counter`;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `registration_link` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`company_id` bigint NOT NULL,
|
||||||
|
`event_uuid` bigint NOT NULL,
|
||||||
|
`salesperson_user_id` bigint NULL,
|
||||||
|
`token` varchar(32) NOT NULL,
|
||||||
|
`enabled` bit(1) NOT NULL DEFAULT b'1',
|
||||||
|
`created_by` varchar(255) NULL,
|
||||||
|
`created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_by` varchar(255) NULL,
|
||||||
|
`updated_at` datetime NULL,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_registration_link_token` (`token`),
|
||||||
|
KEY `idx_registration_link_event` (`event_uuid`, `salesperson_user_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
ALTER TABLE `event_lead`
|
||||||
|
ADD COLUMN `source` varchar(8) NOT NULL DEFAULT 'STAFF' AFTER `lead_type`,
|
||||||
|
ADD COLUMN `consent_at` datetime NULL AFTER `notes`,
|
||||||
|
ADD COLUMN `consent_notice_id` bigint NULL AFTER `consent_at`;
|
||||||
|
|
||||||
|
-- add-qr-self-registration/sql/02-company-privacy-notice.sql
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `company_privacy_notice` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`company_id` bigint NOT NULL,
|
||||||
|
`text_en` text NOT NULL,
|
||||||
|
`text_ms` text NOT NULL,
|
||||||
|
`created_by` varchar(255) NULL,
|
||||||
|
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_company_privacy_notice_company` (`company_id`, `id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- created_at in Malaysian time, like the rows the services write (the server clock may be UTC).
|
||||||
|
INSERT INTO `company_privacy_notice` (`company_id`, `text_en`, `text_ms`, `created_by`, `created_at`)
|
||||||
|
SELECT c.`id`,
|
||||||
|
REPLACE('{company} collects the details you enter on this form (your name, mobile number, email, company, job title and interests) to contact you about our products, services and events, including by phone, SMS, WhatsApp and email. Your details are used only by {company} and the service providers who run this system for us, and are not sold to anyone. We keep them for as long as you remain a contact of ours or until you ask us to delete them. You may ask to see or correct your details, or withdraw this consent, at any time by contacting {company}. Giving your details is voluntary, but without them we cannot follow up with you.', '{company}', c.`name`),
|
||||||
|
REPLACE('{company} mengumpul butiran yang anda masukkan dalam borang ini (nama, nombor telefon bimbit, e-mel, syarikat, jawatan dan minat anda) untuk menghubungi anda mengenai produk, perkhidmatan dan acara kami, termasuk melalui telefon, SMS, WhatsApp dan e-mel. Butiran anda hanya digunakan oleh {company} dan pembekal perkhidmatan yang mengendalikan sistem ini bagi pihak kami, dan tidak dijual kepada sesiapa. Kami menyimpannya selagi anda kekal sebagai kenalan kami atau sehingga anda meminta kami memadamnya. Anda boleh meminta untuk melihat atau membetulkan butiran anda, atau menarik balik persetujuan ini, pada bila-bila masa dengan menghubungi {company}. Pemberian butiran adalah secara sukarela, tetapi tanpanya kami tidak dapat menghubungi anda.', '{company}', c.`name`),
|
||||||
|
'default',
|
||||||
|
DATE_ADD(UTC_TIMESTAMP(), INTERVAL 8 HOUR)
|
||||||
|
FROM `company` c
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM `company_privacy_notice` n WHERE n.`company_id` = c.`id`);
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-01
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
The portal is a Next.js app with shadcn-style components. Every colour already comes from CSS custom properties in `app/globals.css` (enforced by `app/design-tokens.test.ts`), so the look is mostly token values. The current tokens, fonts (Inter plus DM Sans headings) and 1rem radius came from the babyboo portal. Full design: `docs/superpowers/specs/2026-12-01-visual-foundation-design.md`.
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:** replace the token values, fonts, radius and shadow; fix the shell and the wordmark; turn every native select into the shared Radix select.
|
||||||
|
|
||||||
|
**Non-Goals:** booth screen, visitor pages, login (follow-up change); per-company accent; new components or dependencies.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **Token values, not class rewrites.** Change `:root` and `.dark` values in `globals.css`: background white, foreground #0F172A, muted foreground #64748B, muted/secondary #F1F5F9, border #E2E8F0, primary and ring #2563EB, destructive red, plus success and warning tokens if missing. `--radius` becomes 0.5rem (cards 8px, controls 6px).
|
||||||
|
2. **Inter only.** Drop the DM Sans font file and variable from `layout.tsx`; `--font-heading` points at Inter. The test that expects DM Sans on `<html>` is re-targeted to "only Inter" (requirement One Type Family).
|
||||||
|
3. **Wordmark.** Remove `.brand-gradient-text` and its use; the sidebar shows a blue square mark plus solid "Co-Lite".
|
||||||
|
4. **Selects.** Use the existing `app/components/ui/select.tsx`. Radix Select does not accept an empty string as a value, so "All companies" uses a sentinel value mapped back to `undefined`. Tests that used `selectOptions` on native selects open the menu and click the option instead (requirement Styled Dropdown Menus).
|
||||||
|
5. **Dark theme.** Keep the existing `.dark` mechanism; re-derive its values from slate-900/800 surfaces and a lighter blue (#3B82F6) accent.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- [Re-targeted tests could hide a regression] → each changed test maps to a scenario in the new spec; the reviewer checks no assertion is weakened.
|
||||||
|
- [Radix Select in jsdom] → the existing `select.test.tsx` already drives it; reuse its helpers.
|
||||||
|
- [Screens look half-done until booth and visitor pages follow] → those pages are public or phone-only and are next in line.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
The admin portal still wears the inherited babyboo look (brown primary, DM Sans headings, 16px corners, gradient wordmark, unstyled native select menus). The owner chose a replacement direction on 2026-12-01: the category-standard SaaS admin, done well. The invitations screens wait on this foundation.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- New look across the admin portal: white and slate with one blue accent, Inter only, 8px cards and 6px controls, one soft card shadow.
|
||||||
|
- Dark theme re-derived from the same scale; light stays the default.
|
||||||
|
- The wordmark becomes a solid "Co-Lite" with a small mark; no gradient text.
|
||||||
|
- Every dropdown in the admin portal opens a styled option menu instead of the browser's native list (company picker, event form, user form, company status, event-lead forms).
|
||||||
|
- Booth, visitor and login pages are out of scope (follow-up change).
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
- `admin-visual-design`: the admin portal's theme rules: colours from theme tokens only, one accent colour, one type family, light default with a dark theme, the product wordmark, and styled dropdown menus.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- `solvway-admin-portal`: `app/globals.css`, `tailwind.config.ts`, `app/layout.tsx` (fonts), `app/components/app/*` (shell, company picker), `app/components/ui/*` where tokens are not enough, and the five other files with native selects.
|
||||||
|
- Existing tests that pin the old font or drive native selects are re-targeted to the new requirements.
|
||||||
|
- No backend, API or data changes.
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Admin Colours Come From Theme Tokens
|
||||||
|
|
||||||
|
The admin portal SHALL take every colour from the theme tokens. A component MUST NOT use a fixed palette colour, except a modal scrim, a print-only sheet, a QR code's quiet zone, or a frame showing email HTML.
|
||||||
|
|
||||||
|
#### Scenario: A component uses a palette colour
|
||||||
|
|
||||||
|
- **WHEN** a component's classes include a fixed palette colour that is not on the exception list
|
||||||
|
- **THEN** the portal's checks fail
|
||||||
|
|
||||||
|
### Requirement: One Accent Colour
|
||||||
|
|
||||||
|
The admin portal SHALL use slate neutrals for text, surfaces and borders, and one blue accent for primary actions, links, focus rings and the active navigation item. Status colours (success, warning, danger) SHALL appear only where they carry meaning.
|
||||||
|
|
||||||
|
#### Scenario: Primary action
|
||||||
|
|
||||||
|
- **WHEN** a page shows a primary button
|
||||||
|
- **THEN** the button uses the accent colour and the other buttons on the page do not
|
||||||
|
|
||||||
|
#### Scenario: Active navigation item
|
||||||
|
|
||||||
|
- **WHEN** an admin is on the Events page
|
||||||
|
- **THEN** the Events item in the sidebar is marked in the accent colour and no other item is
|
||||||
|
|
||||||
|
### Requirement: One Type Family
|
||||||
|
|
||||||
|
The admin portal SHALL set all text, headings included, in one sans-serif family, with tabular figures for numbers in tables and counts.
|
||||||
|
|
||||||
|
#### Scenario: Fonts loaded
|
||||||
|
|
||||||
|
- **WHEN** any admin page loads
|
||||||
|
- **THEN** only the one family's font file is loaded
|
||||||
|
|
||||||
|
### Requirement: Light Default With A Dark Theme
|
||||||
|
|
||||||
|
The admin portal SHALL show the light theme by default and SHALL offer a dark theme derived from the same neutrals and accent.
|
||||||
|
|
||||||
|
#### Scenario: First visit
|
||||||
|
|
||||||
|
- **WHEN** an admin opens the portal with no theme preference saved
|
||||||
|
- **THEN** the light theme is shown
|
||||||
|
|
||||||
|
#### Scenario: Dark theme chosen
|
||||||
|
|
||||||
|
- **WHEN** an admin switches to the dark theme
|
||||||
|
- **THEN** every page uses the dark tokens and text keeps at least 4.5:1 contrast
|
||||||
|
|
||||||
|
### Requirement: Product Wordmark
|
||||||
|
|
||||||
|
The admin portal SHALL show the product name "Co-Lite" as solid text beside a small mark, and SHALL keep "Powered by Containerverse Sdn. Bhd." in the footer.
|
||||||
|
|
||||||
|
#### Scenario: Sidebar header
|
||||||
|
|
||||||
|
- **WHEN** an admin page loads
|
||||||
|
- **THEN** the sidebar shows the mark and the text "Co-Lite" in a solid colour, not gradient-filled text
|
||||||
|
|
||||||
|
### Requirement: Styled Dropdown Menus
|
||||||
|
|
||||||
|
Every dropdown in the admin portal SHALL open a styled option menu that matches the portal's theme, and SHALL stay usable by keyboard and screen reader.
|
||||||
|
|
||||||
|
#### Scenario: Company picker
|
||||||
|
|
||||||
|
- **WHEN** a super admin opens the company picker in the header
|
||||||
|
- **THEN** a styled menu lists "All companies" and each company code, and choosing one scopes the pages to that company
|
||||||
|
|
||||||
|
#### Scenario: Form dropdown
|
||||||
|
|
||||||
|
- **WHEN** an admin opens the salesperson, temperature or status dropdown on an event lead
|
||||||
|
- **THEN** a styled menu opens, and the chosen value is saved with the form as before
|
||||||
|
|
||||||
|
#### Scenario: Keyboard use
|
||||||
|
|
||||||
|
- **WHEN** an admin focuses a dropdown and presses Enter or Space, then the arrow keys and Enter
|
||||||
|
- **THEN** the menu opens, moves between options, and chooses one
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
Serial. One implementer at a time, Opus review gate per task.
|
||||||
|
|
||||||
|
## 1. Theme
|
||||||
|
|
||||||
|
- [x] 1.1 Token values (light and dark), radius 0.5rem, a card shadow token, Inter only (drop DM Sans).
|
||||||
|
- Depends on: none
|
||||||
|
- Tests first: `<html>` carries only the Inter font variable; `globals.css` has no DM Sans; `--primary` is the blue accent in light and dark.
|
||||||
|
- Scope: `solvway-admin-portal/app/globals.css`, `solvway-admin-portal/app/layout.tsx`, `solvway-admin-portal/app/layout.test.tsx`, `solvway-admin-portal/app/globals.test.ts`, `solvway-admin-portal/app/fonts/**`, `solvway-admin-portal/tailwind.config.ts`
|
||||||
|
- Verify: `cd solvway-admin-portal && npm run lint; echo L=$?; npx tsc --noEmit; echo T=$?; npx vitest run; echo V=$?`
|
||||||
|
|
||||||
|
## 2. Shell
|
||||||
|
|
||||||
|
- [x] 2.1 Sidebar wordmark (mark plus solid "Co-Lite"; remove `brand-gradient-text` from `globals.css`), cards use the shadow token, active item in the accent, header and page header spacing to the reference sketch; company picker becomes the styled select.
|
||||||
|
- Depends on: 1.1
|
||||||
|
- Tests first: sidebar shows "Co-Lite" with no gradient class; only the current nav item is marked active; the company picker opens a menu with "All companies" and each code, and choosing one sets the scope.
|
||||||
|
- Scope: `solvway-admin-portal/app/components/app/**`, `solvway-admin-portal/app/components/ui/**`, `solvway-admin-portal/app/lib/CompanyScope*.tsx`, `solvway-admin-portal/app/globals.css`
|
||||||
|
- Verify: as 1.1
|
||||||
|
|
||||||
|
## 3. Form dropdowns
|
||||||
|
|
||||||
|
- [x] 3.1 Replace the native selects in the event form, user form, company status, and the new and edit event-lead pages with the styled select; values save as before.
|
||||||
|
- Depends on: 2.1
|
||||||
|
- Tests first: each dropdown opens a menu, choosing an option sends that value on save; keyboard opens and chooses.
|
||||||
|
- Scope: `solvway-admin-portal/app/components/events/**`, `solvway-admin-portal/app/components/users/**`, `solvway-admin-portal/app/companies/**`, `solvway-admin-portal/app/event-leads/**`, `solvway-admin-portal/app/companyScope.forms.test.tsx`
|
||||||
|
- Verify: as 1.1
|
||||||
|
|
||||||
|
## 4. Check and record
|
||||||
|
|
||||||
|
- [x] 4.1 Playwright at 1280 and 360 px, light and dark: dashboard, events list, event edit, event leads, a user form, companies; screenshots in the PR. Then the impeccable finish review and DESIGN.md from the built result.
|
||||||
|
- Depends on: 3.1
|
||||||
|
- Scope: `solvway-admin-portal/DESIGN.md`, `openspec/changes/add-visual-foundation/tasks.md`
|
||||||
|
- Verify: as 1.1
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-11-30
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# Design
|
||||||
|
|
||||||
|
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-admin-audit-log-design.md`.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
- **`AppAccessAspect`** (`solvway-mobile-api/.../useraccess/AppAccessAspect.java`) wraps every controller method. It already:
|
||||||
|
- knows the admin from the JWT;
|
||||||
|
- resolves `@AdminModule` from the method, falling back to the class;
|
||||||
|
- refuses with 403 on a missing module, super admin required or pending reset;
|
||||||
|
- publishes a `ResponseTime` record per call to services-log over Pub/Sub (`response-time-log-topic`).
|
||||||
|
- **services-log** stores in MySQL schema `service-log` with JPA. It creates its topics and subscriptions at startup (`configuration/PubSubConfig.java`), listens in `pubsub/PubSubListener.java`, and archives response times on a schedule (`scheduler/ResponseTimeLogArchiveScheduler.java`).
|
||||||
|
- **Local Pub/Sub:** the emulator creates the topics listed in `local/pubsub/topics.txt`.
|
||||||
|
- **Client IP:** the portal already forwards `X-Client-Ip` on every call (`app/lib/server/mobileApi.ts`).
|
||||||
|
- **babyboo reference:**
|
||||||
|
- core-libs `model/AuditEvent.java`;
|
||||||
|
- mobile-api `useraccess/Audited.java`, `useraccess/AuditChanges.java` and the audit part of `useraccess/AppAccessAspect.java`;
|
||||||
|
- `service/AuditLogService.java` and `controller/AdminAuditLogController.java`;
|
||||||
|
- services-log `controller/AuditEventController.java`, `model/AuditEventLog.java`, `repo/AuditEventLogRepository.java` and `service/AuditEventLogPurge.java`;
|
||||||
|
- portal `app/audit-log/page.tsx` and `app/api/audit-log/**`.
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:**
|
||||||
|
- record admin writes, refusals and three sensitive reads;
|
||||||
|
- record allow-listed changes;
|
||||||
|
- delete events after 730 days;
|
||||||
|
- an Audit log screen.
|
||||||
|
|
||||||
|
**Non-Goals:**
|
||||||
|
- member and public calls;
|
||||||
|
- page views;
|
||||||
|
- sign-ins (covered by `login_audit`);
|
||||||
|
- legacy `/log/save` cleanup.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **`AuditEvent` in core-libs:** fields `companyId`, `occurredAt`, `actor`, `module`, `action`, `httpMethod`, `pathTemplate`, `targetId`, `outcome`, `httpStatus`, `clientIp` and `changes` (a JSON string). It is the shared contract, so it lands first.
|
||||||
|
|
||||||
|
2. **Table `service-log`.`audit_event`:**
|
||||||
|
- Columns follow the event fields.
|
||||||
|
- `changes` is TEXT.
|
||||||
|
- Indexes: `occurred_at`, `(actor, occurred_at)` and `(module, action, occurred_at)`.
|
||||||
|
|
||||||
|
3. **What the aspect records:**
|
||||||
|
- **Writes:** every handler under a class mapped to `/api/admin` whose HTTP method is not GET.
|
||||||
|
- **Sensitive GETs:** handlers annotated `@Audited` (lead export, event-lead export, email detail).
|
||||||
|
- **Skipped:** handlers annotated `@Audited(skip = true)` (event-lead `match`) and every `AdminAuthController` handler except `firstLogin`.
|
||||||
|
- **Actor required:** only calls whose admin token resolved to a user are recorded. A refusal at the access check (403 from the module or super-admin check, or `PASSWORD_RESET_REQUIRED`) for such a user is recorded as `FAILURE`.
|
||||||
|
|
||||||
|
4. **Event fields, as the aspect builds them:**
|
||||||
|
- **Action:** `@Audited(action)`; otherwise derived from the handler: drop an `Admin` prefix and a `Controller` suffix, then UPPER_SNAKE both parts and join them, so `AdminUserController.update` becomes `USER_UPDATE`.
|
||||||
|
- **Path template:** the class `@RequestMapping` plus the method mapping, for example `/api/admin/users/{id}`.
|
||||||
|
- **Target id:** the last path variable (the record acted on, e.g. the event lead in `/event-leads/{eventUuid}/leads/{eventLeadUuid}`). `@Audited(target = false)` records none: the unlock path carries a username as typed at a failed sign-in, which can be a mistyped password.
|
||||||
|
- **Outcome:**
|
||||||
|
- `SUCCESS` for a 2xx `ResponseEntity`, or when there is no `ResponseEntity`;
|
||||||
|
- otherwise `FAILURE` with the status, taken from a non-2xx `ResponseEntity` or from a thrown `ResponseStatusException`;
|
||||||
|
- any other exception is `FAILURE` with 500.
|
||||||
|
- **Client IP:** the `X-Client-Ip` header.
|
||||||
|
|
||||||
|
5. **`AuditChanges`:** a request-scoped holder. Services call `AuditChanges.put(field, before, after)` or `AuditChanges.fields(names...)`, and the aspect serialises the result into `changes`. The allow-list is enforced where the values are supplied:
|
||||||
|
- `AdminUserService` create and update: `roles` (role names) and `enabled`;
|
||||||
|
- `AdminRoleService` set modules: `modules` with the codes added and removed;
|
||||||
|
- `AdminLeadService` and `AdminEventLeadService` edits: changed field names only;
|
||||||
|
- `AdminLoginSecurityService` config and password rules: the changed settings with before and after.
|
||||||
|
|
||||||
|
6. **Publishing:** to `audit-event-topic`, after the handler finishes, through the existing `PubSubUtil` and `PubSubTemplate` pattern used for `ResponseTime`. Any exception is logged at WARN and swallowed.
|
||||||
|
|
||||||
|
7. **services-log:**
|
||||||
|
- Creates `audit-event-topic` and `audit-event-subscription` at startup, like the other topics.
|
||||||
|
- The listener saves each `AuditEvent` as an `AuditEventLog`.
|
||||||
|
- A scheduled purge (daily) deletes rows with `occurred_at` older than `audit.retention-days` (env `AUDIT_RETENTION_DAYS`, default 730), in batches.
|
||||||
|
- **`POST /log/audit/search`:** body `{actor, module, action, outcome, from, to, page, size}`. `actor` and `action` match exactly; `from` and `to` are `yyyy-MM-dd` and inclusive. It returns newest first, caps the size at 100, and answers `{content, totalElements, number, size}`.
|
||||||
|
- **`GET /log/audit/{id}`.**
|
||||||
|
- Both need the admin's token at the gateway, like the other `/log/**` routes.
|
||||||
|
|
||||||
|
8. **mobile-api read API:** `AdminAuditLogController` (`@AdminModule("BO_AUDIT_LOG")`):
|
||||||
|
- `GET /api/admin/audit-log?actor&module&action&outcome&from&to&page&size`;
|
||||||
|
- `GET /api/admin/audit-log/{id}` (404 when missing).
|
||||||
|
- The reads themselves are not audited (GET without `@Audited`).
|
||||||
|
|
||||||
|
9. **Portal `/audit-log`:**
|
||||||
|
- **List:** time, who, module (label from the module's i18n key), action, target, outcome with status, and IP.
|
||||||
|
- **Filters:** who, module select, action, outcome, and From/To `DatePicker`.
|
||||||
|
- **Detail `/audit-log/[id]`:** the event fields, then a changes table (field, before, after), or a list of changed fields when only names were recorded.
|
||||||
|
- **Gating:** `RequireModule` and `ROUTE_MODULES`.
|
||||||
|
- **Proxy:** `app/api/audit-log/[[...path]]/route.ts`, GET only.
|
||||||
|
|
||||||
|
10. **Module row:** `(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText')`, with no role grants.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- **Lost events:** Pub/Sub publishing is best-effort, so a broker outage loses events. This is accepted, as in babyboo; the application log still carries the existing `... by ...` lines.
|
||||||
|
- **Role names and settings stored as values:** these are not personal data. Lead personal data is never stored; lead edits keep field names only.
|
||||||
|
- **Path variables as targets:** the last path variable is a UUID or id, except the unlock username, which is not recorded. The concrete path is never stored, so no query string, and therefore no search text, ends up in the log.
|
||||||
|
- **Requests refused before the handler:** malformed JSON or a binding error is answered before `AppAccessAspect` runs, so such calls are not recorded.
|
||||||
|
- **Extra reads for before-values:** a lead edit and a login-security settings save read the current values once before saving, only for the audit. The read is best-effort and cannot fail the save; it adds one internal call.
|
||||||
|
- **One company:** reads do not filter by `company_id`. Add the filter when Co-Lite becomes multi-company.
|
||||||
|
- **Retention:** `AUDIT_RETENTION_DAYS` below 1 stops service-log at startup rather than deleting the whole trail.
|
||||||
|
- **Volume:** one row per admin write. With one company and a handful of admins, 730 days is small.
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# Proposal
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Nothing in Co-Lite records who did what in the admin portal. When an admin edits a user, changes a role's grants, edits or exports leads, or opens a saved email (which can hold a temporary password), the only trace is a line in the application log. Sign-ins are the exception: `login_audit` covers them. Go-live is 2027-01-15, and the company needs an audit trail and a screen to read it.
|
||||||
|
|
||||||
|
babyboo built the same thing (`add-portal-audit-log`, archive 2026-11-19, plus `audit-log-readable-actions`, 2026-11-20). This change ports the admin half of that work, trimmed.
|
||||||
|
|
||||||
|
Design: `docs/superpowers/specs/2026-11-30-admin-audit-log-design.md`.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- **Recording:**
|
||||||
|
- mobile-api's `AppAccessAspect` publishes an audit event for every admin write under `/api/admin/**`, every refusal of a valid admin token, and three sensitive reads: the lead export, the event-lead export and opening an email.
|
||||||
|
- Sign-in, sign-out, refresh, forgot-password and own password change are not recorded, because `login_audit` covers them or there is no actor.
|
||||||
|
- **Each event:**
|
||||||
|
- who and when; the module and a readable action code;
|
||||||
|
- the method and the path template; the target id;
|
||||||
|
- the outcome and status, and the browser IP.
|
||||||
|
- Before/after values only for an allow-list:
|
||||||
|
- a user's role names and enabled flag;
|
||||||
|
- role module grants;
|
||||||
|
- login-security settings;
|
||||||
|
- for lead edits and event-lead edits, the names of the changed fields only, never the values.
|
||||||
|
- **Transport:** a new Pub/Sub topic `audit-event-topic`. services-log subscribes on `audit-event-subscription` and saves to a new `service-log`.`audit_event` table. Publishing is best-effort: a failure never blocks the admin's action.
|
||||||
|
- **Retention:** services-log deletes events older than `AUDIT_RETENTION_DAYS` (default 730) on a schedule.
|
||||||
|
- **Reading:** services-log gets search and detail endpoints. mobile-api gets `GET /api/admin/audit-log` and `GET /api/admin/audit-log/{id}` under the new module `BO_AUDIT_LOG`.
|
||||||
|
- **Portal:** a new `/audit-log` page with a list, filters and a detail view that shows the changes.
|
||||||
|
- **Not in this change:**
|
||||||
|
- member and public calls;
|
||||||
|
- page views;
|
||||||
|
- removing the unused legacy `/log/save` and `back_office_access_log`.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
- `admin-audit-log`: recording admin actions, refusals and sensitive reads; the allow-listed changes; retention; and the Audit log screen.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
None.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- **`solvway-core-libs`:** a new `AuditEvent` message class shared by mobile-api and services-log.
|
||||||
|
- **`solvway-services-log`:**
|
||||||
|
- `AuditEventLog` entity and repository;
|
||||||
|
- the topic and subscription setup and the listener;
|
||||||
|
- the purge;
|
||||||
|
- `/log/audit/search` and `/log/audit/{id}`.
|
||||||
|
- **`solvway-mobile-api`:**
|
||||||
|
- the `Audited` annotation and the `AuditChanges` request holder;
|
||||||
|
- publishing in `AppAccessAspect`;
|
||||||
|
- annotations on the sensitive reads and the read-only POST;
|
||||||
|
- changes supplied by the user, role, lead, event-lead and login-security services;
|
||||||
|
- `AdminAuditLogController`.
|
||||||
|
- **`solvway-admin-portal`:** the `/audit-log` pages, a proxy, a service and i18n keys. Client IP is already forwarded on every call.
|
||||||
|
- **Pub/Sub:** a new topic and subscription. They go in `local/pubsub/topics.txt` and `docs/deployment.md` section 5.
|
||||||
|
- **Database:** `sql/01-audit-event.sql` (DDL in `service-log`) and `sql/02-audit-log-module.sql`, mirrored in `local/seed/03-colite.sql`, plus a rollback script.
|
||||||
|
- **Privacy:** no passwords, tokens, request bodies or lead personal data are stored. User role names and login-security settings are stored as values.
|
||||||
|
- No new dependency.
|
||||||
+105
@@ -0,0 +1,105 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Admin writes are recorded
|
||||||
|
|
||||||
|
The system SHALL record an audit event for every state-changing admin API call made with a valid admin token, successful or not, holding the time, admin username, module, readable action code, HTTP method, path template (never the concrete path or query), target id, outcome with HTTP status, and client IP. Sign-in, sign-out, token refresh, forgot-password, own password change from the user menu, and calls without a valid admin token SHALL NOT be recorded.
|
||||||
|
|
||||||
|
#### Scenario: A user edit is recorded
|
||||||
|
|
||||||
|
- **WHEN** admin `admin` updates user 4
|
||||||
|
- **THEN** an audit event is saved with actor `admin`, module `BO_USERS`, action `USER_UPDATE`, path template `PUT /api/admin/users/{id}`, target `4`, outcome `SUCCESS`, and the client IP
|
||||||
|
|
||||||
|
#### Scenario: A failed write is recorded
|
||||||
|
|
||||||
|
- **WHEN** an admin's role update is refused with status 400
|
||||||
|
- **THEN** an audit event is saved with outcome `FAILURE` and status 400
|
||||||
|
|
||||||
|
#### Scenario: Sign-in is not recorded
|
||||||
|
|
||||||
|
- **WHEN** an admin signs in or signs out
|
||||||
|
- **THEN** no audit event is saved
|
||||||
|
|
||||||
|
#### Scenario: First-login password change is recorded
|
||||||
|
|
||||||
|
- **WHEN** a new admin sets their password at first login
|
||||||
|
- **THEN** an audit event with action `AUTH_FIRST_LOGIN` is saved
|
||||||
|
|
||||||
|
### Requirement: Refused access is recorded
|
||||||
|
|
||||||
|
The system SHALL record an audit event with outcome `FAILURE` when a valid admin token is refused by the access check (missing module, super admin required, or pending first-login change).
|
||||||
|
|
||||||
|
#### Scenario: Missing module
|
||||||
|
|
||||||
|
- **GIVEN** admin `noevents` has no `BO_EVENTS`
|
||||||
|
- **WHEN** `noevents` tries to create an event
|
||||||
|
- **THEN** the request is refused with 403
|
||||||
|
- **AND** an audit event with actor `noevents`, module `BO_EVENTS` and outcome `FAILURE` is saved
|
||||||
|
|
||||||
|
### Requirement: Sensitive reads are recorded
|
||||||
|
|
||||||
|
The system SHALL record an audit event when an admin exports leads, exports event leads, or opens a saved email. Read-only POST calls marked as such SHALL NOT be recorded.
|
||||||
|
|
||||||
|
#### Scenario: Opening an email
|
||||||
|
|
||||||
|
- **WHEN** an admin opens email 12
|
||||||
|
- **THEN** an audit event with action `EMAIL_VIEW` and target `12` is saved
|
||||||
|
|
||||||
|
#### Scenario: Lead export
|
||||||
|
|
||||||
|
- **WHEN** an admin downloads the lead export
|
||||||
|
- **THEN** an audit event with action `LEAD_EXPORT` is saved
|
||||||
|
|
||||||
|
### Requirement: Allow-listed changes
|
||||||
|
|
||||||
|
The system SHALL attach before and after values only for these fields: a user's role names and enabled flag, a role's granted module codes, and the login-security lockout settings and password rules. For lead and event-lead edits the system SHALL record only the names of the fields that changed, never their values. No audit event SHALL contain a password, token, raw request body, or lead name, phone, email or notes.
|
||||||
|
|
||||||
|
#### Scenario: Role change on a user
|
||||||
|
|
||||||
|
- **WHEN** an admin changes user 4's roles from `Sales` to `Sales, Manager`
|
||||||
|
- **THEN** the event's changes show roles before `Sales` and after `Sales, Manager`
|
||||||
|
|
||||||
|
#### Scenario: Lead edit records field names only
|
||||||
|
|
||||||
|
- **WHEN** an admin changes a lead's phone and notes
|
||||||
|
- **THEN** the event's changes list the fields `phone` and `notes`
|
||||||
|
- **AND** neither the old nor the new phone or notes appear in the event
|
||||||
|
|
||||||
|
### Requirement: Recording never blocks the action
|
||||||
|
|
||||||
|
Recording SHALL be best-effort. A failure to publish or save an audit event MUST NOT change the response of the admin call.
|
||||||
|
|
||||||
|
#### Scenario: Publish failure
|
||||||
|
|
||||||
|
- **GIVEN** the audit event cannot be published
|
||||||
|
- **WHEN** an admin updates a user
|
||||||
|
- **THEN** the update succeeds as usual
|
||||||
|
- **AND** the failure is logged
|
||||||
|
|
||||||
|
### Requirement: Retention
|
||||||
|
|
||||||
|
The system SHALL delete audit events older than the configured retention period, 730 days by default, on a schedule.
|
||||||
|
|
||||||
|
#### Scenario: Old events are purged
|
||||||
|
|
||||||
|
- **WHEN** the purge runs with a retention of 730 days
|
||||||
|
- **THEN** events older than 730 days are deleted
|
||||||
|
- **AND** newer events are kept
|
||||||
|
|
||||||
|
### Requirement: Audit log screen
|
||||||
|
|
||||||
|
The system SHALL let an admin with `BO_AUDIT_LOG` list audit events newest first, paged, filtered by actor, module, action, outcome and date range, and open one event to see its details and changes. An admin without `BO_AUDIT_LOG` SHALL be refused.
|
||||||
|
|
||||||
|
#### Scenario: Filter by actor
|
||||||
|
|
||||||
|
- **WHEN** an admin with `BO_AUDIT_LOG` filters the audit log by actor `admin`
|
||||||
|
- **THEN** only events by `admin` are listed, newest first
|
||||||
|
|
||||||
|
#### Scenario: Event detail
|
||||||
|
|
||||||
|
- **WHEN** an admin opens an event for a role grant change
|
||||||
|
- **THEN** the detail shows the event's fields and the modules added and removed
|
||||||
|
|
||||||
|
#### Scenario: Without the module
|
||||||
|
|
||||||
|
- **WHEN** an admin without `BO_AUDIT_LOG` calls the audit log API or opens `/audit-log`
|
||||||
|
- **THEN** the API answers 403 and the page shows Not authorised
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- Co-Lite change add-admin-audit-log: the admin audit trail.
|
||||||
|
-- Target: `service-log`.`audit_event`. Additive only. Run once, after the release package.
|
||||||
|
-- DDL: run with a user that may create tables, not the services' user.
|
||||||
|
-- Written by services-log from the audit-event-topic Pub/Sub messages that mobile-api publishes.
|
||||||
|
USE `service-log`;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `audit_event` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`company_id` bigint NULL,
|
||||||
|
`occurred_at` datetime(6) NOT NULL,
|
||||||
|
`actor` varchar(191) NOT NULL,
|
||||||
|
`module` varchar(64) NULL,
|
||||||
|
`action` varchar(128) NOT NULL,
|
||||||
|
`http_method` varchar(16) NULL,
|
||||||
|
`path_template` varchar(255) NULL,
|
||||||
|
`target_id` varchar(128) NULL,
|
||||||
|
`outcome` varchar(16) NOT NULL COMMENT 'SUCCESS | FAILURE',
|
||||||
|
`http_status` int NULL,
|
||||||
|
`client_ip` varchar(64) NULL,
|
||||||
|
`changes` text NULL COMMENT 'JSON: allow-listed before/after, or changed field names',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_audit_event_occurred_at` (`occurred_at`),
|
||||||
|
KEY `idx_audit_event_actor` (`actor`, `occurred_at`),
|
||||||
|
KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Co-Lite change add-admin-audit-log: the Audit log back-office module (area BO).
|
||||||
|
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
|
||||||
|
-- No role grant: super admins see every module; they grant BO_AUDIT_LOG to other roles under Roles.
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||||
|
(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText');
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Co-Lite change add-admin-audit-log: rollback of 01-02. Destroys the audit trail.
|
||||||
|
USE `service-system`;
|
||||||
|
DELETE FROM `modules_roles` WHERE `module_id` = 41100000;
|
||||||
|
DELETE FROM `module` WHERE `id` = 41100000;
|
||||||
|
|
||||||
|
USE `service-log`;
|
||||||
|
DROP TABLE IF EXISTS `audit_event`;
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
Design: `design.md`. All tasks run serially: each builds on the one before.
|
||||||
|
|
||||||
|
## 1. Data and contract
|
||||||
|
|
||||||
|
- [x] 1.1 SQL and Pub/Sub topic.
|
||||||
|
- Files:
|
||||||
|
- `sql/01-audit-event.sql`: `CREATE TABLE IF NOT EXISTS service-log.audit_event` (design decision 2).
|
||||||
|
- `sql/02-audit-log-module.sql`: the module row (design decision 10).
|
||||||
|
- `sql/99-rollback.sql`.
|
||||||
|
- Mirror 01 and 02 in `local/seed/03-colite.sql`, and add `audit-event-topic audit-event-subscription` to `local/pubsub/topics.txt`.
|
||||||
|
- Apply them to the local database and emulator. This is local only.
|
||||||
|
- Scope: `local/**`, `openspec/changes/add-admin-audit-log/sql/**`
|
||||||
|
- Verify: `select` shows the table and the module row.
|
||||||
|
- [x] 1.2 core-libs `AuditEvent` (design decision 1).
|
||||||
|
- Tests first: JSON round trip through the same `PubSubUtil` used for `ResponseTime`.
|
||||||
|
- Scope: `solvway-core-libs/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-core-libs verify`
|
||||||
|
|
||||||
|
## 2. services-log
|
||||||
|
|
||||||
|
- [x] 2.1 Storage, listener, purge and read endpoints (design decision 7).
|
||||||
|
- Tests first:
|
||||||
|
- the listener saves an event with every field;
|
||||||
|
- search filters by actor, module, action, outcome and dates, returns newest first, caps the size at 100, and rejects a bad date with 400;
|
||||||
|
- detail answers 404 for an unknown id;
|
||||||
|
- the purge deletes only rows older than the retention and reads the env setting.
|
||||||
|
- Scope: `solvway-services-log/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-services-log -am verify`
|
||||||
|
|
||||||
|
## 3. mobile-api
|
||||||
|
|
||||||
|
- [x] 3.1 Recording in `AppAccessAspect`, with `Audited` and `AuditChanges` (design decisions 3, 4 and 6).
|
||||||
|
- Add annotations on the lead export, the event-lead export, the email detail (sensitive) and event-lead `match` (skip).
|
||||||
|
- Tests first:
|
||||||
|
- a write records every field: actor, module, action, method, template, target, outcome and IP;
|
||||||
|
- the derived and the explicit action codes;
|
||||||
|
- a non-2xx response and a thrown status exception record `FAILURE` with the status;
|
||||||
|
- a 403 refusal for a valid user is recorded;
|
||||||
|
- plain GETs, skipped POSTs and the auth endpoints (except first-login) are not recorded;
|
||||||
|
- a call without a user is not recorded;
|
||||||
|
- a publish failure does not change the response;
|
||||||
|
- `AuditChanges` content lands in `changes` and is cleared between requests.
|
||||||
|
- Scope: `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||||
|
- [x] 3.2 Allow-listed changes from the services (design decision 5).
|
||||||
|
- Tests first, one per service:
|
||||||
|
- user role names and enabled flag before and after;
|
||||||
|
- role modules added and removed;
|
||||||
|
- lead and event-lead edits record field names only, and no value appears anywhere in `changes`;
|
||||||
|
- login-security config and rules before and after.
|
||||||
|
- Scope: `solvway-mobile-api/src/main/java/**/service/**` plus their tests
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||||
|
- [x] 3.3 `AdminAuditLogController` and the read service (design decision 8).
|
||||||
|
- Tests first:
|
||||||
|
- the class-level module;
|
||||||
|
- parameter mapping;
|
||||||
|
- a 404 for an unknown id;
|
||||||
|
- only the given filters are forwarded.
|
||||||
|
- Scope: `solvway-mobile-api/src/**` (new audit-log files, constants, tests)
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||||
|
- Live check through the stack:
|
||||||
|
- edit a user and see the event with its changes;
|
||||||
|
- `noevents` creating an event is recorded as `FAILURE`;
|
||||||
|
- opening an email is recorded.
|
||||||
|
|
||||||
|
## 4. Portal
|
||||||
|
|
||||||
|
- [x] 4.1 `/audit-log` list and `/audit-log/[id]` detail, with a proxy, a service and i18n keys (design decision 9).
|
||||||
|
- Tests first:
|
||||||
|
- rows and filters go into the query;
|
||||||
|
- the detail shows a before/after table and a field-name list;
|
||||||
|
- `RequireModule` gates the page;
|
||||||
|
- the proxy is GET only and refuses dot segments.
|
||||||
|
- Scope: `solvway-admin-portal/app/audit-log/**`, `solvway-admin-portal/app/api/audit-log/**`, `solvway-admin-portal/app/lib/**`
|
||||||
|
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||||
|
|
||||||
|
## 5. Check and docs
|
||||||
|
|
||||||
|
- [x] 5.1 Browser check and handover.
|
||||||
|
- Playwright on the local stack:
|
||||||
|
- as admin, change a user's roles, change a role's grants, edit a lead, open an email and export leads, then see each in Audit log with its changes;
|
||||||
|
- as `noevents`, try a forbidden action and see it as `FAILURE`;
|
||||||
|
- `noevents` has no Audit log menu entry and sees Not authorized at `/audit-log`;
|
||||||
|
- the list fits at 1280 px, and the pages work at 360 px.
|
||||||
|
- Docs, in `docs/deployment.md`:
|
||||||
|
- section 3: the new SQL;
|
||||||
|
- section 5: the new topic and subscription;
|
||||||
|
- section 6: `AUDIT_RETENTION_DAYS`.
|
||||||
|
- Scope: `docs/deployment.md`
|
||||||
|
- Verify: screenshots, and the steps above observed.
|
||||||
|
|
||||||
|
## Workflow follow-up
|
||||||
|
|
||||||
|
- Whole-branch review, push, PR to main and merge, then archive on its own branch.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-11-30
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# Design
|
||||||
|
|
||||||
|
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-company-scoping-design.md`.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
- **Identity is a string everywhere:**
|
||||||
|
- services-auth issues the JWT with the user's `username` as subject.
|
||||||
|
- It resolves a token back to a user through services-system `/user/findByUsernameWithPassword/{username}`.
|
||||||
|
- mobile-api resolves the caller from the token about 40 times. It also uses `caller.getUsername()` for `doneBy`, the lockout key, the `login_audit` username and the audit actor.
|
||||||
|
- `user.username` is globally unique (`username_UNIQUE`). Member users live in the same table.
|
||||||
|
- **Already scoped by company:** leads, event leads, event salespersons and interests are queried by the caller's company. mobile-api passes `caller.getCompanyId()` to services-counter.
|
||||||
|
- **Not scoped:**
|
||||||
|
- the users search (services-system);
|
||||||
|
- events (the Tastefully `event` table, services-counter, no `company_id`);
|
||||||
|
- emails (service-email, no `company_id`);
|
||||||
|
- login history and locked users (services-system; `login_audit.company_id` exists but is unused);
|
||||||
|
- the audit log (services-log; `audit_event.company_id` exists but is unused).
|
||||||
|
- **Super admin today:** holds role id 1. Checked in `AppAccessAspect`, `AdminUserService`, `AdminRoleService`, `AdminAclService` and `AdminEmailService`.
|
||||||
|
- **Company today:** `company` is `(id, name, create_date)`, with one row (id 1, "Co-Lite"). No entity or API.
|
||||||
|
- **Emails:** mobile-api `EmailService` publishes emails to `email-save-request-topic`, and service-email saves them.
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:**
|
||||||
|
- Every scoped admin read and write carries the caller's company; super admins see all or a picked company.
|
||||||
|
- Company sign-in without changing services-auth, the token format or member sign-in.
|
||||||
|
- Adding a company needs no code, deploy or database work.
|
||||||
|
|
||||||
|
**Non-Goals:**
|
||||||
|
- Members and the customer portal.
|
||||||
|
- Company admins with their own roles or settings.
|
||||||
|
- Stamping a super admin's audit row with the changed record's company.
|
||||||
|
- Deleting companies.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **The stored username of a staff user is the login name `local@code`.**
|
||||||
|
- The portal sends `company` and `username`. mobile-api builds the login name: `username@company`, lowercased code; a blank company means the plain username, which is a super admin.
|
||||||
|
- services-system stores `john@ins` in `user.username`. The existing unique key then gives per-company uniqueness. services-auth, tokens, `findByUsername*`, `login_audit` and the audit actor all keep working on that one string unchanged.
|
||||||
|
- Screens show the local part (`john`) next to the company. A username input SHALL NOT contain `@`.
|
||||||
|
- Alternative rejected: a new `login_name` column, or a lookup split across company and username. Either would touch services-auth and every token lookup for the same outcome.
|
||||||
|
- The user's choice of approach B is preserved: per-company usernames, a separate Company field and a renamable code.
|
||||||
|
2. **Company code change:**
|
||||||
|
- A services-system `@Transactional` endpoint renames the code and rewrites `username = CONCAT(local, '@', newCode)` for that company's admin users.
|
||||||
|
- Old tokens no longer resolve to a user, so those sessions end on their next request. The username column is the session's identity, so nothing else is needed.
|
||||||
|
- Login history keeps the old names.
|
||||||
|
3. **Company table and API:**
|
||||||
|
- `company` gains `code varchar(20) NOT NULL UNIQUE` and `status char(1) NOT NULL DEFAULT 'A'`.
|
||||||
|
- services-system gets a `Company` entity, repository and `/company/*` endpoints: list, find, save, rename-code.
|
||||||
|
- mobile-api gets `AdminCompanyController` (`/api/admin/companies`), super admin only.
|
||||||
|
4. **Super admin check, in one place:**
|
||||||
|
- `AdminCompanyScope` (mobile-api) defines `isSuper(caller)` as "no company AND holds role 1". It replaces the role-only checks.
|
||||||
|
- `scope(caller, requestedCompanyId)` returns the company to filter by:
|
||||||
|
- staff: their own company, ignoring any request value;
|
||||||
|
- super admin: the requested company, or null for all.
|
||||||
|
- `requireCompanyForCreate(caller, requested)`: a super admin must choose one.
|
||||||
|
- `requireSuper(caller)` answers 403.
|
||||||
|
- Ported from babyboo's `AdminCountryScope` pattern.
|
||||||
|
5. **Inactive company:**
|
||||||
|
- `AdminSessionGuard`, which already loads the caller on every admin request, refuses a staff user whose company is inactive, with the same 401 as a dead session.
|
||||||
|
- `AdminAuthController.login` refuses one with `BAD_LOGIN`.
|
||||||
|
- The company status comes from services-system with the user, by adding `companyStatus` to the user lookup. That avoids an extra call per request.
|
||||||
|
6. **Scoped queries:**
|
||||||
|
- Each backend list or search endpoint takes an optional `companyId`; null means all companies, and only mobile-api decides when null is allowed.
|
||||||
|
- Detail and edit endpoints resolve the record, then compare its company with the scope; a mismatch answers 404.
|
||||||
|
- Where a services-counter query takes a mandatory `companyId` today, it becomes optional for lists.
|
||||||
|
- Every write still takes a concrete company.
|
||||||
|
7. **Events and emails get `company_id`:**
|
||||||
|
- `event.company_id bigint NULL`, set from the scope on create and never changed by edit.
|
||||||
|
- `email.company_id bigint NULL`, set by mobile-api `EmailService` from the user the email is for (forgot password, temporary password) and stored by service-email.
|
||||||
|
- Public form emails and other system emails have no company and are visible to super admins only.
|
||||||
|
8. **Interests become shared:**
|
||||||
|
- The unique key `(company_id, name)` becomes `(name)`; queries stop filtering by company.
|
||||||
|
- `interest.company_id` stays, unused and nullable, so no data is lost.
|
||||||
|
- Writes are super admin only.
|
||||||
|
9. **Login history and audit:**
|
||||||
|
- `login_audit.company_id` is filled from the user that the login name matches; it is already done this way.
|
||||||
|
- The audit actor's company is already stored.
|
||||||
|
- The searches take the scope; NULL-company rows match only when the scope is "all".
|
||||||
|
10. **Portal:**
|
||||||
|
- `AdminAuthContext` gains `companyId`, `companyCode` and `isSuper` from the login response.
|
||||||
|
- Super admins get a header `CompanyPicker`, persisted per tab. It feeds `companyId` into the list queries and the default of create forms.
|
||||||
|
- A `Company` column appears on scoped lists when "All companies" is selected.
|
||||||
|
- The login and forgot-password pages get a Company field.
|
||||||
|
- `/companies` is gated by `isSuper`, not by a module.
|
||||||
|
11. **One-time data step** (change folder SQL plus seed):
|
||||||
|
- Set company 1 to `INS`/`ins`; insert `CV`/`cv`.
|
||||||
|
- Set `admin` to company NULL.
|
||||||
|
- Rewrite the other admin usernames to `username@ins`. First check that none contains `@`; stop if one does.
|
||||||
|
- Set existing events and emails to company 1.
|
||||||
|
- Move the interest unique key.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- **Member usernames share the column.** A member whose username is exactly `john@ins` would block creating staff `john` in INS. Members do not exist in Co-Lite at go-live; the users API reports such a clash as "username taken".
|
||||||
|
- **The login name is visible in history and audit.** Login history and the audit log show `john@ins`, which is clear for staff and super admins alike.
|
||||||
|
- **A code change ends sessions.** This is intentional, and the Companies screen warns before saving.
|
||||||
|
- **Every scoped endpoint must use the scope.** A missed endpoint is a cross-company leak.
|
||||||
|
- Mitigation: one helper, a test per endpoint for another company's record, and a whole-branch review that checks every `/api/admin/**` handler.
|
||||||
|
- **Tokens in flight at deploy:** their subjects (for example `sales1`) no longer match the rewritten usernames, so every session ends. Co-Lite is not deployed yet, so nobody is affected.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Proposal
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Co-Lite goes live on 2027-01-15 with two test-run companies, INS and CV, and more are planned. Each company's staff must see only their own company's data, and one or more super admins must see and manage everything, including creating companies. Everything built so far assumes a single company: users, events, emails, login history and the audit log are unscoped, interests are per company, and there is no way to create a company or tell companies apart at sign-in. Approved design: `docs/superpowers/specs/2026-11-30-company-scoping-design.md`.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- **Companies:** `company` gains a unique `code` and an active/inactive `status`. A new super-admin-only Companies screen lists, creates and edits companies. An inactive company's staff cannot sign in.
|
||||||
|
- **Sign-in:** the admin login page asks for Company, Username and Password; a super admin leaves Company empty. Usernames and emails are unique within a company. Forgot password asks for the same company and username plus the email.
|
||||||
|
- **Super admins:** a super admin is a company-less admin user holding the super admin role. Company staff can never hold that role. There can be several super admins.
|
||||||
|
- **Scoping:** every admin read, write, export and detail lookup is limited to the caller's company: users, events, event leads, leads, emails, login history, locked users and the audit log. Another company's record answers 404. Super admins see all companies, can narrow to one, and pick the company when creating a company-owned record.
|
||||||
|
- **Shared data:** roles, interests, lockout settings and password rules are shared by all companies, and only super admins edit them. Interests become one shared list.
|
||||||
|
- **Portal:** a header company picker and a Company column for super admins; Company fields on the login, forgot-password, user and event forms; the Companies screen.
|
||||||
|
- **BREAKING (sign-in):** company staff must enter their company code to sign in. The deploy signs everyone out.
|
||||||
|
- **Deploy SQL:** company code/status, `company_id` on `event` and `email`, the interest unique key, staff login names, INS and CV setup.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
- `company-scoping`: companies, the Companies screen, company sign-in identity, super admins, and the rule that limits every admin view and action to the caller's company.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
- `admin-access`: staff login and forgot password take a company.
|
||||||
|
- `admin-users`: company membership, per-company username and email uniqueness, super admin creation.
|
||||||
|
- `admin-roles`: editing roles becomes super admin only.
|
||||||
|
- `lead-interests`: one shared interest list, edited by super admins only.
|
||||||
|
- `admin-login-security`: unlock is limited to the caller's company; settings become super admin only.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- **services-system:** company entity, repository and endpoints; user lookup, save and uniqueness by login name; user search by company; login-history and locked-user filters by company.
|
||||||
|
- **services-counter:** `company_id` on events; event queries by company; interest queries become shared; queries accept "all companies" for super admins.
|
||||||
|
- **service-email:** `company_id` on emails, set when an email is saved for a user; search by company.
|
||||||
|
- **services-log:** audit search by company.
|
||||||
|
- **mobile-api:** login and forgot password with company; one company-scope helper used by every admin service; Companies API; super-admin-only guards on roles, interests and login-security settings.
|
||||||
|
- **admin portal:** login, forgot-password, header picker, Company column and fields, Companies screen, super-admin-only screens.
|
||||||
|
- **Database:** additive SQL in the change folder plus a data step for existing users, events and emails; mirrored in `local/seed/03-colite.sql`.
|
||||||
|
- **Unchanged:** services-auth, token format, members and the customer portal.
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Staff login
|
||||||
|
|
||||||
|
The system SHALL let an active admin user log in through the admin portal with company code, username and password, or with username and password and no company for a super admin, and SHALL return the user's name, roles, company, menu and whether a password change is required.
|
||||||
|
|
||||||
|
#### Scenario: Correct credentials
|
||||||
|
|
||||||
|
- **GIVEN** an active admin user `sales1` of active company `ins`
|
||||||
|
- **WHEN** they submit company `ins`, username `sales1` and their password on the login page
|
||||||
|
- **THEN** they are signed in and land on the portal home
|
||||||
|
- **AND** the sidebar shows only the menu entries their roles grant
|
||||||
|
|
||||||
|
#### Scenario: Super admin
|
||||||
|
|
||||||
|
- **GIVEN** the super admin `admin`, who belongs to no company
|
||||||
|
- **WHEN** they submit username `admin` and their password with the company left empty
|
||||||
|
- **THEN** they are signed in
|
||||||
|
|
||||||
|
#### Scenario: Wrong password
|
||||||
|
|
||||||
|
- **WHEN** a user submits a wrong password
|
||||||
|
- **THEN** `/api/admin/auth/login` responds 401
|
||||||
|
- **AND** the login page shows an invalid-credentials message without saying whether the company or username exists
|
||||||
|
|
||||||
|
#### Scenario: Deactivated user
|
||||||
|
|
||||||
|
- **GIVEN** an admin user whose account is deactivated
|
||||||
|
- **WHEN** they submit their correct password
|
||||||
|
- **THEN** login is refused with a 401 and the page shows the same invalid-credentials message
|
||||||
|
|
||||||
|
#### Scenario: Member account
|
||||||
|
|
||||||
|
- **WHEN** a member (non-admin) account submits its correct credentials to the admin login
|
||||||
|
- **THEN** login is refused with a 401
|
||||||
|
|
||||||
|
### Requirement: Forgot password
|
||||||
|
|
||||||
|
The system SHALL let a user request a temporary password by entering their company code, username and email on a public forgot-password page; a super admin leaves the company empty. The response SHALL be the same whether or not the details match an active admin user.
|
||||||
|
|
||||||
|
#### Scenario: Matching username and email
|
||||||
|
|
||||||
|
- **GIVEN** an active admin user `sales1` of company `ins` with email `sales1@example.com`
|
||||||
|
- **WHEN** someone submits company `ins`, username `sales1` and `sales1@example.com`
|
||||||
|
- **THEN** a temporary password is emailed to `sales1@example.com`
|
||||||
|
- **AND** the user must change it at next login
|
||||||
|
- **AND** the page shows "If the details match an account, we have emailed a temporary password."
|
||||||
|
|
||||||
|
#### Scenario: Non-matching details
|
||||||
|
|
||||||
|
- **WHEN** someone submits a company, username and email that do not match an active admin user
|
||||||
|
- **THEN** no password changes and no email is sent
|
||||||
|
- **AND** the page shows the same message as for a match
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Unlock
|
||||||
|
|
||||||
|
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames of their own company that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one of them. A super admin SHALL see and unlock locked usernames of every company, including attempts that match no company. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
|
||||||
|
|
||||||
|
#### Scenario: Unlock a locked username
|
||||||
|
|
||||||
|
- **GIVEN** INS user `sales1` is locked
|
||||||
|
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` unlocks `sales1`
|
||||||
|
- **THEN** `sales1` no longer appears in the locked list
|
||||||
|
- **AND** `sales1` can sign in with the right password
|
||||||
|
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
|
||||||
|
|
||||||
|
#### Scenario: Another company's locked user
|
||||||
|
|
||||||
|
- **GIVEN** CV user `sales2` is locked
|
||||||
|
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` lists locked users or unlocks `sales2` of CV
|
||||||
|
- **THEN** `sales2` is not listed and the unlock answers 404
|
||||||
|
|
||||||
|
### Requirement: Lockout and password-rule settings
|
||||||
|
|
||||||
|
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the lockout settings and the admin password rules, and SHALL let only a super admin change them, because they apply to every company. The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
|
||||||
|
|
||||||
|
#### Scenario: Change the lockout settings
|
||||||
|
|
||||||
|
- **WHEN** a super admin sets the maximum to 3 and the period to 30 minutes
|
||||||
|
- **THEN** the next lock decision in every company uses 3 attempts in 30 minutes
|
||||||
|
|
||||||
|
#### Scenario: Invalid setting
|
||||||
|
|
||||||
|
- **WHEN** a super admin sets the maximum to 0
|
||||||
|
- **THEN** the change is refused with a validation error and the settings stay as they were
|
||||||
|
|
||||||
|
#### Scenario: Change a password rule
|
||||||
|
|
||||||
|
- **WHEN** a super admin sets the minimum length rule to 10
|
||||||
|
- **THEN** a new password of 9 characters is refused by every admin password check
|
||||||
|
|
||||||
|
#### Scenario: Company user changes settings
|
||||||
|
|
||||||
|
- **WHEN** an INS user with `BO_LOGIN_SECURITY` changes a lockout setting or a password rule
|
||||||
|
- **THEN** the change is refused with 403 and the settings stay as they were
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Role list and edit
|
||||||
|
|
||||||
|
The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let only a super admin create and rename them, because roles are shared by every company. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
|
||||||
|
|
||||||
|
#### Scenario: Create role
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates role `ROLE_SALES`
|
||||||
|
- **THEN** it appears in the role list and can be assigned to users of any company
|
||||||
|
|
||||||
|
#### Scenario: Duplicate name
|
||||||
|
|
||||||
|
- **GIVEN** role `ROLE_SALES` exists
|
||||||
|
- **WHEN** a super admin creates another role named `ROLE_SALES`
|
||||||
|
- **THEN** the save is refused with a message
|
||||||
|
|
||||||
|
#### Scenario: Company user edits a role
|
||||||
|
|
||||||
|
- **WHEN** an INS user with `BO_ROLES` creates or renames a role
|
||||||
|
- **THEN** the request is refused with 403 and nothing changes
|
||||||
|
|
||||||
|
### Requirement: Role permissions
|
||||||
|
|
||||||
|
The system SHALL let only a super admin choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. Admins with `BO_ROLES` who are not super admins SHALL see the grants read-only.
|
||||||
|
|
||||||
|
#### Scenario: Grant Users module
|
||||||
|
|
||||||
|
- **GIVEN** role `ROLE_SALES` without `BO_USERS`
|
||||||
|
- **WHEN** a super admin grants `BO_USERS` to `ROLE_SALES` and saves
|
||||||
|
- **THEN** users with `ROLE_SALES` in every company see Users in the sidebar after their next login or session refresh
|
||||||
|
- **AND** `GET /api/admin/users` responds 200 for them
|
||||||
|
|
||||||
|
#### Scenario: Own role
|
||||||
|
|
||||||
|
- **GIVEN** an INS user who is not super admin and holds `ROLE_SALES` and `BO_ROLES`
|
||||||
|
- **WHEN** they change the module grants of `ROLE_SALES`, or of any other role
|
||||||
|
- **THEN** the save is refused with 403 and the grants stay as they were
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Company membership
|
||||||
|
|
||||||
|
Every admin user other than a super admin SHALL belong to exactly one company. A company user's new user SHALL belong to the creating user's company, whatever the request says. A super admin SHALL choose the company of a new user, or no company to create another super admin.
|
||||||
|
|
||||||
|
#### Scenario: Company in the request is ignored
|
||||||
|
|
||||||
|
- **WHEN** an INS user's create-user request carries the CV company id
|
||||||
|
- **THEN** the new user belongs to INS
|
||||||
|
|
||||||
|
#### Scenario: Super admin chooses the company
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates a user and chooses CV
|
||||||
|
- **THEN** the new user belongs to CV
|
||||||
|
|
||||||
|
### Requirement: Create user
|
||||||
|
|
||||||
|
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique within the user's company, so the same username or email may exist in another company. A username SHALL NOT contain `@`. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change and SHALL NOT be sent an email.
|
||||||
|
|
||||||
|
#### Scenario: New user
|
||||||
|
|
||||||
|
- **WHEN** an INS admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
|
||||||
|
- **THEN** the user is saved as active in INS with a pending password change
|
||||||
|
- **AND** `sales1` can sign in with company `ins` and that password and must choose a new password before anything else
|
||||||
|
- **AND** no email is sent
|
||||||
|
|
||||||
|
#### Scenario: Duplicate username
|
||||||
|
|
||||||
|
- **GIVEN** a user `sales1` exists in INS
|
||||||
|
- **WHEN** an admin creates another INS user with username `sales1`
|
||||||
|
- **THEN** the save is refused and the form shows that the username is taken
|
||||||
|
|
||||||
|
#### Scenario: Same username in another company
|
||||||
|
|
||||||
|
- **GIVEN** a user `sales1` exists in INS
|
||||||
|
- **WHEN** a CV admin creates user `sales1` in CV
|
||||||
|
- **THEN** the user is created
|
||||||
|
|
||||||
|
#### Scenario: Weak or mismatched initial password
|
||||||
|
|
||||||
|
- **WHEN** an admin creates a user with a password that fails the admin password rules, or that does not match its confirmation
|
||||||
|
- **THEN** the save is refused with a message on the form
|
||||||
|
- **AND** no user is created
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Companies
|
||||||
|
|
||||||
|
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of lowercase letters, digits and hyphens, compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
|
||||||
|
|
||||||
|
#### Scenario: Create a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates company `CV` with code `cv`
|
||||||
|
- **THEN** it is listed as active
|
||||||
|
- **AND** staff can be created in it
|
||||||
|
|
||||||
|
#### Scenario: Duplicate code
|
||||||
|
|
||||||
|
- **GIVEN** a company with code `ins`
|
||||||
|
- **WHEN** a super admin creates or renames another company to code `INS`
|
||||||
|
- **THEN** the save is refused and the code is reported as taken
|
||||||
|
|
||||||
|
#### Scenario: Not a super admin
|
||||||
|
|
||||||
|
- **WHEN** company staff open the Companies page or call a companies endpoint
|
||||||
|
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||||
|
|
||||||
|
### Requirement: Company sign-in
|
||||||
|
|
||||||
|
The system SHALL sign company staff in with company code, username and password, and SHALL sign super admins in with username and password and no company. The answer SHALL be the same for a wrong or unknown company, an inactive company, an unknown user and a wrong password. A user's sessions SHALL end when their company is deactivated or its code is changed.
|
||||||
|
|
||||||
|
#### Scenario: Staff sign-in
|
||||||
|
|
||||||
|
- **GIVEN** an active user `john` in active company `ins`
|
||||||
|
- **WHEN** they sign in with company `ins`, username `john` and the right password
|
||||||
|
- **THEN** they are signed in as `john` of INS
|
||||||
|
|
||||||
|
#### Scenario: Same username in two companies
|
||||||
|
|
||||||
|
- **GIVEN** a user `john` in INS and a different user `john` in CV
|
||||||
|
- **WHEN** someone signs in with company `cv`, username `john` and CV John's password
|
||||||
|
- **THEN** they are signed in as CV's John and see only CV data
|
||||||
|
|
||||||
|
#### Scenario: Wrong company
|
||||||
|
|
||||||
|
- **WHEN** INS's `john` signs in with company `cv` or a code that does not exist
|
||||||
|
- **THEN** login is refused with the same invalid-credentials answer as a wrong password
|
||||||
|
|
||||||
|
#### Scenario: Inactive company
|
||||||
|
|
||||||
|
- **GIVEN** company CV is deactivated
|
||||||
|
- **WHEN** a CV user signs in with the right password, or uses an existing session
|
||||||
|
- **THEN** the sign-in is refused with the invalid-credentials answer and the session ends
|
||||||
|
|
||||||
|
#### Scenario: Code changed
|
||||||
|
|
||||||
|
- **GIVEN** a signed-in user of the company with code `ins`
|
||||||
|
- **WHEN** a super admin changes that code to `ins-my`
|
||||||
|
- **THEN** the user's session ends
|
||||||
|
- **AND** they sign in again with company `ins-my`
|
||||||
|
|
||||||
|
### Requirement: Super admins
|
||||||
|
|
||||||
|
A super admin SHALL be an admin user who belongs to no company and holds the super admin role. Only a super admin SHALL create another super admin. The super admin role SHALL NOT be granted to a user who belongs to a company, and every admin user who is not a super admin SHALL belong to a company.
|
||||||
|
|
||||||
|
#### Scenario: Create a second super admin
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates a user with no company
|
||||||
|
- **THEN** the user is created as a super admin and signs in without a company
|
||||||
|
|
||||||
|
#### Scenario: Super admin role for company staff
|
||||||
|
|
||||||
|
- **WHEN** anyone assigns the super admin role to a user of INS
|
||||||
|
- **THEN** the save is refused with a message
|
||||||
|
|
||||||
|
### Requirement: Company data is separated
|
||||||
|
|
||||||
|
The system SHALL limit every admin list, search, export, detail, create, edit and action to the caller's company for: users, events, event teams, event leads, leads, emails, login history, locked users and audit events. A record of another company SHALL answer 404, as if it did not exist.
|
||||||
|
|
||||||
|
#### Scenario: Lists show own company only
|
||||||
|
|
||||||
|
- **GIVEN** leads, events and users in INS and in CV
|
||||||
|
- **WHEN** an INS user with the matching modules opens Leads, Events or Users
|
||||||
|
- **THEN** only INS records are listed
|
||||||
|
- **AND** an export contains only INS leads
|
||||||
|
|
||||||
|
#### Scenario: Another company's record by id
|
||||||
|
|
||||||
|
- **GIVEN** a CV lead, event, user or email
|
||||||
|
- **WHEN** an INS user requests it, edits it or acts on it by its id
|
||||||
|
- **THEN** the answer is 404 and nothing changes
|
||||||
|
|
||||||
|
#### Scenario: Same phone in two companies
|
||||||
|
|
||||||
|
- **GIVEN** INS has a lead with mobile `+60123456789`
|
||||||
|
- **WHEN** a CV user captures a lead with the same mobile at a CV event
|
||||||
|
- **THEN** a new CV lead is created and flagged New
|
||||||
|
- **AND** the INS lead is unchanged
|
||||||
|
|
||||||
|
### Requirement: Super admin sees all companies
|
||||||
|
|
||||||
|
The system SHALL show super admins every company's records by default, SHALL let them narrow any scoped list to one company, and SHALL show each record's company in mixed lists. Creating a company-owned record (user, event, event lead) SHALL require a super admin to choose the company.
|
||||||
|
|
||||||
|
#### Scenario: Mixed list
|
||||||
|
|
||||||
|
- **WHEN** a super admin opens Leads with all companies selected
|
||||||
|
- **THEN** INS and CV leads are listed together with a Company column
|
||||||
|
|
||||||
|
#### Scenario: Pick a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin picks CV in the company picker
|
||||||
|
- **THEN** scoped lists show CV records only
|
||||||
|
|
||||||
|
#### Scenario: Create without a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates an event without choosing a company
|
||||||
|
- **THEN** the save is refused and the form asks for a company
|
||||||
|
|
||||||
|
### Requirement: Company of login and audit records
|
||||||
|
|
||||||
|
An audit event and a login-history record SHALL belong to the company of the user who acted, or of the user who tried to sign in when the given company and username match a user. Records with no company SHALL be visible to super admins only.
|
||||||
|
|
||||||
|
#### Scenario: Super admin edits a company record
|
||||||
|
|
||||||
|
- **WHEN** a super admin edits an INS lead
|
||||||
|
- **THEN** the audit event has no company
|
||||||
|
- **AND** INS staff with Audit log do not see it, and super admins do
|
||||||
|
|
||||||
|
#### Scenario: Failed sign-in with an unknown company
|
||||||
|
|
||||||
|
- **WHEN** someone fails to sign in with a company code that does not exist
|
||||||
|
- **THEN** the login-history record has no company and only super admins see it
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Interest list
|
||||||
|
|
||||||
|
The system SHALL keep one interest list shared by all companies. Admins with `BO_INTERESTS` SHALL see the list, and only a super admin SHALL add, rename, reorder, deactivate and reactivate interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case. Interests SHALL NOT be deletable.
|
||||||
|
|
||||||
|
#### Scenario: Add interest
|
||||||
|
|
||||||
|
- **WHEN** a super admin adds `Kitchen appliances`
|
||||||
|
- **THEN** it is listed as active
|
||||||
|
- **AND** staff of every company can tag leads with it
|
||||||
|
|
||||||
|
#### Scenario: Duplicate name
|
||||||
|
|
||||||
|
- **GIVEN** an interest `Kitchen appliances`
|
||||||
|
- **WHEN** a super admin adds `kitchen APPLIANCES`
|
||||||
|
- **THEN** the save is refused and the name is reported as a duplicate
|
||||||
|
|
||||||
|
#### Scenario: Deactivate
|
||||||
|
|
||||||
|
- **GIVEN** an active interest `Cookware`
|
||||||
|
- **WHEN** a super admin deactivates it
|
||||||
|
- **THEN** it is still listed, marked inactive
|
||||||
|
- **AND** it is no longer offered when capturing a lead in any company
|
||||||
|
|
||||||
|
#### Scenario: Company user edits
|
||||||
|
|
||||||
|
- **WHEN** an INS user with `BO_INTERESTS` adds, renames or deactivates an interest
|
||||||
|
- **THEN** the request is refused with 403 and the list is unchanged
|
||||||
|
|
||||||
|
#### Scenario: No module
|
||||||
|
|
||||||
|
- **WHEN** an admin without `BO_INTERESTS` opens the Interests page or calls an interests endpoint
|
||||||
|
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
-- Co-Lite change add-company-scoping: company code and status; INS and CV.
|
||||||
|
-- Target: `service-system`.`company`. Run once, after the release package, before 02 and 03.
|
||||||
|
-- DDL: run with a user that may alter tables, not the services' user.
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
ALTER TABLE `company`
|
||||||
|
ADD COLUMN `code` varchar(20) NULL AFTER `name`,
|
||||||
|
ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`;
|
||||||
|
|
||||||
|
-- The existing company (all current data) becomes INS.
|
||||||
|
UPDATE `company` SET `name` = 'INS', `code` = 'ins' WHERE `id` = 1;
|
||||||
|
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'cv', 'A');
|
||||||
|
|
||||||
|
ALTER TABLE `company`
|
||||||
|
MODIFY COLUMN `code` varchar(20) NOT NULL,
|
||||||
|
ADD UNIQUE KEY `uk_company_code` (`code`);
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- Co-Lite change add-company-scoping: company on events and emails; one shared interest list.
|
||||||
|
-- Run once, after 01. DDL: run with a user that may alter tables.
|
||||||
|
USE `service-counter`;
|
||||||
|
|
||||||
|
ALTER TABLE `event` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_event_company` (`company_id`);
|
||||||
|
UPDATE `event` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||||
|
|
||||||
|
-- Interests are shared by every company: unique by name (case-insensitive collation); company_id kept, unused.
|
||||||
|
ALTER TABLE `interest`
|
||||||
|
DROP INDEX `uk_interest_company_name`,
|
||||||
|
MODIFY COLUMN `company_id` bigint NULL,
|
||||||
|
ADD UNIQUE KEY `uk_interest_name` (`name`);
|
||||||
|
|
||||||
|
USE `service-email`;
|
||||||
|
|
||||||
|
ALTER TABLE `email` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_email_company` (`company_id`);
|
||||||
|
UPDATE `email` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
-- Co-Lite change add-company-scoping: admin sign-in names.
|
||||||
|
-- Super admins (role 1) belong to no company and keep their username.
|
||||||
|
-- Every other admin user keeps company 1 (INS) and is renamed username@ins; they sign in with company "ins".
|
||||||
|
-- Ends every admin session (token subjects no longer match). Run once, after 01 and 02.
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
-- Stop if any admin username already contains '@': it would be ambiguous after the rename.
|
||||||
|
DROP PROCEDURE IF EXISTS `colite_check_admin_usernames`;
|
||||||
|
DELIMITER //
|
||||||
|
CREATE PROCEDURE `colite_check_admin_usernames`()
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM `user` WHERE `type` = 'A' AND `username` LIKE '%@%') THEN
|
||||||
|
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An admin username contains @; rename it before running this script';
|
||||||
|
END IF;
|
||||||
|
END //
|
||||||
|
DELIMITER ;
|
||||||
|
CALL `colite_check_admin_usernames`();
|
||||||
|
DROP PROCEDURE `colite_check_admin_usernames`;
|
||||||
|
|
||||||
|
UPDATE `user` u SET u.`company_id` = NULL
|
||||||
|
WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||||
|
|
||||||
|
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins')
|
||||||
|
WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
-- Co-Lite change add-company-scoping: rollback of 01-03. CV's data, if any, stays in its tables with company 2.
|
||||||
|
USE `service-system`;
|
||||||
|
UPDATE `user` SET `username` = SUBSTRING_INDEX(`username`, '@', 1) WHERE `type` = 'A' AND `username` LIKE '%@%';
|
||||||
|
UPDATE `user` SET `company_id` = 1 WHERE `type` = 'A' AND `company_id` IS NULL;
|
||||||
|
ALTER TABLE `company` DROP INDEX `uk_company_code`, DROP COLUMN `status`, DROP COLUMN `code`;
|
||||||
|
UPDATE `company` SET `name` = 'Co-Lite' WHERE `id` = 1;
|
||||||
|
|
||||||
|
USE `service-counter`;
|
||||||
|
ALTER TABLE `event` DROP KEY `idx_event_company`, DROP COLUMN `company_id`;
|
||||||
|
UPDATE `interest` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||||
|
ALTER TABLE `interest` DROP INDEX `uk_interest_name`, MODIFY COLUMN `company_id` bigint NOT NULL,
|
||||||
|
ADD UNIQUE KEY `uk_interest_company_name` (`company_id`, `name`);
|
||||||
|
|
||||||
|
USE `service-email`;
|
||||||
|
ALTER TABLE `email` DROP KEY `idx_email_company`, DROP COLUMN `company_id`;
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
Design: `design.md`. All tasks run serially, ordered so that sign-in keeps working after each one. Every scoped endpoint gets a test where another company's record answers 404 (or is absent from the list).
|
||||||
|
|
||||||
|
## 1. Data
|
||||||
|
|
||||||
|
- [x] 1.1 SQL and local seed (design decisions 3, 7, 8 and 11).
|
||||||
|
- Files in `sql/`:
|
||||||
|
- `01-company-code-status.sql`: add `code` and `status`; set company 1 to `INS`/`ins`; insert `CV`/`cv`.
|
||||||
|
- `02-company-columns.sql`: add `company_id` to `event` and `email`; set existing rows to company 1; move the interest unique key to `(name)`.
|
||||||
|
- `03-admin-login-names.sql`: stop if any admin username contains `@`; set `admin` to company NULL; rewrite the other admin usernames to `username@ins`.
|
||||||
|
- `99-rollback.sql`.
|
||||||
|
- Mirror them in `local/seed/03-colite.sql`, apply them locally, and confirm `admin` still signs in.
|
||||||
|
- Scope: `local/**`, `openspec/changes/add-company-scoping/sql/**`
|
||||||
|
- Verify: `select` shows the codes, the NULL-company `admin`, the rewritten usernames and the new columns.
|
||||||
|
|
||||||
|
## 2. Backend services
|
||||||
|
|
||||||
|
- [x] 2.1 services-system: companies, users and login security (decisions 1, 2, 3, 5 and 9).
|
||||||
|
- Tests first:
|
||||||
|
- company list, create, edit; duplicate code (ignoring case) refused; code format validated;
|
||||||
|
- rename-code rewrites only that company's admin usernames, in one transaction;
|
||||||
|
- user lookups return the company code and status;
|
||||||
|
- the user search filters by company when given;
|
||||||
|
- email uniqueness is per company;
|
||||||
|
- role 1 cannot be saved on a user with a company;
|
||||||
|
- login history and locked users filter by company, and NULL-company rows appear only for "all".
|
||||||
|
- Scope: `solvway-services-system/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify`
|
||||||
|
- [x] 2.2 services-counter: events, leads, event leads and interests (decisions 6, 7 and 8).
|
||||||
|
- Tests first:
|
||||||
|
- an event is saved with its company and listed by company, or for all when none is given;
|
||||||
|
- lead and event-lead lists accept "all companies";
|
||||||
|
- detail lookups return the record's company;
|
||||||
|
- interests are one list, unique by name ignoring case.
|
||||||
|
- Scope: `solvway-services-counter/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`
|
||||||
|
- [x] 2.3 service-email and services-log (decisions 7 and 9).
|
||||||
|
- Tests first:
|
||||||
|
- an email saved with a company keeps it, and the email search filters by company;
|
||||||
|
- the audit search filters by company, and NULL-company rows appear only for "all".
|
||||||
|
- Scope: `solvway-services-email/src/**`, `solvway-services-log/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-services-email,solvway-services-log -am verify`
|
||||||
|
|
||||||
|
## 3. mobile-api
|
||||||
|
|
||||||
|
- [x] 3.1 Sign-in, company scope and Companies API (decisions 1, 3, 4 and 5).
|
||||||
|
- Tests first:
|
||||||
|
- login and forgot-password build the login name from company and username; a blank company means a super admin;
|
||||||
|
- a wrong company, an inactive company and an unknown user all give `BAD_LOGIN`;
|
||||||
|
- the session guard ends an inactive company's sessions;
|
||||||
|
- `isSuper` needs both no company and role 1;
|
||||||
|
- `scope` ignores a staff request's company;
|
||||||
|
- the Companies API is super admin only;
|
||||||
|
- the login response carries the company and `isSuper`.
|
||||||
|
- Scope: `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||||
|
- [x] 3.2 Users, roles, interests and login-security settings (decisions 1, 4 and 8).
|
||||||
|
- Tests first:
|
||||||
|
- users are listed, created and edited within the scope, and another company's user answers 404;
|
||||||
|
- a username with `@` is refused;
|
||||||
|
- a super admin must choose a company or create a super admin;
|
||||||
|
- role 1 is refused for company users;
|
||||||
|
- role create, rename and grants, interest writes and lockout or password-rule changes answer 403 for company staff;
|
||||||
|
- unlock works only within the caller's company.
|
||||||
|
- Scope: `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||||
|
- [x] 3.3 Events, leads, event leads and exports (decision 6).
|
||||||
|
- Tests first:
|
||||||
|
- each list and export is limited to the scope;
|
||||||
|
- another company's event, lead or event lead answers 404 on detail, edit, capture and export;
|
||||||
|
- a super admin capture or event create without a company is refused;
|
||||||
|
- the event team only offers users of the event's company.
|
||||||
|
- Scope: `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||||
|
- [x] 3.4 Emails, login history and audit log (decisions 7 and 9).
|
||||||
|
- Tests first:
|
||||||
|
- each is limited to the scope;
|
||||||
|
- emails for a user carry that user's company;
|
||||||
|
- another company's email or audit event answers 404.
|
||||||
|
- Scope: `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||||
|
- Live check on the local stack:
|
||||||
|
- INS and CV users each see only their own data;
|
||||||
|
- `admin` sees both;
|
||||||
|
- a CV record by id answers 404 to INS.
|
||||||
|
|
||||||
|
## 4. Portal
|
||||||
|
|
||||||
|
- [x] 4.1 Sign-in, session and Companies screen (decision 10).
|
||||||
|
- Tests first:
|
||||||
|
- the login and forgot-password pages send company, username and password, and a blank company is allowed;
|
||||||
|
- the auth context holds `isSuper` and the company;
|
||||||
|
- `/companies` lists, creates and edits companies, warns before a code change, and is refused for non-super users.
|
||||||
|
- Scope: `solvway-admin-portal/app/**`
|
||||||
|
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||||
|
- [x] 4.2 Company picker, Company column, company fields and super-admin-only screens (decision 10).
|
||||||
|
- Tests first:
|
||||||
|
- the picker is shown only to super admins and feeds the list queries;
|
||||||
|
- the Company column appears for "All companies";
|
||||||
|
- user, event and capture forms show Company for super admins only;
|
||||||
|
- Roles, Interests and the Login security Settings tab are read-only or hidden for company staff.
|
||||||
|
- Scope: `solvway-admin-portal/app/**`
|
||||||
|
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||||
|
|
||||||
|
## 5. Check and docs
|
||||||
|
|
||||||
|
- [x] 5.1 Browser check and handover.
|
||||||
|
- Playwright on the local stack:
|
||||||
|
- `admin` creates CV users and a CV event, then switches the picker between all, INS and CV;
|
||||||
|
- an INS user and a CV user with the same username each sign in with their company and see only their own leads, events, users, emails, login history and audit log;
|
||||||
|
- an INS user opening a CV record by URL sees not-found;
|
||||||
|
- renaming CV's code ends the CV user's session;
|
||||||
|
- deactivating CV blocks its sign-in;
|
||||||
|
- check at 1280 px and 360 px.
|
||||||
|
- Docs, in `docs/deployment.md`:
|
||||||
|
- section 3: the new SQL, and that it ends every session;
|
||||||
|
- section 10: company sign-in and super admins.
|
||||||
|
- Scope: `docs/deployment.md`
|
||||||
|
- Verify: screenshots, and the steps above observed.
|
||||||
|
|
||||||
|
## Workflow follow-up
|
||||||
|
|
||||||
|
- Whole-branch review, with every `/api/admin/**` handler checked for scoping. Then push, PR to main and merge, and archive on its own branch.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-01
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
Approved product design: `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md` (definitions, figures, access). This file fixes the technical contract so the services-counter, mobile-api and portal tasks can be built in parallel.
|
||||||
|
|
||||||
|
Facts the design relies on:
|
||||||
|
- `event_lead.status` already holds OPEN / CONTACTED / QUALIFIED / WON / LOST (event-lead-capture). Only the current value is stored.
|
||||||
|
- `event_lead.captured_at` and `updated_at` are `LocalDateTime.now()` in the services-counter JVM, i.e. wall time in the JVM's default zone (UTC in the containers). There is no zone column.
|
||||||
|
- services-counter has no database tests; every existing test is a Mockito unit test.
|
||||||
|
- Salesperson names live in services-system; mobile-api already resolves them per user id with a per-request map (`AdminLeadService.salesperson`).
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
### 1. Status history table
|
||||||
|
|
||||||
|
`service-counter.event_lead_status_change`:
|
||||||
|
- columns `id` bigint PK auto, `company_id` bigint NOT NULL, `event_lead_id` bigint NOT NULL, `from_status` varchar(10) NULL, `to_status` varchar(10) NOT NULL, `changed_at` datetime NOT NULL, `changed_by` varchar(255) NULL;
|
||||||
|
- key `idx_elsc_event_lead (event_lead_id, changed_at)` and key `idx_elsc_company_to_changed (company_id, to_status, changed_at)`.
|
||||||
|
|
||||||
|
`EventLeadService.capture` saves one row (null → initial status, `changed_at` = the event lead's `captured_at`, `changed_by` = doneBy) in the capture transaction. `update` saves one row when the requested status differs from the stored one (`changed_at` = the new `updated_at`). Entity `EventLeadStatusChange`, repository `EventLeadStatusChangeRepository`. Nothing deletes or updates these rows.
|
||||||
|
|
||||||
|
Backfill (`sql/02-status-change-backfill.sql`, idempotent: only event leads with no history rows):
|
||||||
|
- one row null → OPEN at `captured_at`, `changed_by` = `captured_by`;
|
||||||
|
- where `status <> 'OPEN'`, one row OPEN → status at `COALESCE(updated_at, captured_at)`, `changed_by` = `COALESCE(updated_by, captured_by)`.
|
||||||
|
|
||||||
|
### 2. Aggregate in Java over lean rows, not in SQL
|
||||||
|
|
||||||
|
services-counter runs three plain native queries with bind parameters and aggregates the rows in a pure Java class (`LeadDashboardCalculator`), which is unit-tested without a database:
|
||||||
|
1. **Captures:** event leads with `captured_at` in [fromUtc, toUtc) and the company filter, joined to `event` for name and company: `event_lead.id, event_uuid, event name, company_id, salesperson_user_id, lead_type, status, captured_at`.
|
||||||
|
2. **Wins:** event leads with `status = 'WON'` whose latest history row with `to_status = 'WON'` has `changed_at` in [fromUtc, toUtc): `event_lead.id, captured_at, won_at`.
|
||||||
|
3. **Overdue:** `salesperson_user_id, COUNT(*)` for status not in (WON, LOST) and `next_follow_up_date < today`, grouped by salesperson.
|
||||||
|
|
||||||
|
Interests for the captures come from the existing `EventLeadInterestRepository.findByIdEventLeadIdIn`, in chunks of 1000 ids, and interest names from `InterestRepository`.
|
||||||
|
|
||||||
|
Rejected: one grouped SQL query per figure. Its correctness could only be checked against a live database (no DB tests here), and adding Testcontainers is a new build dependency for one screen.
|
||||||
|
|
||||||
|
`ponytail:` row volume is one row per capture in the period. Fine for thousands per period; move the sums into SQL when one company captures hundreds of thousands of leads a year.
|
||||||
|
|
||||||
|
### 3. Time zone
|
||||||
|
|
||||||
|
mobile-api turns the period into dates; services-counter turns `[from 00:00, to+1 00:00)` in Asia/Kuala_Lumpur into the JVM default zone's wall time for the queries, and turns each stored time back to a Malaysian date for bucketing. "Today" for overdue is today in Asia/Kuala_Lumpur.
|
||||||
|
|
||||||
|
### 4. services-counter contract
|
||||||
|
|
||||||
|
`POST /counter/dashboard/leads` (route already under `/counter/**`), body:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "companyId": 2, "from": "2026-11-01", "to": "2026-11-30", "bucket": "DAY" }
|
||||||
|
```
|
||||||
|
|
||||||
|
`companyId` null = all companies. `bucket` is `DAY` or `MONTH`. `from` after `to` → 400 `INVALID_PERIOD`. Response:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"captures": 10, "newLeads": 6, "wonInPeriod": 3, "medianDaysToWin": 5, "overdueFollowUps": 4,
|
||||||
|
"funnel": { "OPEN": 3, "CONTACTED": 1, "QUALIFIED": 1, "WON": 3, "LOST": 2 },
|
||||||
|
"trend": [ { "bucket": "2026-11-01", "captures": 2, "wins": 0 } ],
|
||||||
|
"events": [ { "eventUuid": "123", "name": "KL Expo", "companyId": 2, "captures": 10, "newLeads": 6, "won": 3 } ],
|
||||||
|
"salespeople": [ { "userId": 7, "assigned": 4, "worked": 3, "won": 1, "lost": 1, "overdue": 2 } ],
|
||||||
|
"interests": [ { "interestId": 5, "name": "Cookware", "captures": 4, "won": 1 } ]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `medianDaysToWin` is null when there are no wins; with an even count it is the lower middle value (whole days).
|
||||||
|
- `trend` lists every bucket in the period, zero-filled; a month bucket is the month's first day.
|
||||||
|
- `events` is ordered by captures descending, then name; `salespeople` by assigned descending, with `userId` null for Unassigned; `salespeople` also includes a salesperson with overdue follow-ups but no captures in the period (assigned 0). `interests` by captures descending, then name.
|
||||||
|
- `eventUuid` is a string (JavaScript loses precision on snowflake ids).
|
||||||
|
|
||||||
|
Rates are not sent; the portal divides.
|
||||||
|
|
||||||
|
### 5. mobile-api contract
|
||||||
|
|
||||||
|
`GET /api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2` under `@AdminModule("BO_DASHBOARD")`:
|
||||||
|
- `from`/`to` optional; when absent, from = first day of the current Malaysian month, to = today (Malaysia).
|
||||||
|
- Bad date format, from after to, or a range of more than 731 days (two years) → 400 `INVALID_PERIOD` (ProblemDetail: `code`, `detail`). The cap keeps one request from building an unbounded bucket list in services-counter, which also refuses a range over 731 days.
|
||||||
|
- bucket = `DAY` when `to - from + 1 <= 62` days, else `MONTH`.
|
||||||
|
- company from `AdminCompanyScope.scope(caller, companyId)`.
|
||||||
|
- Response: the counter response plus `from`, `to`, `bucket`, and each salesperson row gains `name` (the user's name, or null for Unassigned and for a user that no longer exists). Salesperson names are resolved with the existing per-request map pattern.
|
||||||
|
|
||||||
|
### 6. Module
|
||||||
|
|
||||||
|
`service-system.module` row `(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard')`. No role grant: super admins grant it under Roles. Id 40050000 sorts it first in the sidebar, which orders by module id. The portal's route gate (`ROUTE_MODULES`) does not list `/`: the home page itself decides between the dashboard and the welcome, using `hasModule("BO_DASHBOARD")`.
|
||||||
|
|
||||||
|
### 7. Portal
|
||||||
|
|
||||||
|
- `recharts` added to `package.json`; `app/components/ui/chart.tsx` copied from babyboo's portal.
|
||||||
|
- `app/lib/services/adminDashboard.ts`: types for decision 5 and `getLeadDashboard({from, to, companyId})`.
|
||||||
|
- `app/page.tsx`: welcome for users without the module; otherwise the dashboard with a period control (This month / Last month / Custom with the existing date picker), the company picker for super admins (via `useCompanyScope`), tiles, funnel bars, a recharts line or bar chart of captures and wins, and three tables (cards below `md`). Event rows link to `/event-leads/{eventUuid}`. The Company column on the event table shows only when `showCompanyColumn`.
|
||||||
|
- Rates show as whole percent; a null median or zero captures shows "–".
|
||||||
|
- All labels are message keys with English defaults, as on other screens.
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
- Backfilled history times are approximate (deployment notes say so).
|
||||||
|
- A lead whose status was set by a direct DB edit has no history row for that change; the dashboard then misses that win. Nothing in the app does this.
|
||||||
|
- `captured_at` stored in the JVM zone: if production pods ever run in a different zone from when rows were written, older rows shift. Same risk already exists for every listing.
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
Co-Lite exists to generate leads for INS and CV marketing. Managers need to see which events, salespeople and interests produce leads and which of those leads convert (status WON). Today the portal home page is a welcome line, and the system keeps only each event lead's current status, so it cannot say when a lead was won or how long it took. Approved design: `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md`.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- Every event-lead status change is recorded with its time and who made it. Capture records the first status. Existing event leads are backfilled with approximate times.
|
||||||
|
- A lead dashboard on the portal home page for a chosen period (this month, last month, or a custom range):
|
||||||
|
- tiles: captures, new leads, won in period, conversion rate, median days to win, overdue follow-ups;
|
||||||
|
- a status funnel;
|
||||||
|
- a trend of captures and wins;
|
||||||
|
- tables by event, by salesperson and by interest.
|
||||||
|
- A new back-office module `BO_DASHBOARD` gates the dashboard. Users without it keep the welcome page.
|
||||||
|
- Company scoping as on every other admin screen.
|
||||||
|
- The admin portal gains the `recharts` dependency (already used by babyboo's portal) for the trend chart.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
- `lead-dashboard`: the dashboard, its definitions, period rules, access and company scope.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
- `event-lead-capture`: adds the status change history requirement.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- Database `service-counter`: new table `event_lead_status_change`, a backfill, and an index on `event_lead`. `service-system`: one `module` row. SQL in `sql/`, mirrored in `local/seed/03-colite.sql`.
|
||||||
|
- `solvway-services-counter`: history writes on capture and edit; a new dashboard endpoint.
|
||||||
|
- `solvway-mobile-api`: `GET /api/admin/dashboard/leads`.
|
||||||
|
- `solvway-admin-portal`: home page, sidebar link, `recharts`.
|
||||||
|
- `docs/deployment.md`: the new SQL files.
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Event lead status history
|
||||||
|
|
||||||
|
The system SHALL record every change of an event lead's status with the previous status, the new status, the time and the user who made it. Capturing an event lead SHALL record its first status with no previous status, at the capture time. An edit that leaves the status unchanged SHALL record nothing. The history SHALL never be edited or deleted through the application.
|
||||||
|
|
||||||
|
#### Scenario: Capture records the first status
|
||||||
|
|
||||||
|
- **WHEN** staff capture a lead at an event with no status chosen
|
||||||
|
- **THEN** the history holds one entry from no status to OPEN at the capture time, by that user
|
||||||
|
|
||||||
|
#### Scenario: Status change recorded
|
||||||
|
|
||||||
|
- **GIVEN** an OPEN event lead
|
||||||
|
- **WHEN** staff change its status to CONTACTED and later to WON
|
||||||
|
- **THEN** the history holds OPEN to CONTACTED and CONTACTED to WON, each with its time and user
|
||||||
|
|
||||||
|
#### Scenario: Edit without a status change
|
||||||
|
|
||||||
|
- **GIVEN** a CONTACTED event lead
|
||||||
|
- **WHEN** staff change only its temperature and notes
|
||||||
|
- **THEN** no history entry is added
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Dashboard access
|
||||||
|
|
||||||
|
The system SHALL show the lead dashboard on the back-office home page to users granted the `BO_DASHBOARD` module, and SHALL show users without it the welcome message instead of a not-authorised page. The dashboard endpoint SHALL answer 403 to a user without `BO_DASHBOARD`. The sidebar SHALL show a Dashboard link to users with the module.
|
||||||
|
|
||||||
|
#### Scenario: Granted user
|
||||||
|
|
||||||
|
- **GIVEN** a role holding `BO_DASHBOARD` is assigned to `sales1`
|
||||||
|
- **WHEN** `sales1` signs in
|
||||||
|
- **THEN** the home page shows the lead dashboard and the sidebar shows Dashboard
|
||||||
|
|
||||||
|
#### Scenario: User without the module
|
||||||
|
|
||||||
|
- **WHEN** a user without `BO_DASHBOARD` opens the home page or calls the dashboard endpoint
|
||||||
|
- **THEN** the page shows the welcome message and the endpoint responds 403
|
||||||
|
|
||||||
|
### Requirement: Dashboard period
|
||||||
|
|
||||||
|
The dashboard SHALL cover a period of whole days in Malaysia time (Asia/Kuala_Lumpur): this month up to today (the default), last month, or a custom range from one date to another, both included. A range whose start is after its end, or that spans more than 731 days, SHALL be refused with a message. The trend SHALL be counted by day for a period of up to 62 days and by month for a longer one, and SHALL list every day or month in the period, with zero where nothing happened.
|
||||||
|
|
||||||
|
#### Scenario: Default period
|
||||||
|
|
||||||
|
- **WHEN** a user opens the dashboard on 2026-12-10
|
||||||
|
- **THEN** it covers 2026-12-01 to 2026-12-10, with one trend point per day
|
||||||
|
|
||||||
|
#### Scenario: Long range counted by month
|
||||||
|
|
||||||
|
- **WHEN** the user picks 2026-01-01 to 2026-12-31
|
||||||
|
- **THEN** the trend has one point per month, January to December
|
||||||
|
|
||||||
|
#### Scenario: Day boundary in Malaysia time
|
||||||
|
|
||||||
|
- **GIVEN** a lead captured at 2026-11-30 23:30 Malaysia time
|
||||||
|
- **WHEN** the user views 2026-11-01 to 2026-11-30
|
||||||
|
- **THEN** the capture is counted on 30 November
|
||||||
|
|
||||||
|
#### Scenario: Reversed range
|
||||||
|
|
||||||
|
- **WHEN** the user picks a start date after the end date
|
||||||
|
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
|
||||||
|
|
||||||
|
#### Scenario: Range too long
|
||||||
|
|
||||||
|
- **WHEN** the user picks 2024-01-01 to 2026-12-31
|
||||||
|
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
|
||||||
|
|
||||||
|
### Requirement: Capture figures
|
||||||
|
|
||||||
|
For the chosen period the dashboard SHALL show the captures (event leads captured in the period, so a person captured at two events counts twice), the new leads (captures whose lead type is NEW), the conversion rate (the share of the period's captures whose current status is WON, shown as a dash when there are no captures), a funnel of the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST) and the captures in the trend.
|
||||||
|
|
||||||
|
#### Scenario: Conversion of the period's captures
|
||||||
|
|
||||||
|
- **GIVEN** 10 leads captured in November, 3 of them now WON and 2 LOST
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** captures show 10, conversion rate 30%, and the funnel shows WON 3 and LOST 2
|
||||||
|
|
||||||
|
#### Scenario: No captures
|
||||||
|
|
||||||
|
- **WHEN** the user views a period with no captures
|
||||||
|
- **THEN** captures show 0 and the conversion rate shows a dash
|
||||||
|
|
||||||
|
### Requirement: Win figures
|
||||||
|
|
||||||
|
The dashboard SHALL count as won in the period every event lead whose current status is WON and whose latest change to WON falls in the period, whenever it was captured. It SHALL show that count, the wins in the trend, and the median of whole days from capture to the latest change to WON over those event leads, shown as a dash when there are none.
|
||||||
|
|
||||||
|
#### Scenario: Win of an older capture
|
||||||
|
|
||||||
|
- **GIVEN** a lead captured in October and changed to WON on 5 November
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** won in period counts it and the November captures do not
|
||||||
|
|
||||||
|
#### Scenario: Reopened lead
|
||||||
|
|
||||||
|
- **GIVEN** a lead changed to WON on 3 November, back to QUALIFIED on 4 November, and to WON again on 20 November
|
||||||
|
- **WHEN** the user views 1 to 10 November
|
||||||
|
- **THEN** won in period does not count it, because its latest change to WON is 20 November
|
||||||
|
|
||||||
|
#### Scenario: Median days to win
|
||||||
|
|
||||||
|
- **GIVEN** three leads won in November, 2, 5 and 30 days after capture
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** median days to win shows 5
|
||||||
|
|
||||||
|
### Requirement: Overdue follow-ups
|
||||||
|
|
||||||
|
The dashboard SHALL show the event leads that are not WON or LOST and whose next follow-up date is before today in Malaysia time, whatever the chosen period.
|
||||||
|
|
||||||
|
#### Scenario: Overdue counted regardless of period
|
||||||
|
|
||||||
|
- **GIVEN** an OPEN lead captured in August with next follow-up 2026-12-01
|
||||||
|
- **WHEN** the user views November on 2026-12-05
|
||||||
|
- **THEN** overdue follow-ups count it
|
||||||
|
|
||||||
|
### Requirement: Breakdown by event
|
||||||
|
|
||||||
|
The dashboard SHALL list each event with captures in the period, most captures first, with its captures, new leads, won and conversion rate, and each row SHALL open that event's leads listing.
|
||||||
|
|
||||||
|
#### Scenario: Event drill-down
|
||||||
|
|
||||||
|
- **WHEN** the user selects an event row
|
||||||
|
- **THEN** that event's leads listing opens
|
||||||
|
|
||||||
|
### Requirement: Breakdown by salesperson
|
||||||
|
|
||||||
|
The dashboard SHALL list, for the period's captures, each salesperson's assigned, worked (status other than OPEN), won, lost and conversion rate, with their current overdue follow-ups, and SHALL show captures with no salesperson as Unassigned.
|
||||||
|
|
||||||
|
#### Scenario: Salesperson row
|
||||||
|
|
||||||
|
- **GIVEN** in November `sales1` was assigned 4 captures: 1 OPEN, 1 CONTACTED, 1 WON and 1 LOST
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** sales1's row shows assigned 4, worked 3, won 1, lost 1 and conversion rate 25%
|
||||||
|
|
||||||
|
#### Scenario: Unassigned captures
|
||||||
|
|
||||||
|
- **GIVEN** 2 November captures have no salesperson
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** an Unassigned row shows assigned 2
|
||||||
|
|
||||||
|
### Requirement: Breakdown by interest
|
||||||
|
|
||||||
|
The dashboard SHALL list each interest with the period's captures tagged with it and how many of them are now WON. A capture with two interests SHALL count under both.
|
||||||
|
|
||||||
|
#### Scenario: Two interests
|
||||||
|
|
||||||
|
- **GIVEN** a November capture tagged `Cookware` and `Kitchen appliances`, now WON
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** both interests count 1 capture and 1 won
|
||||||
|
|
||||||
|
### Requirement: Phone width
|
||||||
|
|
||||||
|
The dashboard SHALL be usable on a 360 px wide screen without sideways scrolling.
|
||||||
|
|
||||||
|
#### Scenario: Phone
|
||||||
|
|
||||||
|
- **WHEN** a user opens the dashboard at 360 px
|
||||||
|
- **THEN** the tiles stack and the breakdowns show as cards
|
||||||
|
|
||||||
|
### Requirement: Dashboard company scope
|
||||||
|
|
||||||
|
The dashboard SHALL count only the records of the caller's company for company staff. A super admin SHALL see every company's records by default and SHALL be able to narrow the dashboard to one company with the company picker; while all companies are shown, the by-event list SHALL show each event's company.
|
||||||
|
|
||||||
|
#### Scenario: Staff see their company
|
||||||
|
|
||||||
|
- **GIVEN** leads captured at INS and at CV events in November
|
||||||
|
- **WHEN** an INS user with `BO_DASHBOARD` views November
|
||||||
|
- **THEN** every figure counts INS records only
|
||||||
|
|
||||||
|
#### Scenario: Super admin picks a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin picks CV in the company picker
|
||||||
|
- **THEN** every figure counts CV records only
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
-- Co-Lite change add-lead-dashboard: event lead status history (design decision 1).
|
||||||
|
-- Target: `service-counter`. Additive only. Run before the new images go live (services-counter writes this table), then 02.
|
||||||
|
USE `service-counter`;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `event_lead_status_change` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`company_id` bigint NOT NULL,
|
||||||
|
`event_lead_id` bigint NOT NULL,
|
||||||
|
`from_status` varchar(10) NULL,
|
||||||
|
`to_status` varchar(10) NOT NULL,
|
||||||
|
`changed_at` datetime NOT NULL,
|
||||||
|
`changed_by` varchar(255) NULL,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_elsc_event_lead` (`event_lead_id`, `changed_at`),
|
||||||
|
KEY `idx_elsc_company_to_changed` (`company_id`, `to_status`, `changed_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- Dashboard capture query: captures by company and capture time.
|
||||||
|
ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_captured` (`company_id`, `captured_at`);
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
-- Co-Lite change add-lead-dashboard: history for event leads captured before the history existed.
|
||||||
|
-- Target: `service-counter`. Idempotent: touches only event leads with no history row. Times are approximate:
|
||||||
|
-- the first status at capture, the current status (if not OPEN) at the last update.
|
||||||
|
USE `service-counter`;
|
||||||
|
|
||||||
|
INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`)
|
||||||
|
SELECT el.company_id, el.id, NULL, 'OPEN', el.captured_at, el.captured_by
|
||||||
|
FROM `event_lead` el
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id);
|
||||||
|
|
||||||
|
INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`)
|
||||||
|
SELECT el.company_id, el.id, 'OPEN', el.status, COALESCE(el.updated_at, el.captured_at), COALESCE(el.updated_by, el.captured_by)
|
||||||
|
FROM `event_lead` el
|
||||||
|
WHERE el.status <> 'OPEN'
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id AND s.to_status = el.status);
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Co-Lite change add-lead-dashboard: the Dashboard back-office module (area BO).
|
||||||
|
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
|
||||||
|
-- No role grant: super admins see every module; they grant BO_DASHBOARD to other roles under Roles.
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||||
|
(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard');
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Co-Lite change add-lead-dashboard: rollback. Drops the status history (its data is lost).
|
||||||
|
USE `service-system`;
|
||||||
|
DELETE FROM `modules_roles` WHERE `module_id` = 40050000;
|
||||||
|
DELETE FROM `module` WHERE `id` = 40050000;
|
||||||
|
|
||||||
|
USE `service-counter`;
|
||||||
|
ALTER TABLE `event_lead` DROP KEY `idx_event_lead_company_captured`;
|
||||||
|
DROP TABLE IF EXISTS `event_lead_status_change`;
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
Design: `design.md` (technical contract) and `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md` (product).
|
||||||
|
|
||||||
|
Waves:
|
||||||
|
- Wave 0 (serial, controller): 1.1 and 1.2 touch hotspots (SQL, seed, `package.json`).
|
||||||
|
- Wave 1 (parallel, 3 implementers): 2.1, 3.1 and 4.1 build against the fixed contracts in design decisions 4 and 5. Scopes do not overlap: each touches one module.
|
||||||
|
- Wave 2 (serial, controller): 5.1.
|
||||||
|
|
||||||
|
## 1. Data, module and chart dependency
|
||||||
|
|
||||||
|
- [x] 1.1 SQL `sql/01..03` and `99-rollback.sql`; mirror 01 and 03 in `local/seed/03-colite.sql` (02 has nothing to backfill on an empty volume); apply 01, 02 and 03 to the local database.
|
||||||
|
- Depends on: none
|
||||||
|
- Scope: `local/seed/**`, `openspec/changes/add-lead-dashboard/sql/**`
|
||||||
|
- Verify: `SELECT` shows the table, the index, the backfilled rows and the module row.
|
||||||
|
- [x] 1.2 Portal: add `recharts` (same major as babyboo's portal) with `npm install`, and copy babyboo's `app/components/ui/chart.tsx`.
|
||||||
|
- Depends on: none
|
||||||
|
- Scope: `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`, `solvway-admin-portal/app/components/ui/chart.tsx`
|
||||||
|
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
|
||||||
|
|
||||||
|
## 2. services-counter
|
||||||
|
|
||||||
|
- [x] 2.1 Status history writes (decision 1) and the dashboard endpoint (decisions 2 to 4).
|
||||||
|
- Tests first:
|
||||||
|
- capture saves one history row null → initial status at the capture time, by doneBy;
|
||||||
|
- update saves one row when the status changes and none when it stays;
|
||||||
|
- the calculator, from in-memory rows: captures, new leads, funnel, won in period (latest WON only), median days (odd, even, none), overdue per salesperson, Unassigned, salesperson with overdue only, interest double-count, event ordering, zero-filled day and month trend, Malaysia day boundary from JVM-zone times;
|
||||||
|
- the endpoint rejects from after to with 400 `INVALID_PERIOD` and passes a null company as all companies.
|
||||||
|
- Scope: `solvway-services-counter/src/**`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
|
||||||
|
|
||||||
|
## 3. mobile-api
|
||||||
|
|
||||||
|
- [x] 3.1 `GET /api/admin/dashboard/leads` (decision 5).
|
||||||
|
- Tests first:
|
||||||
|
- default period is this Malaysian month to today; DAY bucket up to 62 days, MONTH above;
|
||||||
|
- bad date and from after to → 400 `INVALID_PERIOD`;
|
||||||
|
- staff are scoped to their company, a super admin's `companyId` is passed through, null for all;
|
||||||
|
- salesperson names resolved, null for Unassigned and for a missing user;
|
||||||
|
- the endpoint is gated by `BO_DASHBOARD` (aspect test with the annotation).
|
||||||
|
- Scope: `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
|
||||||
|
|
||||||
|
## 4. Portal
|
||||||
|
|
||||||
|
- [x] 4.1 Home page dashboard (decision 7).
|
||||||
|
- Tests first:
|
||||||
|
- without `BO_DASHBOARD` the welcome shows and the dashboard API is not called;
|
||||||
|
- with it: tiles, funnel, chart container, the three tables with Unassigned, whole-percent rates and "–" for null median and zero captures;
|
||||||
|
- period presets send the right `from`/`to`; a reversed custom range shows the error message;
|
||||||
|
- a super admin's picker sends `companyId` and shows the Company column only for all companies;
|
||||||
|
- an event row links to `/event-leads/{eventUuid}`;
|
||||||
|
- the hard-coded copy sweep stays green (labels as message keys).
|
||||||
|
- Includes the Next proxy route `app/api/dashboard/leads/route.ts` (added after review: the first plan left it out).
|
||||||
|
- Scope: `solvway-admin-portal/app/api/dashboard/**`, `solvway-admin-portal/app/page.tsx`, `solvway-admin-portal/app/page*.test.tsx`, `solvway-admin-portal/app/components/dashboard/**`, `solvway-admin-portal/app/lib/services/adminDashboard*.ts`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`
|
||||||
|
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
|
||||||
|
|
||||||
|
## 5. Release
|
||||||
|
|
||||||
|
- [x] 5.1 `docs/deployment.md` lists the SQL; live check against the local stack (seeded INS and CV event leads with status changes), and Playwright at 1280 and 360 px for a granted user, a user without the module, and a super admin switching company.
|
||||||
|
- Depends on: 1.1 to 4.1
|
||||||
|
- Scope: `docs/deployment.md`, `openspec/changes/add-lead-dashboard/tasks.md`
|
||||||
|
- Verify: full `mvn -T 1C -q verify` of the three touched Maven modules and the portal verify.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-01
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
Approved product design: `docs/superpowers/specs/2026-12-01-qr-self-registration-design.md`. That covers the flow, the matching rules, the consent and the default notice text, the abuse limits and the calls made. This file fixes the technical contracts so services-counter, services-system and mobile-api can be built in parallel, and the portal after them.
|
||||||
|
|
||||||
|
Facts relied on:
|
||||||
|
- Staff capture: mobile-api `AdminEventLeadService.capture` normalises and validates, then posts to services-counter `/counter/eventLead/capture`. On an existing lead, counter `EventLeadService.capture` fills blank fields (`fillBlank`), which registrations must not do.
|
||||||
|
- An event's team is the rows of `event_salesperson` (`/counter/eventSalesperson/findByEventUuid`). An "active member" is an enabled admin user of the event's company (`AdminEventLeadService.isActiveAdminOf`).
|
||||||
|
- `AppAccessAspect` audits admin paths only (`isAdminPath()`), so public endpoints never reach the audit log, and their token cannot either.
|
||||||
|
- A public mobile-api endpoint is `@AppAuth(skipValidate = true)`: it needs the api-key header and no JWT. The portal's server already sends `MOBILE_API_KEY` on every call.
|
||||||
|
- The portal middleware guards every page and `/api/*` route except static files.
|
||||||
|
- `HttpReqRespUtils.getClientIpAddressIfServletRequestExist()` is how the audit log reads the client IP (it checks `X-Forwarded-For` first).
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
### 1. Data (SQL in `sql/`)
|
||||||
|
|
||||||
|
- `service-counter.registration_link`: `id` bigint PK auto, `company_id` bigint NOT NULL, `event_uuid` bigint NOT NULL, `salesperson_user_id` bigint NULL, `token` varchar(32) NOT NULL UNIQUE, `enabled` bit NOT NULL default 1, `created_by`, `created_at`, `updated_by`, `updated_at`. Key `(event_uuid, salesperson_user_id)`. MySQL allows several NULLs in a unique key, so services-counter enforces "one event code per event" when it creates rows, and an `ensure` race is settled by re-reading after the insert.
|
||||||
|
- `service-counter.event_lead`: add `source` varchar(8) NOT NULL DEFAULT 'STAFF', `consent_at` datetime NULL, `consent_notice_id` bigint NULL.
|
||||||
|
- `service-system.company_privacy_notice`: `id` bigint PK auto, `company_id` bigint NOT NULL, `text_en` text NOT NULL, `text_ms` text NOT NULL, `created_by` varchar(255), `created_at` datetime NOT NULL; key `(company_id, id)`. The newest row per company is current. Seeded for every existing company with the default text, `{company}` replaced by `company.name`.
|
||||||
|
- Token: 16 bytes from `SecureRandom`, base64url without padding (22 characters).
|
||||||
|
|
||||||
|
### 2. services-counter contract
|
||||||
|
|
||||||
|
All bodies are JSON. `companyId` is always a concrete company, set by mobile-api.
|
||||||
|
|
||||||
|
- `POST /counter/registrationLink/ensure` `{companyId, eventUuid, salespersonUserIds: [..]}` returns `[{eventUuid, salespersonUserId|null, token, enabled}]`. The event code comes first, then one per given salesperson in the given order; missing rows are created. 404 when the event is not in the company.
|
||||||
|
- `POST /counter/registrationLink/setEnabled` `{companyId, eventUuid, token, enabled, doneBy}` returns the link. 404 when the token is not that event's in that company.
|
||||||
|
- `GET /counter/registrationLink/findByToken/{token}` returns `{companyId, eventUuid, salespersonUserId|null, token, enabled}`, or 404.
|
||||||
|
- `POST /counter/registrationLink/mine` `{companyId, userId, today}` (today is a Malaysian date) covers events of the company where `event_salesperson` has the user, `enabled = Y` and `DATE(date_end) >= today`. Missing personal links are created. It returns `[{eventUuid, eventName, startDate, endDate, location, token, enabled}]`, ordered by start date.
|
||||||
|
- `POST /counter/registration/register` `{companyId, eventUuid, salespersonUserId|null, name, mobileE164, email, companyName, jobTitle, interestIds, consentNoticeId, consentAt}` returns `{outcome: CREATED|LINKED|ALREADY_CAPTURED|ASSIGNED, eventLeadUuid}`. It runs in one transaction:
|
||||||
|
1. **Match.** Look for a lead in the company with `mobile_e164 = mobileE164` (newest id first), then with `email_normalised = email`.
|
||||||
|
2. **New person.** No match creates a new lead and a NEW event lead.
|
||||||
|
3. **Known person, not yet captured here.** The match is not edited. Its event lead is EXISTING, and its notes are `Registered by QR with: <field> <value>; …` for each submitted non-blank value that differs from the lead's (name, mobile, email, company, job title); the notes are null when nothing differs.
|
||||||
|
4. **Already captured.** When the lead is already captured at the event (row exists, or the insert hits `uk_event_lead_event_lead`): if that event lead has no salesperson and `salespersonUserId` is set, assign it (`ASSIGNED`, `updated_by = qr`); otherwise change nothing (`ALREADY_CAPTURED`).
|
||||||
|
5. **The new event lead:** `status OPEN`, `source QR`, `captured_by 'qr'`, `consent_at`, `consent_notice_id`, the interests, plus the status history row null → OPEN by `qr`.
|
||||||
|
|
||||||
|
`EventLeadService.capture` (staff) stays as it is and sets `source STAFF`.
|
||||||
|
|
||||||
|
### 3. services-system contract
|
||||||
|
|
||||||
|
- `GET /company/{id}/privacyNotice` returns the current `{id, companyId, textEn, textMs, createdBy, createdAt}`, or 404.
|
||||||
|
- `POST /company/{id}/privacyNotice` `{textEn, textMs, doneBy}` adds a version and returns it. Both texts are required after trimming and at most 5000 characters each (400 otherwise). 404 for an unknown company.
|
||||||
|
|
||||||
|
### 4. mobile-api contract
|
||||||
|
|
||||||
|
Public (`@AppAuth(skipValidate = true)`, controller `PublicRegistrationController` under `controller..`, path `/api/public/registration/{token}`):
|
||||||
|
|
||||||
|
- **`GET`:**
|
||||||
|
- Page-load limit: Redis key `reg:load:<ip>`, at most 120 per 10 minutes, else 429 `TOO_MANY`. The POST counts against it too, before the code is checked, so guessing codes by POST is slowed as well.
|
||||||
|
- A code works when all of these hold, otherwise 404 `CODE_INACTIVE` with message "This code is no longer active.":
|
||||||
|
- the link exists and is enabled;
|
||||||
|
- its event exists, is enabled and has `dateEnd`'s date (Malaysia) ≥ today;
|
||||||
|
- the company is active (`status A`);
|
||||||
|
- the company has a current notice.
|
||||||
|
- Returns `{eventName, startDate, endDate, location, companyName, notice: {id, textEn, textMs}, interests: [{id, name}]}`, where interests are the active ones.
|
||||||
|
- **`POST`** with `{name, mobile, email, companyName, jobTitle, interestIds, consent, website}`:
|
||||||
|
- The code checks are the same as for `GET`.
|
||||||
|
- A non-blank `website` (honeypot) returns 200 `{eventName}` without saving.
|
||||||
|
- Submission limit: Redis key `reg:submit:<eventUuid>:<ip>`, at most 60 per 10 minutes, else 429 `TOO_MANY`.
|
||||||
|
- Validation is the same as staff capture (required name, mobile or email, lengths, normalisation, interests must be active ones of the company), and `consent` must be true (field `consent`, code `CONSENT_REQUIRED`). Field errors use the existing `details.field` shape.
|
||||||
|
- Salesperson: the link's salesperson when they are on the event's team and are an active admin of the company, else null.
|
||||||
|
- The notice is the current notice at submit time; the client never chooses it.
|
||||||
|
- Calls counter `register` and returns 200 `{eventName}` whatever the outcome.
|
||||||
|
- **Limits:** they count only requests that reach the check. The limit message is "Too many registrations from this device. Try again later."
|
||||||
|
|
||||||
|
Admin:
|
||||||
|
- `GET /api/admin/events/{uuid}/registration-links` (`BO_EVENTS`; event loaded through the company scope) returns `{event: {token, enabled}, members: [{userId, name, username, token, enabled}]}` for every team row, with names resolved per id.
|
||||||
|
- `PUT /api/admin/events/{uuid}/registration-links/{token}` (`BO_EVENTS`) with `{enabled}` returns the link.
|
||||||
|
- `GET /api/admin/my-registration-links` (`ANY_ADMIN`) returns the caller's own links from counter `mine` (Malaysian today). A caller with no company gets `[]`.
|
||||||
|
- `GET` and `PUT /api/admin/companies/{id}/privacy-notice` are super-admin only (`AdminCompanyScope.requireSuper`) and pass through to services-system. `PUT` takes `{textEn, textMs}`.
|
||||||
|
|
||||||
|
### 5. Portal
|
||||||
|
|
||||||
|
- **Dependency:** `qrcode.react` (the same major as babyboo's portal).
|
||||||
|
- **Middleware:** `/r/:token` and `/api/public/:path*` skip the sign-in check. This is security code, so it gets the minimum change and a test that a public path is reachable signed out while admin paths still redirect.
|
||||||
|
- **`/r/[token]`:**
|
||||||
|
- A client page built from the existing UI components, mobile first, without the admin shell (no sidebar or header).
|
||||||
|
- States: loading, inactive, form, field errors, too-many, thank-you with "Register another person".
|
||||||
|
- It uses the proxy `app/api/public/registration/[token]/route.ts` (GET and POST). The proxy sends the visitor IP to mobile-api as `X-Forwarded-For`, set to the last hop of the incoming header (the address the ingress added, the same rule as `X-Client-Ip`), so a visitor cannot choose their own rate-limit key.
|
||||||
|
- **Event edit page:** a "Registration QR" card with:
|
||||||
|
- the event code and every member's code: QR image (`QRCodeSVG`), the link built from `window.location.origin + /r/<token>`, copy, download PNG (`QRCodeCanvas` → `toDataURL`, file `<event>-<name|event>-qr.png`), and an on/off switch;
|
||||||
|
- a note that the link can be pasted into dynamic-qr for a printed code.
|
||||||
|
- **"My QR codes" page** `/my-qr`: reached from the header user menu, shown to every staff user, listing the caller's codes. It is not a module, so `ROUTE_MODULES` leaves it unmapped and any signed-in user may open it.
|
||||||
|
- **Companies page (super admin):** a "Privacy notice" editor with the English and Bahasa Malaysia text areas, save, and "last changed by/at".
|
||||||
|
|
||||||
|
### 6. Gateway access without a user token (added after the live check)
|
||||||
|
|
||||||
|
mobile-api forwards the caller's JWT to the gateway, and a visitor has none, so the gateway's `JWTAuthFilter` refused every call the public flow makes (401). The gateway is internal only (`docs/deployment.md`), and the earlier sign-in work set the precedent of exact, anchored bypass paths.
|
||||||
|
|
||||||
|
- **Bypass only these, each for one HTTP method, with anchored patterns (no `contains`):**
|
||||||
|
- GET `/counter/registrationLink/findByToken/<22 url-safe chars>`
|
||||||
|
- GET `/counter/event/findByUuid/<digits>`
|
||||||
|
- GET `/counter/interest/findByCompany/<digits>`
|
||||||
|
- GET `/counter/eventSalesperson/findByEventUuid/<digits>`
|
||||||
|
- GET `/company/findById/<digits>`
|
||||||
|
- GET `/company/<digits>/privacyNotice` (the POST that saves a notice still needs a token)
|
||||||
|
- GET `/user/<digits>/activeAdminOf/<digits>`
|
||||||
|
- POST `/counter/registration/register`
|
||||||
|
- **`/user/findById` stays closed.** It returns the whole user record, password hashes included. services-system gets `GET /user/{id}/activeAdminOf/{companyId}`, which answers only `true` or `false` (type A, enabled, same company; false for an unknown user), and the public salesperson check uses it.
|
||||||
|
|
||||||
|
### 7. Rejected
|
||||||
|
|
||||||
|
- Matching and capture in mobile-api with two counter calls: not atomic, and it races the unique key.
|
||||||
|
- A notice text copied onto every event lead: a version id is enough and keeps rows small.
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
- Shared venue NAT: 60 submissions per event per 10 minutes from one IP may still be hit at a very busy booth. The message tells the visitor to try later. Raise the limit if it happens.
|
||||||
|
- The visitor IP is the last `X-Forwarded-For` hop, which is right whether Traefik appends to or replaces the header. Behind a second proxy in front of Traefik it would be that proxy's address; the deployment notes say so.
|
||||||
|
- The default notice is a template; INS and CV must review it.
|
||||||
|
- The registration code appears in request logs (mobile-api's response-time log and the gateway's request log). It is printed on the QR code anyway, and the audit log records the event instead; mask the path segment if that ever matters.
|
||||||
|
- The event page loads each team member's user record one call at a time (N+1). Teams are small; batch it if they grow.
|
||||||
|
- The gateway bypass (decision 6) lets any holder of a gateway api-key read those records and register a lead without a user token. The gateway is not exposed outside the cluster, and the paths are exact, so the exposure is limited to callers that already hold a server api-key. Such a caller could post registrations straight to services-counter, skipping mobile-api's code, consent and rate-limit checks: choose the company, event and salesperson, and learn from the outcome whether a mobile or email is already a lead. It could also read whole event records and test user ids against `activeAdminOf`. Narrower projections or a service-to-service credential would close this if the gateway is ever exposed.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
Co-Lite is a lead-generation system for INS and CV (the owner dropped the member app on 2026-12-01). At events, staff type every visitor in by hand. Walk-in visitors should scan a QR code, register themselves, and land in Event Leads and the dashboard, credited to the salesperson whose code they scanned. Approved design: `docs/superpowers/specs/2026-12-01-qr-self-registration-design.md`.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- A public, phone-first registration page `/r/<token>` on the admin portal. It shows the event's details, a short form and a bilingual PDPA consent, and every successful submit gets the same thank-you page.
|
||||||
|
- A registration links to an existing lead without editing it (differences go to the event lead's notes), or creates a new lead. It creates an OPEN event lead with `source = QR` and the consent record.
|
||||||
|
- Registration codes: one per event and one per salesperson per event. Staff with `BO_EVENTS` see, download, copy and switch off codes on the event page. Every staff user sees their own codes on a new "My QR codes" page.
|
||||||
|
- Each company's privacy notice is versioned and edited by super admins on the Companies page. INS and CV are seeded with a default English and Bahasa Malaysia notice. A company without a notice has no working codes.
|
||||||
|
- Abuse limits: per IP per event for submissions and per IP for page loads, plus a honeypot field.
|
||||||
|
- The admin portal gains `qrcode.react` (already used by babyboo's portal) to draw the codes.
|
||||||
|
- dynamic-qr: no code integration. An admin may paste a Co-Lite link into dynamic-qr's console for a repointable printed code.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
- `qr-registration`: registration codes, the public registration page and its rules, consent and privacy notices, and abuse limits.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- `service-counter`: new table `registration_link`; `event_lead` gains `source`, `consent_at` and `consent_notice_id`.
|
||||||
|
- `service-system`: new table `company_privacy_notice`, seeded for INS and CV.
|
||||||
|
- `solvway-services-counter`, `solvway-services-system`, `solvway-mobile-api` (public `/api/public/registration/**`, admin link and notice endpoints), `solvway-admin-portal` (public route outside the admin sign-in guard, event QR section, My QR codes, Companies notice).
|
||||||
|
- New public, unauthenticated surface: covered by the abuse limits and the anti-goals in the design.
|
||||||
|
- `docs/deployment.md`: the SQL, and a note that the default notice must be reviewed.
|
||||||
+127
@@ -0,0 +1,127 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Registration codes
|
||||||
|
|
||||||
|
The system SHALL give every event one registration code and one personal code per member of the event's team. A code SHALL be an unguessable token in a link of the form `/r/<token>`. Staff with `BO_EVENTS` SHALL see each code of an event of their company as a QR image, copy its link, download it as an image, and switch it off or on. Every staff user SHALL see their own personal codes for events of their company that have not ended.
|
||||||
|
|
||||||
|
#### Scenario: Event page codes
|
||||||
|
|
||||||
|
- **GIVEN** event `KL Expo` with `sales1` and `sales2` on its team
|
||||||
|
- **WHEN** a user with `BO_EVENTS` opens the event
|
||||||
|
- **THEN** the event's code and the personal codes of `sales1` and `sales2` are shown, each with its QR image and link
|
||||||
|
|
||||||
|
#### Scenario: Own codes
|
||||||
|
|
||||||
|
- **GIVEN** `sales1` is on the team of `KL Expo`, which ends tomorrow, and of `Penang Fair`, which ended last week
|
||||||
|
- **WHEN** `sales1` opens My QR codes
|
||||||
|
- **THEN** only the personal code for `KL Expo` is listed
|
||||||
|
|
||||||
|
#### Scenario: Switch a code off
|
||||||
|
|
||||||
|
- **WHEN** staff switch off the event code of `KL Expo`
|
||||||
|
- **THEN** scanning that code shows that it is no longer active
|
||||||
|
- **AND** the personal codes still work
|
||||||
|
|
||||||
|
### Requirement: When a code works
|
||||||
|
|
||||||
|
A code SHALL work only while it is switched on, its event is enabled, the event's end date in Malaysia time has not passed, and the event's company has a privacy notice. An inactive or unknown code SHALL show "This code is no longer active." and no event details. A personal code whose salesperson is no longer an active member of the event's team SHALL keep working, and its registrations SHALL have no salesperson.
|
||||||
|
|
||||||
|
#### Scenario: Ended event
|
||||||
|
|
||||||
|
- **GIVEN** `Penang Fair` ended yesterday
|
||||||
|
- **WHEN** a visitor scans its code
|
||||||
|
- **THEN** the page says the code is no longer active and shows no event details
|
||||||
|
|
||||||
|
#### Scenario: Salesperson left the team
|
||||||
|
|
||||||
|
- **GIVEN** `sales2` was removed from the team of `KL Expo`
|
||||||
|
- **WHEN** a visitor registers through `sales2`'s code
|
||||||
|
- **THEN** the registration succeeds and the event lead has no salesperson
|
||||||
|
|
||||||
|
### Requirement: Public registration
|
||||||
|
|
||||||
|
The registration page SHALL show the event's name, dates and location, and a form for name (required), mobile and email (at least one), company, job title, the company's active interests, and the privacy notice consent (required). Inputs SHALL be normalised and limited as in staff capture. Every accepted submission SHALL show the same thank-you page naming the event, with a button to register another person, whether or not the person was already known.
|
||||||
|
|
||||||
|
#### Scenario: Register
|
||||||
|
|
||||||
|
- **WHEN** a visitor scans the code of `KL Expo`, enters name `Aisyah`, mobile `012-345 6701` and ticks the consent
|
||||||
|
- **THEN** the thank-you page names `KL Expo`
|
||||||
|
- **AND** staff see `Aisyah` with mobile `+60123456701` in the event's leads as NEW and OPEN
|
||||||
|
|
||||||
|
#### Scenario: Missing consent or contact
|
||||||
|
|
||||||
|
- **WHEN** a visitor submits without ticking the consent, or without a mobile and an email
|
||||||
|
- **THEN** nothing is saved and the page shows the error under the field
|
||||||
|
|
||||||
|
#### Scenario: Known person gets the same answer
|
||||||
|
|
||||||
|
- **GIVEN** a lead with mobile `+60123456701` exists in the company
|
||||||
|
- **WHEN** a visitor registers with that mobile
|
||||||
|
- **THEN** the page shows the same thank-you page as for a new person
|
||||||
|
|
||||||
|
### Requirement: Registration matching
|
||||||
|
|
||||||
|
A registration SHALL match a lead of the event's company by mobile first and then by email, the newest lead winning among several. A matched lead SHALL NOT be edited: it SHALL be linked as EXISTING, with every submitted value that differs from the lead's written into the event lead's notes. Without a match a new lead SHALL be created as NEW.
|
||||||
|
|
||||||
|
#### Scenario: Existing lead not edited
|
||||||
|
|
||||||
|
- **GIVEN** lead `Aisyah` with mobile `+60123456701` and no email
|
||||||
|
- **WHEN** a visitor registers as `Aisyah Rahman` with that mobile and email `a@example.test`
|
||||||
|
- **THEN** lead `Aisyah` still has no email and its name is unchanged
|
||||||
|
- **AND** the new event lead is EXISTING and its notes list the submitted name and email
|
||||||
|
|
||||||
|
#### Scenario: Mobile beats email
|
||||||
|
|
||||||
|
- **GIVEN** lead `A` has mobile `+60123456701` and lead `B` has email `b@example.test`
|
||||||
|
- **WHEN** a visitor registers with that mobile and that email
|
||||||
|
- **THEN** the registration is linked to lead `A`
|
||||||
|
|
||||||
|
### Requirement: Registration of a person already captured
|
||||||
|
|
||||||
|
When the matched lead is already captured at the event, a registration SHALL change nothing, except that an event lead with no salesperson SHALL get the salesperson of a personal code whose salesperson is an active member of the event's team.
|
||||||
|
|
||||||
|
#### Scenario: Already captured, unassigned
|
||||||
|
|
||||||
|
- **GIVEN** `Aisyah` is captured at `KL Expo` with no salesperson
|
||||||
|
- **WHEN** she registers again through `sales1`'s personal code and `sales1` is on the team
|
||||||
|
- **THEN** her event lead's salesperson becomes `sales1` and nothing else changes
|
||||||
|
|
||||||
|
### Requirement: Registration record
|
||||||
|
|
||||||
|
An event lead created by a registration SHALL have status OPEN, source QR, captured by `qr`, the consent time and the privacy notice version shown, the chosen interests, and the code's salesperson when that salesperson is an active member of the event's team. Event leads captured by staff SHALL have source STAFF. The status history SHALL record the first status by `qr`.
|
||||||
|
|
||||||
|
#### Scenario: Personal code assigns
|
||||||
|
|
||||||
|
- **WHEN** a visitor registers through `sales1`'s personal code for `KL Expo`
|
||||||
|
- **THEN** the event lead's salesperson is `sales1`, its source is QR and it records the consent time and notice version
|
||||||
|
|
||||||
|
### Requirement: Privacy notice
|
||||||
|
|
||||||
|
Each company SHALL have a privacy notice in English and Bahasa Malaysia, kept as versions: saving a change SHALL add a new version and keep the old ones. Only a super admin SHALL edit it, on the Companies page. The registration page SHALL show the company's current notice in both languages. INS and CV SHALL start with the default notice of the design, with the company's name filled in.
|
||||||
|
|
||||||
|
#### Scenario: Edit the notice
|
||||||
|
|
||||||
|
- **GIVEN** CV's notice is version 3
|
||||||
|
- **WHEN** a super admin changes CV's English text and saves
|
||||||
|
- **THEN** CV's registration pages show the new text
|
||||||
|
- **AND** event leads registered before still point to version 3
|
||||||
|
|
||||||
|
#### Scenario: Not a super admin
|
||||||
|
|
||||||
|
- **WHEN** company staff call the privacy notice update endpoint
|
||||||
|
- **THEN** it responds 403
|
||||||
|
|
||||||
|
### Requirement: Registration abuse limits
|
||||||
|
|
||||||
|
The system SHALL accept at most 60 registrations per client IP per event in 10 minutes and serve at most 120 registration page loads per client IP in 10 minutes, answering above either limit with "Too many registrations from this device. Try again later." A submission that fills the hidden honeypot field SHALL get the normal thank-you page and save nothing.
|
||||||
|
|
||||||
|
#### Scenario: Too many submissions
|
||||||
|
|
||||||
|
- **GIVEN** 60 registrations for `KL Expo` from one IP in the last 10 minutes
|
||||||
|
- **WHEN** the 61st arrives from that IP
|
||||||
|
- **THEN** nothing is saved and the page shows the too-many message
|
||||||
|
|
||||||
|
#### Scenario: Honeypot
|
||||||
|
|
||||||
|
- **WHEN** a submission fills the hidden field
|
||||||
|
- **THEN** the thank-you page shows and no lead or event lead is saved
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
-- Co-Lite change add-qr-self-registration: registration codes and the source/consent of event leads (design decision 1).
|
||||||
|
-- Target: `service-counter`. Additive only. Run before the new images go live. Needs a user that may alter tables.
|
||||||
|
USE `service-counter`;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `registration_link` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`company_id` bigint NOT NULL,
|
||||||
|
`event_uuid` bigint NOT NULL,
|
||||||
|
`salesperson_user_id` bigint NULL,
|
||||||
|
`token` varchar(32) NOT NULL,
|
||||||
|
`enabled` bit(1) NOT NULL DEFAULT b'1',
|
||||||
|
`created_by` varchar(255) NULL,
|
||||||
|
`created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_by` varchar(255) NULL,
|
||||||
|
`updated_at` datetime NULL,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_registration_link_token` (`token`),
|
||||||
|
KEY `idx_registration_link_event` (`event_uuid`, `salesperson_user_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
ALTER TABLE `event_lead`
|
||||||
|
ADD COLUMN `source` varchar(8) NOT NULL DEFAULT 'STAFF' AFTER `lead_type`,
|
||||||
|
ADD COLUMN `consent_at` datetime NULL AFTER `notes`,
|
||||||
|
ADD COLUMN `consent_notice_id` bigint NULL AFTER `consent_at`;
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
-- Co-Lite change add-qr-self-registration: versioned privacy notice per company, seeded with the default text.
|
||||||
|
-- Target: `service-system`. Additive only. The default notice is a template, not legal advice: INS and CV should have it
|
||||||
|
-- reviewed, then a super admin saves the reviewed text on the Companies page (which adds a new version).
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `company_privacy_notice` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`company_id` bigint NOT NULL,
|
||||||
|
`text_en` text NOT NULL,
|
||||||
|
`text_ms` text NOT NULL,
|
||||||
|
`created_by` varchar(255) NULL,
|
||||||
|
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_company_privacy_notice_company` (`company_id`, `id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- created_at in Malaysian time, like the rows the services write (the server clock may be UTC).
|
||||||
|
INSERT INTO `company_privacy_notice` (`company_id`, `text_en`, `text_ms`, `created_by`, `created_at`)
|
||||||
|
SELECT c.`id`,
|
||||||
|
REPLACE('{company} collects the details you enter on this form (your name, mobile number, email, company, job title and interests) to contact you about our products, services and events, including by phone, SMS, WhatsApp and email. Your details are used only by {company} and the service providers who run this system for us, and are not sold to anyone. We keep them for as long as you remain a contact of ours or until you ask us to delete them. You may ask to see or correct your details, or withdraw this consent, at any time by contacting {company}. Giving your details is voluntary, but without them we cannot follow up with you.', '{company}', c.`name`),
|
||||||
|
REPLACE('{company} mengumpul butiran yang anda masukkan dalam borang ini (nama, nombor telefon bimbit, e-mel, syarikat, jawatan dan minat anda) untuk menghubungi anda mengenai produk, perkhidmatan dan acara kami, termasuk melalui telefon, SMS, WhatsApp dan e-mel. Butiran anda hanya digunakan oleh {company} dan pembekal perkhidmatan yang mengendalikan sistem ini bagi pihak kami, dan tidak dijual kepada sesiapa. Kami menyimpannya selagi anda kekal sebagai kenalan kami atau sehingga anda meminta kami memadamnya. Anda boleh meminta untuk melihat atau membetulkan butiran anda, atau menarik balik persetujuan ini, pada bila-bila masa dengan menghubungi {company}. Pemberian butiran adalah secara sukarela, tetapi tanpanya kami tidak dapat menghubungi anda.', '{company}', c.`name`),
|
||||||
|
'default',
|
||||||
|
DATE_ADD(UTC_TIMESTAMP(), INTERVAL 8 HOUR)
|
||||||
|
FROM `company` c
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM `company_privacy_notice` n WHERE n.`company_id` = c.`id`);
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Co-Lite change add-qr-self-registration: rollback. Deletes the codes, the notices and the consent records.
|
||||||
|
USE `service-system`;
|
||||||
|
DROP TABLE IF EXISTS `company_privacy_notice`;
|
||||||
|
|
||||||
|
USE `service-counter`;
|
||||||
|
DROP TABLE IF EXISTS `registration_link`;
|
||||||
|
ALTER TABLE `event_lead` DROP COLUMN `consent_notice_id`, DROP COLUMN `consent_at`, DROP COLUMN `source`;
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-01-qr-self-registration-design.md` (product).
|
||||||
|
|
||||||
|
Waves:
|
||||||
|
- Wave 0 (serial, controller): 1.1 and 1.2 touch hotspots (SQL, seed, `package.json`).
|
||||||
|
- Wave 1 (parallel, 3 implementers): 2.1, 3.1 and 4.1 build against the fixed contracts in design decisions 2 to 4. Each touches one module only.
|
||||||
|
- Wave 2 (serial): 5.1, the portal, which also touches the middleware (security).
|
||||||
|
- Wave 3 (serial, controller): 6.1.
|
||||||
|
|
||||||
|
## 1. Data and dependency
|
||||||
|
|
||||||
|
- [x] 1.1 SQL `sql/01`, `02`, `99`; mirror 01 and 02 in `local/seed/03-colite.sql`; apply 01 and 02 to the local database.
|
||||||
|
- Depends on: none
|
||||||
|
- Scope: `local/seed/**`, `openspec/changes/add-qr-self-registration/sql/**`
|
||||||
|
- Verify: `SELECT` shows the table, the new `event_lead` columns, and one notice per company with the company name filled in.
|
||||||
|
- [x] 1.2 Portal: add `qrcode.react` (same major as babyboo's portal).
|
||||||
|
- Depends on: none
|
||||||
|
- Scope: `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`
|
||||||
|
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
|
||||||
|
|
||||||
|
## 2. services-counter
|
||||||
|
|
||||||
|
- [x] 2.1 Registration links and the registration capture (decision 2).
|
||||||
|
- Tests first:
|
||||||
|
- `ensure` creates the event code and missing personal codes once, keeps order, and makes 22-character unique tokens;
|
||||||
|
- `setEnabled` refuses another company's or another event's token;
|
||||||
|
- `findByToken` returns the link, or 404;
|
||||||
|
- `mine` lists only enabled, not-ended events where the user is on the team, creating missing links;
|
||||||
|
- `register`:
|
||||||
|
- new person → NEW, OPEN, QR, `qr`, consent fields, interests, history null → OPEN by `qr`;
|
||||||
|
- known by mobile → EXISTING, lead unchanged, notes list only differing submitted values (null when none);
|
||||||
|
- mobile beats email when they match different leads;
|
||||||
|
- newest lead wins among several;
|
||||||
|
- already captured: unassigned + salesperson → ASSIGNED; otherwise ALREADY_CAPTURED with nothing changed;
|
||||||
|
- the unique-key race → treated as already captured;
|
||||||
|
- staff capture still sets `source STAFF`.
|
||||||
|
- Scope: `solvway-services-counter/src/**`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
|
||||||
|
|
||||||
|
## 3. services-system
|
||||||
|
|
||||||
|
- [x] 3.1 Company privacy notice versions (decision 3).
|
||||||
|
- Tests first:
|
||||||
|
- GET returns the newest version, 404 when none;
|
||||||
|
- POST adds a version, keeps older ones, trims, requires both texts, at most 5000 characters each, 404 for an unknown company.
|
||||||
|
- Scope: `solvway-services-system/src/**`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-services-system verify`
|
||||||
|
|
||||||
|
## 4. mobile-api
|
||||||
|
|
||||||
|
- [x] 4.1 Public registration endpoints and the admin link and notice endpoints (decision 4).
|
||||||
|
- Tests first:
|
||||||
|
- **GET code checks:** inactive for each failing condition (unknown, switched off, event disabled, ended, company inactive, no notice); the active payload includes only active interests;
|
||||||
|
- **POST rejections:** honeypot → 200 and no counter call; consent missing → 400 `CONSENT_REQUIRED` on field `consent`;
|
||||||
|
- **POST validation:** same field rules as staff capture; an inactive interest is refused;
|
||||||
|
- **POST salesperson:** the code's salesperson is passed when active on the team, null otherwise;
|
||||||
|
- **POST notice:** the current notice id comes from the server;
|
||||||
|
- **Limits:** 120 page loads per IP and 60 submissions per IP per event per 10 minutes → 429 `TOO_MANY` (Redis mocked); the IP comes from `HttpReqRespUtils.getClientIpAddressIfServletRequestExist`;
|
||||||
|
- **Admin:** links endpoint scoped by company and gated `BO_EVENTS`; toggle; my links for the caller only and `[]` without a company; privacy notice GET/PUT super-admin only (403 for staff).
|
||||||
|
- Scope: `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
|
||||||
|
|
||||||
|
- [x] 4.2 Gateway access for the public flow (decision 6), found by the live check.
|
||||||
|
- Depends on: 4.1
|
||||||
|
- Tests first:
|
||||||
|
- gateway: each decision-6 path passes without a user token for its method; POST `/company/1/privacyNotice`, GET `/user/findById/1`, POST `/counter/registrationLink/ensure` and a path with an extra segment still get 401;
|
||||||
|
- services-system: `activeAdminOf` is true only for an enabled type-A user of that company, false otherwise and for an unknown user;
|
||||||
|
- mobile-api: the public salesperson check uses `activeAdminOf` and never `findById`.
|
||||||
|
- Scope: `solvway-api-gateway/src/**`, `solvway-services-system/src/**`, `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-api-gateway,solvway-services-system,solvway-mobile-api verify`
|
||||||
|
|
||||||
|
## 5. Portal
|
||||||
|
|
||||||
|
- [x] 5.1 Public page, proxy, middleware, event QR card, My QR codes, Companies privacy notice (decision 5).
|
||||||
|
- Depends on: 1.2 and the contracts of 4.1
|
||||||
|
- Tests first:
|
||||||
|
- middleware: `/r/x` and `/api/public/registration/x` pass signed out, and `/events` still redirects;
|
||||||
|
- proxy forwards GET and POST with the client IP;
|
||||||
|
- public page: inactive message, the form with both notice texts, required consent, field errors, too-many, thank-you with "Register another person" resetting the form, honeypot field hidden from people and from assistive technology;
|
||||||
|
- event QR card: codes, copy, switch (hidden without write access), download;
|
||||||
|
- My QR codes: list and empty state;
|
||||||
|
- Companies notice editor: super admin only, save, error;
|
||||||
|
- the hard-coded copy sweep stays green.
|
||||||
|
- Scope: `solvway-admin-portal/app/**`, `solvway-admin-portal/middleware.ts`, `solvway-admin-portal/middleware*.test.ts`
|
||||||
|
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
|
||||||
|
|
||||||
|
## 6. Release
|
||||||
|
|
||||||
|
- [x] 6.1 `docs/deployment.md` (SQL, notice review, the Traefik `X-Forwarded-For` note, dynamic-qr usage); live check on the local stack; Playwright at 1280 and 360 px:
|
||||||
|
- a visitor registers through an event code and a personal code;
|
||||||
|
- the inactive, consent and too-many paths;
|
||||||
|
- staff toggle a code and see My QR codes;
|
||||||
|
- a super admin edits a notice.
|
||||||
|
- Depends on: 1.1 to 5.1
|
||||||
|
- Scope: `docs/deployment.md`, `openspec/changes/add-qr-self-registration/tasks.md`
|
||||||
|
- Verify: the three Maven modules and the portal verify.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-01
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
The whole-branch review of add-company-scoping (PR #25) found that the code trusts the "every non-super admin belongs to a company" rule instead of enforcing it. An admin user with no company who is not a super admin (left over from before companies, or created by a direct DB edit) is scoped to all companies. A company user who still holds role 1 skips every module check and is treated as a super admin when reading super admins' emails.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- Company scope fails closed: an admin with no company who is not a super admin gets 403 `COMPANY_REQUIRED` on every company-scoped admin endpoint instead of seeing all companies.
|
||||||
|
- The admin module check grants all modules only to a super admin (no company and role 1), not to any holder of role 1.
|
||||||
|
- The email detail hides super admins' emails from every caller who is not a super admin, using the same super-admin test.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
- `company-scoping`: adds the "Invalid admins fail closed" requirement for the two invalid states.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- `solvway-mobile-api`: `AdminCompanyScope`, `AppAccessAspect`, `AdminEmailService`.
|
||||||
|
- No API shape, schema or portal change. Valid users (super admins, and staff with a company) see no difference.
|
||||||
|
- Deferred: the capture event list still loads only the first 100 enabled events (marked `ponytail:` in `AdminEventLeadService`).
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Invalid admins fail closed
|
||||||
|
|
||||||
|
The system SHALL refuse every company-scoped request from an admin with no company who is not a super admin, and SHALL grant a company user who holds the super admin role only the modules and records their company and other roles allow.
|
||||||
|
|
||||||
|
#### Scenario: Admin without a company who is not a super admin
|
||||||
|
|
||||||
|
- **GIVEN** an admin user with no company and no super admin role
|
||||||
|
- **WHEN** they open Leads, Events, Users or any other company-scoped list or record
|
||||||
|
- **THEN** the request is refused with 403
|
||||||
|
- **AND** no company's records are returned
|
||||||
|
|
||||||
|
#### Scenario: Company user still holding the super admin role
|
||||||
|
|
||||||
|
- **GIVEN** a user of INS who holds the super admin role and a role granting only Leads
|
||||||
|
- **WHEN** they open Users or another super admin's email
|
||||||
|
- **THEN** the request is refused with 403
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
## 1. Fail closed
|
||||||
|
|
||||||
|
- [x] 1.1 `AdminCompanyScope.scope` and `requireCompanyForCreate` refuse (403 `COMPANY_REQUIRED`) an admin with no company who is not a super admin
|
||||||
|
- Depends on: none
|
||||||
|
- Scope: `solvway-mobile-api/src/**/useraccess/AdminCompanyScope*.java`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
|
||||||
|
- [x] 1.2 `AppAccessAspect` skips the module check only for `AdminCompanyScope.isSuper`; `AdminEmailService` uses the same test
|
||||||
|
- Depends on: 1.1
|
||||||
|
- Scope: `solvway-mobile-api/src/**/useraccess/AppAccessAspect*.java`, `solvway-mobile-api/src/**/service/AdminEmailService*.java`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-01
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
Company codes are stored and shown in lowercase (`ins`, `cv`). The owner wants them in capitals (`INS`, `CV`), and the Companies screen cannot change `cv` to `CV`: the portal treats a case-only change as no change, and services-system lowercases every code it saves.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- Company codes are stored and shown in capitals: 2 to 20 characters of `A-Z`, `0-9` and `-`. Any code entered is turned to capitals before it is checked and saved.
|
||||||
|
- Sign-in keeps ignoring case: staff can type `cv`, `Cv` or `CV`.
|
||||||
|
- Staff login names follow the code (`sales9@CV`).
|
||||||
|
- A one-off SQL turns the existing codes and staff login names to capitals.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
- `company-scoping`: the code format of the Companies requirement becomes capitals.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- **services-system:** `CompanyService` code validation and normalisation.
|
||||||
|
- **mobile-api:** the admin login builds the login name with the code in capitals.
|
||||||
|
- **portal:** the Companies code fields show and send capitals. A case-only rename is no longer treated as no change.
|
||||||
|
- **Data:** `sql/01-uppercase-codes.sql` on `service-system`. Signed-in staff must sign in again after it runs, as after any code change.
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
# Spec Delta
|
||||||
|
|
||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Companies
|
||||||
|
|
||||||
|
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of capital letters, digits and hyphens. A code entered in any case SHALL be stored in capitals, and codes SHALL be compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
|
||||||
|
|
||||||
|
#### Scenario: Create a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates company `CV` with code `cv`
|
||||||
|
- **THEN** it is listed as active with code `CV`
|
||||||
|
- **AND** staff can be created in it
|
||||||
|
|
||||||
|
#### Scenario: Duplicate code
|
||||||
|
|
||||||
|
- **GIVEN** a company with code `INS`
|
||||||
|
- **WHEN** a super admin creates or renames another company to code `ins`
|
||||||
|
- **THEN** the save is refused and the code is reported as taken
|
||||||
|
|
||||||
|
#### Scenario: Not a super admin
|
||||||
|
|
||||||
|
- **WHEN** company staff open the Companies page or call a companies endpoint
|
||||||
|
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||||
|
|
||||||
|
#### Scenario: Sign-in ignores case
|
||||||
|
|
||||||
|
- **GIVEN** company code `CV` and its user `sales9`
|
||||||
|
- **WHEN** they sign in with company `cv`
|
||||||
|
- **THEN** they are signed in as `sales9` of CV
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Co-Lite change uppercase-company-codes: company codes and staff login names in capitals.
|
||||||
|
-- Target: `service-system`. Signed-in staff must sign in again afterwards. Idempotent.
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
UPDATE `user` u JOIN `company` c ON c.`id` = u.`company_id`
|
||||||
|
SET u.`username` = CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', UPPER(c.`code`))
|
||||||
|
WHERE u.`type` = 'A' AND u.`username` LIKE CONCAT('%@', c.`code`) AND BINARY u.`username` <> BINARY CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', UPPER(c.`code`));
|
||||||
|
|
||||||
|
UPDATE `company` SET `code` = UPPER(`code`) WHERE BINARY `code` <> BINARY UPPER(`code`);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Co-Lite change uppercase-company-codes: rollback to lowercase codes and login names.
|
||||||
|
USE `service-system`;
|
||||||
|
|
||||||
|
UPDATE `user` u JOIN `company` c ON c.`id` = u.`company_id`
|
||||||
|
SET u.`username` = CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', LOWER(c.`code`))
|
||||||
|
WHERE u.`type` = 'A' AND u.`username` LIKE CONCAT('%@', c.`code`);
|
||||||
|
|
||||||
|
UPDATE `company` SET `code` = LOWER(`code`);
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
Serial. One implementer, in this session.
|
||||||
|
|
||||||
|
## 1. Data
|
||||||
|
|
||||||
|
- [x] 1.1 `sql/01-uppercase-codes.sql` and `sql/99-rollback.sql`; change the codes in `local/seed/03-colite.sql` to `INS` and `CV` (the `@ins` login names it builds follow); apply 01 to the local database.
|
||||||
|
- Depends on: none
|
||||||
|
- Scope: `local/seed/**`, `openspec/changes/uppercase-company-codes/sql/**`
|
||||||
|
- Verify: `SELECT code FROM company` gives `INS`, `CV`; staff login names end in `@INS` or `@CV`.
|
||||||
|
|
||||||
|
## 2. Backend
|
||||||
|
|
||||||
|
- [x] 2.1 services-system `CompanyService` stores codes in capitals (`^[A-Z0-9-]{2,20}$`, entered value trimmed and turned to capitals); mobile-api admin login and forgot-password build the login name with the code in capitals.
|
||||||
|
- Depends on: 1.1
|
||||||
|
- Tests first: create with `cv` stores `CV`; rename `cv` to `CV` on a company whose code is `cv` succeeds; `ins` is taken when `INS` exists; an invalid code is refused; login with company `cv` looks up `user@CV`.
|
||||||
|
- Scope: `solvway-services-system/src/**`, `solvway-mobile-api/src/**`
|
||||||
|
- Verify: `mvn -T 1C -q -pl solvway-services-system,solvway-mobile-api verify`
|
||||||
|
|
||||||
|
## 3. Portal
|
||||||
|
|
||||||
|
- [x] 3.1 Companies: code inputs show capitals as typed and the rename compares case-sensitively, so `cv` to `CV` is a change.
|
||||||
|
- Depends on: 2.1
|
||||||
|
- Tests first: typing `cv` shows `CV`; renaming `cv` to `CV` sends the request.
|
||||||
|
- Scope: `solvway-admin-portal/app/**`
|
||||||
|
- Verify: `cd solvway-admin-portal && npm run lint; echo L=$?; npx tsc --noEmit; echo T=$?; npx vitest run; echo V=$?`
|
||||||
|
|
||||||
|
## 4. Release
|
||||||
|
|
||||||
|
- [x] 4.1 `docs/deployment.md` notes the SQL and that staff sign in again; Playwright: Companies shows `INS` and `CV`, sign in as `sales9` with company `cv` works.
|
||||||
|
- Depends on: 3.1
|
||||||
|
- Scope: `docs/deployment.md`, `openspec/changes/uppercase-company-codes/tasks.md`
|
||||||
|
- Verify: the 2.1 and 3.1 verifies.
|
||||||
@@ -8,20 +8,26 @@ Staff log in to the Co-Lite admin portal, and every admin page and `/api/admin/*
|
|||||||
|
|
||||||
### Requirement: Staff login
|
### Requirement: Staff login
|
||||||
|
|
||||||
The system SHALL let an active admin user log in with username and password through the admin portal, and SHALL return the user's name, roles, menu and whether a password change is required.
|
The system SHALL let an active admin user log in through the admin portal with company code, username and password, or with username and password and no company for a super admin, and SHALL return the user's name, roles, company, menu and whether a password change is required.
|
||||||
|
|
||||||
#### Scenario: Correct credentials
|
#### Scenario: Correct credentials
|
||||||
|
|
||||||
- **GIVEN** an active admin user `admin` with password `colite-dev-admin`
|
- **GIVEN** an active admin user `sales1` of active company `ins`
|
||||||
- **WHEN** they submit those credentials on the login page
|
- **WHEN** they submit company `ins`, username `sales1` and their password on the login page
|
||||||
- **THEN** they are signed in and land on the portal home
|
- **THEN** they are signed in and land on the portal home
|
||||||
- **AND** the sidebar shows only the menu entries their roles grant
|
- **AND** the sidebar shows only the menu entries their roles grant
|
||||||
|
|
||||||
|
#### Scenario: Super admin
|
||||||
|
|
||||||
|
- **GIVEN** the super admin `admin`, who belongs to no company
|
||||||
|
- **WHEN** they submit username `admin` and their password with the company left empty
|
||||||
|
- **THEN** they are signed in
|
||||||
|
|
||||||
#### Scenario: Wrong password
|
#### Scenario: Wrong password
|
||||||
|
|
||||||
- **WHEN** a user submits a wrong password
|
- **WHEN** a user submits a wrong password
|
||||||
- **THEN** `/api/admin/auth/login` responds 401
|
- **THEN** `/api/admin/auth/login` responds 401
|
||||||
- **AND** the login page shows an invalid-credentials message without saying whether the username exists
|
- **AND** the login page shows an invalid-credentials message without saying whether the company or username exists
|
||||||
|
|
||||||
#### Scenario: Deactivated user
|
#### Scenario: Deactivated user
|
||||||
|
|
||||||
@@ -53,19 +59,19 @@ The system SHALL require a user whose password is temporary (new user or reset)
|
|||||||
|
|
||||||
### Requirement: Forgot password
|
### Requirement: Forgot password
|
||||||
|
|
||||||
The system SHALL let a user request a temporary password by entering their username and email on a public forgot-password page. The response SHALL be the same whether or not the username and email match an active admin user.
|
The system SHALL let a user request a temporary password by entering their company code, username and email on a public forgot-password page; a super admin leaves the company empty. The response SHALL be the same whether or not the details match an active admin user.
|
||||||
|
|
||||||
#### Scenario: Matching username and email
|
#### Scenario: Matching username and email
|
||||||
|
|
||||||
- **GIVEN** an active admin user with username `sales1` and email `sales1@example.com`
|
- **GIVEN** an active admin user `sales1` of company `ins` with email `sales1@example.com`
|
||||||
- **WHEN** someone submits `sales1` and `sales1@example.com`
|
- **WHEN** someone submits company `ins`, username `sales1` and `sales1@example.com`
|
||||||
- **THEN** a temporary password is emailed to `sales1@example.com`
|
- **THEN** a temporary password is emailed to `sales1@example.com`
|
||||||
- **AND** the user must change it at next login
|
- **AND** the user must change it at next login
|
||||||
- **AND** the page shows "If the details match an account, we have emailed a temporary password."
|
- **AND** the page shows "If the details match an account, we have emailed a temporary password."
|
||||||
|
|
||||||
#### Scenario: Non-matching details
|
#### Scenario: Non-matching details
|
||||||
|
|
||||||
- **WHEN** someone submits a username and email that do not match an active admin user
|
- **WHEN** someone submits a company, username and email that do not match an active admin user
|
||||||
- **THEN** no password changes and no email is sent
|
- **THEN** no password changes and no email is sent
|
||||||
- **AND** the page shows the same message as for a match
|
- **AND** the page shows the same message as for a match
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# admin-audit-log Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Record who did what in the admin portal: every admin write, chosen sensitive reads and refused attempts, with allow-listed before/after values and no personal data, kept for a configurable retention and readable on the Audit log screen by admins granted `BO_AUDIT_LOG`.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Admin writes are recorded
|
||||||
|
|
||||||
|
The system SHALL record an audit event for every state-changing admin API call made with a valid admin token, successful or not, holding the time, admin username, module, readable action code, HTTP method, path template (never the concrete path or query), target id, outcome with HTTP status, and client IP. Sign-in, sign-out, token refresh, forgot-password, own password change from the user menu, and calls without a valid admin token SHALL NOT be recorded.
|
||||||
|
|
||||||
|
#### Scenario: A user edit is recorded
|
||||||
|
|
||||||
|
- **WHEN** admin `admin` updates user 4
|
||||||
|
- **THEN** an audit event is saved with actor `admin`, module `BO_USERS`, action `USER_UPDATE`, path template `PUT /api/admin/users/{id}`, target `4`, outcome `SUCCESS`, and the client IP
|
||||||
|
|
||||||
|
#### Scenario: A failed write is recorded
|
||||||
|
|
||||||
|
- **WHEN** an admin's role update is refused with status 400
|
||||||
|
- **THEN** an audit event is saved with outcome `FAILURE` and status 400
|
||||||
|
|
||||||
|
#### Scenario: Sign-in is not recorded
|
||||||
|
|
||||||
|
- **WHEN** an admin signs in or signs out
|
||||||
|
- **THEN** no audit event is saved
|
||||||
|
|
||||||
|
#### Scenario: First-login password change is recorded
|
||||||
|
|
||||||
|
- **WHEN** a new admin sets their password at first login
|
||||||
|
- **THEN** an audit event with action `AUTH_FIRST_LOGIN` is saved
|
||||||
|
|
||||||
|
### Requirement: Refused access is recorded
|
||||||
|
|
||||||
|
The system SHALL record an audit event with outcome `FAILURE` when a valid admin token is refused by the access check (missing module, super admin required, or pending first-login change).
|
||||||
|
|
||||||
|
#### Scenario: Missing module
|
||||||
|
|
||||||
|
- **GIVEN** admin `noevents` has no `BO_EVENTS`
|
||||||
|
- **WHEN** `noevents` tries to create an event
|
||||||
|
- **THEN** the request is refused with 403
|
||||||
|
- **AND** an audit event with actor `noevents`, module `BO_EVENTS` and outcome `FAILURE` is saved
|
||||||
|
|
||||||
|
### Requirement: Sensitive reads are recorded
|
||||||
|
|
||||||
|
The system SHALL record an audit event when an admin exports leads, exports event leads, or opens a saved email. Read-only POST calls marked as such SHALL NOT be recorded.
|
||||||
|
|
||||||
|
#### Scenario: Opening an email
|
||||||
|
|
||||||
|
- **WHEN** an admin opens email 12
|
||||||
|
- **THEN** an audit event with action `EMAIL_VIEW` and target `12` is saved
|
||||||
|
|
||||||
|
#### Scenario: Lead export
|
||||||
|
|
||||||
|
- **WHEN** an admin downloads the lead export
|
||||||
|
- **THEN** an audit event with action `LEAD_EXPORT` is saved
|
||||||
|
|
||||||
|
### Requirement: Allow-listed changes
|
||||||
|
|
||||||
|
The system SHALL attach before and after values only for these fields: a user's role names and enabled flag, a role's granted module codes, and the login-security lockout settings and password rules. For lead and event-lead edits the system SHALL record only the names of the fields that changed, never their values. No audit event SHALL contain a password, token, raw request body, or lead name, phone, email or notes.
|
||||||
|
|
||||||
|
#### Scenario: Role change on a user
|
||||||
|
|
||||||
|
- **WHEN** an admin changes user 4's roles from `Sales` to `Sales, Manager`
|
||||||
|
- **THEN** the event's changes show roles before `Sales` and after `Sales, Manager`
|
||||||
|
|
||||||
|
#### Scenario: Lead edit records field names only
|
||||||
|
|
||||||
|
- **WHEN** an admin changes a lead's phone and notes
|
||||||
|
- **THEN** the event's changes list the fields `phone` and `notes`
|
||||||
|
- **AND** neither the old nor the new phone or notes appear in the event
|
||||||
|
|
||||||
|
### Requirement: Recording never blocks the action
|
||||||
|
|
||||||
|
Recording SHALL be best-effort. A failure to publish or save an audit event MUST NOT change the response of the admin call.
|
||||||
|
|
||||||
|
#### Scenario: Publish failure
|
||||||
|
|
||||||
|
- **GIVEN** the audit event cannot be published
|
||||||
|
- **WHEN** an admin updates a user
|
||||||
|
- **THEN** the update succeeds as usual
|
||||||
|
- **AND** the failure is logged
|
||||||
|
|
||||||
|
### Requirement: Retention
|
||||||
|
|
||||||
|
The system SHALL delete audit events older than the configured retention period, 730 days by default, on a schedule.
|
||||||
|
|
||||||
|
#### Scenario: Old events are purged
|
||||||
|
|
||||||
|
- **WHEN** the purge runs with a retention of 730 days
|
||||||
|
- **THEN** events older than 730 days are deleted
|
||||||
|
- **AND** newer events are kept
|
||||||
|
|
||||||
|
### Requirement: Audit log screen
|
||||||
|
|
||||||
|
The system SHALL let an admin with `BO_AUDIT_LOG` list audit events newest first, paged, filtered by actor, module, action, outcome and date range, and open one event to see its details and changes. An admin without `BO_AUDIT_LOG` SHALL be refused.
|
||||||
|
|
||||||
|
#### Scenario: Filter by actor
|
||||||
|
|
||||||
|
- **WHEN** an admin with `BO_AUDIT_LOG` filters the audit log by actor `admin`
|
||||||
|
- **THEN** only events by `admin` are listed, newest first
|
||||||
|
|
||||||
|
#### Scenario: Event detail
|
||||||
|
|
||||||
|
- **WHEN** an admin opens an event for a role grant change
|
||||||
|
- **THEN** the detail shows the event's fields and the modules added and removed
|
||||||
|
|
||||||
|
#### Scenario: Without the module
|
||||||
|
|
||||||
|
- **WHEN** an admin without `BO_AUDIT_LOG` calls the audit log API or opens `/audit-log`
|
||||||
|
- **THEN** the API answers 403 and the page shows Not authorised
|
||||||
@@ -89,16 +89,22 @@ The system SHALL refuse sign-in for a locked username before checking the passwo
|
|||||||
|
|
||||||
### Requirement: Unlock
|
### Requirement: Unlock
|
||||||
|
|
||||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
|
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames of their own company that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one of them. A super admin SHALL see and unlock locked usernames of every company, including attempts that match no company. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
|
||||||
|
|
||||||
#### Scenario: Unlock a locked username
|
#### Scenario: Unlock a locked username
|
||||||
|
|
||||||
- **GIVEN** `sales1` is locked
|
- **GIVEN** INS user `sales1` is locked
|
||||||
- **WHEN** an admin with `BO_LOGIN_SECURITY` unlocks `sales1`
|
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` unlocks `sales1`
|
||||||
- **THEN** `sales1` no longer appears in the locked list
|
- **THEN** `sales1` no longer appears in the locked list
|
||||||
- **AND** `sales1` can sign in with the right password
|
- **AND** `sales1` can sign in with the right password
|
||||||
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
|
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
|
||||||
|
|
||||||
|
#### Scenario: Another company's locked user
|
||||||
|
|
||||||
|
- **GIVEN** CV user `sales2` is locked
|
||||||
|
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` lists locked users or unlocks `sales2` of CV
|
||||||
|
- **THEN** `sales2` is not listed and the unlock answers 404
|
||||||
|
|
||||||
### Requirement: Login history screen
|
### Requirement: Login history screen
|
||||||
|
|
||||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, newest first and paged, filtered by username, event and date range.
|
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, newest first and paged, filtered by username, event and date range.
|
||||||
@@ -115,19 +121,24 @@ The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, n
|
|||||||
|
|
||||||
### Requirement: Lockout and password-rule settings
|
### Requirement: Lockout and password-rule settings
|
||||||
|
|
||||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` read and change the lockout settings (on/off, maximum attempts, period, time unit) and the admin password rules (each rule's on/off status and value). The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
|
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the lockout settings and the admin password rules, and SHALL let only a super admin change them, because they apply to every company. The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
|
||||||
|
|
||||||
#### Scenario: Change the lockout settings
|
#### Scenario: Change the lockout settings
|
||||||
|
|
||||||
- **WHEN** an admin sets the maximum to 3 and the period to 30 minutes
|
- **WHEN** a super admin sets the maximum to 3 and the period to 30 minutes
|
||||||
- **THEN** the next lock decision uses 3 attempts in 30 minutes
|
- **THEN** the next lock decision in every company uses 3 attempts in 30 minutes
|
||||||
|
|
||||||
#### Scenario: Invalid setting
|
#### Scenario: Invalid setting
|
||||||
|
|
||||||
- **WHEN** an admin sets the maximum to 0
|
- **WHEN** a super admin sets the maximum to 0
|
||||||
- **THEN** the change is refused with a validation error and the settings stay as they were
|
- **THEN** the change is refused with a validation error and the settings stay as they were
|
||||||
|
|
||||||
#### Scenario: Change a password rule
|
#### Scenario: Change a password rule
|
||||||
|
|
||||||
- **WHEN** an admin sets the minimum length rule to 10
|
- **WHEN** a super admin sets the minimum length rule to 10
|
||||||
- **THEN** a new password of 9 characters is refused by every admin password check
|
- **THEN** a new password of 9 characters is refused by every admin password check
|
||||||
|
|
||||||
|
#### Scenario: Company user changes settings
|
||||||
|
|
||||||
|
- **WHEN** an INS user with `BO_LOGIN_SECURITY` changes a lockout setting or a password rule
|
||||||
|
- **THEN** the change is refused with 403 and the settings stay as they were
|
||||||
@@ -8,35 +8,40 @@ Admins with the Roles module define roles and choose which back-office modules e
|
|||||||
|
|
||||||
### Requirement: Role list and edit
|
### Requirement: Role list and edit
|
||||||
|
|
||||||
The system SHALL let an admin with `BO_ROLES` list, create and rename admin roles. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
|
The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let only a super admin create and rename them, because roles are shared by every company. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
|
||||||
|
|
||||||
#### Scenario: Create role
|
#### Scenario: Create role
|
||||||
|
|
||||||
- **WHEN** an admin with `BO_ROLES` creates role `ROLE_SALES`
|
- **WHEN** a super admin creates role `ROLE_SALES`
|
||||||
- **THEN** it appears in the role list and can be assigned to users
|
- **THEN** it appears in the role list and can be assigned to users of any company
|
||||||
|
|
||||||
#### Scenario: Duplicate name
|
#### Scenario: Duplicate name
|
||||||
|
|
||||||
- **GIVEN** role `ROLE_SALES` exists
|
- **GIVEN** role `ROLE_SALES` exists
|
||||||
- **WHEN** an admin creates another role named `ROLE_SALES`
|
- **WHEN** a super admin creates another role named `ROLE_SALES`
|
||||||
- **THEN** the save is refused with a message
|
- **THEN** the save is refused with a message
|
||||||
|
|
||||||
|
#### Scenario: Company user edits a role
|
||||||
|
|
||||||
|
- **WHEN** an INS user with `BO_ROLES` creates or renames a role
|
||||||
|
- **THEN** the request is refused with 403 and nothing changes
|
||||||
|
|
||||||
### Requirement: Role permissions
|
### Requirement: Role permissions
|
||||||
|
|
||||||
The system SHALL let an admin with `BO_ROLES` choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. An admin who is not super admin SHALL NOT change the grants of a role they hold.
|
The system SHALL let only a super admin choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. Admins with `BO_ROLES` who are not super admins SHALL see the grants read-only.
|
||||||
|
|
||||||
#### Scenario: Grant Users module
|
#### Scenario: Grant Users module
|
||||||
|
|
||||||
- **GIVEN** role `ROLE_SALES` without `BO_USERS`
|
- **GIVEN** role `ROLE_SALES` without `BO_USERS`
|
||||||
- **WHEN** an admin grants `BO_USERS` to `ROLE_SALES` and saves
|
- **WHEN** a super admin grants `BO_USERS` to `ROLE_SALES` and saves
|
||||||
- **THEN** users with `ROLE_SALES` see Users in the sidebar after their next login or session refresh
|
- **THEN** users with `ROLE_SALES` in every company see Users in the sidebar after their next login or session refresh
|
||||||
- **AND** `GET /api/admin/users` responds 200 for them
|
- **AND** `GET /api/admin/users` responds 200 for them
|
||||||
|
|
||||||
#### Scenario: Own role
|
#### Scenario: Own role
|
||||||
|
|
||||||
- **GIVEN** an admin who is not super admin and holds `ROLE_SALES`
|
- **GIVEN** an INS user who is not super admin and holds `ROLE_SALES` and `BO_ROLES`
|
||||||
- **WHEN** they change the module grants of `ROLE_SALES` and save
|
- **WHEN** they change the module grants of `ROLE_SALES`, or of any other role
|
||||||
- **THEN** the save is refused with a message, so no admin can widen their own access or lock themselves out of role management
|
- **THEN** the save is refused with 403 and the grants stay as they were
|
||||||
|
|
||||||
### Requirement: Back-office module set
|
### Requirement: Back-office module set
|
||||||
|
|
||||||
|
|||||||
@@ -18,22 +18,27 @@ The system SHALL list admin users only (never members), paginated on the server,
|
|||||||
|
|
||||||
### Requirement: Create user
|
### Requirement: Create user
|
||||||
|
|
||||||
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change, SHALL belong to the creating admin's company, and SHALL NOT be sent an email.
|
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique within the user's company, so the same username or email may exist in another company. A username SHALL NOT contain `@`. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change and SHALL NOT be sent an email.
|
||||||
|
|
||||||
#### Scenario: New user
|
#### Scenario: New user
|
||||||
|
|
||||||
- **WHEN** an admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
|
- **WHEN** an INS admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
|
||||||
- **THEN** the user is saved as active with a pending password change
|
- **THEN** the user is saved as active in INS with a pending password change
|
||||||
- **AND** `sales1` can sign in with that password and must choose a new password before anything else
|
- **AND** `sales1` can sign in with company `ins` and that password and must choose a new password before anything else
|
||||||
- **AND** no email is sent
|
- **AND** no email is sent
|
||||||
- **AND** the user's company is the creating admin's company
|
|
||||||
|
|
||||||
#### Scenario: Duplicate username
|
#### Scenario: Duplicate username
|
||||||
|
|
||||||
- **GIVEN** a user `sales1` exists
|
- **GIVEN** a user `sales1` exists in INS
|
||||||
- **WHEN** an admin creates another user with username `sales1`
|
- **WHEN** an admin creates another INS user with username `sales1`
|
||||||
- **THEN** the save is refused and the form shows that the username is taken
|
- **THEN** the save is refused and the form shows that the username is taken
|
||||||
|
|
||||||
|
#### Scenario: Same username in another company
|
||||||
|
|
||||||
|
- **GIVEN** a user `sales1` exists in INS
|
||||||
|
- **WHEN** a CV admin creates user `sales1` in CV
|
||||||
|
- **THEN** the user is created
|
||||||
|
|
||||||
#### Scenario: Weak or mismatched initial password
|
#### Scenario: Weak or mismatched initial password
|
||||||
|
|
||||||
- **WHEN** an admin creates a user with a password that fails the admin password rules, or that does not match its confirmation
|
- **WHEN** an admin creates a user with a password that fails the admin password rules, or that does not match its confirmation
|
||||||
@@ -97,12 +102,17 @@ The system SHALL let an admin with `BO_USERS` give an active admin user a new pa
|
|||||||
|
|
||||||
### Requirement: Company membership
|
### Requirement: Company membership
|
||||||
|
|
||||||
Every admin user SHALL belong to exactly one company. The company SHALL be set by the system from the creating admin, never from the request.
|
Every admin user other than a super admin SHALL belong to exactly one company. A company user's new user SHALL belong to the creating user's company, whatever the request says. A super admin SHALL choose the company of a new user, or no company to create another super admin.
|
||||||
|
|
||||||
#### Scenario: Company in the request is ignored
|
#### Scenario: Company in the request is ignored
|
||||||
|
|
||||||
- **WHEN** a create-user request carries a company id different from the admin's own
|
- **WHEN** an INS user's create-user request carries the CV company id
|
||||||
- **THEN** the new user gets the admin's company
|
- **THEN** the new user belongs to INS
|
||||||
|
|
||||||
|
#### Scenario: Super admin chooses the company
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates a user and chooses CV
|
||||||
|
- **THEN** the new user belongs to CV
|
||||||
|
|
||||||
### Requirement: Temporary password refusals
|
### Requirement: Temporary password refusals
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
# company-scoping Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Separate the data of each company using Co-Lite (INS and CV at go-live): staff sign in with their company code and see only their own company's records, while company-less super admins manage companies and see every company.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Companies
|
||||||
|
|
||||||
|
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of capital letters, digits and hyphens. A code entered in any case SHALL be stored in capitals, and codes SHALL be compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
|
||||||
|
|
||||||
|
#### Scenario: Create a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates company `CV` with code `cv`
|
||||||
|
- **THEN** it is listed as active with code `CV`
|
||||||
|
- **AND** staff can be created in it
|
||||||
|
|
||||||
|
#### Scenario: Duplicate code
|
||||||
|
|
||||||
|
- **GIVEN** a company with code `INS`
|
||||||
|
- **WHEN** a super admin creates or renames another company to code `ins`
|
||||||
|
- **THEN** the save is refused and the code is reported as taken
|
||||||
|
|
||||||
|
#### Scenario: Not a super admin
|
||||||
|
|
||||||
|
- **WHEN** company staff open the Companies page or call a companies endpoint
|
||||||
|
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||||
|
|
||||||
|
#### Scenario: Sign-in ignores case
|
||||||
|
|
||||||
|
- **GIVEN** company code `CV` and its user `sales9`
|
||||||
|
- **WHEN** they sign in with company `cv`
|
||||||
|
- **THEN** they are signed in as `sales9` of CV
|
||||||
|
|
||||||
|
### Requirement: Company sign-in
|
||||||
|
|
||||||
|
The system SHALL sign company staff in with company code, username and password, and SHALL sign super admins in with username and password and no company. The answer SHALL be the same for a wrong or unknown company, an inactive company, an unknown user and a wrong password. A user's sessions SHALL end when their company is deactivated or its code is changed.
|
||||||
|
|
||||||
|
#### Scenario: Staff sign-in
|
||||||
|
|
||||||
|
- **GIVEN** an active user `john` in active company `ins`
|
||||||
|
- **WHEN** they sign in with company `ins`, username `john` and the right password
|
||||||
|
- **THEN** they are signed in as `john` of INS
|
||||||
|
|
||||||
|
#### Scenario: Same username in two companies
|
||||||
|
|
||||||
|
- **GIVEN** a user `john` in INS and a different user `john` in CV
|
||||||
|
- **WHEN** someone signs in with company `cv`, username `john` and CV John's password
|
||||||
|
- **THEN** they are signed in as CV's John and see only CV data
|
||||||
|
|
||||||
|
#### Scenario: Wrong company
|
||||||
|
|
||||||
|
- **WHEN** INS's `john` signs in with company `cv` or a code that does not exist
|
||||||
|
- **THEN** login is refused with the same invalid-credentials answer as a wrong password
|
||||||
|
|
||||||
|
#### Scenario: Inactive company
|
||||||
|
|
||||||
|
- **GIVEN** company CV is deactivated
|
||||||
|
- **WHEN** a CV user signs in with the right password, or uses an existing session
|
||||||
|
- **THEN** the sign-in is refused with the invalid-credentials answer and the session ends
|
||||||
|
|
||||||
|
#### Scenario: Code changed
|
||||||
|
|
||||||
|
- **GIVEN** a signed-in user of the company with code `ins`
|
||||||
|
- **WHEN** a super admin changes that code to `ins-my`
|
||||||
|
- **THEN** the user's session ends
|
||||||
|
- **AND** they sign in again with company `ins-my`
|
||||||
|
|
||||||
|
### Requirement: Super admins
|
||||||
|
|
||||||
|
A super admin SHALL be an admin user who belongs to no company and holds the super admin role. Only a super admin SHALL create another super admin. The super admin role SHALL NOT be granted to a user who belongs to a company, and every admin user who is not a super admin SHALL belong to a company.
|
||||||
|
|
||||||
|
#### Scenario: Create a second super admin
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates a user with no company
|
||||||
|
- **THEN** the user is created as a super admin and signs in without a company
|
||||||
|
|
||||||
|
#### Scenario: Super admin role for company staff
|
||||||
|
|
||||||
|
- **WHEN** anyone assigns the super admin role to a user of INS
|
||||||
|
- **THEN** the save is refused with a message
|
||||||
|
|
||||||
|
### Requirement: Company data is separated
|
||||||
|
|
||||||
|
The system SHALL limit every admin list, search, export, detail, create, edit and action to the caller's company for: users, events, event teams, event leads, leads, emails, login history, locked users and audit events. A record of another company SHALL answer 404, as if it did not exist.
|
||||||
|
|
||||||
|
#### Scenario: Lists show own company only
|
||||||
|
|
||||||
|
- **GIVEN** leads, events and users in INS and in CV
|
||||||
|
- **WHEN** an INS user with the matching modules opens Leads, Events or Users
|
||||||
|
- **THEN** only INS records are listed
|
||||||
|
- **AND** an export contains only INS leads
|
||||||
|
|
||||||
|
#### Scenario: Another company's record by id
|
||||||
|
|
||||||
|
- **GIVEN** a CV lead, event, user or email
|
||||||
|
- **WHEN** an INS user requests it, edits it or acts on it by its id
|
||||||
|
- **THEN** the answer is 404 and nothing changes
|
||||||
|
|
||||||
|
#### Scenario: Same phone in two companies
|
||||||
|
|
||||||
|
- **GIVEN** INS has a lead with mobile `+60123456789`
|
||||||
|
- **WHEN** a CV user captures a lead with the same mobile at a CV event
|
||||||
|
- **THEN** a new CV lead is created and flagged New
|
||||||
|
- **AND** the INS lead is unchanged
|
||||||
|
|
||||||
|
### Requirement: Super admin sees all companies
|
||||||
|
|
||||||
|
The system SHALL show super admins every company's records by default, SHALL let them narrow any scoped list to one company, and SHALL show each record's company in mixed lists. Creating a company-owned record (user, event, event lead) SHALL require a super admin to choose the company.
|
||||||
|
|
||||||
|
#### Scenario: Mixed list
|
||||||
|
|
||||||
|
- **WHEN** a super admin opens Leads with all companies selected
|
||||||
|
- **THEN** INS and CV leads are listed together with a Company column
|
||||||
|
|
||||||
|
#### Scenario: Pick a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin picks CV in the company picker
|
||||||
|
- **THEN** scoped lists show CV records only
|
||||||
|
|
||||||
|
#### Scenario: Create without a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin creates an event without choosing a company
|
||||||
|
- **THEN** the save is refused and the form asks for a company
|
||||||
|
|
||||||
|
### Requirement: Company of login and audit records
|
||||||
|
|
||||||
|
An audit event and a login-history record SHALL belong to the company of the user who acted, or of the user who tried to sign in when the given company and username match a user. Records with no company SHALL be visible to super admins only.
|
||||||
|
|
||||||
|
#### Scenario: Super admin edits a company record
|
||||||
|
|
||||||
|
- **WHEN** a super admin edits an INS lead
|
||||||
|
- **THEN** the audit event has no company
|
||||||
|
- **AND** INS staff with Audit log do not see it, and super admins do
|
||||||
|
|
||||||
|
#### Scenario: Failed sign-in with an unknown company
|
||||||
|
|
||||||
|
- **WHEN** someone fails to sign in with a company code that does not exist
|
||||||
|
- **THEN** the login-history record has no company and only super admins see it
|
||||||
|
|
||||||
|
### Requirement: Invalid admins fail closed
|
||||||
|
|
||||||
|
The system SHALL refuse every company-scoped request from an admin with no company who is not a super admin, and SHALL grant a company user who holds the super admin role only the modules and records their company and other roles allow.
|
||||||
|
|
||||||
|
#### Scenario: Admin without a company who is not a super admin
|
||||||
|
|
||||||
|
- **GIVEN** an admin user with no company and no super admin role
|
||||||
|
- **WHEN** they open Leads, Events, Users or any other company-scoped list or record
|
||||||
|
- **THEN** the request is refused with 403
|
||||||
|
- **AND** no company's records are returned
|
||||||
|
|
||||||
|
#### Scenario: Company user still holding the super admin role
|
||||||
|
|
||||||
|
- **GIVEN** a user of INS who holds the super admin role and a role granting only Leads
|
||||||
|
- **WHEN** they open Users or another super admin's email
|
||||||
|
- **THEN** the request is refused with 403
|
||||||
@@ -150,3 +150,24 @@ The system SHALL let staff with `BO_EVENT_LEADS` change an event lead's salesper
|
|||||||
- **GIVEN** an event lead tagged `Cookware`, and `Cookware` is then deactivated
|
- **GIVEN** an event lead tagged `Cookware`, and `Cookware` is then deactivated
|
||||||
- **WHEN** staff change the lead's status
|
- **WHEN** staff change the lead's status
|
||||||
- **THEN** the save succeeds and the lead is still tagged `Cookware`
|
- **THEN** the save succeeds and the lead is still tagged `Cookware`
|
||||||
|
|
||||||
|
### Requirement: Event lead status history
|
||||||
|
|
||||||
|
The system SHALL record every change of an event lead's status with the previous status, the new status, the time and the user who made it. Capturing an event lead SHALL record its first status with no previous status, at the capture time. An edit that leaves the status unchanged SHALL record nothing. The history SHALL never be edited or deleted through the application.
|
||||||
|
|
||||||
|
#### Scenario: Capture records the first status
|
||||||
|
|
||||||
|
- **WHEN** staff capture a lead at an event with no status chosen
|
||||||
|
- **THEN** the history holds one entry from no status to OPEN at the capture time, by that user
|
||||||
|
|
||||||
|
#### Scenario: Status change recorded
|
||||||
|
|
||||||
|
- **GIVEN** an OPEN event lead
|
||||||
|
- **WHEN** staff change its status to CONTACTED and later to WON
|
||||||
|
- **THEN** the history holds OPEN to CONTACTED and CONTACTED to WON, each with its time and user
|
||||||
|
|
||||||
|
#### Scenario: Edit without a status change
|
||||||
|
|
||||||
|
- **GIVEN** a CONTACTED event lead
|
||||||
|
- **WHEN** staff change only its temperature and notes
|
||||||
|
- **THEN** no history entry is added
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
# lead-dashboard Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Show managers on the back-office home page how many leads each period, event, salesperson and interest produced and how many converted (status WON), so marketing can see which events turn visitors into customers.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Dashboard access
|
||||||
|
|
||||||
|
The system SHALL show the lead dashboard on the back-office home page to users granted the `BO_DASHBOARD` module, and SHALL show users without it the welcome message instead of a not-authorised page. The dashboard endpoint SHALL answer 403 to a user without `BO_DASHBOARD`. The sidebar SHALL show a Dashboard link to users with the module.
|
||||||
|
|
||||||
|
#### Scenario: Granted user
|
||||||
|
|
||||||
|
- **GIVEN** a role holding `BO_DASHBOARD` is assigned to `sales1`
|
||||||
|
- **WHEN** `sales1` signs in
|
||||||
|
- **THEN** the home page shows the lead dashboard and the sidebar shows Dashboard
|
||||||
|
|
||||||
|
#### Scenario: User without the module
|
||||||
|
|
||||||
|
- **WHEN** a user without `BO_DASHBOARD` opens the home page or calls the dashboard endpoint
|
||||||
|
- **THEN** the page shows the welcome message and the endpoint responds 403
|
||||||
|
|
||||||
|
### Requirement: Dashboard period
|
||||||
|
|
||||||
|
The dashboard SHALL cover a period of whole days in Malaysia time (Asia/Kuala_Lumpur): this month up to today (the default), last month, or a custom range from one date to another, both included. A range whose start is after its end, or that spans more than 731 days, SHALL be refused with a message. The trend SHALL be counted by day for a period of up to 62 days and by month for a longer one, and SHALL list every day or month in the period, with zero where nothing happened.
|
||||||
|
|
||||||
|
#### Scenario: Default period
|
||||||
|
|
||||||
|
- **WHEN** a user opens the dashboard on 2026-12-10
|
||||||
|
- **THEN** it covers 2026-12-01 to 2026-12-10, with one trend point per day
|
||||||
|
|
||||||
|
#### Scenario: Long range counted by month
|
||||||
|
|
||||||
|
- **WHEN** the user picks 2026-01-01 to 2026-12-31
|
||||||
|
- **THEN** the trend has one point per month, January to December
|
||||||
|
|
||||||
|
#### Scenario: Day boundary in Malaysia time
|
||||||
|
|
||||||
|
- **GIVEN** a lead captured at 2026-11-30 23:30 Malaysia time
|
||||||
|
- **WHEN** the user views 2026-11-01 to 2026-11-30
|
||||||
|
- **THEN** the capture is counted on 30 November
|
||||||
|
|
||||||
|
#### Scenario: Reversed range
|
||||||
|
|
||||||
|
- **WHEN** the user picks a start date after the end date
|
||||||
|
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
|
||||||
|
|
||||||
|
#### Scenario: Range too long
|
||||||
|
|
||||||
|
- **WHEN** the user picks 2024-01-01 to 2026-12-31
|
||||||
|
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
|
||||||
|
|
||||||
|
### Requirement: Capture figures
|
||||||
|
|
||||||
|
For the chosen period the dashboard SHALL show the captures (event leads captured in the period, so a person captured at two events counts twice), the new leads (captures whose lead type is NEW), the conversion rate (the share of the period's captures whose current status is WON, shown as a dash when there are no captures), a funnel of the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST) and the captures in the trend.
|
||||||
|
|
||||||
|
#### Scenario: Conversion of the period's captures
|
||||||
|
|
||||||
|
- **GIVEN** 10 leads captured in November, 3 of them now WON and 2 LOST
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** captures show 10, conversion rate 30%, and the funnel shows WON 3 and LOST 2
|
||||||
|
|
||||||
|
#### Scenario: No captures
|
||||||
|
|
||||||
|
- **WHEN** the user views a period with no captures
|
||||||
|
- **THEN** captures show 0 and the conversion rate shows a dash
|
||||||
|
|
||||||
|
### Requirement: Win figures
|
||||||
|
|
||||||
|
The dashboard SHALL count as won in the period every event lead whose current status is WON and whose latest change to WON falls in the period, whenever it was captured. It SHALL show that count, the wins in the trend, and the median of whole days from capture to the latest change to WON over those event leads, shown as a dash when there are none.
|
||||||
|
|
||||||
|
#### Scenario: Win of an older capture
|
||||||
|
|
||||||
|
- **GIVEN** a lead captured in October and changed to WON on 5 November
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** won in period counts it and the November captures do not
|
||||||
|
|
||||||
|
#### Scenario: Reopened lead
|
||||||
|
|
||||||
|
- **GIVEN** a lead changed to WON on 3 November, back to QUALIFIED on 4 November, and to WON again on 20 November
|
||||||
|
- **WHEN** the user views 1 to 10 November
|
||||||
|
- **THEN** won in period does not count it, because its latest change to WON is 20 November
|
||||||
|
|
||||||
|
#### Scenario: Median days to win
|
||||||
|
|
||||||
|
- **GIVEN** three leads won in November, 2, 5 and 30 days after capture
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** median days to win shows 5
|
||||||
|
|
||||||
|
### Requirement: Overdue follow-ups
|
||||||
|
|
||||||
|
The dashboard SHALL show the event leads that are not WON or LOST and whose next follow-up date is before today in Malaysia time, whatever the chosen period.
|
||||||
|
|
||||||
|
#### Scenario: Overdue counted regardless of period
|
||||||
|
|
||||||
|
- **GIVEN** an OPEN lead captured in August with next follow-up 2026-12-01
|
||||||
|
- **WHEN** the user views November on 2026-12-05
|
||||||
|
- **THEN** overdue follow-ups count it
|
||||||
|
|
||||||
|
### Requirement: Breakdown by event
|
||||||
|
|
||||||
|
The dashboard SHALL list each event with captures in the period, most captures first, with its captures, new leads, won and conversion rate, and each row SHALL open that event's leads listing.
|
||||||
|
|
||||||
|
#### Scenario: Event drill-down
|
||||||
|
|
||||||
|
- **WHEN** the user selects an event row
|
||||||
|
- **THEN** that event's leads listing opens
|
||||||
|
|
||||||
|
### Requirement: Breakdown by salesperson
|
||||||
|
|
||||||
|
The dashboard SHALL list, for the period's captures, each salesperson's assigned, worked (status other than OPEN), won, lost and conversion rate, with their current overdue follow-ups, and SHALL show captures with no salesperson as Unassigned.
|
||||||
|
|
||||||
|
#### Scenario: Salesperson row
|
||||||
|
|
||||||
|
- **GIVEN** in November `sales1` was assigned 4 captures: 1 OPEN, 1 CONTACTED, 1 WON and 1 LOST
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** sales1's row shows assigned 4, worked 3, won 1, lost 1 and conversion rate 25%
|
||||||
|
|
||||||
|
#### Scenario: Unassigned captures
|
||||||
|
|
||||||
|
- **GIVEN** 2 November captures have no salesperson
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** an Unassigned row shows assigned 2
|
||||||
|
|
||||||
|
### Requirement: Breakdown by interest
|
||||||
|
|
||||||
|
The dashboard SHALL list each interest with the period's captures tagged with it and how many of them are now WON. A capture with two interests SHALL count under both.
|
||||||
|
|
||||||
|
#### Scenario: Two interests
|
||||||
|
|
||||||
|
- **GIVEN** a November capture tagged `Cookware` and `Kitchen appliances`, now WON
|
||||||
|
- **WHEN** the user views November
|
||||||
|
- **THEN** both interests count 1 capture and 1 won
|
||||||
|
|
||||||
|
### Requirement: Phone width
|
||||||
|
|
||||||
|
The dashboard SHALL be usable on a 360 px wide screen without sideways scrolling.
|
||||||
|
|
||||||
|
#### Scenario: Phone
|
||||||
|
|
||||||
|
- **WHEN** a user opens the dashboard at 360 px
|
||||||
|
- **THEN** the tiles stack and the breakdowns show as cards
|
||||||
|
|
||||||
|
### Requirement: Dashboard company scope
|
||||||
|
|
||||||
|
The dashboard SHALL count only the records of the caller's company for company staff. A super admin SHALL see every company's records by default and SHALL be able to narrow the dashboard to one company with the company picker; while all companies are shown, the by-event list SHALL show each event's company.
|
||||||
|
|
||||||
|
#### Scenario: Staff see their company
|
||||||
|
|
||||||
|
- **GIVEN** leads captured at INS and at CV events in November
|
||||||
|
- **WHEN** an INS user with `BO_DASHBOARD` views November
|
||||||
|
- **THEN** every figure counts INS records only
|
||||||
|
|
||||||
|
#### Scenario: Super admin picks a company
|
||||||
|
|
||||||
|
- **WHEN** a super admin picks CV in the company picker
|
||||||
|
- **THEN** every figure counts CV records only
|
||||||
@@ -8,25 +8,31 @@ Admins with the Interests module maintain the list of products and services that
|
|||||||
|
|
||||||
### Requirement: Interest list
|
### Requirement: Interest list
|
||||||
|
|
||||||
The system SHALL let an admin with `BO_INTERESTS` list, add, rename, reorder, deactivate and reactivate interests for their company. An interest name SHALL be required, at most 100 characters, and unique within the company ignoring case. Interests SHALL NOT be deletable.
|
The system SHALL keep one interest list shared by all companies. Admins with `BO_INTERESTS` SHALL see the list, and only a super admin SHALL add, rename, reorder, deactivate and reactivate interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case. Interests SHALL NOT be deletable.
|
||||||
|
|
||||||
#### Scenario: Add interest
|
#### Scenario: Add interest
|
||||||
|
|
||||||
- **WHEN** an admin with `BO_INTERESTS` adds `Kitchen appliances`
|
- **WHEN** a super admin adds `Kitchen appliances`
|
||||||
- **THEN** it is listed as active
|
- **THEN** it is listed as active
|
||||||
|
- **AND** staff of every company can tag leads with it
|
||||||
|
|
||||||
#### Scenario: Duplicate name
|
#### Scenario: Duplicate name
|
||||||
|
|
||||||
- **GIVEN** an interest `Kitchen appliances`
|
- **GIVEN** an interest `Kitchen appliances`
|
||||||
- **WHEN** an admin adds `kitchen APPLIANCES`
|
- **WHEN** a super admin adds `kitchen APPLIANCES`
|
||||||
- **THEN** the save is refused and the name is reported as a duplicate
|
- **THEN** the save is refused and the name is reported as a duplicate
|
||||||
|
|
||||||
#### Scenario: Deactivate
|
#### Scenario: Deactivate
|
||||||
|
|
||||||
- **GIVEN** an active interest `Cookware`
|
- **GIVEN** an active interest `Cookware`
|
||||||
- **WHEN** an admin deactivates it
|
- **WHEN** a super admin deactivates it
|
||||||
- **THEN** it is still listed, marked inactive
|
- **THEN** it is still listed, marked inactive
|
||||||
- **AND** it is no longer offered when capturing a lead
|
- **AND** it is no longer offered when capturing a lead in any company
|
||||||
|
|
||||||
|
#### Scenario: Company user edits
|
||||||
|
|
||||||
|
- **WHEN** an INS user with `BO_INTERESTS` adds, renames or deactivates an interest
|
||||||
|
- **THEN** the request is refused with 403 and the list is unchanged
|
||||||
|
|
||||||
#### Scenario: No module
|
#### Scenario: No module
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# qr-registration Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Walk-in visitors scan an event or salesperson QR code and register themselves as a lead, with recorded PDPA consent, abuse limits and staff tools to show, print and switch off codes.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Registration codes
|
||||||
|
|
||||||
|
The system SHALL give every event one registration code and one personal code per member of the event's team. A code SHALL be an unguessable token in a link of the form `/r/<token>`. Staff with `BO_EVENTS` SHALL see each code of an event of their company as a QR image, copy its link, download it as an image, and switch it off or on. Every staff user SHALL see their own personal codes for events of their company that have not ended.
|
||||||
|
|
||||||
|
#### Scenario: Event page codes
|
||||||
|
|
||||||
|
- **GIVEN** event `KL Expo` with `sales1` and `sales2` on its team
|
||||||
|
- **WHEN** a user with `BO_EVENTS` opens the event
|
||||||
|
- **THEN** the event's code and the personal codes of `sales1` and `sales2` are shown, each with its QR image and link
|
||||||
|
|
||||||
|
#### Scenario: Own codes
|
||||||
|
|
||||||
|
- **GIVEN** `sales1` is on the team of `KL Expo`, which ends tomorrow, and of `Penang Fair`, which ended last week
|
||||||
|
- **WHEN** `sales1` opens My QR codes
|
||||||
|
- **THEN** only the personal code for `KL Expo` is listed
|
||||||
|
|
||||||
|
#### Scenario: Switch a code off
|
||||||
|
|
||||||
|
- **WHEN** staff switch off the event code of `KL Expo`
|
||||||
|
- **THEN** scanning that code shows that it is no longer active
|
||||||
|
- **AND** the personal codes still work
|
||||||
|
|
||||||
|
### Requirement: When a code works
|
||||||
|
|
||||||
|
A code SHALL work only while it is switched on, its event is enabled, the event's end date in Malaysia time has not passed, and the event's company has a privacy notice. An inactive or unknown code SHALL show "This code is no longer active." and no event details. A personal code whose salesperson is no longer an active member of the event's team SHALL keep working, and its registrations SHALL have no salesperson.
|
||||||
|
|
||||||
|
#### Scenario: Ended event
|
||||||
|
|
||||||
|
- **GIVEN** `Penang Fair` ended yesterday
|
||||||
|
- **WHEN** a visitor scans its code
|
||||||
|
- **THEN** the page says the code is no longer active and shows no event details
|
||||||
|
|
||||||
|
#### Scenario: Salesperson left the team
|
||||||
|
|
||||||
|
- **GIVEN** `sales2` was removed from the team of `KL Expo`
|
||||||
|
- **WHEN** a visitor registers through `sales2`'s code
|
||||||
|
- **THEN** the registration succeeds and the event lead has no salesperson
|
||||||
|
|
||||||
|
### Requirement: Public registration
|
||||||
|
|
||||||
|
The registration page SHALL show the event's name, dates and location, and a form for name (required), mobile and email (at least one), company, job title, the company's active interests, and the privacy notice consent (required). Inputs SHALL be normalised and limited as in staff capture. Every accepted submission SHALL show the same thank-you page naming the event, with a button to register another person, whether or not the person was already known.
|
||||||
|
|
||||||
|
#### Scenario: Register
|
||||||
|
|
||||||
|
- **WHEN** a visitor scans the code of `KL Expo`, enters name `Aisyah`, mobile `012-345 6701` and ticks the consent
|
||||||
|
- **THEN** the thank-you page names `KL Expo`
|
||||||
|
- **AND** staff see `Aisyah` with mobile `+60123456701` in the event's leads as NEW and OPEN
|
||||||
|
|
||||||
|
#### Scenario: Missing consent or contact
|
||||||
|
|
||||||
|
- **WHEN** a visitor submits without ticking the consent, or without a mobile and an email
|
||||||
|
- **THEN** nothing is saved and the page shows the error under the field
|
||||||
|
|
||||||
|
#### Scenario: Known person gets the same answer
|
||||||
|
|
||||||
|
- **GIVEN** a lead with mobile `+60123456701` exists in the company
|
||||||
|
- **WHEN** a visitor registers with that mobile
|
||||||
|
- **THEN** the page shows the same thank-you page as for a new person
|
||||||
|
|
||||||
|
### Requirement: Registration matching
|
||||||
|
|
||||||
|
A registration SHALL match a lead of the event's company by mobile first and then by email, the newest lead winning among several. A matched lead SHALL NOT be edited: it SHALL be linked as EXISTING, with every submitted value that differs from the lead's written into the event lead's notes. Without a match a new lead SHALL be created as NEW.
|
||||||
|
|
||||||
|
#### Scenario: Existing lead not edited
|
||||||
|
|
||||||
|
- **GIVEN** lead `Aisyah` with mobile `+60123456701` and no email
|
||||||
|
- **WHEN** a visitor registers as `Aisyah Rahman` with that mobile and email `a@example.test`
|
||||||
|
- **THEN** lead `Aisyah` still has no email and its name is unchanged
|
||||||
|
- **AND** the new event lead is EXISTING and its notes list the submitted name and email
|
||||||
|
|
||||||
|
#### Scenario: Mobile beats email
|
||||||
|
|
||||||
|
- **GIVEN** lead `A` has mobile `+60123456701` and lead `B` has email `b@example.test`
|
||||||
|
- **WHEN** a visitor registers with that mobile and that email
|
||||||
|
- **THEN** the registration is linked to lead `A`
|
||||||
|
|
||||||
|
### Requirement: Registration of a person already captured
|
||||||
|
|
||||||
|
When the matched lead is already captured at the event, a registration SHALL change nothing, except that an event lead with no salesperson SHALL get the salesperson of a personal code whose salesperson is an active member of the event's team.
|
||||||
|
|
||||||
|
#### Scenario: Already captured, unassigned
|
||||||
|
|
||||||
|
- **GIVEN** `Aisyah` is captured at `KL Expo` with no salesperson
|
||||||
|
- **WHEN** she registers again through `sales1`'s personal code and `sales1` is on the team
|
||||||
|
- **THEN** her event lead's salesperson becomes `sales1` and nothing else changes
|
||||||
|
|
||||||
|
### Requirement: Registration record
|
||||||
|
|
||||||
|
An event lead created by a registration SHALL have status OPEN, source QR, captured by `qr`, the consent time and the privacy notice version shown, the chosen interests, and the code's salesperson when that salesperson is an active member of the event's team. Event leads captured by staff SHALL have source STAFF. The status history SHALL record the first status by `qr`.
|
||||||
|
|
||||||
|
#### Scenario: Personal code assigns
|
||||||
|
|
||||||
|
- **WHEN** a visitor registers through `sales1`'s personal code for `KL Expo`
|
||||||
|
- **THEN** the event lead's salesperson is `sales1`, its source is QR and it records the consent time and notice version
|
||||||
|
|
||||||
|
### Requirement: Privacy notice
|
||||||
|
|
||||||
|
Each company SHALL have a privacy notice in English and Bahasa Malaysia, kept as versions: saving a change SHALL add a new version and keep the old ones. Only a super admin SHALL edit it, on the Companies page. The registration page SHALL show the company's current notice in both languages. INS and CV SHALL start with the default notice of the design, with the company's name filled in.
|
||||||
|
|
||||||
|
#### Scenario: Edit the notice
|
||||||
|
|
||||||
|
- **GIVEN** CV's notice is version 3
|
||||||
|
- **WHEN** a super admin changes CV's English text and saves
|
||||||
|
- **THEN** CV's registration pages show the new text
|
||||||
|
- **AND** event leads registered before still point to version 3
|
||||||
|
|
||||||
|
#### Scenario: Not a super admin
|
||||||
|
|
||||||
|
- **WHEN** company staff call the privacy notice update endpoint
|
||||||
|
- **THEN** it responds 403
|
||||||
|
|
||||||
|
### Requirement: Registration abuse limits
|
||||||
|
|
||||||
|
The system SHALL accept at most 60 registrations per client IP per event in 10 minutes and serve at most 120 registration page loads per client IP in 10 minutes, answering above either limit with "Too many registrations from this device. Try again later." A submission that fills the hidden honeypot field SHALL get the normal thank-you page and save nothing.
|
||||||
|
|
||||||
|
#### Scenario: Too many submissions
|
||||||
|
|
||||||
|
- **GIVEN** 60 registrations for `KL Expo` from one IP in the last 10 minutes
|
||||||
|
- **WHEN** the 61st arrives from that IP
|
||||||
|
- **THEN** nothing is saved and the page shows the too-many message
|
||||||
|
|
||||||
|
#### Scenario: Honeypot
|
||||||
|
|
||||||
|
- **WHEN** a submission fills the hidden field
|
||||||
|
- **THEN** the thank-you page shows and no lead or event lead is saved
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
---
|
||||||
|
name: Co-Lite Admin
|
||||||
|
description: The category-standard SaaS admin for event leads, executed with care.
|
||||||
|
colors:
|
||||||
|
primary: "#2563EB"
|
||||||
|
primary-foreground: "#FFFFFF"
|
||||||
|
accent-tint: "#EFF6FF"
|
||||||
|
accent-ink: "#1D4ED8"
|
||||||
|
ground: "#F8FAFC"
|
||||||
|
surface: "#FFFFFF"
|
||||||
|
ink: "#0F172A"
|
||||||
|
ink-muted: "#475569"
|
||||||
|
slate-tint: "#F1F5F9"
|
||||||
|
hairline: "#E2E8F0"
|
||||||
|
control-stroke: "#7C8BA1"
|
||||||
|
positive: "#15803D"
|
||||||
|
warning: "#B45309"
|
||||||
|
negative: "#B91C1C"
|
||||||
|
destructive: "#DC2626"
|
||||||
|
chart-teal: "#0F766E"
|
||||||
|
chart-amber: "#D97706"
|
||||||
|
chart-violet: "#7C3AED"
|
||||||
|
chart-rose: "#E11D48"
|
||||||
|
typography:
|
||||||
|
headline:
|
||||||
|
fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif"
|
||||||
|
fontSize: "24px"
|
||||||
|
fontWeight: 600
|
||||||
|
lineHeight: 1.33
|
||||||
|
letterSpacing: "-0.025em"
|
||||||
|
title:
|
||||||
|
fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif"
|
||||||
|
fontSize: "16px"
|
||||||
|
fontWeight: 600
|
||||||
|
lineHeight: 1
|
||||||
|
body:
|
||||||
|
fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif"
|
||||||
|
fontSize: "14px"
|
||||||
|
fontWeight: 400
|
||||||
|
lineHeight: 1.43
|
||||||
|
label:
|
||||||
|
fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif"
|
||||||
|
fontSize: "12px"
|
||||||
|
fontWeight: 600
|
||||||
|
lineHeight: 1.33
|
||||||
|
letterSpacing: "0.025em"
|
||||||
|
figure:
|
||||||
|
fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif"
|
||||||
|
fontSize: "24px"
|
||||||
|
fontWeight: 600
|
||||||
|
fontFeature: "\"tnum\" 1"
|
||||||
|
rounded:
|
||||||
|
sm: "4px"
|
||||||
|
md: "6px"
|
||||||
|
lg: "8px"
|
||||||
|
full: "9999px"
|
||||||
|
spacing:
|
||||||
|
xs: "4px"
|
||||||
|
sm: "8px"
|
||||||
|
md: "16px"
|
||||||
|
lg: "24px"
|
||||||
|
components:
|
||||||
|
button-primary:
|
||||||
|
backgroundColor: "{colors.primary}"
|
||||||
|
textColor: "{colors.primary-foreground}"
|
||||||
|
rounded: "{rounded.md}"
|
||||||
|
padding: "8px 16px"
|
||||||
|
height: "36px"
|
||||||
|
button-outline:
|
||||||
|
backgroundColor: "{colors.ground}"
|
||||||
|
textColor: "{colors.ink}"
|
||||||
|
rounded: "{rounded.md}"
|
||||||
|
padding: "8px 16px"
|
||||||
|
height: "36px"
|
||||||
|
button-outline-hover:
|
||||||
|
backgroundColor: "{colors.accent-tint}"
|
||||||
|
textColor: "{colors.accent-ink}"
|
||||||
|
button-ghost-hover:
|
||||||
|
backgroundColor: "{colors.accent-tint}"
|
||||||
|
textColor: "{colors.accent-ink}"
|
||||||
|
input:
|
||||||
|
backgroundColor: "{colors.surface}"
|
||||||
|
textColor: "{colors.ink}"
|
||||||
|
rounded: "{rounded.md}"
|
||||||
|
padding: "4px 12px"
|
||||||
|
height: "36px"
|
||||||
|
card:
|
||||||
|
backgroundColor: "{colors.surface}"
|
||||||
|
textColor: "{colors.ink}"
|
||||||
|
rounded: "{rounded.lg}"
|
||||||
|
padding: "24px"
|
||||||
|
table-head:
|
||||||
|
backgroundColor: "{colors.slate-tint}"
|
||||||
|
textColor: "{colors.ink-muted}"
|
||||||
|
typography: "{typography.label}"
|
||||||
|
height: "40px"
|
||||||
|
badge-positive:
|
||||||
|
textColor: "{colors.positive}"
|
||||||
|
rounded: "{rounded.full}"
|
||||||
|
padding: "2px 8px"
|
||||||
|
nav-item-active:
|
||||||
|
backgroundColor: "{colors.accent-tint}"
|
||||||
|
textColor: "{colors.accent-ink}"
|
||||||
|
rounded: "{rounded.lg}"
|
||||||
|
height: "44px"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Design System: Co-Lite Admin
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
**Creative North Star: "The Category Standard"**
|
||||||
|
|
||||||
|
Co-Lite looks like the best ordinary SaaS admin and nothing more: white and slate, one blue accent, Inter, no brand gimmicks. The owner chose this deliberately over more characterful worlds; the measure is Stripe Dashboard, Linear and Vercel. Its quality lives in restraint and in the details: exact hairlines, aligned figures, honest contrast, consistent control heights.
|
||||||
|
|
||||||
|
The page is a pale slate ground (#F8FAFC) carrying white surfaces: the sidebar, the sticky header and every card are white with a 1px slate hairline. Density is office density: 36px controls, 14px working text, sortable tables inside cards, KPI figures in tabular numerals. An admin should read an event's numbers and filter a lead table without having to learn anything.
|
||||||
|
|
||||||
|
This world replaces the inherited babyboo look (brown primary, DM Sans, 16px soft corners, gradient wordmark). That look is retired and must not return; `app/globals.test.ts` fails on DM Sans and on any "brown", "gold" or "dusty" in the stylesheet.
|
||||||
|
|
||||||
|
**Key Characteristics:**
|
||||||
|
- Pale slate ground, white surfaces, 1px slate hairlines.
|
||||||
|
- One blue accent for primary actions, links, focus and the active nav item.
|
||||||
|
- Inter for everything; figures, IDs and percentages on tabular numerals.
|
||||||
|
- Small, quiet radii: 6px controls, 8px cards and tables, full pills for status.
|
||||||
|
- Depth from hairlines first, with only a whisper of shadow.
|
||||||
|
- Colour comes only from theme tokens, never palette classes.
|
||||||
|
|
||||||
|
## Colors
|
||||||
|
|
||||||
|
Slate neutrals with a single blue voice, plus muted semantic and chart tones that each carry a text label.
|
||||||
|
|
||||||
|
### Primary
|
||||||
|
- **Action Blue** (primary): filled primary buttons, links in tables (event names), the brand mark square, the avatar, focus rings (as a 3px ring at 50% opacity), and the first chart series. In dark mode it lightens to #60A5FA with near-black text (#0B1220).
|
||||||
|
- **Blue Tint** (accent-tint) with **Deep Blue Ink** (accent-ink): the active sidebar item, hover on outline and ghost buttons, menu highlights and `::selection`. The tint is a ground, never text; the ink is the text on it.
|
||||||
|
|
||||||
|
### Secondary
|
||||||
|
- **Semantic tones**: Forest (positive), Burnt Amber (warning), Brick (negative) appear only as status pills (10% fill, 30% border, full-strength text) and as delta text. **Signal Red** (destructive) fills destructive buttons and outlines destructive-outline ones.
|
||||||
|
- **Chart tones**: Deep Teal, Amber, Violet, Rose follow Action Blue as chart series 2 to 5. Teal and violet double as category pills ("kinds", not states).
|
||||||
|
|
||||||
|
### Neutral
|
||||||
|
- **Slate Ground** (ground): the page behind everything, and the fill of outline buttons.
|
||||||
|
- **White Surface** (surface): sidebar, header, cards, popovers, menus, input fields.
|
||||||
|
- **Slate Ink** (ink): all primary text and headings.
|
||||||
|
- **Muted Slate** (ink-muted): labels, meta lines, descriptions, table header text, idle nav items. It is #475569, darker than the direction contract's #64748B, so it clears 4.5:1 on the slate tint.
|
||||||
|
- **Slate Tint** (slate-tint): table header rows, secondary buttons, muted fills, row hover at 50%.
|
||||||
|
- **Hairline** (hairline): every border and divider; the default border colour of every element.
|
||||||
|
- **Control Stroke** (control-stroke): the border of inputs and select triggers only, darker than the hairline so a field's boundary reaches 3:1.
|
||||||
|
|
||||||
|
**Dark theme** is a supported mechanism (`.dark` on html, toggled in the header), not the default. It re-derives the same roles from the slate and blue scale: ground #020617, surfaces #0F172A, ink #F1F5F9, muted #94A3B8, tint #1E293B, accent tint #172554 with ink #BFDBFE, control stroke #64748B, primary #60A5FA. Semantic and chart tones move to their 400 steps.
|
||||||
|
|
||||||
|
### Named Rules
|
||||||
|
**The One Voice Rule.** Blue is the only interactive colour. Primary actions, links, focus and the current location are blue; nothing else is. Semantic and chart tones never mark something clickable.
|
||||||
|
|
||||||
|
**The Token-Only Rule.** Colour enters a component only through theme tokens (`bg-primary`, `text-muted-foreground`, `border-input`). Tailwind palette classes (`bg-slate-100`, `text-blue-600`, `bg-white`) are banned and `app/design-tokens.test.ts` fails on them, with a short reasoned allowlist (modal scrims, print sheets, QR quiet zones, email previews).
|
||||||
|
|
||||||
|
**The Measured Contrast Rule.** Every text pair clears 4.5:1 and every control border clears 3:1 against ground and surface, in both themes. `app/globals.test.ts` checks this; a new token pair joins that test before it ships.
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
|
||||||
|
**Display Font:** none (no display face)
|
||||||
|
**Body Font:** Inter (with ui-sans-serif, system-ui), self-hosted variable woff2 via next/font/local
|
||||||
|
**Label/Mono Font:** Inter; the mono role aliases sans
|
||||||
|
|
||||||
|
**Character:** One family doing every job, separated by weight and size only. Headings at 600 with a slight negative track; working text at 14px.
|
||||||
|
|
||||||
|
### Hierarchy
|
||||||
|
- **Headline** (600, 24px, -0.025em): the page title in the page header, one per page.
|
||||||
|
- **Title** (600, 16px, line-height 1): card titles ("Funnel", "By event"). Section headings h1 to h4 take 600 and -0.015em globally.
|
||||||
|
- **Body** (400, 14px): controls, table cells, form text, descriptions. The document base is 16px / 1.6 and inputs render 16px below the md breakpoint to avoid mobile zoom.
|
||||||
|
- **Label** (600, 12px, 0.025em, uppercase): table column headers only. Form labels are 14px sentence case.
|
||||||
|
- **Figure** (600, 24px, tabular numerals): KPI tile values; every other number, date and percentage also uses the tabular class at its own size.
|
||||||
|
|
||||||
|
### Named Rules
|
||||||
|
**The Aligned Figures Rule.** Any figure, ID, date or percentage carries tabular numerals (the `.tabular` class), so columns and KPI rows line up digit for digit.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
An app shell: a sticky 240px white sidebar (collapsible to a 76px icon rail on desktop, a left sheet below the lg breakpoint) beside a column holding a sticky 56px white header and the main area. The sidebar's top block is header-high so its bottom hairline continues the header's. Main content sits on the slate ground with 16px padding, centred up to 1600px.
|
||||||
|
|
||||||
|
Page anatomy: breadcrumb in the header, page header (title, optional meta line, actions right-aligned and wrapping), then filter row, then the content card. Rhythm is a 4px base: 8px between related controls, 16px between blocks and around the page, 24px inside cards. KPI tiles sit in one row of equal columns. Tables scroll horizontally inside their card with a soft shadow on whichever edge has more content. The page reserves the scrollbar gutter so overlays never shift the layout.
|
||||||
|
|
||||||
|
The footer credit "Powered by Containerverse Sdn. Bhd." sits at the foot of the sidebar on desktop and under the content on mobile, in 12px muted text.
|
||||||
|
|
||||||
|
## Elevation & Depth
|
||||||
|
|
||||||
|
Flat surfaces separated by hairlines, with a whisper of shadow that only says "this lifts slightly". Cards carry the card shadow; controls carry a barely-there shadow; floating layers (menus, popovers, toasts, dialogs) step up. In dark mode the card shadow becomes a single dark drop and hairlines do the work.
|
||||||
|
|
||||||
|
### Shadow Vocabulary
|
||||||
|
- **Card** (`box-shadow: 0 1px 2px rgb(15 23 42 / 0.06), 0 1px 3px rgb(15 23 42 / 0.04)`): cards and data-table frames.
|
||||||
|
- **Control** (`box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05)`): inputs, select triggers, outline buttons.
|
||||||
|
- **Float** (`box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)`): select menus, dropdowns, popovers, toasts.
|
||||||
|
- **Modal** (`box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)`): dialogs, over a 50% black scrim.
|
||||||
|
|
||||||
|
### Named Rules
|
||||||
|
**The Hairline First Rule.** Separation comes from the 1px hairline and the ground/surface step; shadow never replaces a border and never exceeds the four steps above.
|
||||||
|
|
||||||
|
## Shapes
|
||||||
|
|
||||||
|
Small, precise corners. Controls (buttons, inputs, selects, menus) are 6px; cards, table frames, tabs lists, nav items and dialogs are 8px; status and category pills and avatars are fully round. Inside a card, anything rounded takes the card's radius minus its padding with an 8px floor, so nested controls and tables render at 8px and corners stay concentric at every depth. The brand mark is a 24px blue square at 6px radius beside the "Co-Lite" wordmark in 18px semibold slate.
|
||||||
|
|
||||||
|
## Components
|
||||||
|
|
||||||
|
### Buttons
|
||||||
|
Quiet, compact, unmistakable.
|
||||||
|
- **Shape:** gently squared (6px), 36px tall; sm 32px, lg 40px, xs 24px. Icon buttons keep a 44px invisible hit area.
|
||||||
|
- **Primary:** Action Blue fill, white 14px medium text, 16px side padding; hover at 90% fill.
|
||||||
|
- **Outline:** ground fill, hairline border, control shadow; hover turns blue tint with deep blue ink. Used for secondary actions and pager controls.
|
||||||
|
- **Secondary:** slate tint fill, ink text. **Ghost:** no fill until hover tint (header icons, row actions). **Link:** blue text, underline on hover.
|
||||||
|
- **Destructive:** Signal Red fill; **destructive-outline:** red text and 40% red border on ground.
|
||||||
|
- **Focus:** border turns blue plus a 3px blue ring at 50%. **Disabled:** 50% opacity, no pointer.
|
||||||
|
- A selected preset in a segmented choice (This month / Last month / Custom) is the primary variant; the others are outline.
|
||||||
|
|
||||||
|
### Chips (status pills)
|
||||||
|
- **Style:** fully round, 12px medium text, 2px 8px padding. Semantic pills use their tone at 10% fill, 30% border, full-strength text; neutral uses slate tint with muted text.
|
||||||
|
- **State:** status uses positive / warning / negative; kinds use teal, violet or blue-tint "contrast". Every pill keeps its text label, so colour is never the only signal.
|
||||||
|
|
||||||
|
### Cards / Containers
|
||||||
|
- **Corner Style:** 8px.
|
||||||
|
- **Background:** white surface on the slate ground.
|
||||||
|
- **Shadow Strategy:** Card shadow (see Elevation).
|
||||||
|
- **Border:** 1px hairline.
|
||||||
|
- **Internal Padding:** 24px, with 24px between header, content and footer.
|
||||||
|
|
||||||
|
### Inputs / Fields
|
||||||
|
- **Style:** white field, 1px control-stroke border, 6px radius, 36px tall, 12px side padding, control shadow; placeholder in muted slate. Select triggers match exactly, with a 16px chevron at 50%.
|
||||||
|
- **Focus:** blue border plus 3px blue ring at 50%.
|
||||||
|
- **Error / Disabled:** `aria-invalid` turns the border Signal Red with a 20% red ring; disabled at 50% opacity.
|
||||||
|
- Menus (select content, dropdowns, the company picker) open as white floating panels with hairline border, 6px radius and Float shadow; dates use the styled date picker, never native date inputs.
|
||||||
|
|
||||||
|
### Data Tables
|
||||||
|
- Live inside a card or an 8px framed container. Header row in slate tint, 40px tall, 12px semibold uppercase muted labels with sort chevrons; cells 14px with 8px padding; rows separated by hairlines, hovering at 50% slate tint. The pager below reads "1-7 of 7" left and outline Previous / Next right.
|
||||||
|
|
||||||
|
### Navigation
|
||||||
|
- **Sidebar:** white, right hairline. Items are 44px tall, 8px radius, 20px outline icon plus 14px medium label. Idle: muted slate, hover slate tint with ink. Active: blue tint with deep blue ink, `aria-current="page"`. Groups expand with a rotating chevron and indent children behind a left hairline. The collapsed rail shows icons only, with groups opening as a side popover.
|
||||||
|
- **Header:** white, bottom hairline, 56px; breadcrumb left; company picker (a styled select), locale switcher, theme toggle and user menu (blue avatar initial) right.
|
||||||
|
|
||||||
|
### Data States
|
||||||
|
- Empty: centred muted icon, 14px muted message and a corrective action. Error: a 40% red-bordered panel on 5% red with an alert icon and an outline Retry. Loading: skeleton rows in a bordered surface.
|
||||||
|
|
||||||
|
## Do's and Don'ts
|
||||||
|
|
||||||
|
### Do:
|
||||||
|
- **Do** reach for colour only through theme tokens; if a role is missing, add a token in `app/globals.css` (both themes) and a contrast pair in `app/globals.test.ts`.
|
||||||
|
- **Do** keep Action Blue for primary actions, links, focus and the active nav item.
|
||||||
|
- **Do** put every figure, date, ID and percentage on tabular numerals.
|
||||||
|
- **Do** use 36px controls at 6px radius and 8px cards with the card shadow and a hairline.
|
||||||
|
- **Do** border inputs and select triggers with the control stroke, not the hairline, so they reach 3:1.
|
||||||
|
- **Do** give every status pill a text label.
|
||||||
|
|
||||||
|
### Don't:
|
||||||
|
- **Don't** use Tailwind palette classes or raw white/black backgrounds outside the test's allowlist.
|
||||||
|
- **Don't** bring back the babyboo look: brown or gold primaries, DM Sans, 16px soft corners, gradient wordmarks, the giraffe-spot pattern.
|
||||||
|
- **Don't** add a second typeface or a display face; Inter carries everything.
|
||||||
|
- **Don't** use semantic or chart tones to mark something clickable.
|
||||||
|
- **Don't** add shadows beyond the four steps, or let a shadow stand in for a hairline.
|
||||||
|
- **Don't** apply this system to the booth (My QR), visitor pages (/r, /i, /c) or login screens piecemeal; they move onto it in their own follow-up change.
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Product
|
||||||
|
|
||||||
|
<!-- impeccable:product-schema 1 -->
|
||||||
|
|
||||||
|
## Platform
|
||||||
|
|
||||||
|
web
|
||||||
|
|
||||||
|
## Users
|
||||||
|
|
||||||
|
- **Office admins (primary).** Staff of INS and CV, and company-less super admins, working at a desk. They set up events and teams, manage guest lists and invitations, follow up and export leads, and manage users, roles, companies and privacy notices. When the needs of the two staff groups clash, the admin's needs win.
|
||||||
|
- **Booth staff.** Salespeople at an event, mostly on a phone. They show their personal QR code, capture visitors, and check their own leads.
|
||||||
|
- **Visitors and guests.** Members of the public on their own phone, with no account. They open a QR, invite or check-in link, fill in a short form and give consent.
|
||||||
|
|
||||||
|
## Product Purpose
|
||||||
|
|
||||||
|
Co-Lite turns event attendance into leads for one company group (INS and CV at go-live). It captures who registered, who was invited, and who actually came, through four routes: staff capture at the booth, walk-in QR codes, personal invite links, and self check-in at the door. Every lead is followed up from one listing.
|
||||||
|
|
||||||
|
Success at go-live (2027-01-15) means:
|
||||||
|
- every visitor at an INS or CV event becomes a lead with consent;
|
||||||
|
- admins can see invited, registered, attended and walk-in numbers against capacity;
|
||||||
|
- nothing is lost between the booth and follow-up.
|
||||||
|
|
||||||
|
## Positioning
|
||||||
|
|
||||||
|
An event-day lead tool, not a general CRM. Its core is the booth and the event day. Hosting events and a member web portal come later (phase 2): leave room for them, but do not design for them yet.
|
||||||
|
|
||||||
|
## Operating Context
|
||||||
|
|
||||||
|
- **Admins:** on desktop browsers in the office, before, during and after events.
|
||||||
|
- **Booth staff:** on phones at a busy booth, often one-handed. A QR code is shown full screen for a visitor to scan.
|
||||||
|
- **Visitors:** scan printed or on-screen QR codes on their own phones, often on venue Wi-Fi.
|
||||||
|
- **Invitations:** sent by email. Until an SMTP provider is set up, emails are only saved and listed under Emails, and admins copy links by hand.
|
||||||
|
- **Companies:** two companies (INS and CV) on one system. Staff see only their own company's data, and super admins see all.
|
||||||
|
|
||||||
|
## Capabilities and Constraints
|
||||||
|
|
||||||
|
- **Stack:** Next.js admin portal calling JSON admin APIs in mobile-api, with Java/Spring services behind an internal gateway.
|
||||||
|
- **Access:** screens are controlled by back-office modules assigned to roles (for example `BO_EVENTS`, `BO_EVENT_GUESTS`, `BO_LEADS_EDIT`, `BO_LEADS_EXPORT`). Staff sign in with company code, username and password.
|
||||||
|
- **Visitor pages are public:**
|
||||||
|
- `/r/<token>` walk-in registration;
|
||||||
|
- `/i/<token>` invite;
|
||||||
|
- `/c/<token>` check-in.
|
||||||
|
|
||||||
|
The privacy-notice consent on these pages is bilingual (English and Bahasa Malaysia) by spec.
|
||||||
|
- **Admin UI languages:** English and Bahasa Malaysia (locale switcher).
|
||||||
|
- **Not at go-live:** member app, member portal, rewards, built-in WhatsApp sending.
|
||||||
|
- **Undecided:** per-company logo or accent in the UI; a dark theme as a supported default.
|
||||||
|
|
||||||
|
## Brand Commitments
|
||||||
|
|
||||||
|
- The product name is **Co-Lite**.
|
||||||
|
- The footer keeps "Powered by Containerverse Sdn. Bhd."
|
||||||
|
- The current look (inherited from the babyboo admin portal) is not binding, and the owner welcomes a complete revamp.
|
||||||
|
- Visual direction (chosen 2026-12-01): the category standard for admin tools, executed with care: white and slate, one blue accent, Inter, no brand gimmicks. The quality bar is Stripe Dashboard, Linear and Vercel.
|
||||||
|
|
||||||
|
## Evidence on Hand
|
||||||
|
|
||||||
|
- There are no real customer data, testimonials or case studies.
|
||||||
|
- Local data is test-only (for example the event "LC CV Expo" and test registrations).
|
||||||
|
- Tastefully customer data must never be copied in.
|
||||||
|
|
||||||
|
## Product Principles
|
||||||
|
|
||||||
|
1. **Admins first.** Dense, scannable lists and forms serve the office user; booth and visitor screens stay just as fast in their own context.
|
||||||
|
2. **Every route counts the same.** Staff capture, QR, invite and check-in all end up as one lead, and the numbers agree everywhere.
|
||||||
|
3. **Consent before capture.** No visitor data is kept without the company's privacy notice and the visitor's consent.
|
||||||
|
4. **One company at a time.** Staff only ever see their own company's events, leads and guests.
|
||||||
|
5. **Leads now, events later.** Build for event leads today without locking out event hosting tomorrow.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
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 * as route from "./route";
|
||||||
|
|
||||||
|
const { GET } = route;
|
||||||
|
const req = (url: string) => new Request(url) as unknown as Parameters<typeof GET>[0];
|
||||||
|
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("/api/audit-log/[[...path]]", () => {
|
||||||
|
it("is GET only", () => {
|
||||||
|
expect(Object.keys(route).filter((k) => /^(GET|POST|PUT|PATCH|DELETE)$/.test(k))).toEqual(["GET"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 401 without a session", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue(null);
|
||||||
|
expect((await GET(req("http://localhost/api/audit-log"), ctx())).status).toBe(401);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses dot segments", async () => {
|
||||||
|
expect((await GET(req("http://localhost/api/audit-log/.."), ctx([".."]))).status).toBe(400);
|
||||||
|
expect((await GET(req("http://localhost/api/audit-log/."), ctx(["."]))).status).toBe(400);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards the query to the list", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
|
||||||
|
const res = await GET(req("http://localhost/api/audit-log?actor=a&page=0&size=20"), ctx());
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log?actor=a&page=0&size=20", { token: "jwt" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards one event by encoded id", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: "a/b" } });
|
||||||
|
await GET(req("http://localhost/api/audit-log/a%2Fb"), ctx(["a/b"]));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log/a%2Fb", { token: "jwt" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||||
|
import { getToken } from "@/app/lib/server/session";
|
||||||
|
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||||
|
|
||||||
|
// Read-only proxy for /api/admin/audit-log[/<id>]; mobile-api owns the BO_AUDIT_LOG guard. Audit events are never writable from the portal, so GET is the only method.
|
||||||
|
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest, { params }: Ctx) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const { path = [] } = await params;
|
||||||
|
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||||
|
const target = `/api/admin/audit-log${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
|
||||||
|
const result = await callMobileApi<unknown>(target, { token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
|
||||||
|
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||||
|
|
||||||
|
import { POST } from "./route";
|
||||||
|
|
||||||
|
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }));
|
||||||
|
|
||||||
|
describe("POST /api/auth/forgot-password company", () => {
|
||||||
|
it("forwards a trimmed company", async () => {
|
||||||
|
await POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify({ company: " ins ", username: "john", email: "j@x.com" }) }) as never);
|
||||||
|
expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", email: "j@x.com" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -5,11 +5,15 @@ import { callMobileApi } from "@/app/lib/server/mobileApi";
|
|||||||
// the answer must not reveal whether the account exists, so upstream errors are never forwarded.
|
// the answer must not reveal whether the account exists, so upstream errors are never forwarded.
|
||||||
// Same-origin and body-size checks are enforced for every /api write by middleware.
|
// Same-origin and body-size checks are enforced for every /api write by middleware.
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const body = (await req.json().catch(() => ({}))) as { username?: unknown; email?: unknown };
|
const body = (await req.json().catch(() => ({}))) as { company?: unknown; username?: unknown; email?: unknown };
|
||||||
const username = typeof body.username === "string" ? body.username.trim() : "";
|
const username = typeof body.username === "string" ? body.username.trim() : "";
|
||||||
const email = typeof body.email === "string" ? body.email.trim() : "";
|
const email = typeof body.email === "string" ? body.email.trim() : "";
|
||||||
|
const company = typeof body.company === "string" ? body.company.trim() : "";
|
||||||
if (username && email) {
|
if (username && email) {
|
||||||
await callMobileApi("/api/admin/auth/forgot-password", { method: "POST", body: { username, email } });
|
await callMobileApi("/api/admin/auth/forgot-password", {
|
||||||
|
method: "POST",
|
||||||
|
body: { ...(company && { company }), username, email },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), setSession: vi.fn() }));
|
||||||
|
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||||
|
vi.mock("@/app/lib/server/session", () => ({ setSession: mocks.setSession }));
|
||||||
|
|
||||||
|
import { POST } from "./route";
|
||||||
|
|
||||||
|
const req = (body: unknown) =>
|
||||||
|
new Request("http://localhost/api/auth/login", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters<typeof POST>[0];
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
data: { token: "t", name: "N", roles: [], aclMenu: {}, resetPasswordRequired: "false" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("POST /api/auth/login company", () => {
|
||||||
|
it("forwards a trimmed company", async () => {
|
||||||
|
await POST(req({ company: " ins ", username: "john", password: "pw" }));
|
||||||
|
expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", password: "pw" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -14,7 +14,7 @@ import type { AdminLoginResponse } from "@/app/lib/types";
|
|||||||
// echoed back here, keeping this handler's response minimal.
|
// echoed back here, keeping this handler's response minimal.
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const body = await req.json().catch(() => ({}));
|
const body = await req.json().catch(() => ({}));
|
||||||
const { username, password } = body as { username?: string; password?: string };
|
const { company, username, password } = body as { company?: string; username?: string; password?: string };
|
||||||
|
|
||||||
const identifier = (username ?? "").trim();
|
const identifier = (username ?? "").trim();
|
||||||
if (!identifier || !password) {
|
if (!identifier || !password) {
|
||||||
@@ -23,7 +23,8 @@ export async function POST(req: NextRequest) {
|
|||||||
|
|
||||||
const result = await callMobileApi<AdminLoginResponse>("/api/admin/auth/login", {
|
const result = await callMobileApi<AdminLoginResponse>("/api/admin/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: { username: identifier, password },
|
// A blank company is a super-admin login: omit the key rather than send "".
|
||||||
|
body: { ...(company?.trim() && { company: company.trim() }), username: identifier, password },
|
||||||
// Real-client context for the login_audit trail (X-Client-Ip / X-Client-User-Agent).
|
// Real-client context for the login_audit trail (X-Client-Ip / X-Client-User-Agent).
|
||||||
headers: clientContextHeaders(req),
|
headers: clientContextHeaders(req),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
|
||||||
|
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||||
|
vi.mock("@/app/lib/server/session", () => ({ getToken: vi.fn().mockResolvedValue("jwt") }));
|
||||||
|
vi.mock("@/app/lib/server/sessionRefresh", () => ({ maybeRefreshSession: vi.fn() }));
|
||||||
|
|
||||||
|
import { GET } from "./route";
|
||||||
|
|
||||||
|
beforeEach(() => mocks.callMobileApi.mockReset());
|
||||||
|
|
||||||
|
describe("GET /api/auth/session company", () => {
|
||||||
|
it("passes companyId, companyCode and isSuper through", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
data: { id: 1, username: "john@ins", name: "J", roles: [], aclMenu: {}, companyId: 7, companyCode: "ins", isSuper: false },
|
||||||
|
});
|
||||||
|
const res = await GET(new Request("http://localhost/api/auth/session") as never);
|
||||||
|
expect(await res.json()).toMatchObject({ companyId: 7, companyCode: "ins", isSuper: false });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -25,6 +25,9 @@ export async function GET(req: NextRequest) {
|
|||||||
const result = await callMobileApi<AdminMeResponse>("/api/admin/me", { token });
|
const result = await callMobileApi<AdminMeResponse>("/api/admin/me", { token });
|
||||||
if (!result.ok) return errorResponse(result);
|
if (!result.ok) return errorResponse(result);
|
||||||
|
|
||||||
const { id, username, name, roles, aclMenu, branch } = result.data;
|
const { id, username, name, roles, aclMenu, branch, companyId, companyCode, isSuper } = result.data;
|
||||||
return NextResponse.json({ id, username, name, roles, aclMenu, branch: branch ?? null });
|
return NextResponse.json({
|
||||||
|
id, username, name, roles, aclMenu, branch: branch ?? null,
|
||||||
|
companyId, companyCode, isSuper,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
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 { POST } from "./route";
|
||||||
|
|
||||||
|
const call = (body: unknown) =>
|
||||||
|
POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify(body) }) as never, { params: Promise.resolve({ id: "7" }) });
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("POST /api/companies/[id]/code", () => {
|
||||||
|
it("returns 401 without a session", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue(null);
|
||||||
|
expect((await call({ code: "new" })).status).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards the code to /api/admin/companies/{id}/code", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 7, code: "new" } });
|
||||||
|
await call({ code: "new" });
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies/7/code", {
|
||||||
|
method: "POST",
|
||||||
|
body: { code: "new" },
|
||||||
|
token: "jwt",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
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";
|
||||||
|
import type { AdminCompany } from "@/app/lib/types";
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const { id } = await params;
|
||||||
|
const { code } = (await req.json().catch(() => ({}))) as { code?: string };
|
||||||
|
const result = await callMobileApi<AdminCompany>(`/api/admin/companies/${encodeURIComponent(id)}/code`, {
|
||||||
|
method: "POST",
|
||||||
|
body: { code },
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -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<{ id: string }> };
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest, { params }: Ctx) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const { id } = await params;
|
||||||
|
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/companies/${encodeURIComponent(id)}/privacy-notice`, { 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 { id } = await params;
|
||||||
|
const body = await req.json().catch(() => ({}));
|
||||||
|
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/companies/${encodeURIComponent(id)}/privacy-notice`, {
|
||||||
|
method: "PUT",
|
||||||
|
body,
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
const post = (body: unknown) =>
|
||||||
|
new Request("http://localhost/api/companies", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters<typeof POST>[0];
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("/api/companies", () => {
|
||||||
|
it("GET returns 401 without a session", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue(null);
|
||||||
|
expect((await GET()).status).toBe(401);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("GET forwards to /api/admin/companies", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] });
|
||||||
|
await GET();
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", { token: "jwt" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST forwards id, name, code and status", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1 } });
|
||||||
|
await POST(post({ id: 1, name: "Ins", code: "ins", status: "A", extra: "x" }));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", {
|
||||||
|
method: "POST",
|
||||||
|
body: { id: 1, name: "Ins", code: "ins", status: "A" },
|
||||||
|
token: "jwt",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST relays a 409 from the API", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "Code already used" });
|
||||||
|
const res = await POST(post({ name: "Ins", code: "ins", status: "A" }));
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
expect((await res.json()).error).toBe("Code already used");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
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";
|
||||||
|
import type { AdminCompany } from "@/app/lib/types";
|
||||||
|
|
||||||
|
// Super admin only; the mobile-api answers 403 for anyone else, and validation (400) and duplicate codes (409) too.
|
||||||
|
export async function GET() {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const result = await callMobileApi<AdminCompany[]>("/api/admin/companies", { 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 { id, name, code, status } = (await req.json().catch(() => ({}))) as Partial<AdminCompany>;
|
||||||
|
const result = await callMobileApi<AdminCompany>("/api/admin/companies", {
|
||||||
|
method: "POST",
|
||||||
|
body: { id, name, code, status },
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
type Req = Parameters<typeof GET>[0];
|
||||||
|
const req = (url: string) => new Request(`http://localhost${url}`) as unknown as Req;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { captures: 1 } });
|
||||||
|
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("/api/dashboard/leads", () => {
|
||||||
|
it("returns 401 without a session", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue(null);
|
||||||
|
const res = await GET(req("/api/dashboard/leads"));
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards the query string to mobile-api", async () => {
|
||||||
|
const res = await GET(req("/api/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({ captures: 1 });
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2", { token: "jwt-abc" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes an upstream INVALID_PERIOD with its code", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Start date must be on or before end date.", status: 400, code: "INVALID_PERIOD" });
|
||||||
|
const res = await GET(req("/api/dashboard/leads?from=2026-11-30&to=2026-11-01"));
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(((await res.json()) as Record<string, unknown>).code).toBe("INVALID_PERIOD");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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";
|
||||||
|
|
||||||
|
// Proxy for /api/admin/dashboard/leads; mobile-api owns period validation and the BO_DASHBOARD guard.
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const result = await callMobileApi<unknown>(`/api/admin/dashboard/leads${new URL(req.url).search}`, { token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
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 PUT(req: NextRequest, { params }: { params: Promise<{ uuid: string; token: string }> }) {
|
||||||
|
const session = await getToken();
|
||||||
|
if (!session) return unauthorized();
|
||||||
|
const { uuid, token } = await params;
|
||||||
|
const body = await req.json().catch(() => ({}));
|
||||||
|
const result = await callMobileApi<Record<string, unknown>>(
|
||||||
|
`/api/admin/events/${encodeURIComponent(uuid)}/registration-links/${encodeURIComponent(token)}`,
|
||||||
|
{ method: "PUT", body, token: session },
|
||||||
|
);
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -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, { params }: { params: Promise<{ uuid: string }> }) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const { uuid } = await params;
|
||||||
|
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/${encodeURIComponent(uuid)}/registration-links`, { token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -16,6 +16,8 @@ export async function GET(req: NextRequest) {
|
|||||||
if (enabled !== "Y" && enabled !== "N") return badRequest("enabled must be Y or N.");
|
if (enabled !== "Y" && enabled !== "N") return badRequest("enabled must be Y or N.");
|
||||||
qs.set("enabled", enabled);
|
qs.set("enabled", enabled);
|
||||||
}
|
}
|
||||||
|
const companyId = params.get("companyId");
|
||||||
|
if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId);
|
||||||
qs.set("page", params.get("page") ?? "0");
|
qs.set("page", params.get("page") ?? "0");
|
||||||
qs.set("size", params.get("size") ?? "20");
|
qs.set("size", params.get("size") ?? "20");
|
||||||
const sortBy = params.get("sortBy");
|
const sortBy = params.get("sortBy");
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ export async function GET(req: NextRequest) {
|
|||||||
const token = await getToken();
|
const token = await getToken();
|
||||||
if (!token) return unauthorized();
|
if (!token) return unauthorized();
|
||||||
|
|
||||||
const result = await callMobileApi<Record<string, unknown>>("/api/admin/events/salesperson-options", { token });
|
const companyId = new URL(req.url).searchParams.get("companyId");
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId);
|
||||||
|
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/salesperson-options${qs.size ? `?${qs}` : ""}`, { token });
|
||||||
if (!result.ok) return errorResponse(result);
|
if (!result.ok) return errorResponse(result);
|
||||||
return NextResponse.json(result.data);
|
return NextResponse.json(result.data);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
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 { POST } from "./route";
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
|
||||||
|
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("/api/login-security unlock", () => {
|
||||||
|
it("POST forwards the companyId query to the upstream URL", async () => {
|
||||||
|
const req = new Request("http://localhost/api/login-security/locked/a/unlock?companyId=2", { method: "POST", body: "{}", headers: { "Content-Type": "application/json" } });
|
||||||
|
await POST(req as unknown as Parameters<typeof POST>[0], { params: Promise.resolve({ path: ["locked", "a", "unlock"] }) });
|
||||||
|
expect(mocks.callMobileApi.mock.calls[0][0]).toBe("/api/admin/login-security/locked/a/unlock?companyId=2");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -11,7 +11,7 @@ async function forward(method: "GET" | "POST" | "PUT", req: NextRequest, { param
|
|||||||
if (!token) return unauthorized();
|
if (!token) return unauthorized();
|
||||||
const { path = [] } = await params;
|
const { path = [] } = await params;
|
||||||
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||||
const target = `/api/admin/login-security${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${method === "GET" ? new URL(req.url).search : ""}`;
|
const target = `/api/admin/login-security${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
if (method !== "GET") {
|
if (method !== "GET") {
|
||||||
const text = await req.text();
|
const text = await req.text();
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { NextResponse } 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() {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const result = await callMobileApi<unknown>("/api/admin/my-registration-links", { token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
|
||||||
|
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||||
|
|
||||||
|
import { GET, POST } from "./route";
|
||||||
|
|
||||||
|
type Req = Parameters<typeof GET>[0];
|
||||||
|
const ctx = { params: Promise.resolve({ token: "tok/1" }) };
|
||||||
|
const req = (init: RequestInit = {}) => new Request("http://localhost/api/public/registration/tok", init) as unknown as Req;
|
||||||
|
|
||||||
|
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { eventName: "Expo" } }));
|
||||||
|
|
||||||
|
describe("/api/public/registration/[token]", () => {
|
||||||
|
it("GET forwards without a session and with the visitor IP", async () => {
|
||||||
|
const res = await GET(req({ headers: { "x-forwarded-for": "203.0.113.7" } }), ctx);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({ eventName: "Expo" });
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/registration/tok%2F1", {
|
||||||
|
headers: { "X-Forwarded-For": "203.0.113.7" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST forwards the body and drops client-written X-Forwarded-For entries and sends only the last hop", async () => {
|
||||||
|
const body = { name: "A", website: "" };
|
||||||
|
await POST(req({ method: "POST", body: JSON.stringify(body), headers: { "x-forwarded-for": "6.6.6.6, 203.0.113.7" } }), ctx);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/registration/tok%2F1", {
|
||||||
|
method: "POST",
|
||||||
|
body,
|
||||||
|
headers: { "X-Forwarded-For": "203.0.113.7" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to X-Real-Ip and sends no header when no address is known", async () => {
|
||||||
|
await GET(req({ headers: { "x-real-ip": "192.0.2.9" } }), ctx);
|
||||||
|
expect(mocks.callMobileApi.mock.calls[0][1].headers).toEqual({ "X-Forwarded-For": "192.0.2.9" });
|
||||||
|
await GET(req(), ctx);
|
||||||
|
expect(mocks.callMobileApi.mock.calls[1][1].headers).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes upstream failures with status and code", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Too many registrations from this device. Try again later.", status: 429, code: "TOO_MANY" });
|
||||||
|
const res = await POST(req({ method: "POST", body: "{}" }), ctx);
|
||||||
|
expect(res.status).toBe(429);
|
||||||
|
expect(((await res.json()) as Record<string, unknown>).code).toBe("TOO_MANY");
|
||||||
|
});
|
||||||
|
});
|
||||||
Loaded 100 of 411 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user