Files
co-lite/openspec/changes/add-qr-self-registration/design.md
T

96 lines
9.7 KiB
Markdown

## 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`.
- 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, 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`, keeping any incoming value first.
- **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. 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.
- `X-Forwarded-For` is client-controlled unless Traefik overwrites it. Locally there is no proxy. The deployment notes ask that Traefik be set to replace, not append, the header for the portal.
- The default notice is a template; INS and CV must review it.