Compare commits

..
Author SHA1 Message Date
ngqileandClaude Opus 5.5 17880e592b docs(openspec): archive add-visual-foundation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 20:16:55 +08:00
ngqile c82b9365dd Merge pull request 'feat: visual foundation for the admin portal (add-visual-foundation)' (#35) from add-visual-foundation into main
CI / build-and-publish (push) Failing after 0s
2026-12-01 12:16:34 +00:00
ngqileandClaude Opus 5.5 372ef7a6c6 docs: DESIGN.md for the new admin look; align panel corners and dialog surface
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 20:16:16 +08:00
ngqileandClaude Opus 5.5 e0ae164a82 fix: keep the company name together in the footer credit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 20:08:32 +08:00
ngqileandClaude Opus 5.5 a02d923f88 fix: review findings for the visual foundation
Input borders reach 3:1, contrast checks for token pairs, white input fill,
company placeholder and team hint, KPI baseline, one-line footer credit,
tabular dates, selection colour, unused contrast tokens removed, and the
events page no longer exports a non-page value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 20:05:21 +08:00
ngqileandClaude Opus 5.5 91675ffb30 fix: no empty row in the company dropdowns
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 19:53:22 +08:00
ngqileandClaude Opus 5.5 a84128cb83 feat: styled dropdown menus in admin forms
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 19:44:53 +08:00
ngqileandClaude Opus 5.5 0710571894 feat: shell wordmark, accent nav item and styled company picker
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 19:35:22 +08:00
ngqileandClaude Opus 5.5 37cb996bc0 feat: slate and blue theme tokens, Inter only
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 19:25:51 +08:00
ngqileandClaude Opus 5.5 899b25f45d docs: move the wordmark class removal to the shell task
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 19:05:26 +08:00
ngqileandClaude Opus 5.5 2a78ef0a79 docs: visual foundation design and OpenSpec change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 18:59:24 +08:00
ngqileandClaude Opus 5.5 92a90d5f48 docs: Co-Lite PRODUCT.md for the visual revamp
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 16:51:42 +08:00
ngqile c5b64c15d0 Merge pull request 'docs(openspec): archive uppercase-company-codes' (#34) from archive-uppercase-company-codes into main
CI / build-and-publish (push) Failing after 0s
2026-12-01 08:41:23 +00:00
ngqileandClaude Opus 5.5 6eec747757 docs(openspec): archive uppercase-company-codes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 16:41:15 +08:00
ngqile 10b32280ad Merge pull request 'feat: company codes in capitals' (#33) from uppercase-company-codes into main
CI / build-and-publish (push) Failing after 0s
2026-12-01 08:41:03 +00:00
ngqileandClaude Opus 5.5 cbe48c2db9 fix: locale-independent code upper-casing; refresh note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 16:40:50 +08:00
ngqileandClaude Opus 5.5 39139ed7b1 docs: uppercase company codes deployment notes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 16:34:33 +08:00
ngqileandClaude Opus 5.5 5e5762cdcb feat: companies screen shows codes in capitals and allows case-only renames
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 16:22:03 +08:00
ngqileandClaude Opus 5.5 41c616b3f6 feat: store company codes in capitals
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 16:13:29 +08:00
ngqileandClaude Opus 5.5 ff4b12c2e9 docs(openspec): propose uppercase-company-codes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 16:07:34 +08:00
ngqile 3ab1a0e0e3 Merge pull request 'docs(openspec): archive add-qr-self-registration' (#32) from archive-add-qr-self-registration into main
CI / build-and-publish (push) Failing after 0s
2026-12-01 06:11:37 +00:00
ngqileandClaude Opus 5.5 5583cf5897 docs(openspec): archive add-qr-self-registration
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 14:11:28 +08:00
ngqile 03b85737d7 Merge pull request 'feat: QR self-registration for walk-in visitors' (#31) from add-qr-self-registration into main
CI / build-and-publish (push) Failing after 0s
2026-12-01 06:11:05 +00:00
ngqileandClaude Opus 5.5 9438fd8cf1 docs: tick QR registration release task
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 14:10:40 +08:00
ngqileandClaude Opus 5.5 d532bdcda4 fix(qr): inactive answer for malformed codes, undated events, switched-off badge, reset-pending sessions
A code of the wrong shape now shows "no longer active" instead of failing,
My QR codes skips events with no end date and marks switched-off codes,
and a session waiting on a password reset can still open a QR page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 14:04:12 +08:00
ngqileandClaude Opus 5.5 c6c220265f docs: correct QR rate-limit and proxy notes, time zone, design risks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 13:49:25 +08:00
ngqileandClaude Opus 5.5 9163557945 fix(qr): tell same-named salespeople apart; bilingual consent tick box
Member codes on the event page are labelled "name (username)", as in the
team list, and the consent tick box reads in English and Bahasa Malaysia.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 13:35:57 +08:00
ngqileandClaude Opus 5.5 2d1513aa80 docs(deployment): QR self-registration SQL, notice review, Traefik and gateway notes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 13:07:39 +08:00
ngqileandClaude Opus 5.5 adbbdc6185 fix(sql): seed privacy notices in Malaysian time; tick 5.1
The services write local Malaysian time, but the seed used the server clock
(UTC), so the editor showed the default notice eight hours early.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 13:07:21 +08:00
ngqileandClaude Opus 5.5 08c45e9109 feat(portal): QR self-registration page, event QR card, My QR codes, privacy notice editor
The public /r/<code> page (no admin shell, never redirects a visitor to the
staff login), its proxy sending only the last X-Forwarded-For hop, the event
page's Registration QR card, a My QR codes page in the user menu, and the
super-admin privacy notice editor on Companies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:57:18 +08:00
ngqileandClaude Opus 5.5 f13dac58a4 docs(openspec): gateway bypass risks; tick 4.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:37:51 +08:00
ngqileandClaude Opus 5.5 eff4899c0d fix(gateway): let the public QR registration reach its backend calls
A visitor has no user token, so the gateway refused every call the public
page makes. Open only the exact method and path pairs it needs, and replace
the full user lookup with a yes/no activeAdminOf endpoint so no user record
is exposed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:37:51 +08:00
ngqileandClaude Opus 5.5 1a7c542f5e docs(openspec): QR rate-limit key is the last X-Forwarded-For hop
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:33:04 +08:00
ngqileandClaude Opus 5.5 5036196031 docs(openspec): gateway access for the public QR flow (task 4.2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:26:09 +08:00
ngqileandClaude Opus 5.5 6ebfbfb1ac docs: tick QR registration wave 1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:18:30 +08:00
ngqileandClaude Opus 5.5 ffda35b785 docs(openspec): POST counts against the QR page-load limit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:16:59 +08:00
ngqileandClaude Opus 5.5 cf8478d00c feat(mobile-api): public QR registration and registration-link admin APIs
Public page and submit for a registration code (one 404 for every unusable
code, load and submit limits, honeypot, consent), event and own codes for
staff, the switch audited against the event uuid rather than the token,
and the super-admin privacy-notice endpoints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:16:58 +08:00
ngqileandClaude Opus 5.5 ab1643e36e feat(system): versioned company privacy notice
GET and POST /company/{id}/privacyNotice: the newest row is current and
saving always adds a version, so consent records keep pointing at the
text the visitor saw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:15:16 +08:00
ngqileandClaude Opus 5.5 85b40424ce feat(counter): registration links and QR self-registration capture
Registration links (event code and personal codes, oldest wins on a
duplicate), lookup by token, the caller's own codes, and the capture that
matches by mobile then email, never edits a matched lead, and records the
source and consent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 12:15:16 +08:00
ngqileandClaude Opus 5.5 9c9469f5e5 docs: tick QR registration wave 0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 11:53:48 +08:00
ngqileandClaude Opus 5.5 0345314c89 chore(portal): add qrcode.react 4.2.0 (as in babyboo's portal)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 11:53:48 +08:00
ngqileandClaude Opus 5.5 2842ef423f feat(db): registration links, event lead source and consent, company privacy notices
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 11:53:48 +08:00
ngqileandClaude Opus 5.5 6fbbdaa3c5 docs: QR self-registration design and OpenSpec change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 11:52:00 +08:00
ngqile 065a8561e3 Merge pull request 'docs(openspec): archive add-lead-dashboard' (#30) from archive-add-lead-dashboard into main
CI / build-and-publish (push) Failing after 1s
2026-12-01 02:51:45 +00:00
ngqileandClaude Opus 5.5 61d17d5e38 docs(openspec): archive add-lead-dashboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:51:37 +08:00
ngqile a8d42a8a25 Merge pull request 'feat: lead dashboard with status history (conversion = WON)' (#29) from add-lead-dashboard into main
CI / build-and-publish (push) Failing after 1s
2026-12-01 02:51:22 +00:00
148 changed files with 6344 additions and 314 deletions

No files matched your search

+2
View File
@@ -16,5 +16,7 @@
# Playwright
.playwright-mcp/
solvway-admin-portal/.impeccable/
# Build output
target/
+20
View File
@@ -105,6 +105,21 @@ Run the three in order, with a user that may alter tables. File `03` ends every
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:**
- 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`.
@@ -236,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.
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
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.
@@ -302,6 +319,9 @@ 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.
- **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.
- **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.
@@ -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.
+51 -3
View File
@@ -185,8 +185,8 @@ 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');
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,
@@ -226,7 +226,7 @@ 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')
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)
@@ -253,3 +253,51 @@ 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,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.
@@ -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
@@ -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`;
@@ -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 @@
## 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-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.
@@ -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.
@@ -0,0 +1,81 @@
# admin-visual-design Specification
## Purpose
Keep the admin portal's look consistent and accessible: colours from theme tokens only, slate neutrals with one blue accent, one type family, a light default with a dark theme, the Co-Lite wordmark, and styled dropdown menus.
## 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
+10 -4
View File
@@ -8,18 +8,18 @@ Separate the data of each company using Co-Lite (INS and CV at go-live): staff s
### 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.
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
- **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`
- **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
@@ -27,6 +27,12 @@ The system SHALL let a super admin list, create and edit companies, each with a
- **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.
+21
View File
@@ -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
- **WHEN** staff change the lead's status
- **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
+158
View File
@@ -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
+133
View File
@@ -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
+256
View File
@@ -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.
+69
View File
@@ -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,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,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);
}
@@ -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");
});
});
@@ -0,0 +1,35 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { clientIp } from "@/app/lib/server/clientContext";
import { errorResponse } from "@/app/lib/server/apiRoute";
// Public (signed-out) proxy for the QR registration page: no session token.
// X-Forwarded-For is rebuilt from clientIp(req) only (the LAST hop, same trusted rule as X-Client-Ip):
// client-written entries in an incoming header are never forwarded, so the rate-limit key cannot be spoofed.
type Ctx = { params: Promise<{ token: string }> };
function forwardedFor(req: NextRequest): Record<string, string> {
const xff = clientIp(req);
return xff ? { "X-Forwarded-For": xff } : {};
}
export async function GET(req: NextRequest, { params }: Ctx) {
const { token } = await params;
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
headers: forwardedFor(req),
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function POST(req: NextRequest, { params }: Ctx) {
const { token } = await params;
const body = await req.json().catch(() => ({}));
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
method: "POST",
body,
headers: forwardedFor(req),
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,43 @@
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 as getLinks } from "./events/[uuid]/registration-links/route";
import { PUT as putLink } from "./events/[uuid]/registration-links/[token]/route";
import { GET as getMine } from "./my-registration-links/route";
import { GET as getNotice, PUT as putNotice } from "./companies/[id]/privacy-notice/route";
const req = (init?: RequestInit) => new Request("http://localhost/x", init) as never;
const p = <T,>(v: T) => ({ params: Promise.resolve(v) });
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { ok: 1 } });
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("registration admin proxies", () => {
it("require a session", async () => {
mocks.getToken.mockResolvedValue(null);
for (const res of [await getLinks(req(), p({ uuid: "e" })), await getMine(), await getNotice(req(), p({ id: "1" }))]) {
expect(res.status).toBe(401);
}
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forward to the admin endpoints with the token", async () => {
await getLinks(req(), p({ uuid: "e1" }));
await putLink(req({ method: "PUT", body: '{"enabled":false}' }), p({ uuid: "e1", token: "t1" }));
await getMine();
await getNotice(req(), p({ id: "2" }));
await putNotice(req({ method: "PUT", body: '{"textEn":"a","textMs":"b"}' }), p({ id: "2" }));
expect(mocks.callMobileApi.mock.calls).toEqual([
["/api/admin/events/e1/registration-links", { token: "jwt" }],
["/api/admin/events/e1/registration-links/t1", { method: "PUT", body: { enabled: false }, token: "jwt" }],
["/api/admin/my-registration-links", { token: "jwt" }],
["/api/admin/companies/2/privacy-notice", { token: "jwt" }],
["/api/admin/companies/2/privacy-notice", { method: "PUT", body: { textEn: "a", textMs: "b" }, token: "jwt" }],
]);
});
});
@@ -13,7 +13,7 @@ vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth
import CompaniesPage from "./page";
beforeEach(() => {
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "INS", status: "A" }]);
mocks.apiPost.mockReset();
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
});
@@ -24,7 +24,7 @@ describe("CompaniesPage fixes", () => {
await userEvent.click(await screen.findByRole("button", { name: "Change code" }));
const input = screen.getByLabelText("New code");
await userEvent.clear(input);
await userEvent.type(input, " INS ");
await userEvent.type(input, " ins ");
await userEvent.click(screen.getByRole("button", { name: "Confirm" }));
expect(mocks.apiPost).not.toHaveBeenCalled();
expect(screen.getByRole("alert")).toBeInTheDocument();
@@ -0,0 +1,74 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ isSuper: true, apiGet: vi.fn(), getPrivacyNotice: vi.fn(), savePrivacyNotice: vi.fn() }));
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
apiGet: mocks.apiGet,
apiPost: vi.fn(),
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ loading: false, isSuper: mocks.isSuper }) }));
vi.mock("@/app/lib/services/adminRegistration", () => ({
getPrivacyNotice: mocks.getPrivacyNotice,
savePrivacyNotice: mocks.savePrivacyNotice,
}));
import CompaniesPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
beforeEach(() => {
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
mocks.getPrivacyNotice.mockReset().mockResolvedValue({ id: 3, companyId: 1, textEn: "Old EN", textMs: "Old MS", createdBy: "boss", createdAt: "2026-11-30T10:00:00" });
mocks.savePrivacyNotice.mockReset().mockResolvedValue({ id: 4, companyId: 1, textEn: "x", textMs: "y", createdBy: "boss", createdAt: "2026-12-01T09:30:00" });
mocks.isSuper = true;
});
async function openEditor() {
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: "Privacy notice" }));
}
describe("Companies privacy notice editor", () => {
it("loads both languages and shows who changed it last", async () => {
await openEditor();
expect(await screen.findByDisplayValue("Old EN")).toBeInTheDocument();
expect(screen.getByDisplayValue("Old MS")).toBeInTheDocument();
expect(screen.getByText(/boss/)).toBeInTheDocument();
expect(mocks.getPrivacyNotice).toHaveBeenCalledWith(1);
});
it("saves the edited text", async () => {
await openEditor();
const en = await screen.findByLabelText("English");
await userEvent.clear(en);
await userEvent.type(en, "New EN");
await userEvent.click(screen.getByRole("button", { name: "Save notice" }));
await waitFor(() => expect(mocks.savePrivacyNotice).toHaveBeenCalledWith(1, { textEn: "New EN", textMs: "Old MS" }));
});
it("shows the server error and starts empty when there is no notice", async () => {
mocks.getPrivacyNotice.mockResolvedValue(null);
mocks.savePrivacyNotice.mockRejectedValue(new ApiError("Notice text is required.", 400, { error: "Notice text is required." }));
await openEditor();
const en = (await screen.findByLabelText("English")) as HTMLTextAreaElement;
expect(en.value).toBe("");
await userEvent.click(screen.getByRole("button", { name: "Save notice" }));
expect(await screen.findByText("Notice text is required.")).toBeInTheDocument();
});
it("does not crash when the notice has no createdAt or createdBy", async () => {
mocks.getPrivacyNotice.mockResolvedValue({ id: 3, companyId: 1, textEn: "Old EN", textMs: "Old MS" });
await openEditor();
expect(await screen.findByDisplayValue("Old EN")).toBeInTheDocument();
expect(screen.queryByText(/Last changed/i)).toBeNull();
});
it("does not offer the editor to a non-super admin", async () => {
mocks.isSuper = false;
render(<CompaniesPage />);
await waitFor(() => expect(screen.queryByRole("button", { name: "Privacy notice" })).toBeNull());
expect(mocks.getPrivacyNotice).not.toHaveBeenCalled();
});
});
@@ -46,6 +46,19 @@ describe("CompaniesPage", () => {
);
});
it("saves the status chosen in the styled dropdown", async () => {
mocks.apiPost.mockResolvedValue({ id: 1 });
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: "Edit" }));
await userEvent.click(screen.getByLabelText("Status"));
await userEvent.click(await screen.findByRole("option", { name: "Inactive" }));
await userEvent.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() =>
expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { id: 1, name: "Insight", status: "I" }),
);
});
it("edits name and status only, with no code field", async () => {
mocks.apiPost.mockResolvedValue({ id: 1 });
render(<CompaniesPage />);
+84 -13
View File
@@ -6,6 +6,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { DataTable } from "@/app/components/ui/data-table";
import { PageHeader } from "@/app/components/ui/page-header";
@@ -14,6 +15,7 @@ import { Badge } from "@/app/components/ui/badge";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { NotAuthorized } from "@/app/lib/RequireModule";
import { getPrivacyNotice, savePrivacyNotice, type PrivacyNotice } from "@/app/lib/services/adminRegistration";
import { changeAdminCompanyCode, listAdminCompanies, saveAdminCompany } from "@/app/lib/services/adminCompanies";
import type { AdminCompany } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
@@ -38,7 +40,7 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
if ((mode === "code" ? newCode : form.code).trim() === "" && (mode === "code" || !form.id)) {
return setError(t("CompCodeRequired"));
}
if (mode === "code" && newCode.trim().toLowerCase() === company.code.toLowerCase()) {
if (mode === "code" && newCode.trim().toUpperCase() === company.code) {
return setError(t("CompCodeUnchanged"));
}
setError(null);
@@ -73,7 +75,7 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
<p className="text-sm">{t("CompChangeCodeWarning")}</p>
<div className="space-y-1.5">
<Label htmlFor="company-new-code">{t("CompNewCode")}</Label>
<Input id="company-new-code" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
<Input id="company-new-code" className="uppercase" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
</div>
</>
) : (
@@ -85,21 +87,18 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
{!form.id && (
<div className="space-y-1.5">
<Label htmlFor="company-code">{t("Code")}</Label>
<Input id="company-code" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
<Input id="company-code" className="uppercase" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="company-status">{t("Status")}</Label>
<select
id="company-status"
value={form.status}
onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as AdminCompany["status"] }))}
disabled={saving}
className="h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm"
>
<option value="A">{t("CompActive")}</option>
<option value="I">{t("CompInactive")}</option>
</select>
<Select value={form.status} onValueChange={(v) => setForm((f) => ({ ...f, status: v as AdminCompany["status"] }))} disabled={saving}>
<SelectTrigger id="company-status" className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="A">{t("CompActive")}</SelectItem>
<SelectItem value="I">{t("CompInactive")}</SelectItem>
</SelectContent>
</Select>
</div>
</>
)}
@@ -114,6 +113,73 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
);
}
function PrivacyNoticeDialog({ company, onClose }: { company: AdminCompany; onClose: () => void }) {
const t = useT();
const [notice, setNotice] = useState<PrivacyNotice | null>(null);
const [textEn, setTextEn] = useState("");
const [textMs, setTextMs] = useState("");
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
getPrivacyNotice(company.id!)
.then((n) => {
setNotice(n);
setTextEn(n?.textEn ?? "");
setTextMs(n?.textMs ?? "");
})
.catch(() => setError(t("PrivLoadFailed")));
}, [company.id, t]);
async function save(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
setSaving(true);
try {
setNotice(await savePrivacyNotice(company.id!, { textEn, textMs }));
} catch (err) {
setError(err instanceof Error && err.message ? err.message : t("PrivSaveFailed"));
} finally {
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("PrivNotice")}</DialogTitle>
</DialogHeader>
{error && (
<div className="text-sm text-destructive" role="alert">
{error}
</div>
)}
<form onSubmit={save} className="space-y-4" noValidate>
<div className="space-y-1.5">
<Label htmlFor="notice-en">{t("RegNoticeEn")}</Label>
<textarea id="notice-en" className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm" rows={5} value={textEn} onChange={(e) => setTextEn(e.target.value)} disabled={saving} />
</div>
<div className="space-y-1.5">
<Label htmlFor="notice-ms">{t("RegNoticeMs")}</Label>
<textarea id="notice-ms" className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm" rows={5} value={textMs} onChange={(e) => setTextMs(e.target.value)} disabled={saving} />
</div>
{notice?.createdAt && notice.createdBy && (
<p className="text-xs text-muted-foreground">
{t("PrivLastChanged", { user: notice.createdBy, date: notice.createdAt.replace("T", " ").slice(0, 16) })}
</p>
)}
<DialogFooter>
<Button type="submit" disabled={saving}>
{t("PrivSave")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
function CompaniesPageContent() {
const t = useT();
const [companies, setCompanies] = useState<AdminCompany[]>([]);
@@ -121,6 +187,7 @@ function CompaniesPageContent() {
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [dialog, setDialog] = useState<DialogState | null>(null);
const [noticeFor, setNoticeFor] = useState<AdminCompany | null>(null);
const [page, setPage] = useState(1);
const { tableRef, pageSize } = useFitPageSize();
const size = pageSize ?? MIN_PAGE_SIZE;
@@ -165,6 +232,9 @@ function CompaniesPageContent() {
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "code", company: row.original })}>
{t("CompChangeCode")}
</Button>
<Button variant="outline" size="sm" onClick={() => setNoticeFor(row.original)}>
{t("PrivNotice")}
</Button>
</div>
),
},
@@ -200,6 +270,7 @@ function CompaniesPageContent() {
empty={<EmptyState title={t("CompNone")} />}
/>
{noticeFor && <PrivacyNoticeDialog company={noticeFor} onClose={() => setNoticeFor(null)} />}
{dialog && <CompanyDialog state={dialog} onClose={() => setDialog(null)} onSaved={refetch} />}
</>
);
@@ -0,0 +1,54 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
apiGet: mocks.apiGet,
apiPost: mocks.apiPost,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import CompaniesPage from "./page";
beforeEach(() => {
mocks.apiGet.mockReset().mockResolvedValue([{ id: 2, name: "Clever", code: "cv", status: "A" }]);
mocks.apiPost.mockReset().mockResolvedValue({ id: 2, code: "CV" });
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
});
async function openChangeCode() {
render(<CompaniesPage />);
const row = (await screen.findByText("Clever")).closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: /change code/i }));
return screen.getByLabelText("New code");
}
describe("CompaniesPage company codes in capitals", () => {
it("treats a change of case as a change and posts it", async () => {
const code = await openChangeCode();
await userEvent.clear(code);
await userEvent.type(code, "CV");
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies/2/code", { code: "CV" }));
});
it("still refuses the same code typed in any case", async () => {
mocks.apiGet.mockResolvedValue([{ id: 2, name: "Clever", code: "CV", status: "A" }]);
const code = await openChangeCode();
await userEvent.clear(code);
await userEvent.type(code, "cv");
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
expect(await screen.findByRole("alert")).toBeInTheDocument();
expect(mocks.apiPost).not.toHaveBeenCalled();
});
it("shows code inputs in capitals", async () => {
const code = await openChangeCode();
expect(code).toHaveClass("uppercase");
await userEvent.keyboard("{Escape}");
await userEvent.click(screen.getByRole("button", { name: /add company/i }));
expect(screen.getByLabelText("Code")).toHaveClass("uppercase");
});
});
@@ -49,7 +49,7 @@ describe("UserForm company", () => {
const user = userEvent.setup();
render(<UserForm onSubmit={onSubmit} />);
const company = await screen.findByRole("combobox", { name: "Company" });
expect(company).toHaveValue("2");
expect(company).toHaveTextContent("CV");
await fillUser(user);
await user.click(screen.getByLabelText("HQ"));
await user.click(screen.getByRole("button", { name: /create|save/i }));
@@ -60,7 +60,8 @@ describe("UserForm company", () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<UserForm onSubmit={onSubmit} />);
await user.selectOptions(await screen.findByRole("combobox", { name: "Company" }), "super");
await user.click(await screen.findByRole("combobox", { name: "Company" }));
await user.click(await screen.findByRole("option", { name: "Super admin (no company)" }));
await fillUser(user);
await user.click(screen.getByLabelText("HQ"));
await user.click(screen.getByRole("button", { name: /create|save/i }));
@@ -106,6 +107,13 @@ describe("UserForm company", () => {
await user.click(screen.getByRole("button", { name: /create|save/i }));
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
});
it("lists only the company codes and Super admin in the Company menu, with no blank option", async () => {
mocks.useCompanyScope.mockReturnValue(scope(undefined));
const user = userEvent.setup();
render(<UserForm onSubmit={vi.fn()} />);
await user.click(await screen.findByRole("combobox", { name: "Company" }));
expect((await screen.findAllByRole("option")).map((o) => o.textContent)).toEqual(["INS", "CV", "Super admin (no company)"]);
});
});
describe("EventForm company", () => {
@@ -113,7 +121,7 @@ describe("EventForm company", () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<EventForm onSubmit={onSubmit} />);
expect(await screen.findByRole("combobox", { name: "Company" })).toHaveValue("2");
expect(await screen.findByRole("combobox", { name: "Company" })).toHaveTextContent("CV");
await user.type(screen.getByLabelText("Name"), "Expo");
await user.type(screen.getByLabelText("Location"), "KL");
pickDate("Start date", "2026-12-01");
@@ -133,7 +141,8 @@ describe("EventForm company", () => {
const user = userEvent.setup();
const { unmount } = render(<EventForm onSubmit={vi.fn()} />);
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(2));
await user.selectOptions(screen.getByRole("combobox", { name: "Company" }), "1");
await user.click(screen.getByRole("combobox", { name: "Company" }));
await user.click(await screen.findByRole("option", { name: "INS" }));
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(1));
unmount();
mocks.useCompanyScope.mockReturnValue(scope(1));
@@ -161,4 +170,38 @@ describe("EventForm company required", () => {
expect(onSubmit).not.toHaveBeenCalled();
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
});
it("lists only the company codes in the Company menu, with no blank option", async () => {
mocks.useCompanyScope.mockReturnValue(scope(undefined));
const user = userEvent.setup();
render(<EventForm onSubmit={vi.fn()} />);
await user.click(await screen.findByRole("combobox", { name: "Company" }));
expect((await screen.findAllByRole("option")).map((o) => o.textContent)).toEqual(["INS", "CV"]);
});
});
describe("company picker placeholder and team hint", () => {
it("shows a placeholder in the empty company picker on the user form", async () => {
mocks.useCompanyScope.mockReturnValue(scope(undefined));
render(<UserForm onSubmit={vi.fn()} />);
expect(await screen.findByRole("combobox", { name: "Company" })).toHaveTextContent("Select a company");
});
it("shows a placeholder in the empty company picker on the event form", async () => {
mocks.useCompanyScope.mockReturnValue(scope(undefined));
render(<EventForm onSubmit={vi.fn()} />);
expect(await screen.findByRole("combobox", { name: "Company" })).toHaveTextContent("Select a company");
});
it("hints to choose a company before the team can be listed, then lists it", async () => {
mocks.useCompanyScope.mockReturnValue(scope(undefined));
const user = userEvent.setup();
render(<EventForm onSubmit={vi.fn()} />);
expect(await screen.findByText("Choose a company to list its team")).toBeInTheDocument();
expect(screen.queryByRole("checkbox", { name: /Alice/ })).not.toBeInTheDocument();
await user.click(screen.getByRole("combobox", { name: "Company" }));
await user.click(await screen.findByRole("option", { name: "CV" }));
expect(await screen.findByRole("checkbox", { name: /Alice/ })).toBeInTheDocument();
expect(screen.queryByText("Choose a company to list its team")).not.toBeInTheDocument();
});
});
@@ -3,6 +3,10 @@
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useCompanyScope } from "@/app/lib/CompanyScope";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
// Radix Select rejects "" as an item value, so "All companies" is this sentinel, mapped to undefined.
const ALL = "all";
// Header company filter; super admins only (staff are always scoped by the server).
export default function CompanyPicker() {
@@ -11,16 +15,16 @@ export default function CompanyPicker() {
const t = useT();
if (!isSuper) return null;
return (
<select
aria-label={t("Company")}
value={companyId ?? ""}
onChange={(e) => setCompanyId(e.target.value ? Number(e.target.value) : undefined)}
className="h-9 rounded-md border bg-background px-2 text-sm"
>
<option value="">{t("AllCompanies")}</option>
{companies.map((c) => (
<option key={c.id} value={c.id}>{c.code}</option>
))}
</select>
<Select value={companyId === undefined ? ALL : String(companyId)} onValueChange={(v) => setCompanyId(v === ALL ? undefined : Number(v))}>
<SelectTrigger aria-label={t("Company")} className="min-w-36">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>{t("AllCompanies")}</SelectItem>
{companies.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>
))}
</SelectContent>
</Select>
);
}
@@ -31,7 +31,7 @@ describe("Header: change password", () => {
render(<Header />);
await userEvent.click(screen.getByRole("button", { name: /admin user/i }));
const items = (await screen.findAllByRole("menuitem")).map((i) => i.textContent);
expect(items).toEqual(["Change password", "Logout"]);
expect(items).toEqual(["My QR codes", "Change password", "Logout"]);
});
it("blocks empty fields and mismatched passwords without calling the server", async () => {
@@ -55,7 +55,7 @@ export default function Header() {
const initial = (name ?? "?").slice(0, 1).toUpperCase();
return (
<header className="sticky top-0 z-30 flex h-16 shrink-0 items-center gap-2 border-b bg-card px-4">
<header className="sticky top-0 z-30 flex h-14 shrink-0 items-center gap-2 border-b bg-card px-4">
<Sheet open={menuOpen} onOpenChange={setMenuOpen}>
<Button
variant="ghost"
@@ -68,7 +68,7 @@ export default function Header() {
</Button>
<SheetContent side="left" className="w-[var(--sidebar-width)] max-w-[85vw] bg-sidebar p-0">
<SheetTitle className="sr-only">{t("HeaderMenu")}</SheetTitle>
<div className="flex h-16 shrink-0 items-center border-b px-4">
<div className="flex h-14 shrink-0 items-center border-b px-4">
<BrandLink onClick={() => setMenuOpen(false)} />
</div>
<SidebarNav onNavigate={() => setMenuOpen(false)} />
@@ -108,6 +108,9 @@ export default function Header() {
<span className="block text-sm font-medium">{name}</span>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => router.push("/my-qr")}>
{t("QrMyTitle")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setChangingPassword(true)}>
<KeyRound aria-hidden="true" className="size-4" />
{t("PwdChangeMenu")}
@@ -14,7 +14,7 @@ export default function PoweredBy({ compact = false }: { compact?: boolean }) {
target="_blank"
rel="noopener noreferrer"
title={`${POWERED_BY.prefix} ${POWERED_BY.name}`}
className="text-xs text-muted-foreground underline hover:text-foreground"
className="text-xs text-muted-foreground hover:text-foreground hover:underline"
>
{/* The accessible name starts with the visible text (WCAG 2.5.3 Label in Name). */}
{POWERED_BY.short}{" "}
@@ -29,7 +29,7 @@ export default function PoweredBy({ compact = false }: { compact?: boolean }) {
href={POWERED_BY.href}
target="_blank"
rel="noopener noreferrer"
className="underline hover:text-foreground"
className="whitespace-nowrap hover:text-foreground hover:underline"
>
{POWERED_BY.name}
</a>
@@ -392,9 +392,9 @@ describe("Sidebar icon rail", () => {
const sales = screen.getByRole("button", { name: "Sales & orders" });
const stock = screen.getByRole("button", { name: "Stock" });
expect(sales).toHaveAttribute("data-current", "true");
expect(sales.className).toContain("bg-sidebar-primary");
expect(sales).toHaveClass("bg-sidebar-accent", "text-sidebar-accent-foreground");
expect(stock).not.toHaveAttribute("data-current");
expect(stock.className).not.toContain("bg-sidebar-primary");
expect(stock).not.toHaveClass("bg-sidebar-accent");
});
it("keeps a current top-level leaf filled in the rail", async () => {
@@ -405,7 +405,7 @@ describe("Sidebar icon rail", () => {
const link = screen.getByRole("link", { name: "Dashboard" });
expect(link).toHaveAttribute("aria-current", "page");
expect(link.className).toContain("bg-sidebar-primary");
expect(link).toHaveClass("bg-sidebar-accent", "text-sidebar-accent-foreground");
});
it("keeps the footer credit visible in a compact form", async () => {
@@ -430,7 +430,7 @@ describe("Sidebar icon rail", () => {
expect(within(brandRow()).queryByRole("link")).toBeNull();
expect(within(brandRow()).getByRole("button", { name: "Expand sidebar" })).toBeInTheDocument();
expect(brandRow()).toHaveClass("h-16", "justify-center");
expect(brandRow()).toHaveClass("h-14", "justify-center");
await user.click(screen.getByRole("button", { name: "Expand sidebar" }));
expect(within(brandRow()).getByRole("link", { name: /Co-Lite/ })).toBeInTheDocument();
@@ -488,3 +488,35 @@ describe("Sidebar icon rail", () => {
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
});
});
// add-visual-foundation: Product Wordmark / One Accent Colour.
describe("Sidebar visual identity", () => {
afterEach(() => {
state.pathname = "/";
});
it("shows the Co-Lite mark and a solid wordmark, not gradient-filled text", () => {
state.links = [];
const { container } = render(<Sidebar />);
const word = screen.getByText("Co-Lite");
expect(word).not.toHaveClass("brand-wordmark");
expect(word.className).not.toMatch(/gradient|text-transparent/);
expect(container.querySelector("[data-slot='brand-mark']")).not.toBeNull();
});
it("marks only the current top-level item in the accent, not a solid primary fill", () => {
state.links = [
{ name: "Events", url: "/events", iconName: "Users", children: [] },
{ name: "Leads", url: "/leads", iconName: "Users", children: [] },
];
state.pathname = "/events";
render(<Sidebar />);
const events = screen.getByRole("link", { name: "Events" });
const leads = screen.getByRole("link", { name: "Leads" });
expect(events).toHaveAttribute("aria-current", "page");
expect(events).toHaveClass("bg-sidebar-accent", "text-sidebar-accent-foreground");
expect(events).not.toHaveClass("bg-sidebar-primary");
expect(leads).not.toHaveClass("bg-sidebar-accent");
expect(leads).not.toHaveClass("bg-sidebar-primary");
});
});
@@ -44,10 +44,8 @@ function NavNode({ link, depth, trail, onNavigate }: { link: SidebarLink; depth:
"focus-visible:ring-2 focus-visible:ring-sidebar-ring focus-visible:outline-none",
depth === 0 ? "min-h-11 text-sm font-medium" : "min-h-9 text-sm",
active
? depth === 0
? "bg-sidebar-primary text-sidebar-primary-foreground"
: "bg-sidebar-accent font-medium text-sidebar-accent-foreground"
: "text-muted-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
? "bg-sidebar-accent font-medium text-sidebar-accent-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
{/* eslint-disable-next-line react-hooks/static-components -- Icon comes from
@@ -98,7 +96,7 @@ function NavGroup({
"focus-visible:ring-2 focus-visible:ring-sidebar-ring focus-visible:outline-none",
depth === 0 ? "min-h-11 text-sm font-medium" : "min-h-9 text-sm",
active ? "text-sidebar-accent-foreground" : "text-muted-foreground",
"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
"hover:bg-muted hover:text-foreground",
)}
>
{Icon && <Icon aria-hidden="true" className="size-5 shrink-0" />}
@@ -124,8 +122,8 @@ const railItemClass = cn(
"flex size-11 items-center justify-center rounded-lg transition-colors",
"focus-visible:ring-2 focus-visible:ring-sidebar-ring focus-visible:outline-none",
);
const railIdleClass = "text-muted-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground";
const railActiveClass = "bg-sidebar-primary text-sidebar-primary-foreground";
const railIdleClass = "text-muted-foreground hover:bg-muted hover:text-foreground";
const railActiveClass = "bg-sidebar-accent text-sidebar-accent-foreground";
function RailNode({ link, trail }: { link: SidebarLink; trail: SidebarLink[] }) {
const t = useT();
@@ -241,7 +239,8 @@ export function BrandLink({ onClick }: { onClick?: () => void }) {
onClick={onClick}
className="flex items-center gap-2.5 rounded-md focus-visible:ring-2 focus-visible:ring-sidebar-ring focus-visible:outline-none"
>
<span className="brand-wordmark text-lg">{BRAND}</span>
<span data-slot="brand-mark" aria-hidden="true" className="size-6 shrink-0 rounded-md bg-primary" />
<span className="text-lg font-semibold tracking-tight text-foreground">{BRAND}</span>
</Link>
);
}
@@ -270,7 +269,7 @@ export default function Sidebar() {
// Expanded on the server and during hydration; the stored choice is applied after mount so both renders agree.
const [collapsed, setCollapsed] = useState(false);
// The width animates only after a toggle: applying a stored collapse on load must not animate
// 272 -> 76px (and reflow the page) on every navigation.
// 240 -> 76px (and reflow the page) on every navigation.
const [animate, setAnimate] = useState(false);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- localStorage is only readable after mount; reading it during render would make the hydration render disagree with the server.
@@ -297,7 +296,7 @@ export default function Sidebar() {
{/* Header-high in both states so its border lines up with the header's; the rail shows only the toggle. */}
<div
className={cn(
"flex h-16 shrink-0 items-center border-b",
"flex h-14 shrink-0 items-center border-b",
collapsed ? "justify-center" : "justify-between gap-2 px-4",
)}
>
@@ -320,7 +319,7 @@ export default function Sidebar() {
<SidebarNav collapsed={collapsed} />
<div className={cn("shrink-0 border-t text-center", collapsed ? "px-1 py-3" : "p-3")}>
<div className={cn("shrink-0 border-t", collapsed ? "px-1 py-3" : "p-3")}>
<PoweredBy compact={collapsed} />
</div>
</aside>
@@ -40,9 +40,9 @@ function bucketLabel(bucket: string, kind: "DAY" | "MONTH"): string {
function Tile({ label, value }: { label: string; value: string }) {
return (
<div role="group" aria-label={label} className="rounded-xl border bg-card p-4">
<div role="group" aria-label={label} className="flex flex-col rounded-lg border bg-card shadow-card p-4">
<div className="text-sm text-muted-foreground">{label}</div>
<div className="mt-1 text-2xl font-semibold tabular">{value}</div>
<div className="mt-auto pt-1 text-2xl font-semibold tabular">{value}</div>
</div>
);
}
@@ -5,6 +5,7 @@ import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { Switch } from "@/app/components/ui/switch";
import { DatePicker } from "@/app/components/ui/date-picker";
import { ErrorState } from "@/app/components/ui/states";
@@ -179,22 +180,23 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
{showCompany && (
<div className="space-y-1.5">
<Label htmlFor="evt-company">{t("Company")}</Label>
<select
id="evt-company"
<Select
value={companyChoice}
onChange={(e) => {
setCompanyChoice(e.target.value);
onValueChange={(v) => {
setCompanyChoice(v);
setSelectedIds(new Set()); // the team is company-specific
}}
disabled={saving}
aria-invalid={!!fieldErrors.company}
className="h-9 w-full rounded-md border bg-background px-2 text-sm"
>
<option value="" />
{scope.companies.map((c) => (
<option key={c.id} value={c.id}>{c.code}</option>
))}
</select>
<SelectTrigger id="evt-company" aria-invalid={!!fieldErrors.company} className="w-full">
<SelectValue placeholder={t("SelectCompany")} />
</SelectTrigger>
<SelectContent>
{scope.companies.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>
))}
</SelectContent>
</Select>
{fieldErrors.company && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.company}
@@ -296,7 +298,9 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
</p>
)}
<div className="max-h-48 space-y-1 overflow-y-auto rounded-md border p-2">
{loadingPickers ? (
{showCompany && !companyChoice ? (
<p className="text-sm text-muted-foreground">{t("TeamNeedsCompany")}</p>
) : loadingPickers ? (
<p className="text-sm text-muted-foreground">{t("Loading")}</p>
) : (
optionList.map((opt) => {
@@ -0,0 +1,72 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { forwardRef } from "react";
const mocks = vi.hoisted(() => ({ getEventLinks: vi.fn(), setLinkEnabled: vi.fn() }));
vi.mock("@/app/lib/services/adminRegistration", () => mocks);
vi.mock("qrcode.react", () => ({
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
QRCodeCanvas: forwardRef<HTMLCanvasElement>(function QRCodeCanvas(_, ref) {
return <canvas ref={ref} />;
}),
}));
import { RegistrationQrCard } from "./RegistrationQrCard";
const links = {
event: { token: "ev1", enabled: true },
members: [
{ userId: 5, name: "Aini", username: "aini@cv", token: "m1", enabled: false },
{ userId: 6, name: "Bob", username: "", token: "m2", enabled: true },
],
};
beforeEach(() => {
mocks.getEventLinks.mockReset().mockResolvedValue(links);
mocks.setLinkEnabled.mockReset().mockResolvedValue(undefined);
});
describe("RegistrationQrCard", () => {
it("lists the event code and each team member code with a QR", async () => {
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Aini (aini@cv)");
const values = screen.getAllByTestId("qr-svg").map((e) => e.getAttribute("data-value"));
expect(values).toEqual([`${window.location.origin}/r/ev1`, `${window.location.origin}/r/m1`, `${window.location.origin}/r/m2`]);
expect(screen.getByText(/dynamic-qr/)).toBeTruthy();
expect(mocks.getEventLinks).toHaveBeenCalledWith("u1");
});
it("labels a member without a username by name only", async () => {
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Bob");
expect(screen.queryByText(/\(\)/)).toBeNull();
});
it("names the PNG download after the event and the member's name and username", async () => {
const user = userEvent.setup();
const names: string[] = [];
vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue("data:image/png;base64,");
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) {
names.push(this.download);
});
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Aini (aini@cv)");
await user.click(screen.getAllByRole("button", { name: "Download PNG" })[1]);
expect(names).toEqual(["expo-aini-aini-cv-qr.png"]);
});
it("toggles a code through the API", async () => {
const user = userEvent.setup();
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Aini (aini@cv)");
await user.click(screen.getAllByRole("switch")[1]);
await waitFor(() => expect(mocks.setLinkEnabled).toHaveBeenCalledWith("u1", "m1", true));
});
it("hides the switches without write access", async () => {
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite={false} />);
await screen.findByText("Aini (aini@cv)");
expect(screen.queryAllByRole("switch")).toHaveLength(0);
});
});
@@ -0,0 +1,64 @@
"use client";
import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ErrorState } from "@/app/components/ui/states";
import { QrCodeItem } from "@/app/components/registration/QrCodeItem";
import { getEventLinks, setLinkEnabled, type EventLinks } from "@/app/lib/services/adminRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
export function RegistrationQrCard({ eventUuid, eventName, canWrite }: { eventUuid: string; eventName: string; canWrite: boolean }) {
const t = useT();
const [links, setLinks] = useState<EventLinks | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
getEventLinks(eventUuid)
.then((l) => !cancelled && setLinks(l))
.catch(() => !cancelled && setError(t("QrLoadFailed")));
return () => {
cancelled = true;
};
}, [eventUuid, t]);
async function toggle(token: string, enabled: boolean) {
setError(null);
try {
await setLinkEnabled(eventUuid, token, enabled);
setLinks((l) =>
l && {
event: l.event.token === token ? { ...l.event, enabled } : l.event,
members: l.members.map((m) => (m.token === token ? { ...m, enabled } : m)),
},
);
} catch {
setError(t("QrSaveFailed"));
}
}
const onToggle = (token: string) => (canWrite ? (on: boolean) => toggle(token, on) : undefined);
return (
<Card>
<CardHeader>
<CardTitle>{t("QrCardTitle")}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">{t("QrNote")}</p>
{error && <ErrorState message={error} />}
{links && (
<>
<QrCodeItem label={t("QrEventCode")} eventName={eventName} token={links.event.token} enabled={links.event.enabled} onToggle={onToggle(links.event.token)} />
{links.members.map((m) => {
const label = m.username ? `${m.name} (${m.username})` : m.name;
return (
<QrCodeItem key={m.token} label={label} eventName={eventName} fileLabel={label} token={m.token} enabled={m.enabled} onToggle={onToggle(m.token)} />
);
})}
</>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,52 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { forwardRef } from "react";
vi.mock("qrcode.react", () => ({
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
QRCodeCanvas: forwardRef<HTMLCanvasElement, { value: string }>(function C({ value }, ref) {
return <canvas ref={(el) => { if (el) el.toDataURL = () => "data:image/png;base64,AAA"; if (typeof ref === "function") ref(el); else if (ref) ref.current = el; }} data-value={value} />;
}),
}));
import { QrCodeItem } from "./QrCodeItem";
let clicked: HTMLAnchorElement | undefined;
beforeEach(() => {
clicked = undefined;
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) { clicked = this; });
});
afterEach(() => vi.restoreAllMocks());
describe("QrCodeItem", () => {
it("renders the QR for the origin link, copies it and downloads a slugified PNG", async () => {
const user = userEvent.setup(); // installs a clipboard stub on navigator
const writeText = vi.spyOn(navigator.clipboard, "writeText");
const link = `${window.location.origin}/r/abc`;
render(<QrCodeItem label="Aini Binti" eventName="Expo 2026!" fileLabel="Aini Binti" token="abc" enabled />);
expect(screen.getByTestId("qr-svg").getAttribute("data-value")).toBe(link);
expect(screen.getByText(link)).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Copy link" }));
expect(writeText).toHaveBeenCalledWith(link);
await user.click(screen.getByRole("button", { name: "Download PNG" }));
expect(clicked?.download).toBe("expo-2026-aini-binti-qr.png");
expect(clicked?.href).toBe("data:image/png;base64,AAA");
});
it("uses event as the file name part when there is no member", async () => {
const user = userEvent.setup();
render(<QrCodeItem label="Event code" eventName="Expo" token="abc" enabled />);
await user.click(screen.getByRole("button", { name: "Download PNG" }));
expect(clicked?.download).toBe("expo-event-qr.png");
});
it("shows a switch only when a toggle handler is given", async () => {
const onToggle = vi.fn();
const { rerender } = render(<QrCodeItem label="x" eventName="E" token="t" enabled onToggle={onToggle} />);
await userEvent.click(screen.getByRole("switch"));
expect(onToggle).toHaveBeenCalledWith(false);
rerender(<QrCodeItem label="x" eventName="E" token="t" enabled />);
expect(screen.queryByRole("switch")).toBeNull();
});
});
@@ -0,0 +1,69 @@
"use client";
import { useRef, useState } from "react";
import { QRCodeCanvas, QRCodeSVG } from "qrcode.react";
import { Copy, Download } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Switch } from "@/app/components/ui/switch";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
/** One registration code: QR, link, copy, PNG download and (when onToggle is given) an on/off switch. */
export function QrCodeItem({
label,
eventName,
fileLabel,
token,
enabled,
onToggle,
}: {
label: string;
eventName: string;
/** Member name for the download file name; omit for the event code. */
fileLabel?: string;
token: string;
enabled: boolean;
onToggle?: (enabled: boolean) => void;
}) {
const t = useT();
const canvas = useRef<HTMLCanvasElement>(null);
const [copied, setCopied] = useState(false);
const link = `${window.location.origin}/r/${token}`;
async function copy() {
await navigator.clipboard.writeText(link);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
function download() {
if (!canvas.current) return;
const a = document.createElement("a");
a.href = canvas.current.toDataURL("image/png");
a.download = `${slug(eventName)}-${slug(fileLabel || "event")}-qr.png`;
a.click();
}
return (
<div className="flex flex-col gap-3 rounded-lg border p-4 sm:flex-row sm:items-center">
<QRCodeSVG value={link} size={128} className="shrink-0" />
<QRCodeCanvas ref={canvas} value={link} size={512} className="hidden" />
<div className="min-w-0 flex-1 space-y-2">
<p className="text-sm font-medium">{label}</p>
<p className="break-all text-xs text-muted-foreground">{link}</p>
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" onClick={copy}>
<Copy aria-hidden="true" className="size-4" />
{copied ? t("QrCopied") : t("QrCopy")}
</Button>
<Button variant="outline" size="sm" onClick={download}>
<Download aria-hidden="true" className="size-4" />
{t("QrDownload")}
</Button>
{onToggle && <Switch checked={enabled} onCheckedChange={onToggle} aria-label={t("QrEnabled")} />}
</div>
</div>
</div>
);
}
@@ -24,7 +24,7 @@ const badgeVariants = cva(
// Category tones (feedback 2026-10-21: every type/fulfilment pill was the same beige). For
// kinds, not states — status keeps positive/warning/negative. Each pill keeps its text label,
// so colour is never the only signal.
contrast: "border-contrast/30 bg-contrast-soft text-contrast-foreground",
contrast: "bg-accent text-accent-foreground",
teal: "border-chart-2/30 bg-chart-2/10 text-chart-2",
violet: "border-chart-4/30 bg-chart-4/10 text-chart-4",
link: "text-primary underline-offset-4 [a&]:hover:underline",
@@ -7,7 +7,7 @@ function Card({ className, ...props }: React.ComponentProps<"div">) {
<div
data-slot="card"
className={cn(
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
"flex flex-col gap-6 rounded-lg border bg-card py-6 text-card-foreground shadow-card",
className
)}
{...props}
@@ -75,7 +75,7 @@ function DialogContent({
ref={setRefs}
data-slot="dialog-content"
className={cn(
"fixed inset-0 z-50 m-auto grid h-fit w-full max-w-[calc(100%-2rem)] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
"fixed inset-0 z-50 m-auto grid h-fit w-full max-w-[calc(100%-2rem)] gap-4 rounded-lg border bg-card p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
className
)}
{...props}
@@ -8,7 +8,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
type={type}
data-slot="input"
className={cn(
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
"h-9 w-full min-w-0 rounded-md border border-input bg-card px-3 py-1 text-base shadow-sm transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
"aria-[invalid=true]:border-destructive aria-[invalid=true]:ring-destructive/20 dark:aria-[invalid=true]:ring-destructive/40",
className
@@ -37,7 +37,7 @@ function SelectTrigger({
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-sm transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-destructive aria-[invalid=true]:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 [&>[data-slot=select-value]]:line-clamp-1 [&>[data-slot=select-value]]:min-w-0 [&>[data-slot=select-value]]:overflow-hidden [&>[data-slot=select-value]]:flex [&>[data-slot=select-value]]:items-center [&>[data-slot=select-value]]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-[invalid=true]:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-card px-3 py-2 text-sm whitespace-nowrap shadow-sm transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-destructive aria-[invalid=true]:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 [&>[data-slot=select-value]]:line-clamp-1 [&>[data-slot=select-value]]:min-w-0 [&>[data-slot=select-value]]:overflow-hidden [&>[data-slot=select-value]]:flex [&>[data-slot=select-value]]:items-center [&>[data-slot=select-value]]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-[invalid=true]:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
@@ -76,7 +76,7 @@ export function ErrorState({
export function TableSkeleton({ rows = 5, columns = 4 }: { rows?: number; columns?: number }) {
const t = useT()
return (
<div role="status" className="space-y-3 rounded-xl border bg-card p-3">
<div role="status" className="space-y-3 rounded-lg border bg-card shadow-card p-3">
<span className="sr-only">{t("UiLoading")}</span>
{Array.from({ length: rows }).map((_, r) => (
<div key={r} className="flex gap-3">
@@ -23,7 +23,7 @@ function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
// A gold header row with dusty-blue text (--table-head; owner request 2026-10-23). Opaque, so
// A slate header row (--table-head). Opaque, so
// a sticky header still covers the rows scrolling under it.
className={cn("bg-table-head [&_tr]:border-b [&_tr]:hover:bg-transparent", className)}
{...props}
@@ -7,6 +7,7 @@ import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { Switch } from "@/app/components/ui/switch";
import { ErrorState } from "@/app/components/ui/states";
import { roleLabel } from "@/app/lib/roleLabel";
@@ -220,20 +221,17 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
{showCompany && (
<div className="space-y-1.5">
<Label htmlFor="user-company">{t("Company")}</Label>
<select
id="user-company"
value={company}
onChange={(e) => setCompany(e.target.value)}
disabled={saving}
aria-invalid={!!fieldErrors.company}
className="h-9 w-full rounded-md border bg-background px-2 text-sm"
>
<option value="" />
{scope.companies.map((c) => (
<option key={c.id} value={c.id}>{c.code}</option>
))}
<option value="super">{t("CompanySuperAdmin")}</option>
</select>
<Select value={company} onValueChange={(v) => setCompany(v)} disabled={saving}>
<SelectTrigger id="user-company" aria-invalid={!!fieldErrors.company} className="w-full">
<SelectValue placeholder={t("SelectCompany")} />
</SelectTrigger>
<SelectContent>
{scope.companies.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>
))}
<SelectItem value="super">{t("CompanySuperAdmin")}</SelectItem>
</SelectContent>
</Select>
{fieldErrors.company && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.company}
@@ -59,6 +59,12 @@ beforeEach(() => {
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
});
// Radix selects: open the combobox, then click the option (a native selectOptions no longer applies).
const pick = async (user: ReturnType<typeof userEvent.setup>, label: string, option: string) => {
await user.click(screen.getByLabelText(label));
await user.click(await screen.findByRole("option", { name: option }));
};
describe("EventLeadPage", { timeout: 20000 }, () => {
it("renders NotAuthorized when the module is absent", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
@@ -86,9 +92,9 @@ describe("EventLeadPage", { timeout: 20000 }, () => {
it("prefills the editable fields from the event lead", async () => {
await open();
expect(screen.getByLabelText("Salesperson")).toHaveValue("7");
expect(screen.getByLabelText("Temperature")).toHaveValue("WARM");
expect(screen.getByLabelText("Status")).toHaveValue("CONTACTED");
expect(screen.getByLabelText("Salesperson")).toHaveTextContent("Jane Sales");
expect(screen.getByLabelText("Temperature")).toHaveTextContent("Warm");
expect(screen.getByLabelText("Status")).toHaveTextContent("Contacted");
expect(screen.getByLabelText("Product A")).toBeChecked();
expect(screen.getByLabelText("Next follow-up")).toHaveValue("01/12/2026");
expect(screen.getByLabelText("Notes")).toHaveValue("Call back");
@@ -96,7 +102,8 @@ describe("EventLeadPage", { timeout: 20000 }, () => {
it("keeps the current salesperson selectable when not on the event team list", async () => {
await open();
const select = screen.getByLabelText("Salesperson");
await userEvent.setup().click(screen.getByLabelText("Salesperson"));
const select = await screen.findByRole("listbox");
expect(within(select).getByRole("option", { name: "Jane Sales" })).toBeInTheDocument();
expect(within(select).getByRole("option", { name: "Bob Other" })).toBeInTheDocument();
expect(within(select).getByRole("option", { name: "None" })).toBeInTheDocument();
@@ -128,9 +135,9 @@ describe("EventLeadPage", { timeout: 20000 }, () => {
it("saves edited values", async () => {
const user = await open();
await user.selectOptions(screen.getByLabelText("Salesperson"), "8");
await user.selectOptions(screen.getByLabelText("Temperature"), "HOT");
await user.selectOptions(screen.getByLabelText("Status"), "WON");
await pick(user, "Salesperson", "Bob Other");
await pick(user, "Temperature", "Hot");
await pick(user, "Status", "Won");
await user.click(screen.getByLabelText("Product B"));
await user.click(screen.getByLabelText("Product C"));
pickDate("Next follow-up", "2026-12-05");
@@ -146,8 +153,8 @@ describe("EventLeadPage", { timeout: 20000 }, () => {
it("sends null for emptied fields", async () => {
const user = await open();
await user.selectOptions(screen.getByLabelText("Salesperson"), "");
await user.selectOptions(screen.getByLabelText("Temperature"), "");
await pick(user, "Salesperson", "None");
await pick(user, "Temperature", "None");
await user.clear(screen.getByLabelText("Notes"));
await user.click(screen.getByLabelText("Product A"));
await user.click(screen.getByLabelText("Product B"));
@@ -7,6 +7,7 @@ import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { DatePicker } from "@/app/components/ui/date-picker";
import { Label } from "@/app/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
@@ -27,7 +28,9 @@ const CODE_MESSAGE: Record<string, string> = {
INVALID_VALUE: "LeadErrInvalidValue",
};
const FIELDS = ["salespersonId", "temperature", "status", "interestIds", "nextFollowUpDate", "notes"];
const SELECT_CLASS = "min-h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
// Radix Select rejects "" as an item value, so "None" is this sentinel, mapped back to "".
const NONE = "none";
const TEXTAREA_CLASS = "min-h-11 w-full rounded-md border border-input bg-card px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
const TALL = "min-h-11";
type Loaded = { lead: EventLeadRow; salespeople: SalespersonOption[]; interests: InterestOption[] };
@@ -156,19 +159,28 @@ function EventLead() {
</div>
{field("salespersonId", t("LeadSalesperson"),
<select {...fieldProps("salespersonId")} className={SELECT_CLASS} value={salespersonId} onChange={(e) => setSalespersonId(e.target.value)} disabled={busy}>
<option value="">{t("LeadNone")}</option>
{salespeople.map((s) => <option key={s.id} value={String(s.id)}>{s.name}</option>)}
</select>)}
<Select value={salespersonId || NONE} onValueChange={(v) => setSalespersonId(v === NONE ? "" : v)} disabled={busy}>
<SelectTrigger {...fieldProps("salespersonId")} className="min-h-11 w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>{t("LeadNone")}</SelectItem>
{salespeople.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
</SelectContent>
</Select>)}
{field("temperature", t("LeadTemperature"),
<select {...fieldProps("temperature")} className={SELECT_CLASS} value={temperature} onChange={(e) => setTemperature(e.target.value)} disabled={busy}>
<option value="">{t("LeadNone")}</option>
{TEMPERATURES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
</select>)}
<Select value={temperature || NONE} onValueChange={(v) => setTemperature(v === NONE ? "" : v)} disabled={busy}>
<SelectTrigger {...fieldProps("temperature")} className="min-h-11 w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>{t("LeadNone")}</SelectItem>
{TEMPERATURES.map(([v, k]) => <SelectItem key={v} value={v}>{t(k)}</SelectItem>)}
</SelectContent>
</Select>)}
{field("status", t("LeadStatus"),
<select {...fieldProps("status")} className={SELECT_CLASS} value={status} onChange={(e) => setStatus(e.target.value)} disabled={busy}>
{STATUSES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
</select>)}
<Select value={status} onValueChange={setStatus} disabled={busy}>
<SelectTrigger {...fieldProps("status")} className="min-h-11 w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{STATUSES.map(([v, k]) => <SelectItem key={v} value={v}>{t(k)}</SelectItem>)}
</SelectContent>
</Select>)}
<fieldset {...fieldProps("interestIds")} className="space-y-1">
<legend className="mb-1.5 text-sm font-medium">{t("LeadInterests")}</legend>
@@ -184,7 +196,7 @@ function EventLead() {
{field("nextFollowUpDate", t("LeadNextFollowUp"),
<DatePicker {...fieldProps("nextFollowUpDate")} className="h-11" value={nextFollowUpDate} onChange={setNextFollowUpDate} disabled={busy} />)}
{field("notes", t("LeadNotes"),
<textarea {...fieldProps("notes")} className={`${SELECT_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
<textarea {...fieldProps("notes")} className={`${TEXTAREA_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
<div className="flex flex-col-reverse gap-3 sm:flex-row">
{backLink}
@@ -27,6 +27,11 @@ import { ApiError } from "@/app/lib/clientApi";
import { memoryRouter } from "@/test/memoryRouter";
import NewEventLeadPage from "./page";
// Radix selects: open the combobox, then click the option (a native selectOptions no longer applies).
const pick = async (user: ReturnType<typeof userEvent.setup>, label: string, option: string) => {
await user.click(screen.getByLabelText(label));
await user.click(await screen.findByRole("option", { name: option }));
};
const SERVER_MSG = "Server says: internal detail xyz";
const apiError = (code: string, extra: { errors?: string[]; details?: Record<string, unknown> } = {}) =>
new ApiError(SERVER_MSG, 400, { code, errors: [], details: {}, ...extra });
@@ -171,13 +176,17 @@ describe("NewEventLeadPage", { timeout: 20000 }, () => {
await user.type(screen.getByLabelText("Company"), "Initech");
await user.type(screen.getByLabelText("Job title"), "COO");
await user.type(screen.getByLabelText("Notes"), "Met at booth");
expect(screen.getByLabelText("Status")).toHaveValue("OPEN");
expect(screen.getByLabelText("Status")).toHaveTextContent("Open");
expect(screen.getByLabelText("Status")).toHaveClass("min-h-11");
expect(within(screen.getByLabelText("Temperature")).getByRole("option", { name: "Hot" })).toBeInTheDocument();
await user.click(screen.getByLabelText("Temperature"));
expect(within(await screen.findByRole("listbox")).getByRole("option", { name: "Hot" })).toBeInTheDocument();
await user.keyboard("{Escape}");
await user.click(screen.getByLabelText("Salesperson"));
expect(await screen.findByRole("option", { name: "Jane Sales" })).toBeInTheDocument();
await user.selectOptions(screen.getByLabelText("Salesperson"), "7");
await user.selectOptions(screen.getByLabelText("Temperature"), "HOT");
await user.selectOptions(screen.getByLabelText("Status"), "QUALIFIED");
await user.keyboard("{Escape}");
await pick(user, "Salesperson", "Jane Sales");
await pick(user, "Temperature", "Hot");
await pick(user, "Status", "Qualified");
expect(screen.queryByLabelText("Product B")).toBeNull();
await user.click(await screen.findByLabelText("Product A"));
pickDate("Next follow-up", "2026-12-05");
@@ -199,6 +208,42 @@ describe("NewEventLeadPage", { timeout: 20000 }, () => {
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1"));
});
it("opens styled menus for salesperson, temperature and status, and saves the chosen values", async () => {
const user = await toStep1Match([]);
await user.type(await screen.findByLabelText("Name"), "Dee Menu");
const menu = async (label: string) => {
await user.click(screen.getByLabelText(label));
return within(await screen.findByRole("listbox")).getAllByRole("option").map((o) => o.textContent);
};
expect(await menu("Salesperson")).toEqual(["None", "Jane Sales"]);
await user.keyboard("{Escape}");
expect(await menu("Temperature")).toEqual(["None", "Hot", "Warm", "Cold"]);
await user.keyboard("{Escape}");
expect(await menu("Status")).toEqual(["Open", "Contacted", "Qualified", "Won", "Lost"]);
await user.keyboard("{Escape}");
await pick(user, "Salesperson", "Jane Sales");
await pick(user, "Temperature", "Warm");
await pick(user, "Status", "Won");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1));
expect(mocks.captureEventLead.mock.calls[0][1]).toMatchObject({ salespersonId: 7, temperature: "WARM", status: "WON" });
});
it("a dropdown opens with Space, moves with the arrow keys and chooses with Enter", async () => {
const user = await toStep1Match([]);
await user.type(await screen.findByLabelText("Name"), "Kay Board");
await screen.findByLabelText("Temperature");
await user.tab();
screen.getByLabelText("Temperature").focus();
await user.keyboard(" ");
expect(await screen.findByRole("listbox")).toBeVisible();
await user.keyboard("{ArrowDown}{Enter}");
expect(screen.getByLabelText("Temperature")).toHaveTextContent("Hot");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1));
expect(mocks.captureEventLead.mock.calls[0][1]).toMatchObject({ temperature: "HOT" });
});
it("Back returns to step 1", async () => {
const user = await toStep1Match([]);
await user.click(await screen.findByRole("button", { name: "Back" }));
@@ -298,17 +343,17 @@ describe("NewEventLeadPage", { timeout: 20000 }, () => {
it("preselects the capturing user as salesperson when on the team", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true, id: 7 });
const user = await toStep1Match([]);
await screen.findByRole("option", { name: "Jane Sales" });
await waitFor(() => expect(screen.getByLabelText("Salesperson")).toHaveValue("7"));
await waitFor(() => expect(screen.getByLabelText("Salesperson")).toHaveTextContent("Jane Sales"));
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledWith("evt-1", expect.objectContaining({ salespersonId: 7 })));
});
it("leaves the salesperson empty when the capturing user is not on the team", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true, id: 99 });
await toStep1Match([]);
const user = await toStep1Match([]);
await user.click(await screen.findByLabelText("Salesperson"));
await screen.findByRole("option", { name: "Jane Sales" });
expect(screen.getByLabelText("Salesperson")).toHaveValue("");
expect(screen.getByLabelText("Salesperson")).toHaveTextContent("None");
});
it("keeps the options-load failure visible after matching", async () => {
@@ -7,6 +7,7 @@ import { Button } from "@/app/components/ui/button";
import { DatePicker } from "@/app/components/ui/date-picker";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { PageHeader } from "@/app/components/ui/page-header";
import { ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
@@ -30,7 +31,9 @@ const CODE_MESSAGE: Record<string, string> = {
};
// Codes that name their field themselves when the server omits details.field.
const IMPLIED_FIELD: Record<string, string> = { INVALID_MOBILE: "mobile", INVALID_EMAIL: "email" };
const SELECT_CLASS = "min-h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
// Radix Select rejects "" as an item value, so "None" is this sentinel, mapped back to "".
const NONE = "none";
const TEXTAREA_CLASS = "min-h-11 w-full rounded-md border border-input bg-card px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
const TALL = "min-h-11";
type Step = "match" | "details";
@@ -272,19 +275,28 @@ function NewEventLead() {
)}
{field("salespersonId", t("LeadSalesperson"),
<select {...fieldProps("salespersonId")} className={SELECT_CLASS} value={salespersonId} onChange={(e) => setSalespersonId(e.target.value)} disabled={busy}>
<option value="">{t("LeadNone")}</option>
{salespeople.map((s) => <option key={s.id} value={String(s.id)}>{s.name}</option>)}
</select>)}
<Select value={salespersonId || NONE} onValueChange={(v) => setSalespersonId(v === NONE ? "" : v)} disabled={busy}>
<SelectTrigger {...fieldProps("salespersonId")} className="min-h-11 w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>{t("LeadNone")}</SelectItem>
{salespeople.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
</SelectContent>
</Select>)}
{field("temperature", t("LeadTemperature"),
<select {...fieldProps("temperature")} className={SELECT_CLASS} value={temperature} onChange={(e) => setTemperature(e.target.value)} disabled={busy}>
<option value="">{t("LeadNone")}</option>
{TEMPERATURES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
</select>)}
<Select value={temperature || NONE} onValueChange={(v) => setTemperature(v === NONE ? "" : v)} disabled={busy}>
<SelectTrigger {...fieldProps("temperature")} className="min-h-11 w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>{t("LeadNone")}</SelectItem>
{TEMPERATURES.map(([v, k]) => <SelectItem key={v} value={v}>{t(k)}</SelectItem>)}
</SelectContent>
</Select>)}
{field("status", t("LeadStatus"),
<select {...fieldProps("status")} className={SELECT_CLASS} value={status} onChange={(e) => setStatus(e.target.value)} disabled={busy}>
{STATUSES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
</select>)}
<Select value={status} onValueChange={setStatus} disabled={busy}>
<SelectTrigger {...fieldProps("status")} className="min-h-11 w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{STATUSES.map(([v, k]) => <SelectItem key={v} value={v}>{t(k)}</SelectItem>)}
</SelectContent>
</Select>)}
<fieldset {...fieldProps("interestIds")} className="space-y-1">
<legend className="mb-1.5 text-sm font-medium">{t("LeadInterests")}</legend>
@@ -300,7 +312,7 @@ function NewEventLead() {
{field("nextFollowUpDate", t("LeadNextFollowUp"),
<DatePicker {...fieldProps("nextFollowUpDate")} className="h-11" value={nextFollowUpDate} onChange={setNextFollowUpDate} disabled={busy} />)}
{field("notes", t("LeadNotes"),
<textarea {...fieldProps("notes")} className={`${SELECT_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
<textarea {...fieldProps("notes")} className={`${TEXTAREA_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
<div className="flex flex-col-reverse gap-3 sm:flex-row">
<Button type="button" variant="outline" className={TALL} onClick={() => { setFieldErrors({}); setFormError(null); setStep("match"); }} disabled={busy}>{t("Back")}</Button>
@@ -206,7 +206,7 @@ function EventLeadsDetailPageContent() {
accessorKey: "nextFollowUpDate",
header: t("LeadNextFollowUp"),
enableSorting: false,
cell: ({ row }) => <span>{row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}</span>,
cell: ({ row }) => <span className="tabular">{row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}</span>,
},
],
[t, showCompanyColumn, codeOf],
@@ -6,6 +6,8 @@ import { Alert, AlertDescription } from "@/app/components/ui/alert";
import { PageHeader } from "@/app/components/ui/page-header";
import { Skeleton } from "@/app/components/ui/skeleton";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RegistrationQrCard } from "@/app/components/events/RegistrationQrCard";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { RequireModule } from "@/app/lib/RequireModule";
import { ApiError } from "@/app/lib/clientApi";
import { getAdminEvent, saveAdminEvent } from "@/app/lib/services/adminEvents";
@@ -18,6 +20,7 @@ function EditEventPageContent() {
const { uuid } = useParams<{ uuid: string }>();
const searchParams = useSearchParams();
const { hasModule } = useAdminAuth();
const [event, setEvent] = useState<AdminEvent | null>(null);
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
@@ -114,6 +117,9 @@ function EditEventPageContent() {
)}
<EventForm initial={event} onSubmit={handleSubmit} submitLabel={t("Save")} />
{/* ponytail: no read-only role for events yet; the events module is the write gate for the code switches. */}
<RegistrationQrCard eventUuid={event.uuid} eventName={event.name} canWrite={hasModule("BO_EVENTS")} />
</div>
);
}
+3 -3
View File
@@ -25,7 +25,7 @@ import { formatDmy } from "@/app/lib/date-input";
const DEFAULTS = { q: "", enabled: "" };
export const EVENT_STATUS_FILTER_OPTIONS = [{ value: "Y", label: "Enabled" }, { value: "N", label: "Disabled" }];
const EVENT_STATUS_FILTER_OPTIONS = [{ value: "Y", label: "Enabled" }, { value: "N", label: "Disabled" }];
function EventsPageContent() {
const t = useT();
@@ -84,12 +84,12 @@ function EventsPageContent() {
{
accessorKey: "startDate",
header: t("EvtStartDate"),
cell: ({ row }) => <span>{formatDmy(row.original.startDate)}</span>,
cell: ({ row }) => <span className="tabular">{formatDmy(row.original.startDate)}</span>,
},
{
accessorKey: "endDate",
header: t("EvtEndDate"),
cell: ({ row }) => <span>{formatDmy(row.original.endDate)}</span>,
cell: ({ row }) => <span className="tabular">{formatDmy(row.original.endDate)}</span>,
},
{
accessorKey: "enabled",
+105 -114
View File
@@ -5,162 +5,162 @@
/*
* Design tokens, ported from src/styles/_variables.scss + tailwind.css
* (Tailwind 4 @theme) into plain CSS custom properties for Tailwind 3's
* postcss-based build (see tailwind.config.ts). The old stylesheet's two
* Sass-only mixins in actual use (brand-gradient-text, custom-scrollbar) are
* folded in below as .brand-wordmark/.scrollable. Fonts (Inter, DM Sans) load
* via next/font in app/layout.tsx, which sets --font-inter / --font-dm-sans.
* postcss-based build (see tailwind.config.ts). The old stylesheet's
* Sass-only mixin in actual use (custom-scrollbar) is
* folded in below as .scrollable. Inter, the one type family,
* loads via next/font in app/layout.tsx, which sets --font-inter.
*
* CURRENT SKIN: Co-Lite. Brand primary #6E3E17 (warm brown), accent #F2BC57 (warm gold), body #121212.
* CURRENT SKIN: Co-Lite. Slate neutrals with one blue accent (--primary/--ring #2563EB).
* To re-skin for another client, edit the values below; nothing else should
* change.
*/
:root {
--radius: 1rem;
/* Data-table frames (owner request 2026-10-23: 20px read too soft for dense tables): 12px, the
scale's sm step, as its own token so tables can move independently of cards. */
--table-radius: calc(var(--radius) - 4px);
--radius: 0.5rem;
/* Data-table frames share the card radius (8px), as their own token so tables can still move
independently of cards. */
--table-radius: 8px;
/* The radius scale (tailwind.config.ts reads these). */
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-sm: 4px;
--radius-md: 6px;
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-xl: 12px;
--sidebar-width: 272px;
--sidebar-width: 240px;
--sidebar-width-collapsed: 76px;
--header-height: 64px;
--header-height: 56px;
--content-max-width: 1600px;
--background: #fdfbf7;
--foreground: #121212;
--background: #F8FAFC;
--foreground: #0F172A;
--card: #ffffff;
--card-foreground: #121212;
--card: #FFFFFF;
--card-foreground: #0F172A;
--popover: #ffffff;
--popover-foreground: #121212;
--popover: #FFFFFF;
--popover-foreground: #0F172A;
--primary: #6e3e17;
--primary-foreground: #ffffff;
--primary: #2563EB;
--primary-foreground: #FFFFFF;
--secondary: #f5ede3;
--secondary-foreground: #3a2410;
--secondary: #F1F5F9;
--secondary-foreground: #0F172A;
--muted: #f7f2ea;
--muted-foreground: #6f5b48;
--muted: #F1F5F9;
--muted-foreground: #475569;
--accent: #f2bc57;
--accent-foreground: #3a2410;
--accent-strong: #9a6212;
--accent: #EFF6FF;
--accent-foreground: #1D4ED8;
--accent-strong: #1D4ED8;
--positive: #1b6e3e;
--negative: #b3261e;
--warning: #8f5200;
--positive: #15803D;
--negative: #B91C1C;
--warning: #B45309;
--destructive: #b3261e;
--destructive-foreground: #ffffff;
--destructive: #DC2626;
--destructive-foreground: #FFFFFF;
--border: #ede4d8;
--input: #8d7761;
--ring: #6e3e17;
--border: #E2E8F0;
--input: #7C8BA1;
--ring: #2563EB;
--chart-1: #6e3e17;
--chart-2: #1f6f6b;
--chart-3: #a15c00;
--chart-4: #7b5ac6;
--chart-5: #a63d5b;
--chart-1: #2563EB;
--chart-2: #0F766E;
--chart-3: #D97706;
--chart-4: #7C3AED;
--chart-5: #E11D48;
/* The contrast colour (dusty blue, approved 2026-10-22 — design.md Part 3): type/category pills
and secondary highlights. Never a primary action, never status. */
--contrast: #4f7396;
--contrast-foreground: #3e5c7a;
--contrast-soft: #e4ecf3;
/* Data-table header row (owner request 2026-10-23: gold with dusty-blue text instead of light
brown). Soft gold, not the full --accent: dusty blue on full gold is only 4.0:1. Opaque, so a
sticky header covers the rows under it. */
--table-head: #f7d99a;
--table-head-foreground: #3e5c7a;
/* Data-table header row: a slate tint with slate text. Opaque, so a sticky header covers the
rows under it. */
--table-head: #F1F5F9;
--table-head-foreground: #475569;
/* Giraffe-spot brand pattern (same artwork as the customer portal's --giraffe-motif): a seamless
tile of coat patches, shape only — used as a mask by .giraffe-spots below. */
--giraffe-tile: 180px;
--giraffe-motif: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="180" height="180" viewBox="0 0 180 180"%3E%3Cpath d="M9.1 -0.2Q15.0 -5.6 23.9 -5.3L37.9 -4.9Q46.8 -4.6 50.4 -1.0L56.1 4.7Q59.7 8.4 56.0 18.6L50.2 34.8Q46.6 45.0 37.4 47.5L23.1 51.3Q13.9 53.7 8.9 47.6L0.9 38.0Q-4.1 31.9 -4.7 26.9L-5.6 18.9Q-6.2 13.8 -0.2 8.4ZM9.1 179.8Q15.0 174.4 23.9 174.7L37.9 175.1Q46.8 175.4 50.4 179.0L56.1 184.7Q59.7 188.4 56.0 198.6L50.2 214.8Q46.6 225.0 37.4 227.5L23.1 231.3Q13.9 233.7 8.9 227.6L0.9 218.0Q-4.1 211.9 -4.7 206.9L-5.6 198.9Q-6.2 193.8 -0.2 188.4ZM230.2 34.8Q226.6 45.0 217.4 47.5L203.1 51.3Q193.9 53.7 188.9 47.6L180.9 38.0Q175.9 31.9 175.3 26.9L174.4 18.9Q173.8 13.8 179.8 8.4L189.1 -0.2Q195.0 -5.6 203.9 -5.3L217.9 -4.9Q226.8 -4.6 230.4 -1.0L236.1 4.7Q239.7 8.4 236.0 18.6ZM230.2 214.8Q226.6 225.0 217.4 227.5L203.1 231.3Q193.9 233.7 188.9 227.6L180.9 218.0Q175.9 211.9 175.3 206.9L174.4 198.9Q173.8 193.8 179.8 188.4L189.1 179.8Q195.0 174.4 203.9 174.7L217.9 175.1Q226.8 175.4 230.4 179.0L236.1 184.7Q239.7 188.4 236.0 198.6ZM12.7 70.7Q15.2 58.5 24.3 56.1L38.6 52.3Q47.8 49.9 55.8 57.4L68.3 69.3Q76.4 76.9 70.4 86.7L61.1 102.2Q55.1 112.1 41.5 109.3L20.1 104.8Q6.4 101.9 8.9 89.8ZM49.1 156.8Q45.9 170.4 37.5 170.1L24.4 169.7Q16.0 169.5 11.5 152.7L4.4 126.3Q-0.2 109.5 1.0 108.7L2.9 107.4Q4.0 106.5 18.2 109.5L40.5 114.2Q54.7 117.1 55.4 118.5L56.5 120.6Q57.2 121.9 54.0 135.5ZM229.1 156.8Q225.9 170.4 217.5 170.1L204.4 169.7Q196.0 169.5 191.5 152.7L184.4 126.3Q179.8 109.5 181.0 108.7L182.9 107.4Q184.0 106.5 198.2 109.5L220.5 114.2Q234.7 117.1 235.4 118.5L236.5 120.6Q237.2 121.9 234.0 135.5ZM59.5 54.1Q51.4 46.4 55.0 36.3L60.7 20.3Q64.4 10.2 74.6 9.7L90.7 9.0Q101.0 8.6 103.9 24.4L108.5 49.3Q111.4 65.2 111.2 65.8L110.9 66.8Q110.6 67.4 102.2 69.2L88.8 72.0Q80.3 73.7 72.2 66.1ZM78.1 126.0Q61.6 119.6 61.0 118.3L59.9 116.3Q59.2 115.0 65.4 104.8L75.0 88.8Q81.1 78.7 89.6 76.9L103.0 74.1Q111.5 72.4 119.4 83.5L131.8 100.9Q139.6 112.1 134.2 120.5L125.7 133.8Q120.3 142.3 103.9 135.9ZM74.3 4.7Q63.6 5.2 60.0 1.5L54.3 -4.2Q50.6 -7.9 53.7 -21.1L58.6 -41.8Q61.6 -55.0 77.6 -48.8L102.8 -39.1Q118.8 -32.9 118.7 -27.7L118.6 -19.5Q118.6 -14.2 113.9 -9.3L106.6 -1.4Q101.9 3.5 91.2 4.0ZM74.3 184.7Q63.6 185.2 60.0 181.5L54.3 175.8Q50.6 172.1 53.7 158.9L58.6 138.2Q61.6 125.0 77.6 131.2L102.8 140.9Q118.8 147.1 118.7 152.3L118.6 160.5Q118.6 165.8 113.9 170.7L106.6 178.6Q101.9 183.5 91.2 184.0ZM155.6 7.5Q168.9 14.4 169.4 19.2L170.3 26.8Q170.8 31.6 155.4 40.0L131.2 53.1Q115.8 61.5 113.0 46.2L108.5 22.1Q105.7 6.8 110.2 2.0L117.1 -5.4Q121.6 -10.1 134.8 -3.3ZM155.6 187.5Q168.9 194.4 169.4 199.2L170.3 206.8Q170.8 211.6 155.4 220.0L131.2 233.1Q115.8 241.5 113.0 226.2L108.5 202.1Q105.7 186.8 110.2 182.0L117.1 174.6Q121.6 169.9 134.8 176.7ZM-56.7 80.4Q-64.7 69.2 -64.5 68.6L-64.2 67.7Q-64.0 67.1 -48.1 58.4L-23.0 44.8Q-7.1 36.1 -2.2 42.0L5.4 51.3Q10.3 57.2 7.8 69.8L3.8 89.7Q1.2 102.4 -0.2 103.4L-2.5 105.0Q-3.9 106.0 -13.0 107.0L-27.1 108.4Q-36.2 109.3 -44.1 98.1ZM123.3 80.4Q115.3 69.2 115.5 68.6L115.8 67.7Q116.0 67.1 131.9 58.4L157.0 44.8Q172.9 36.1 177.8 42.0L185.4 51.3Q190.3 57.2 187.8 69.8L183.8 89.7Q181.2 102.4 179.8 103.4L177.5 105.0Q176.1 106.0 167.0 107.0L152.9 108.4Q143.8 109.3 135.9 98.1ZM-13.6 -68.0Q-4.9 -68.9 -0.4 -52.1L6.7 -25.7Q11.2 -8.9 5.5 -3.7L-3.5 4.5Q-9.2 9.8 -22.4 2.9L-43.2 -7.9Q-56.4 -14.7 -56.4 -20.1L-56.2 -28.5Q-56.2 -33.9 -50.5 -42.8L-41.6 -56.8Q-35.9 -65.7 -27.2 -66.6ZM-13.6 112.0Q-4.9 111.1 -0.4 127.9L6.7 154.3Q11.2 171.1 5.5 176.3L-3.5 184.5Q-9.2 189.8 -22.4 182.9L-43.2 172.1Q-56.4 165.3 -56.4 159.9L-56.2 151.5Q-56.2 146.1 -50.5 137.2L-41.6 123.2Q-35.9 114.3 -27.2 113.4ZM166.4 -68.0Q175.1 -68.9 179.6 -52.1L186.7 -25.7Q191.2 -8.9 185.5 -3.7L176.5 4.5Q170.8 9.8 157.6 2.9L136.8 -7.9Q123.6 -14.7 123.6 -20.1L123.8 -28.5Q123.8 -33.9 129.5 -42.8L138.4 -56.8Q144.1 -65.7 152.8 -66.6ZM166.4 112.0Q175.1 111.1 179.6 127.9L186.7 154.3Q191.2 171.1 185.5 176.3L176.5 184.5Q170.8 189.8 157.6 182.9L136.8 172.1Q123.6 165.3 123.6 159.9L123.8 151.5Q123.8 146.1 129.5 137.2L138.4 123.2Q144.1 114.3 152.8 113.4Z"/%3E%3C/svg%3E');
--sidebar: #ffffff;
--sidebar-foreground: #121212;
--sidebar-primary: #6e3e17;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #f7f2ea;
--sidebar-accent-foreground: #6e3e17;
--sidebar-border: #ede4d8;
--sidebar-ring: #6e3e17;
--sidebar: #FFFFFF;
--sidebar-foreground: #0F172A;
--sidebar-primary: #2563EB;
--sidebar-primary-foreground: #FFFFFF;
--sidebar-accent: #EFF6FF;
--sidebar-accent-foreground: #1D4ED8;
--sidebar-border: #E2E8F0;
--sidebar-ring: #2563EB;
--font-heading: var(--font-dm-sans), ui-sans-serif, system-ui, sans-serif;
--shadow-card: 0 1px 2px rgb(15 23 42 / 0.06), 0 1px 3px rgb(15 23 42 / 0.04);
--font-heading: var(--font-sans);
--font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
--font-mono: var(--font-sans);
}
.dark {
--background: #17120f;
--foreground: #f8f4ef;
--background: #020617;
--foreground: #F1F5F9;
--card: #211a16;
--card-foreground: #f8f4ef;
--card: #0F172A;
--card-foreground: #F1F5F9;
--popover: #211a16;
--popover-foreground: #f8f4ef;
--popover: #0F172A;
--popover-foreground: #F1F5F9;
--primary: #d9a05b;
--primary-foreground: #241a10;
--primary: #60A5FA;
--primary-foreground: #0B1220;
--secondary: #2e251f;
--secondary-foreground: #f8f4ef;
--secondary: #1E293B;
--secondary-foreground: #F1F5F9;
--muted: #2e251f;
--muted-foreground: #bca994;
--muted: #1E293B;
--muted-foreground: #94A3B8;
--accent: #f2bc57;
--accent-foreground: #241a10;
--accent-strong: #f2bc57;
--accent: #172554;
--accent-foreground: #BFDBFE;
--accent-strong: #93C5FD;
--positive: #6fcf97;
--negative: #f08a82;
--warning: #f0b94a;
--positive: #4ADE80;
--negative: #F87171;
--warning: #FBBF24;
--destructive: #f08a82;
--destructive-foreground: #241a10;
--destructive: #F87171;
--destructive-foreground: #0B1220;
--border: #332a23;
--input: #7a6a5c;
--ring: #d9a05b;
--border: #1E293B;
--input: #64748B;
--ring: #60A5FA;
--chart-1: #d9a05b;
--chart-2: #5fc9c0;
--chart-3: #f0b94a;
--chart-4: #b49bf0;
--chart-5: #e88aa5;
--chart-1: #60A5FA;
--chart-2: #2DD4BF;
--chart-3: #FBBF24;
--chart-4: #A78BFA;
--chart-5: #FB7185;
--contrast: #9db8d2;
--contrast-foreground: #dbe7f2;
--contrast-soft: #22303d;
--table-head: #4a3a1a;
--table-head-foreground: #dbe7f2;
--table-head: #1E293B;
--table-head-foreground: #CBD5E1;
--sidebar: #211a16;
--sidebar-foreground: #f8f4ef;
--sidebar-primary: #d9a05b;
--sidebar-primary-foreground: #241a10;
--sidebar-accent: #2e251f;
--sidebar-accent-foreground: #f2bc57;
--sidebar-border: #332a23;
--sidebar-ring: #d9a05b;
--sidebar: #0F172A;
--sidebar-foreground: #F1F5F9;
--sidebar-primary: #60A5FA;
--sidebar-primary-foreground: #0B1220;
--sidebar-accent: #172554;
--sidebar-accent-foreground: #BFDBFE;
--sidebar-border: #1E293B;
--sidebar-ring: #60A5FA;
--shadow-card: 0 1px 2px rgb(0 0 0 / 0.4);
}
* {
border-color: var(--border);
}
::selection {
background: var(--accent);
color: var(--accent-foreground);
}
html {
scrollbar-gutter: stable;
}
@@ -209,19 +209,10 @@ h4 {
}
/*
* Ported from src/styles/_mixins.scss (brand-gradient-text, custom-scrollbar):
* plain classes rather than Sass mixins, since Tailwind 3's postcss build has
* no Sass step. Used by app/components/app/Sidebar.tsx (wordmark, scrollable nav).
* Ported from src/styles/_mixins.scss (custom-scrollbar): a plain class rather than
* a Sass mixin, since Tailwind 3's postcss build has no Sass step. Used by
* app/components/app/Sidebar.tsx (scrollable nav).
*/
.brand-wordmark {
background-image: linear-gradient(to right, var(--primary), var(--accent));
background-clip: text;
-webkit-background-clip: text;
color: transparent;
font-family: var(--font-heading);
font-weight: 700;
}
.scrollable {
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
+35
View File
@@ -11,4 +11,39 @@ describe("globals.css", () => {
expect(css).toMatch(/html\s*\{[^}]*scrollbar-gutter:\s*stable/);
expect(css).toMatch(/html body\[data-scroll-locked\]\s*\{[^}]*margin-right:\s*0\s*!important/);
});
it("uses one type family, the Inter accent blue and the 0.5rem radius", () => {
const css = readFileSync(join(__dirname, "globals.css"), "utf8");
const block = (sel: string) => css.match(new RegExp(`${sel}\\s*\\{([\\s\\S]*?)\\n\\}`))?.[1] ?? "";
expect(css).not.toMatch(/dm-sans|DM Sans/i);
expect(block(":root")).toMatch(/--primary:\s*#2563eb/i);
expect(block("\\.dark")).toMatch(/--primary:\s*#60a5fa/i);
expect(block(":root")).toMatch(/--radius:\s*0\.5rem/);
expect(block(":root")).toMatch(/--table-head:\s*#f1f5f9/i);
expect(block("\\.dark")).toMatch(/--table-head:\s*#1e293b/i);
expect(block(":root")).toMatch(/--muted-foreground:\s*#475569/i);
expect(css).not.toMatch(/dusty|gold|brown/i);
});
// WCAG 2.x: 4.5:1 for text, 3:1 for the boundary of a form control (1.4.11).
it.each([":root", "\\.dark"])("meets WCAG contrast for text and control borders in %s", (sel) => {
const css = readFileSync(join(__dirname, "globals.css"), "utf8");
const body = css.match(new RegExp(`${sel}\\s*\\{([\\s\\S]*?)\\n\\}`))?.[1] ?? "";
const tok = (name: string) => body.match(new RegExp(`--${name}:\\s*(#[0-9a-f]{6})`, "i"))?.[1] ?? "";
const lum = (hex: string) => {
const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
const ratio = (a: string, b: string) => {
const [x, y] = [lum(tok(a)), lum(tok(b))];
return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
};
const text: [string, string][] = [
["foreground", "background"], ["foreground", "card"],
["muted-foreground", "background"], ["muted-foreground", "card"], ["muted-foreground", "muted"],
["primary-foreground", "primary"], ["destructive-foreground", "destructive"],
["accent-foreground", "accent"], ["table-head-foreground", "table-head"],
];
for (const [fg, bg] of text) expect(ratio(fg, bg), `${fg} on ${bg}`).toBeGreaterThanOrEqual(4.5);
for (const bg of ["background", "card"]) expect(ratio("input", bg), `input on ${bg}`).toBeGreaterThanOrEqual(3);
});
});
+2 -2
View File
@@ -89,10 +89,10 @@ describe("RootLayout i18n wiring", () => {
expect(el.props.lang).toBe("zh-TW");
});
it("puts the Inter and DM Sans font variable classes on html", async () => {
it("puts only the Inter font variable class on html", async () => {
const el = await RootLayout({ children: <div>page</div> });
expect(el.props.className).toContain("--font-inter");
expect(el.props.className).toContain("--font-dm-sans");
expect(el.props.className).not.toContain("--font-dm-sans");
});
// Spec: "The Admin Portal Displays Labels From The Message Catalog" -- the
+1 -7
View File
@@ -16,12 +16,6 @@ const inter = localFont({
variable: "--font-inter",
display: "swap",
});
const dmSans = localFont({
src: "./fonts/dm-sans-latin-wght-normal.woff2",
weight: "100 1000",
variable: "--font-dm-sans",
display: "swap",
});
export async function generateMetadata(): Promise<Metadata> {
const t = await getServerT();
@@ -44,7 +38,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
const [{ locale, locales }, messages] = await Promise.all([requestLocale(), requestCatalog()]);
return (
<html lang={locale.replace("_", "-")} className={`${inter.variable} ${dmSans.variable}`}>
<html lang={locale.replace("_", "-")} className={inter.variable}>
<body className="antialiased">
<LocalesProvider locales={locales}>
<MessagesProvider locale={locale} messages={messages}>
@@ -32,13 +32,19 @@ beforeEach(() => {
mocks.useAdminAuth.mockReset().mockReturnValue({ isSuper: true });
});
const openPicker = async (user: ReturnType<typeof userEvent.setup>) => {
const picker = await screen.findByRole("combobox", { name: "Company" });
await user.click(picker);
return picker;
};
describe("CompanyPicker", () => {
it("is shown to a super admin with All companies plus each company", async () => {
const user = userEvent.setup();
renderScope();
const picker = await screen.findByRole("combobox", { name: "Company" });
await waitFor(() => expect(picker.querySelectorAll("option")).toHaveLength(3));
expect([...picker.querySelectorAll("option")].map((o) => o.textContent)).toEqual(["All companies", "INS", "CV"]);
expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV");
await waitFor(() => expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV"));
await openPicker(user);
expect((await screen.findAllByRole("option")).map((o) => o.textContent)).toEqual(["All companies", "INS", "CV"]);
});
it("is not shown to staff, who never load companies or get a companyId", async () => {
@@ -53,16 +59,29 @@ describe("CompanyPicker", () => {
it("feeds the chosen company into the scope and keeps it for the tab; All companies clears it", async () => {
const user = userEvent.setup();
renderScope();
const picker = await screen.findByRole("combobox", { name: "Company" });
await waitFor(() => expect(picker.querySelectorAll("option")).toHaveLength(3));
await user.selectOptions(picker, "2");
await waitFor(() => expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV"));
await openPicker(user);
await user.click(await screen.findByRole("option", { name: "CV" }));
expect(screen.getByTestId("probe")).toHaveTextContent("2|false|CV");
expect(sessionStorage.getItem("company-scope")).toBe("2");
await user.selectOptions(picker, "");
await openPicker(user);
await user.click(await screen.findByRole("option", { name: "All companies" }));
expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV");
expect(sessionStorage.getItem("company-scope")).toBeNull();
});
it("opens with Enter, moves with the arrow keys and chooses with Enter", async () => {
const user = userEvent.setup();
renderScope();
await waitFor(() => expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV"));
const picker = await screen.findByRole("combobox", { name: "Company" });
picker.focus();
await user.keyboard("{Enter}");
await screen.findByRole("option", { name: "INS" });
await user.keyboard("{ArrowDown}{Enter}");
expect(screen.getByTestId("probe")).toHaveTextContent("1|false|CV");
});
it("restores the choice from sessionStorage", async () => {
sessionStorage.setItem("company-scope", "1");
renderScope();
@@ -20,6 +20,8 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
AllCompanies: "All companies",
CompanySuperAdmin: "Super admin (no company)",
ChooseCompany: "Choose a company.",
SelectCompany: "Select a company",
TeamNeedsCompany: "Choose a company to list its team",
SuperAdminNeedsRole: "A super admin must have the Super admin role.",
CompanyBlankForSuper: "Leave blank for super admin",
BO_COMPANIES: "Companies",
@@ -463,4 +465,41 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PwdRule_SYMBOLIC_LENGTH_MAX: "Maximum symbols",
PwdRule_NO_OTHER_LANGUAGE: "Latin characters only",
PwdRule_SPACE_NOT_ALLOWED: "No spaces",
// QR self-registration (public page, QR cards, privacy notice)
RegInactive: "This code is no longer active.",
RegLoadFailed: "Could not load this page. Try again later.",
RegName: "Your name",
RegMobile: "Mobile number",
RegEmail: "Email",
RegCompany: "Company",
RegJobTitle: "Job title",
RegInterests: "Interests (optional)",
RegNoticeEn: "English",
RegNoticeMs: "Bahasa Malaysia",
RegConsentEn: "I agree to {company} using my details as described above.",
RegConsentMs: "Saya bersetuju {company} menggunakan butiran saya seperti yang diterangkan di atas.",
RegSubmit: "Register",
RegAnother: "Register another person",
RegThanks: "Thank you, you're registered for {event}",
RegNameRequired: "Enter your name.",
RegContactRequired: "Enter a mobile number or an email.",
RegTooMany: "Too many registrations from this device. Try again later.",
RegFailed: "Could not register. Try again.",
QrCardTitle: "Registration QR",
QrEventCode: "Event code",
QrCopy: "Copy link",
QrCopied: "Link copied",
QrDownload: "Download PNG",
QrEnabled: "Enabled",
QrNote: "Paste the link into the dynamic-qr console to get a QR that can be changed later.",
QrLoadFailed: "Could not load registration codes.",
QrSaveFailed: "Could not change the code.",
QrMyTitle: "My QR codes",
QrSwitchedOff: "Switched off",
QrMyNone: "You have no registration codes yet.",
PrivNotice: "Privacy notice",
PrivSave: "Save notice",
PrivSaveFailed: "Could not save the notice.",
PrivLoadFailed: "Could not load the notice.",
PrivLastChanged: "Last changed by {user} on {date}",
};
+3 -2
View File
@@ -8,8 +8,9 @@
// resetPasswordRequired); it is reached right after login, so it stays public.
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forgot-password"]);
// /r/<token> is the QR self-registration page: visitors are not signed in. (A prefix, so PUBLIC_PATHS stays exact.)
export function isPublicPath(pathname: string): boolean {
return PUBLIC_PATHS.has(pathname);
return PUBLIC_PATHS.has(pathname) || /^\/r\/[^/]+$/.test(pathname);
}
export interface SessionState {
@@ -24,7 +25,7 @@ export function guardDecision(pathname: string, session: SessionState | null): s
return isPublicPath(pathname) ? null : "/login";
}
// A pending reset confines the session to the set-password form (/login stays reachable).
if (session?.resetRequired && pathname !== "/reset-password" && pathname !== "/login") {
if (session?.resetRequired && !/^\/r\/[^/]+$/.test(pathname) && pathname !== "/reset-password" && pathname !== "/login") {
return "/reset-password";
}
return null;
@@ -0,0 +1,41 @@
import { ApiError, apiGet, apiPut } from "@/app/lib/clientApi";
export interface RegistrationLink {
token: string;
enabled: boolean;
}
export interface EventLinks {
event: RegistrationLink;
members: (RegistrationLink & { userId: number; name: string; username: string })[];
}
export interface MyLink extends RegistrationLink {
eventUuid: string;
eventName: string;
startDate: string;
endDate: string;
location: string;
}
export interface PrivacyNotice {
id: number;
companyId: number;
textEn: string;
textMs: string;
createdBy: string;
createdAt: string;
}
export const getEventLinks = (uuid: string) => apiGet<EventLinks>(`/api/events/${encodeURIComponent(uuid)}/registration-links`);
export const setLinkEnabled = (uuid: string, token: string, enabled: boolean) =>
apiPut(`/api/events/${encodeURIComponent(uuid)}/registration-links/${encodeURIComponent(token)}`, { enabled });
export const getMyLinks = () => apiGet<MyLink[]>("/api/my-registration-links");
export async function getPrivacyNotice(companyId: number): Promise<PrivacyNotice | null> {
try {
return await apiGet<PrivacyNotice>(`/api/companies/${companyId}/privacy-notice`);
} catch (err) {
if (err instanceof ApiError && err.status === 404) return null; // no notice published yet
throw err;
}
}
export const savePrivacyNotice = (companyId: number, body: { textEn: string; textMs: string }) =>
apiPut<PrivacyNotice>(`/api/companies/${companyId}/privacy-notice`, body);
@@ -0,0 +1,32 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { getRegistration, submitRegistration } from "./publicRegistration";
import { ApiError } from "@/app/lib/clientApi";
const body = { name: "A", mobile: "", email: "a@b.co", companyName: "", jobTitle: "", interestIds: [], consent: true, website: "" };
describe("publicRegistration service", () => {
const originalLocation = window.location;
beforeEach(() => {
Object.defineProperty(window, "location", { value: { ...window.location, assign: vi.fn() }, writable: true, configurable: true });
});
afterEach(() => {
Object.defineProperty(window, "location", { value: originalLocation, writable: true, configurable: true });
vi.unstubAllGlobals();
});
it("never sends a visitor to the admin login on a 401", async () => {
vi.stubGlobal("fetch", vi.fn().mockImplementation(async () => new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 })));
await expect(getRegistration("t")).rejects.toMatchObject({ status: 401 });
await expect(submitRegistration("t", body)).rejects.toBeInstanceOf(ApiError);
expect(window.location.assign).not.toHaveBeenCalled();
});
it("posts JSON and returns the parsed body", async () => {
const f = vi.fn().mockResolvedValue(new Response(JSON.stringify({ eventName: "Expo" }), { status: 200 }));
vi.stubGlobal("fetch", f);
expect(await submitRegistration("a/b", body)).toEqual({ eventName: "Expo" });
expect(f.mock.calls[0][0]).toBe("/api/public/registration/a%2Fb");
expect(f.mock.calls[0][1].method).toBe("POST");
});
});
@@ -0,0 +1,47 @@
import { ApiError } from "@/app/lib/clientApi";
export interface RegistrationInfo {
eventName: string;
startDate: string;
endDate: string;
location: string;
companyName: string;
notice: { id: number; textEn: string; textMs: string };
interests: { id: number; name: string }[];
}
export interface RegistrationBody {
name: string;
mobile: string;
email: string;
companyName: string;
jobTitle: string;
interestIds: number[];
consent: boolean;
website: string;
}
const url = (token: string) => `/api/public/registration/${encodeURIComponent(token)}`;
// Plain fetch on purpose: clientApi redirects a 401 to the admin /login, which a visitor must never see.
async function call<T>(token: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(url(token), { ...init, headers: init?.body ? { "Content-Type": "application/json" } : {} });
} catch {
throw new ApiError("Request failed", 0);
}
const text = await res.text();
let data: unknown;
try {
data = text ? JSON.parse(text) : undefined;
} catch {
data = undefined;
}
if (!res.ok) throw new ApiError(`Request failed (${res.status})`, res.status, data);
return data as T;
}
export const getRegistration = (token: string) => call<RegistrationInfo>(token);
export const submitRegistration = (token: string, body: RegistrationBody) =>
call<{ eventName: string }>(token, { method: "POST", body: JSON.stringify(body) });
@@ -247,7 +247,7 @@ function LockoutForm() {
const num = (v: string) => (v === "" ? 0 : Number(v));
return (
<section className="space-y-4 rounded-xl border bg-card p-4">
<section className="space-y-4 rounded-lg border bg-card shadow-card p-4">
<h2 className="text-base font-semibold">{t("LsLockoutTitle")}</h2>
<div className="flex items-center gap-2">
<Switch id="ls-enabled" disabled={readOnly} checked={cfg.enabled} onCheckedChange={(enabled) => setCfg({ ...cfg, enabled })} />
@@ -321,7 +321,7 @@ function PasswordRulesForm() {
const edit = (id: number, patch: Partial<RuleEdit>) => setEdits((e) => ({ ...e, [id]: { ...e[id], ...patch } }));
return (
<section className="space-y-4 rounded-xl border bg-card p-4">
<section className="space-y-4 rounded-lg border bg-card shadow-card p-4">
<h2 className="text-base font-semibold">{t("LsRulesTitle")}</h2>
<Table>
<TableHeader>
@@ -0,0 +1,42 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
const mocks = vi.hoisted(() => ({ getMyLinks: vi.fn() }));
vi.mock("@/app/lib/services/adminRegistration", () => mocks);
vi.mock("qrcode.react", () => ({
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
QRCodeCanvas: () => <canvas />,
}));
import MyQrPage from "./page";
beforeEach(() => mocks.getMyLinks.mockReset());
describe("My QR codes", () => {
it("lists the caller's codes with event, dates, location and QR", async () => {
mocks.getMyLinks.mockResolvedValue([
{ eventUuid: "u1", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", token: "t1", enabled: true },
]);
render(<MyQrPage />);
await screen.findByText("Expo 2026");
expect(screen.getByText(/KLCC/)).toBeTruthy();
expect(screen.getByText(/2026-12-01/)).toBeTruthy();
expect(screen.getByTestId("qr-svg").getAttribute("data-value")).toBe(`${window.location.origin}/r/t1`);
expect(screen.getByRole("button", { name: "Copy link" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Download PNG" })).toBeTruthy();
});
it("marks a switched-off code", async () => {
mocks.getMyLinks.mockResolvedValue([
{ eventUuid: "u1", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", token: "t1", enabled: false },
]);
render(<MyQrPage />);
await screen.findByText("Switched off");
});
it("shows an empty state", async () => {
mocks.getMyLinks.mockResolvedValue([]);
render(<MyQrPage />);
await screen.findByText("You have no registration codes yet.");
});
});
+39
View File
@@ -0,0 +1,39 @@
"use client";
import { useEffect, useState } from "react";
import { PageHeader } from "@/app/components/ui/page-header";
import { Badge } from "@/app/components/ui/badge";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { QrCodeItem } from "@/app/components/registration/QrCodeItem";
import { getMyLinks, type MyLink } from "@/app/lib/services/adminRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// Any signed-in staff user; deliberately not in ROUTE_MODULES. Read-only: no on/off switch.
export default function MyQrPage() {
const t = useT();
const [links, setLinks] = useState<MyLink[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
getMyLinks().then(setLinks).catch(() => setError(t("QrLoadFailed")));
}, [t]);
return (
<>
<PageHeader title={t("QrMyTitle")} />
{error && <ErrorState message={error} />}
{links?.length === 0 && <EmptyState title={t("QrMyNone")} />}
<div className="space-y-3">
{links?.map((l) => (
<div key={l.token} className="space-y-1">
<p className="text-sm text-muted-foreground">
{l.startDate} - {l.endDate} | {l.location}
</p>
{!l.enabled && <Badge variant="warning">{t("QrSwitchedOff")}</Badge>}
<QrCodeItem label={l.eventName} eventName={l.eventName} token={l.token} enabled={l.enabled} />
</div>
))}
</div>
</>
);
}
@@ -0,0 +1,172 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({ getRegistration: vi.fn(), submitRegistration: vi.fn() }));
vi.mock("@/app/lib/services/publicRegistration", () => mocks);
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "tok1" }) }));
import { ApiError } from "@/app/lib/clientApi";
import RegisterPage from "./page";
const info = {
eventName: "Expo 2026",
startDate: "2026-12-01",
endDate: "2026-12-02",
location: "KLCC",
companyName: "INS",
notice: { id: 7, textEn: "We keep your data safe.", textMs: "Data anda selamat." },
interests: [{ id: 1, name: "Skincare" }, { id: 2, name: "Wellness" }],
};
beforeEach(() => {
mocks.getRegistration.mockReset().mockResolvedValue(info);
mocks.submitRegistration.mockReset().mockResolvedValue({ eventName: "Expo 2026" });
});
async function ready() {
render(<RegisterPage />);
await screen.findByLabelText("Your name");
}
describe("/r/[token] public page", () => {
it("shows a loading state, then the event, notice in both languages and the form", async () => {
render(<RegisterPage />);
expect(screen.getByRole("status")).toBeTruthy();
await screen.findByText("Expo 2026");
expect(screen.getByText("We keep your data safe.")).toBeTruthy();
expect(screen.getByText("Data anda selamat.")).toBeTruthy();
expect(screen.getByLabelText("Skincare")).toBeTruthy();
expect(mocks.getRegistration).toHaveBeenCalledWith("tok1");
});
it("shows the consent tick box text in English and Bahasa Malaysia with the company name", async () => {
await ready();
const box = screen.getByRole("checkbox", { name: /I agree to INS using my details as described above\./ });
expect(box).toBeTruthy();
expect(screen.getByText("Saya bersetuju INS menggunakan butiran saya seperti yang diterangkan di atas.")).toBeTruthy();
});
it("shows only the inactive message, no event details, when the code is off", async () => {
mocks.getRegistration.mockRejectedValue(new ApiError("x", 404, { code: "CODE_INACTIVE" }));
render(<RegisterPage />);
await screen.findByText("This code is no longer active.");
expect(screen.queryByText("Expo 2026")).toBeNull();
expect(screen.queryByLabelText("Your name")).toBeNull();
});
it("hides the honeypot from people and assistive tech", async () => {
await ready();
const hp = document.querySelector('input[name="website"]') as HTMLInputElement;
expect(hp).toBeTruthy();
expect(hp.tabIndex).toBe(-1);
expect(hp.getAttribute("autocomplete")).toBe("off");
expect(hp.closest("[aria-hidden='true']")).toBeTruthy();
});
it("submits the form, then shows thank-you and lets another person register", async () => {
const user = userEvent.setup();
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Mobile number"), "0123456789");
await user.type(screen.getByLabelText("Company"), "Acme");
await user.type(screen.getByLabelText("Job title"), "Buyer");
await user.click(screen.getByLabelText("Wellness"));
await user.click(screen.getByLabelText(/I agree to INS using my details as described above\./));
await user.click(screen.getByRole("button", { name: "Register" }));
await screen.findByText("Thank you, you're registered for Expo 2026");
expect(mocks.submitRegistration).toHaveBeenCalledWith("tok1", {
name: "Aini", mobile: "0123456789", email: "", companyName: "Acme", jobTitle: "Buyer",
interestIds: [2], consent: true, website: "",
});
await user.click(screen.getByRole("button", { name: "Register another person" }));
const name = (await screen.findByLabelText("Your name")) as HTMLInputElement;
expect(name.value).toBe("");
expect((screen.getByLabelText(/I agree to INS using my details as described above\./) as HTMLElement).getAttribute("aria-checked")).toBe("false");
expect((screen.getByLabelText("Wellness") as HTMLElement).getAttribute("aria-checked")).toBe("false");
expect((document.querySelector('input[name="website"]') as HTMLInputElement).value).toBe("");
});
it("clears a filled honeypot too when registering another person", async () => {
const user = userEvent.setup();
await ready();
await user.type(document.querySelector('input[name="website"]') as HTMLInputElement, "spam");
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByRole("button", { name: "Register" }));
await user.click(await screen.findByRole("button", { name: "Register another person" }));
await screen.findByLabelText("Your name");
expect((document.querySelector('input[name="website"]') as HTMLInputElement).value).toBe("");
});
it("asks for a name and a mobile or email before calling the API", async () => {
const user = userEvent.setup();
await ready();
await user.click(screen.getByRole("button", { name: "Register" }));
expect(screen.getByText("Enter your name.")).toBeTruthy();
expect(screen.getByText("Enter a mobile number or an email.")).toBeTruthy();
expect(mocks.submitRegistration).not.toHaveBeenCalled();
});
it("shows a server field error under the field", async () => {
const user = userEvent.setup();
mocks.submitRegistration.mockRejectedValue(
new ApiError("x", 400, { code: "VALIDATION", details: { field: "consent", code: "CONSENT_REQUIRED" }, error: "Consent is required." }),
);
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByRole("button", { name: "Register" }));
const msg = await screen.findByText("Consent is required.");
const box = screen.getByLabelText(/I agree to INS using my details as described above\./);
expect(box.getAttribute("aria-describedby")).toBe(msg.id);
expect(box.getAttribute("aria-invalid")).toBe("true");
});
it("shows the form-level error for a field the page does not render", async () => {
const user = userEvent.setup();
mocks.submitRegistration.mockRejectedValue(
new ApiError("x", 400, { code: "VALIDATION", details: { field: "interestIds" }, error: "Unknown interest." }),
);
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByRole("button", { name: "Register" }));
expect((await screen.findByRole("alert")).textContent).toBe("Unknown interest.");
});
it("shows a generic error, not the server text, for a 401", async () => {
const user = userEvent.setup();
mocks.submitRegistration.mockRejectedValue(new ApiError("Unauthorized", 401, { error: "Unauthorized" }));
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByRole("button", { name: "Register" }));
expect((await screen.findByRole("alert")).textContent).toBe("Could not register. Try again.");
});
it("gives inputs, buttons and checkbox rows large tap targets", async () => {
await ready();
expect(screen.getByLabelText("Your name").className).toContain("h-11");
expect(screen.getByRole("button", { name: "Register" }).className).toContain("h-11");
for (const l of ["Wellness", /I agree to INS using my details/]) {
const label = document.querySelector(`label[for="${screen.getByLabelText(l).id}"]`)!;
expect(label.className).toContain("w-full");
expect(label.className).toContain("min-h-11");
}
});
it("shows too-many and inactive messages from submit", async () => {
const user = userEvent.setup();
mocks.submitRegistration.mockRejectedValueOnce(new ApiError("x", 429, { code: "TOO_MANY" }));
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByLabelText(/I agree to INS using my details as described above\./));
await user.click(screen.getByRole("button", { name: "Register" }));
await screen.findByText("Too many registrations from this device. Try again later.");
mocks.submitRegistration.mockRejectedValueOnce(new ApiError("x", 404, { code: "CODE_INACTIVE" }));
await user.click(screen.getByRole("button", { name: "Register" }));
await waitFor(() => expect(screen.getByText("This code is no longer active.")).toBeTruthy());
});
});
+172
View File
@@ -0,0 +1,172 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { useParams } from "next/navigation";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { ApiError } from "@/app/lib/clientApi";
import { getRegistration, submitRegistration, type RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const EMPTY = { name: "", mobile: "", email: "", companyName: "", jobTitle: "", interestIds: [] as number[], consent: false, website: "" };
// Fields the form renders; a server error for any other field goes to the form-level alert.
const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"];
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
const BOX = "size-6";
type Phase = "loading" | "inactive" | "form" | "done";
function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
if (!(err instanceof ApiError)) return {};
const d = (err.data ?? {}) as { code?: string; error?: string; details?: { field?: string } };
return { status: err.status, code: d.code, error: d.error, field: d.details?.field };
}
// Public, signed-out, mobile-first page (no admin shell: AppShell skips it via isPublicPath).
export default function RegisterPage() {
const t = useT();
const { token } = useParams<{ token: string }>();
const [phase, setPhase] = useState<Phase>("loading");
const [info, setInfo] = useState<RegistrationInfo | null>(null);
const [form, setForm] = useState(EMPTY);
const [errors, setErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
useEffect(() => {
getRegistration(token)
.then((i) => {
setInfo(i);
setPhase("form");
})
.catch((err) => {
if (apiData(err).code === "CODE_INACTIVE") setPhase("inactive");
else {
setFormError(apiData(err).code === "TOO_MANY" ? t("RegTooMany") : t("RegLoadFailed"));
setPhase("form");
}
});
}, [token, t]);
const set = (patch: Partial<typeof EMPTY>) => setForm((f) => ({ ...f, ...patch }));
async function submit(e: FormEvent) {
e.preventDefault();
const errs: Record<string, string> = {};
if (!form.name.trim()) errs.name = t("RegNameRequired");
if (!form.mobile.trim() && !form.email.trim()) errs.mobile = t("RegContactRequired");
setErrors(errs);
setFormError(null);
if (Object.keys(errs).length) return;
setSaving(true);
try {
await submitRegistration(token, {
...form,
name: form.name.trim(),
mobile: form.mobile.trim(),
email: form.email.trim(),
companyName: form.companyName.trim(),
jobTitle: form.jobTitle.trim(),
});
setPhase("done");
} catch (err) {
const { status, code, error, field } = apiData(err);
if (code === "CODE_INACTIVE") setPhase("inactive");
else if (code === "TOO_MANY") setFormError(t("RegTooMany"));
else if (status === 400 && error && field && FIELDS.includes(field)) setErrors({ [field]: error });
else setFormError(status === 400 && error ? error : t("RegFailed"));
} finally {
setSaving(false);
}
}
const field = (id: keyof typeof EMPTY, label: string, type = "text") => (
<div className="space-y-1.5">
<Label htmlFor={`reg-${id}`}>{label}</Label>
<Input id={`reg-${id}`} className="h-11" type={type} value={String(form[id])} onChange={(e) => set({ [id]: e.target.value })} disabled={saving} aria-invalid={!!errors[id]} aria-describedby={errors[id] ? `reg-${id}-error` : undefined} />
{errors[id] && <p id={`reg-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>}
</div>
);
let body;
if (phase === "loading") body = <p role="status">{t("UiLoading")}</p>;
else if (phase === "inactive") body = <p role="alert">{t("RegInactive")}</p>;
else if (phase === "done") {
body = (
<div className="space-y-4">
<p role="status" className="text-lg font-medium">{t("RegThanks", { event: info?.eventName ?? "" })}</p>
<Button
className="h-11"
onClick={() => {
setForm(EMPTY);
setErrors({});
setPhase("form");
}}
>
{t("RegAnother")}
</Button>
</div>
);
} else {
body = (
<form onSubmit={submit} className="space-y-4" noValidate>
{info && (
<div>
<h1 className="text-2xl font-semibold">{info.eventName}</h1>
<p className="text-sm text-muted-foreground">
{info.companyName} | {info.startDate} - {info.endDate} | {info.location}
</p>
</div>
)}
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
{info && (
<>
{field("name", t("RegName"))}
{field("mobile", t("RegMobile"), "tel")}
{field("email", t("RegEmail"), "email")}
{field("companyName", t("RegCompany"))}
{field("jobTitle", t("RegJobTitle"))}
{info.interests.length > 0 && (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
{info.interests.map((i) => (
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
<Checkbox
className={BOX}
id={`reg-interest-${i.id}`}
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
)}
<div className="space-y-2 rounded-md border p-3 text-sm">
<h2 className="font-medium">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-medium">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
<Label htmlFor="reg-consent" className={ROW}>
<Checkbox id="reg-consent" className={BOX} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
<span>
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
</span>
</Label>
{errors.consent && <p id="reg-consent-error" className="text-sm text-destructive">{errors.consent}</p>}
{/* Honeypot: people never see or reach it; bots fill it and the server drops the submission. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<input name="website" tabIndex={-1} autoComplete="off" value={form.website} onChange={(e) => set({ website: e.target.value })} />
</div>
<Button type="submit" className="h-11 w-full" disabled={saving}>{t("RegSubmit")}</Button>
</>
)}
</form>
);
}
return <main className="mx-auto w-full max-w-md px-4 py-6">{body}</main>;
}
@@ -19,7 +19,6 @@ const FILES = globSync("app/**/*.tsx", { cwd: ROOT }).filter((f) => !/\.test\.ts
// selectors/markers, not Tailwind utilities.
const PROJECT_CLASSES = new Set([
"tabular",
"brand-wordmark",
"scrollable",
"giraffe-spots",
"print-handover",
@@ -0,0 +1,36 @@
import { describe, it, expect } from "vitest";
import { NextRequest } from "next/server";
import { guardDecision } from "./app/lib/routeGuard";
import { middleware } from "./middleware";
// add-qr-self-registration: the QR landing page and its proxy are reachable signed out; admin paths still are not.
const get = (path: string) => middleware(new NextRequest(new URL(path, "https://portal.test")));
describe("middleware: public registration paths", () => {
it("lets a signed-out visitor open /r/<token>", async () => {
const res = await get("/r/abc123");
expect(res.headers.get("x-middleware-next")).toBe("1");
expect(res.headers.get("location")).toBeNull();
});
it("lets a signed-out visitor reach the public registration proxy", async () => {
const res = await get("/api/public/registration/abc123");
expect(res.headers.get("x-middleware-next")).toBe("1");
});
it("still redirects a signed-out visitor from admin paths", async () => {
for (const path of ["/events", "/my-qr", "/r", "/r/"]) {
const res = await get(path);
expect(res.headers.get("location"), path).toContain("/login");
}
});
});
describe("routeGuard: /r/<token> with a pending password reset", () => {
it("stays reachable; admin paths still go to /reset-password", () => {
const s = { present: true, resetRequired: true };
expect(guardDecision("/r/abc123", s)).toBeNull();
expect(guardDecision("/events", s)).toBe("/reset-password");
expect(guardDecision("/r", s)).toBe("/reset-password");
});
});
+10
View File
@@ -13,6 +13,7 @@
"clsx": "^2.1.1",
"lucide-react": "^1.28.0",
"next": "^16.4.5",
"qrcode.react": "4.2.0",
"radix-ui": "^1.6.7",
"react": "^19.2.8",
"react-day-picker": "10.0.1",
@@ -8849,6 +8850,15 @@
"node": ">=6"
}
},
"node_modules/qrcode.react": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more