diff --git a/docs/deployment.md b/docs/deployment.md index 455c089..56bb57d 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -105,6 +105,15 @@ 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. + +**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 +245,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/`) 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 +313,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. diff --git a/docs/superpowers/specs/2026-12-01-qr-self-registration-design.md b/docs/superpowers/specs/2026-12-01-qr-self-registration-design.md new file mode 100644 index 0000000..049ef19 --- /dev/null +++ b/docs/superpowers/specs/2026-12-01-qr-self-registration-design.md @@ -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:///r/`. +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 ", 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/`, 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. diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 9bcabb6..42b24bc 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -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`); diff --git a/openspec/changes/add-qr-self-registration/.openspec.yaml b/openspec/changes/add-qr-self-registration/.openspec.yaml new file mode 100644 index 0000000..785b150 --- /dev/null +++ b/openspec/changes/add-qr-self-registration/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-01 diff --git a/openspec/changes/add-qr-self-registration/design.md b/openspec/changes/add-qr-self-registration/design.md new file mode 100644 index 0000000..160932b --- /dev/null +++ b/openspec/changes/add-qr-self-registration/design.md @@ -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: ; …` 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:`, 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::`, 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/`, copy, download PNG (`QRCodeCanvas` → `toDataURL`, file `--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/` + - GET `/counter/interest/findByCompany/` + - GET `/counter/eventSalesperson/findByEventUuid/` + - GET `/company/findById/` + - GET `/company//privacyNotice` (the POST that saves a notice still needs a token) + - GET `/user//activeAdminOf/` + - 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. diff --git a/openspec/changes/add-qr-self-registration/proposal.md b/openspec/changes/add-qr-self-registration/proposal.md new file mode 100644 index 0000000..b3aec4c --- /dev/null +++ b/openspec/changes/add-qr-self-registration/proposal.md @@ -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/` 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. diff --git a/openspec/changes/add-qr-self-registration/specs/qr-registration/spec.md b/openspec/changes/add-qr-self-registration/specs/qr-registration/spec.md new file mode 100644 index 0000000..c45c701 --- /dev/null +++ b/openspec/changes/add-qr-self-registration/specs/qr-registration/spec.md @@ -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/`. 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 diff --git a/openspec/changes/add-qr-self-registration/sql/01-registration-link.sql b/openspec/changes/add-qr-self-registration/sql/01-registration-link.sql new file mode 100644 index 0000000..e6cdc16 --- /dev/null +++ b/openspec/changes/add-qr-self-registration/sql/01-registration-link.sql @@ -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`; diff --git a/openspec/changes/add-qr-self-registration/sql/02-company-privacy-notice.sql b/openspec/changes/add-qr-self-registration/sql/02-company-privacy-notice.sql new file mode 100644 index 0000000..3c5a3f4 --- /dev/null +++ b/openspec/changes/add-qr-self-registration/sql/02-company-privacy-notice.sql @@ -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`); diff --git a/openspec/changes/add-qr-self-registration/sql/99-rollback.sql b/openspec/changes/add-qr-self-registration/sql/99-rollback.sql new file mode 100644 index 0000000..f49a079 --- /dev/null +++ b/openspec/changes/add-qr-self-registration/sql/99-rollback.sql @@ -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`; diff --git a/openspec/changes/add-qr-self-registration/tasks.md b/openspec/changes/add-qr-self-registration/tasks.md new file mode 100644 index 0000000..73770c1 --- /dev/null +++ b/openspec/changes/add-qr-self-registration/tasks.md @@ -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. diff --git a/solvway-admin-portal/app/api/companies/[id]/privacy-notice/route.ts b/solvway-admin-portal/app/api/companies/[id]/privacy-notice/route.ts new file mode 100644 index 0000000..0c18794 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/[id]/privacy-notice/route.ts @@ -0,0 +1,29 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +type Ctx = { params: Promise<{ 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>(`/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>(`/api/admin/companies/${encodeURIComponent(id)}/privacy-notice`, { + method: "PUT", + body, + token, + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/events/[uuid]/registration-links/[token]/route.ts b/solvway-admin-portal/app/api/events/[uuid]/registration-links/[token]/route.ts new file mode 100644 index 0000000..a862b10 --- /dev/null +++ b/solvway-admin-portal/app/api/events/[uuid]/registration-links/[token]/route.ts @@ -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>( + `/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); +} diff --git a/solvway-admin-portal/app/api/events/[uuid]/registration-links/route.ts b/solvway-admin-portal/app/api/events/[uuid]/registration-links/route.ts new file mode 100644 index 0000000..e9d6321 --- /dev/null +++ b/solvway-admin-portal/app/api/events/[uuid]/registration-links/route.ts @@ -0,0 +1,13 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +export async function GET(_req: NextRequest, { params }: { params: Promise<{ uuid: string }> }) { + const token = await getToken(); + if (!token) return unauthorized(); + const { uuid } = await params; + const result = await callMobileApi>(`/api/admin/events/${encodeURIComponent(uuid)}/registration-links`, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/my-registration-links/route.ts b/solvway-admin-portal/app/api/my-registration-links/route.ts new file mode 100644 index 0000000..3609706 --- /dev/null +++ b/solvway-admin-portal/app/api/my-registration-links/route.ts @@ -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("/api/admin/my-registration-links", { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/public/registration/[token]/route.test.ts b/solvway-admin-portal/app/api/public/registration/[token]/route.test.ts new file mode 100644 index 0000000..1a3b4c8 --- /dev/null +++ b/solvway-admin-portal/app/api/public/registration/[token]/route.test.ts @@ -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[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).code).toBe("TOO_MANY"); + }); +}); diff --git a/solvway-admin-portal/app/api/public/registration/[token]/route.ts b/solvway-admin-portal/app/api/public/registration/[token]/route.ts new file mode 100644 index 0000000..2df1369 --- /dev/null +++ b/solvway-admin-portal/app/api/public/registration/[token]/route.ts @@ -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 { + 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>(`/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>(`/api/public/registration/${encodeURIComponent(token)}`, { + method: "POST", + body, + headers: forwardedFor(req), + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/registrationAdminRoutes.test.ts b/solvway-admin-portal/app/api/registrationAdminRoutes.test.ts new file mode 100644 index 0000000..3c01e50 --- /dev/null +++ b/solvway-admin-portal/app/api/registrationAdminRoutes.test.ts @@ -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 = (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" }], + ]); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.privacy.test.tsx b/solvway-admin-portal/app/companies/page.privacy.test.tsx new file mode 100644 index 0000000..40bebc6 --- /dev/null +++ b/solvway-admin-portal/app/companies/page.privacy.test.tsx @@ -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()).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(); + 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(); + await waitFor(() => expect(screen.queryByRole("button", { name: "Privacy notice" })).toBeNull()); + expect(mocks.getPrivacyNotice).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.tsx b/solvway-admin-portal/app/companies/page.tsx index 451c8bf..70b7d3c 100644 --- a/solvway-admin-portal/app/companies/page.tsx +++ b/solvway-admin-portal/app/companies/page.tsx @@ -14,6 +14,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"; @@ -114,6 +115,73 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos ); } +function PrivacyNoticeDialog({ company, onClose }: { company: AdminCompany; onClose: () => void }) { + const t = useT(); + const [notice, setNotice] = useState(null); + const [textEn, setTextEn] = useState(""); + const [textMs, setTextMs] = useState(""); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(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) { + 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 ( + !open && onClose()}> + + + {t("PrivNotice")} + + {error && ( +
+ {error} +
+ )} +
+
+ +