From 6fbbdaa3c5ef522fb123166fb88813805a026eaf Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 11:52:00 +0800 Subject: [PATCH 01/20] docs: QR self-registration design and OpenSpec change Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../2026-12-01-qr-self-registration-design.md | 156 ++++++++++++++++++ .../add-qr-self-registration/.openspec.yaml | 2 + .../add-qr-self-registration/design.md | 95 +++++++++++ .../add-qr-self-registration/proposal.md | 29 ++++ .../specs/qr-registration/spec.md | 127 ++++++++++++++ .../sql/01-registration-link.sql | 24 +++ .../sql/02-company-privacy-notice.sql | 23 +++ .../sql/99-rollback.sql | 7 + .../changes/add-qr-self-registration/tasks.md | 88 ++++++++++ 9 files changed, 551 insertions(+) create mode 100644 docs/superpowers/specs/2026-12-01-qr-self-registration-design.md create mode 100644 openspec/changes/add-qr-self-registration/.openspec.yaml create mode 100644 openspec/changes/add-qr-self-registration/design.md create mode 100644 openspec/changes/add-qr-self-registration/proposal.md create mode 100644 openspec/changes/add-qr-self-registration/specs/qr-registration/spec.md create mode 100644 openspec/changes/add-qr-self-registration/sql/01-registration-link.sql create mode 100644 openspec/changes/add-qr-self-registration/sql/02-company-privacy-notice.sql create mode 100644 openspec/changes/add-qr-self-registration/sql/99-rollback.sql create mode 100644 openspec/changes/add-qr-self-registration/tasks.md 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/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..d629e0b --- /dev/null +++ b/openspec/changes/add-qr-self-registration/design.md @@ -0,0 +1,95 @@ +## 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`. + - 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, 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/`, 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. 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. 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..9e86d6b --- /dev/null +++ b/openspec/changes/add-qr-self-registration/sql/02-company-privacy-notice.sql @@ -0,0 +1,23 @@ +-- 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; + +INSERT INTO `company_privacy_notice` (`company_id`, `text_en`, `text_ms`, `created_by`) +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' +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..a71707e --- /dev/null +++ b/openspec/changes/add-qr-self-registration/tasks.md @@ -0,0 +1,88 @@ +# 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 + +- [ ] 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. +- [ ] 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 + +- [ ] 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 + +- [ ] 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 + +- [ ] 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` + +## 5. Portal + +- [ ] 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 + +- [ ] 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. -- 2.54.1 From 2842ef423f4a6dc251c519b2c43459206ac2fd91 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 11:53:48 +0800 Subject: [PATCH 02/20] feat(db): registration links, event lead source and consent, company privacy notices Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 9bcabb6..b1d4eb1 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -253,3 +253,49 @@ 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; + +INSERT INTO `company_privacy_notice` (`company_id`, `text_en`, `text_ms`, `created_by`) +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' +FROM `company` c +WHERE NOT EXISTS (SELECT 1 FROM `company_privacy_notice` n WHERE n.`company_id` = c.`id`); -- 2.54.1 From 0345314c89cb0f6f2dbc68fe97981c48ac64d94b Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 11:53:48 +0800 Subject: [PATCH 03/20] chore(portal): add qrcode.react 4.2.0 (as in babyboo's portal) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- solvway-admin-portal/package-lock.json | 10 ++++++++++ solvway-admin-portal/package.json | 1 + 2 files changed, 11 insertions(+) diff --git a/solvway-admin-portal/package-lock.json b/solvway-admin-portal/package-lock.json index adf58ee..3afae0e 100644 --- a/solvway-admin-portal/package-lock.json +++ b/solvway-admin-portal/package-lock.json @@ -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", diff --git a/solvway-admin-portal/package.json b/solvway-admin-portal/package.json index e2cd4b1..25d973e 100644 --- a/solvway-admin-portal/package.json +++ b/solvway-admin-portal/package.json @@ -19,6 +19,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", -- 2.54.1 From 9c9469f5e57755144ec4cdad3f4801153c1c6ffe Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 11:53:48 +0800 Subject: [PATCH 04/20] docs: tick QR registration wave 0 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-qr-self-registration/tasks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/add-qr-self-registration/tasks.md b/openspec/changes/add-qr-self-registration/tasks.md index a71707e..af26461 100644 --- a/openspec/changes/add-qr-self-registration/tasks.md +++ b/openspec/changes/add-qr-self-registration/tasks.md @@ -10,11 +10,11 @@ Waves: ## 1. Data and dependency -- [ ] 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. +- [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. -- [ ] 1.2 Portal: add `qrcode.react` (same major as babyboo's portal). +- [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.54.1 From 85b40424cefc2bd53b42ae8033e884591ba327ff Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:15:13 +0800 Subject: [PATCH 05/20] 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 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../controller/RegistrationController.java | 46 +++ .../services/counter/model/EventLead.java | 7 + .../counter/model/RegistrationLink.java | 40 +++ .../counter/repo/EventRepository.java | 1 + .../repo/EventSalespersonRepository.java | 2 + .../services/counter/repo/LeadRepository.java | 4 + .../repo/RegistrationLinkRepository.java | 17 ++ .../counter/service/EventLeadService.java | 4 +- .../service/RegistrationLinkService.java | 128 +++++++++ .../counter/service/RegistrationService.java | 123 ++++++++ .../service/RegistrationLinkServiceTest.java | 243 ++++++++++++++++ .../service/RegistrationServiceTest.java | 264 ++++++++++++++++++ 12 files changed, 877 insertions(+), 2 deletions(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/RegistrationController.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/RegistrationLink.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/repo/RegistrationLinkRepository.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkServiceTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationServiceTest.java diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/RegistrationController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/RegistrationController.java new file mode 100644 index 0000000..45c51ae --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/RegistrationController.java @@ -0,0 +1,46 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.service.RegistrationLinkService; +import com.solvway.services.counter.service.RegistrationService; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/counter") +@AllArgsConstructor +public class RegistrationController { + private final RegistrationLinkService linkService; + private final RegistrationService registrationService; + + @PostMapping("/registrationLink/ensure") + public List ensure(@RequestBody RegistrationLinkService.EnsureRequest req) { + return linkService.ensure(req); + } + + @PostMapping("/registrationLink/setEnabled") + public RegistrationLinkService.LinkView setEnabled(@RequestBody RegistrationLinkService.SetEnabledRequest req) { + return linkService.setEnabled(req); + } + + @GetMapping("/registrationLink/findByToken/{token}") + public RegistrationLinkService.LinkLookup findByToken(@PathVariable("token") String token) { + return linkService.findByToken(token); + } + + @PostMapping("/registrationLink/mine") + public List mine(@RequestBody RegistrationLinkService.MineRequest req) { + return linkService.mine(req); + } + + @PostMapping("/registration/register") + public RegistrationService.RegisterResult register(@RequestBody RegistrationService.RegisterRequest req) { + return registrationService.register(req); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java index 82c44b6..692f642 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java @@ -48,6 +48,13 @@ public class EventLead { private String capturedBy; + /** STAFF (captured in the portal) or QR (self-registered). */ + private String source = "STAFF"; + + private LocalDateTime consentAt; + + private Long consentNoticeId; + @Column(updatable = false) private LocalDateTime capturedAt = LocalDateTime.now(); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/RegistrationLink.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/RegistrationLink.java new file mode 100644 index 0000000..7b82e3b --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/RegistrationLink.java @@ -0,0 +1,40 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** A QR registration code: salespersonUserId null is the event code, otherwise a salesperson's personal code. */ +@Getter +@Setter +@Entity +@Table(name = "registration_link") +public class RegistrationLink { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private long companyId; + + @Column(name = "event_uuid") + private long eventUuid; + + @Column(name = "salesperson_user_id") + private Long salespersonUserId; + + private String token; + + private boolean enabled = true; + + @Column(updatable = false) + private String createdBy; + + @Column(updatable = false) + private LocalDateTime createdAt = LocalDateTime.now(); + + private String updatedBy; + + private LocalDateTime updatedAt; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java index c6f7cdf..07ac178 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java @@ -12,6 +12,7 @@ import java.util.Optional; @Repository public interface EventRepository extends JpaRepository , JpaRepositoryCustom{ Optional findByUuid(long uuid); + java.util.List findByCompanyIdAndUuidIn(Long companyId, java.util.Collection uuids); Optional findTop1ByDateStartLessThanEqualAndDateEndGreaterThanEqualAndEnabledOrderByDateStartDesc(LocalDateTime dateStart, LocalDateTime dateEnd, GeneralEnum.FlagYesNo enabled); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java index de84937..40f8116 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java @@ -13,6 +13,8 @@ import java.util.List; public interface EventSalespersonRepository extends JpaRepository { List findByEventUuid(long eventUuid); + List findByCompanyIdAndUserId(long companyId, long userId); + @Modifying @Query("delete from EventSalesperson e where e.eventUuid = :eventUuid") void deleteByEventUuid(@Param("eventUuid") long eventUuid); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java index 2539fa8..62a4a4a 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java @@ -19,6 +19,10 @@ public interface LeadRepository extends JpaRepository { List findMatches(@Param("companyId") long companyId, @Param("mobile") String mobile, @Param("email") String email, Pageable pageable); + Optional findFirstByCompanyIdAndMobileE164OrderByIdDesc(long companyId, String mobileE164); + + Optional findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(long companyId, String emailNormalised); + Optional findByUuidAndCompanyId(long uuid, long companyId); Optional findByUuid(long uuid); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/RegistrationLinkRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/RegistrationLinkRepository.java new file mode 100644 index 0000000..1364322 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/RegistrationLinkRepository.java @@ -0,0 +1,17 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.RegistrationLink; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface RegistrationLinkRepository extends JpaRepository { + Optional findByToken(String token); + + Optional findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(long eventUuid, long salespersonUserId); + + List findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(long eventUuid); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java index f73f635..06c8df0 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java @@ -175,7 +175,7 @@ public class EventLeadService { return detail(eventLead, lead, interestIds); } - private void recordStatusChange(EventLead e, String from, String to, LocalDateTime at, String by) { + public void recordStatusChange(EventLead e, String from, String to, LocalDateTime at, String by) { EventLeadStatusChange row = new EventLeadStatusChange(); row.setCompanyId(e.getCompanyId()); row.setEventLeadId(e.getId()); @@ -190,7 +190,7 @@ public class EventLeadService { if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); } - private List saveInterests(long eventLeadId, long companyId, List requested) { + public List saveInterests(long eventLeadId, long companyId, List requested) { List ids = requested == null ? List.of() : requested.stream().filter(Objects::nonNull).distinct().toList(); if (!ids.isEmpty()) { eventLeadInterestRepository.saveAll(ids.stream().map(id -> { diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java new file mode 100644 index 0000000..276027d --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java @@ -0,0 +1,128 @@ +package com.solvway.services.counter.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventSalesperson; +import com.solvway.services.counter.model.RegistrationLink; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.EventSalespersonRepository; +import com.solvway.services.counter.repo.RegistrationLinkRepository; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.security.SecureRandom; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + +/** QR registration codes per event: one event code and one personal code per salesperson. */ +@Service +@AllArgsConstructor +public class RegistrationLinkService { + private static final SecureRandom RANDOM = new SecureRandom(); + + public record EnsureRequest(Long companyId, long eventUuid, List salespersonUserIds) {} + public record SetEnabledRequest(Long companyId, long eventUuid, String token, boolean enabled, String doneBy) {} + public record MineRequest(Long companyId, long userId, String today) {} + public record LinkView(long eventUuid, Long salespersonUserId, String token, boolean enabled) {} + public record LinkLookup(long companyId, long eventUuid, Long salespersonUserId, String token, boolean enabled) {} + public record MineRow(String eventUuid, String eventName, String startDate, String endDate, String location, + String token, boolean enabled) {} + + private final RegistrationLinkRepository linkRepository; + private final EventRepository eventRepository; + private final EventSalespersonRepository eventSalespersonRepository; + + @Transactional + public List ensure(EnsureRequest req) { + requireEvent(req.companyId(), req.eventUuid()); + List out = new ArrayList<>(); + out.add(eventCode(req.companyId(), req.eventUuid())); + if (req.salespersonUserIds() != null) { + req.salespersonUserIds().stream().filter(Objects::nonNull).distinct() + .forEach(uid -> out.add(personal(req.companyId(), req.eventUuid(), uid))); + } + return out.stream().map(RegistrationLinkService::view).toList(); + } + + @Transactional + public LinkView setEnabled(SetEnabledRequest req) { + requireEvent(req.companyId(), req.eventUuid()); + RegistrationLink link = linkRepository.findByToken(req.token()) + .filter(l -> l.getEventUuid() == req.eventUuid() && l.getCompanyId() == req.companyId()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + link.setEnabled(req.enabled()); + link.setUpdatedBy(req.doneBy()); + link.setUpdatedAt(LocalDateTime.now()); + return view(linkRepository.save(link)); + } + + public LinkLookup findByToken(String token) { + RegistrationLink l = linkRepository.findByToken(token) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + return new LinkLookup(l.getCompanyId(), l.getEventUuid(), l.getSalespersonUserId(), l.getToken(), l.isEnabled()); + } + + @Transactional + public List mine(MineRequest req) { + LocalDate today = LocalDate.parse(req.today()); + List uuids = eventSalespersonRepository.findByCompanyIdAndUserId(req.companyId(), req.userId()).stream() + .map(EventSalesperson::getEventUuid).toList(); + if (uuids.isEmpty()) return List.of(); + return eventRepository.findByCompanyIdAndUuidIn(req.companyId(), uuids).stream() + .filter(e -> e.getEnabled() == GeneralEnum.FlagYesNo.Y && !e.getDateEnd().toLocalDate().isBefore(today)) + .sorted(Comparator.comparing(Event::getDateStart)) + .map(e -> { + RegistrationLink l = personal(req.companyId(), e.getUuid(), req.userId()); + return new MineRow(String.valueOf(e.getUuid()), e.getName(), e.getDateStart().toLocalDate().toString(), + e.getDateEnd().toLocalDate().toString(), e.getLocation(), l.getToken(), l.isEnabled()); + }).toList(); + } + + private void requireEvent(Long companyId, long eventUuid) { + eventRepository.findByUuid(eventUuid) + .filter(e -> companyId != null && companyId.equals(e.getCompanyId())) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND")); + } + + private RegistrationLink eventCode(long companyId, long eventUuid) { + List codes = linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(eventUuid); + if (codes.isEmpty()) { + // The key is not unique, so concurrent first calls can each insert a code and each return its own once + // (REPEATABLE READ hides the other insert from this re-read). Later calls converge on the oldest row; + // the losing token stays enabled but is never shown. + // ponytail: no unique key for personal/event codes; add one, or re-read in a new transaction, if it matters. + linkRepository.save(newLink(companyId, eventUuid, null)); + codes = linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(eventUuid); + } + return codes.get(0); + } + + private RegistrationLink personal(long companyId, long eventUuid, long userId) { + return linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(eventUuid, userId) + .orElseGet(() -> linkRepository.save(newLink(companyId, eventUuid, userId))); + } + + private static RegistrationLink newLink(long companyId, long eventUuid, Long userId) { + byte[] bytes = new byte[16]; + RANDOM.nextBytes(bytes); + RegistrationLink l = new RegistrationLink(); + l.setCompanyId(companyId); + l.setEventUuid(eventUuid); + l.setSalespersonUserId(userId); + l.setToken(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + l.setCreatedBy("system"); + return l; + } + + private static LinkView view(RegistrationLink l) { + return new LinkView(l.getEventUuid(), l.getSalespersonUserId(), l.getToken(), l.isEnabled()); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java new file mode 100644 index 0000000..b2d4eb0 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java @@ -0,0 +1,123 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import lombok.AllArgsConstructor; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * QR self-registration. Values arrive validated and normalised by mobile-api, which also picks the salesperson. + * Never log a lead's name, mobile or email. + */ +@Service +@AllArgsConstructor +public class RegistrationService { + public record RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, + String email, String companyName, String jobTitle, List interestIds, + Long consentNoticeId, LocalDateTime consentAt) {} + public record RegisterResult(String outcome, String eventLeadUuid) {} + + private static final String QR = "qr"; + + private final TransactionTemplate transactionTemplate; + private final LeadRepository leadRepository; + private final EventLeadRepository eventLeadRepository; + private final EventLeadService eventLeadService; + + public RegisterResult register(RegisterRequest req) { + try { + return transactionTemplate.execute(s -> registerOnce(req)); + } catch (DataIntegrityViolationException e) { + // Any constraint violation lands here, not only uk_event_lead_event_lead (the same person captured at + // this event between our lookup and insert); one retry, then the exception propagates. + // The failed flush leaves the transaction rollback-only and the session unusable, so the exception + // must not be handled inside it. It has been rolled back by now; a second run in a fresh transaction + // finds the winner's row by the normal lookup and reports ALREADY_CAPTURED or ASSIGNED. + return transactionTemplate.execute(s -> registerOnce(req)); + } + } + + private RegisterResult registerOnce(RegisterRequest req) { + Optional match = Optional.empty(); + if (req.mobileE164() != null) { + match = leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(req.companyId(), req.mobileE164()); + } + if (match.isEmpty() && req.email() != null) { + match = leadRepository.findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(req.companyId(), req.email()); + } + + Lead lead; + String leadType; + String notes = null; + if (match.isEmpty()) { + lead = new Lead(); + lead.setCompanyId(req.companyId()); + lead.setName(req.name()); + lead.setMobileE164(req.mobileE164()); + lead.setEmailNormalised(req.email()); + lead.setCompanyName(req.companyName()); + lead.setJobTitle(req.jobTitle()); + lead.setCreatedBy(QR); + lead = leadRepository.saveAndFlush(lead); + leadType = "NEW"; + } else { + lead = match.get(); + Optional captured = eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid()); + if (captured.isPresent()) return alreadyCaptured(captured.get(), req.salespersonUserId()); + notes = differences(lead, req); + leadType = "EXISTING"; + } + + EventLead e = new EventLead(); + e.setCompanyId(req.companyId()); + e.setEventUuid(req.eventUuid()); + e.setLeadUuid(lead.getUuid()); + e.setSalespersonUserId(req.salespersonUserId()); + e.setLeadType(leadType); + e.setStatus("OPEN"); + e.setNotes(notes); + e.setSource("QR"); + e.setCapturedBy(QR); + e.setConsentAt(req.consentAt()); + e.setConsentNoticeId(req.consentNoticeId()); + e = eventLeadRepository.saveAndFlush(e); + eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR); + eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds()); + return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid())); + } + + private RegisterResult alreadyCaptured(EventLead e, Long salespersonUserId) { + if (e.getSalespersonUserId() == null && salespersonUserId != null) { + e.setSalespersonUserId(salespersonUserId); + e.setUpdatedBy(QR); + e.setUpdatedAt(LocalDateTime.now()); + eventLeadRepository.save(e); + return new RegisterResult("ASSIGNED", String.valueOf(e.getUuid())); + } + return new RegisterResult("ALREADY_CAPTURED", String.valueOf(e.getUuid())); + } + + /** Submitted non-blank values that differ from the lead's, as an event-lead note; null when nothing differs. */ + private static String differences(Lead lead, RegisterRequest req) { + List parts = new ArrayList<>(); + diff(parts, "name", req.name(), lead.getName()); + diff(parts, "mobile", req.mobileE164(), lead.getMobileE164()); + diff(parts, "email", req.email(), lead.getEmailNormalised()); + diff(parts, "company", req.companyName(), lead.getCompanyName()); + diff(parts, "job title", req.jobTitle(), lead.getJobTitle()); + return parts.isEmpty() ? null : "Registered by QR with: " + String.join("; ", parts); + } + + private static void diff(List parts, String label, String submitted, String current) { + if (submitted != null && !submitted.isBlank() && !submitted.equals(current)) parts.add(label + " " + submitted); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkServiceTest.java new file mode 100644 index 0000000..264147b --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkServiceTest.java @@ -0,0 +1,243 @@ +package com.solvway.services.counter.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventSalesperson; +import com.solvway.services.counter.model.RegistrationLink; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.EventSalespersonRepository; +import com.solvway.services.counter.repo.RegistrationLinkRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RegistrationLinkServiceTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + + @Mock private RegistrationLinkRepository linkRepository; + @Mock private EventRepository eventRepository; + @Mock private EventSalespersonRepository eventSalespersonRepository; + + private RegistrationLinkService service; + + @BeforeEach + void setUp() { + service = new RegistrationLinkService(linkRepository, eventRepository, eventSalespersonRepository); + lenient().when(linkRepository.save(any(RegistrationLink.class))).then(returnsFirstArg()); + } + + private static Event event(long uuid, long company, String name, LocalDateTime start, LocalDateTime end, GeneralEnum.FlagYesNo enabled) { + Event e = new Event(); + // uuid is a field with a default; set through reflection-free route: the setter exists via Lombok + e.setUuid(uuid); + e.setName(name); + e.setLocation("KLCC"); + e.setDateStart(start); + e.setDateEnd(end); + e.setEnabled(enabled); + try { + var f = Event.class.getDeclaredField("companyId"); + f.setAccessible(true); + f.set(e, company); + } catch (ReflectiveOperationException ex) { + throw new IllegalStateException(ex); + } + return e; + } + + private static RegistrationLink link(Long salesperson, String token, boolean enabled) { + RegistrationLink l = new RegistrationLink(); + l.setCompanyId(COMPANY); + l.setEventUuid(EVENT); + l.setSalespersonUserId(salesperson); + l.setToken(token); + l.setEnabled(enabled); + return l; + } + + private void eventInCompany() { + when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(event(EVENT, COMPANY, "Expo", LocalDateTime.now(), LocalDateTime.now(), GeneralEnum.FlagYesNo.Y))); + } + + // --- ensure --- + + @Test + void ensureCreatesEventCodeThenPersonalCodesInGivenOrderWith22CharTokens() { + eventInCompany(); + RegistrationLink code = link(null, "EVENTCODE", true); + when(linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(EVENT)).thenReturn(List.of()).thenReturn(List.of(code)); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(eq(EVENT), anyLong())).thenReturn(Optional.empty()); + + List out = service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of(9L, 7L))); + + assertThat(out).extracting(RegistrationLinkService.LinkView::salespersonUserId).containsExactly(null, 9L, 7L); + assertThat(out.get(0).token()).isEqualTo("EVENTCODE"); + assertThat(out.get(1).token()).hasSize(22).matches("[A-Za-z0-9_-]{22}"); + assertThat(out.get(1).token()).isNotEqualTo(out.get(2).token()); + assertThat(out).allMatch(RegistrationLinkService.LinkView::enabled); + ArgumentCaptor saved = ArgumentCaptor.forClass(RegistrationLink.class); + verify(linkRepository, times(3)).save(saved.capture()); + assertThat(saved.getAllValues()).allMatch(l -> l.getCompanyId() == COMPANY && l.getEventUuid() == EVENT && "system".equals(l.getCreatedBy())); + } + + @Test + void ensureCreatesNothingWhenAllCodesExist() { + eventInCompany(); + when(linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(EVENT)).thenReturn(List.of(link(null, "E", true))); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(EVENT, 9L)).thenReturn(Optional.of(link(9L, "P9", false))); + + List out = service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of(9L))); + + assertThat(out).extracting(RegistrationLinkService.LinkView::token).containsExactly("E", "P9"); + assertThat(out.get(1).enabled()).isFalse(); + verify(linkRepository, never()).save(any()); + } + + @Test + void ensureUsesOldestEventCodeWhenAConcurrentEnsureInsertedAnother() { + eventInCompany(); + when(linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(EVENT)) + .thenReturn(List.of()) + .thenReturn(List.of(link(null, "OLDEST", true), link(null, "NEWER", true))); + + List out = service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of())); + + assertThat(out).extracting(RegistrationLinkService.LinkView::token).containsExactly("OLDEST"); + } + + @Test + void ensureIs404WhenEventIsInAnotherCompany() { + when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(event(EVENT, 99L, "Expo", LocalDateTime.now(), LocalDateTime.now(), GeneralEnum.FlagYesNo.Y))); + + assertThatThrownBy(() -> service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of()))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(linkRepository, never()).save(any()); + } + + // --- setEnabled --- + + @Test + void setEnabledUpdatesLinkAndAudit() { + eventInCompany(); + RegistrationLink l = link(null, "T", true); + when(linkRepository.findByToken("T")).thenReturn(Optional.of(l)); + + RegistrationLinkService.LinkView v = service.setEnabled(new RegistrationLinkService.SetEnabledRequest(COMPANY, EVENT, "T", false, "admin")); + + assertThat(v.enabled()).isFalse(); + assertThat(l.getUpdatedBy()).isEqualTo("admin"); + assertThat(l.getUpdatedAt()).isNotNull(); + verify(linkRepository).save(l); + } + + @Test + void setEnabledRefusesAnotherCompanysToken() { + eventInCompany(); + RegistrationLink l = link(null, "T", true); + l.setCompanyId(99L); + when(linkRepository.findByToken("T")).thenReturn(Optional.of(l)); + + assertThatThrownBy(() -> service.setEnabled(new RegistrationLinkService.SetEnabledRequest(COMPANY, EVENT, "T", false, "a"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(linkRepository, never()).save(any()); + } + + @Test + void setEnabledRefusesAnotherEventsToken() { + eventInCompany(); + RegistrationLink l = link(null, "T", true); + l.setEventUuid(555L); + when(linkRepository.findByToken("T")).thenReturn(Optional.of(l)); + + assertThatThrownBy(() -> service.setEnabled(new RegistrationLinkService.SetEnabledRequest(COMPANY, EVENT, "T", false, "a"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + // --- findByToken --- + + @Test + void findByTokenReturnsTheLink() { + when(linkRepository.findByToken("T")).thenReturn(Optional.of(link(7L, "T", true))); + + RegistrationLinkService.LinkLookup v = service.findByToken("T"); + + assertThat(v.companyId()).isEqualTo(COMPANY); + assertThat(v.eventUuid()).isEqualTo(EVENT); + assertThat(v.salespersonUserId()).isEqualTo(7L); + assertThat(v.enabled()).isTrue(); + } + + @Test + void findByTokenIs404WhenUnknown() { + when(linkRepository.findByToken("X")).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.findByToken("X")) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + // --- mine --- + + @Test + void ensureUsesOldestPersonalCodeFirstLookupSoDuplicatesNeverBreakIt() { + eventInCompany(); + when(linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(EVENT)).thenReturn(List.of(link(null, "E", true))); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(EVENT, 9L)).thenReturn(Optional.of(link(9L, "OLDEST", true))); + + List out = service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of(9L))); + + assertThat(out).extracting(RegistrationLinkService.LinkView::token).containsExactly("E", "OLDEST"); + verify(linkRepository, never()).save(any()); + } + + @Test + void mineListsOnlyEnabledNotEndedTeamEventsOrderedByStartAndCreatesMissingLinks() { + EventSalesperson r1 = new EventSalesperson(); r1.setEventUuid(1L); + EventSalesperson r2 = new EventSalesperson(); r2.setEventUuid(2L); + EventSalesperson r3 = new EventSalesperson(); r3.setEventUuid(3L); + EventSalesperson r4 = new EventSalesperson(); r4.setEventUuid(4L); + when(eventSalespersonRepository.findByCompanyIdAndUserId(COMPANY, 7L)).thenReturn(List.of(r1, r2, r3, r4)); + Event later = event(1L, COMPANY, "Later", LocalDateTime.of(2026, 12, 10, 9, 0), LocalDateTime.of(2026, 12, 12, 18, 0), GeneralEnum.FlagYesNo.Y); + Event endsToday = event(2L, COMPANY, "EndsToday", LocalDateTime.of(2026, 12, 1, 9, 0), LocalDateTime.of(2026, 12, 1, 1, 0), GeneralEnum.FlagYesNo.Y); + Event ended = event(3L, COMPANY, "Ended", LocalDateTime.of(2026, 11, 1, 9, 0), LocalDateTime.of(2026, 11, 30, 23, 59), GeneralEnum.FlagYesNo.Y); + Event disabled = event(4L, COMPANY, "Off", LocalDateTime.of(2026, 12, 5, 9, 0), LocalDateTime.of(2026, 12, 6, 9, 0), GeneralEnum.FlagYesNo.N); + when(eventRepository.findByCompanyIdAndUuidIn(eq(COMPANY), anyCollection())).thenReturn(List.of(later, endsToday, ended, disabled)); + RegistrationLink existing = link(7L, "HAVE", true); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(1L, 7L)).thenReturn(Optional.of(existing)); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(2L, 7L)).thenReturn(Optional.empty()); + + List out = service.mine(new RegistrationLinkService.MineRequest(COMPANY, 7L, "2026-12-01")); + + assertThat(out).extracting(RegistrationLinkService.MineRow::eventName).containsExactly("EndsToday", "Later"); + assertThat(out.get(1).eventUuid()).isEqualTo("1"); + assertThat(out.get(1).startDate()).isEqualTo("2026-12-10"); + assertThat(out.get(1).endDate()).isEqualTo("2026-12-12"); + assertThat(out.get(1).location()).isEqualTo("KLCC"); + assertThat(out.get(1).token()).isEqualTo("HAVE"); + assertThat(out.get(0).token()).hasSize(22); + verify(linkRepository, times(1)).save(any()); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationServiceTest.java new file mode 100644 index 0000000..8f902f6 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationServiceTest.java @@ -0,0 +1,264 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.EventLeadInterest; +import com.solvway.services.counter.model.EventLeadStatusChange; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventLeadStatusChangeRepository; +import com.solvway.services.counter.repo.LeadRepository; +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RegistrationServiceTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + private static final String MOBILE = "+60123456789"; + private static final String EMAIL = "aisyah@example.com"; + private static final LocalDateTime CONSENT_AT = LocalDateTime.of(2026, 12, 1, 10, 0); + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository interestRepository; + @Mock private EventLeadStatusChangeRepository statusChangeRepository; + + private RegistrationService service; + private EventLeadService eventLeadService; + + @BeforeEach + void setUp() { + eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, interestRepository, statusChangeRepository); + service = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)), + leadRepository, eventLeadRepository, eventLeadService); + lenient().when(leadRepository.saveAndFlush(any(Lead.class))).then(returnsFirstArg()); + lenient().when(eventLeadRepository.saveAndFlush(any(EventLead.class))).then(i -> { + EventLead e = i.getArgument(0); + e.setId(1L); + return e; + }); + } + + private static Lead lead(String name, String mobile, String email, String company, String job) { + Lead l = new Lead(); + l.setCompanyId(COMPANY); + l.setName(name); + l.setMobileE164(mobile); + l.setEmailNormalised(email); + l.setCompanyName(company); + l.setJobTitle(job); + return l; + } + + private static RegistrationService.RegisterRequest req(String name, String mobile, String email, String company, String job, Long salesperson) { + return new RegistrationService.RegisterRequest(COMPANY, EVENT, salesperson, name, mobile, email, company, job, + List.of(5L, 6L), 77L, CONSENT_AT); + } + + private EventLead savedEventLead() { + ArgumentCaptor c = ArgumentCaptor.forClass(EventLead.class); + verify(eventLeadRepository).saveAndFlush(c.capture()); + return c.getValue(); + } + + @Test + void newPersonCreatesLeadAndEventLeadWithHistoryInterestsAndConsent() { + RegistrationService.RegisterResult r = service.register(req("Aisyah", MOBILE, EMAIL, "Acme", "CEO", 7L)); + + assertThat(r.outcome()).isEqualTo("CREATED"); + ArgumentCaptor lc = ArgumentCaptor.forClass(Lead.class); + verify(leadRepository).saveAndFlush(lc.capture()); + Lead l = lc.getValue(); + assertThat(l.getCompanyId()).isEqualTo(COMPANY); + assertThat(l.getName()).isEqualTo("Aisyah"); + assertThat(l.getMobileE164()).isEqualTo(MOBILE); + assertThat(l.getEmailNormalised()).isEqualTo(EMAIL); + assertThat(l.getCompanyName()).isEqualTo("Acme"); + assertThat(l.getJobTitle()).isEqualTo("CEO"); + assertThat(l.getCreatedBy()).isEqualTo("qr"); + EventLead e = savedEventLead(); + assertThat(r.eventLeadUuid()).isEqualTo(String.valueOf(e.getUuid())); + assertThat(e.getLeadUuid()).isEqualTo(l.getUuid()); + assertThat(e.getLeadType()).isEqualTo("NEW"); + assertThat(e.getStatus()).isEqualTo("OPEN"); + assertThat(e.getSource()).isEqualTo("QR"); + assertThat(e.getCapturedBy()).isEqualTo("qr"); + assertThat(e.getSalespersonUserId()).isEqualTo(7L); + assertThat(e.getConsentAt()).isEqualTo(CONSENT_AT); + assertThat(e.getConsentNoticeId()).isEqualTo(77L); + assertThat(e.getNotes()).isNull(); + ArgumentCaptor hc = ArgumentCaptor.forClass(EventLeadStatusChange.class); + verify(statusChangeRepository).save(hc.capture()); + assertThat(hc.getValue().getFromStatus()).isNull(); + assertThat(hc.getValue().getToStatus()).isEqualTo("OPEN"); + assertThat(hc.getValue().getChangedBy()).isEqualTo("qr"); + @SuppressWarnings("unchecked") ArgumentCaptor> ic = ArgumentCaptor.forClass(Iterable.class); + verify(interestRepository).saveAll(ic.capture()); + assertThat(ic.getValue()).hasSize(2); + } + + @Test + void knownByMobileLeavesLeadUntouchedAndNotesOnlyDifferingValues() { + Lead existing = lead("Aisyah", MOBILE, "old@example.com", "Acme", null); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + + RegistrationService.RegisterResult r = service.register(req("Aisyah Binti", MOBILE, EMAIL, "Acme", "CEO", null)); + + assertThat(r.outcome()).isEqualTo("LINKED"); + verify(leadRepository, never()).saveAndFlush(any()); + verify(leadRepository, never()).save(any()); + assertThat(existing.getName()).isEqualTo("Aisyah"); + assertThat(existing.getUpdatedAt()).isNull(); + EventLead e = savedEventLead(); + assertThat(e.getLeadType()).isEqualTo("EXISTING"); + assertThat(e.getLeadUuid()).isEqualTo(existing.getUuid()); + assertThat(e.getSource()).isEqualTo("QR"); + assertThat(e.getNotes()).isEqualTo("Registered by QR with: name Aisyah Binti; email aisyah@example.com; job title CEO"); + } + + @Test + void knownPersonWithNothingDifferingHasNullNotes() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, "Acme", "CEO"); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + + service.register(req("Aisyah", MOBILE, EMAIL, "Acme", "CEO", null)); + + assertThat(savedEventLead().getNotes()).isNull(); + } + + @Test + void blankSubmittedValuesAreNotNoted() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, "Acme", "CEO"); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + + service.register(req("Aisyah", MOBILE, EMAIL, " ", null, null)); + + assertThat(savedEventLead().getNotes()).isNull(); + } + + @Test + void mobileMatchBeatsEmailMatch() { + Lead byMobile = lead("ByMobile", MOBILE, null, null, null); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(byMobile)); + + service.register(req("X", MOBILE, EMAIL, null, null, null)); + + assertThat(savedEventLead().getLeadUuid()).isEqualTo(byMobile.getUuid()); + verify(leadRepository, never()).findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(any(Long.class), any()); + } + + @Test + void fallsBackToEmailWhenMobileMatchesNothingOrIsNull() { + Lead byEmail = lead("ByEmail", null, EMAIL, null, null); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.empty()); + when(leadRepository.findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(COMPANY, EMAIL)).thenReturn(Optional.of(byEmail)); + + service.register(req("ByEmail", MOBILE, EMAIL, null, null, null)); + + assertThat(savedEventLead().getLeadUuid()).isEqualTo(byEmail.getUuid()); + } + + @Test + void nullMobileAndEmailMatchNothing() { + RegistrationService.RegisterResult r = service.register(req("Aisyah", null, null, null, null, null)); + + assertThat(r.outcome()).isEqualTo("CREATED"); + verify(leadRepository, never()).findFirstByCompanyIdAndMobileE164OrderByIdDesc(any(Long.class), any()); + verify(leadRepository, never()).findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(any(Long.class), any()); + } + + @Test + void alreadyCapturedUnassignedGetsTheSalesperson() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, null, null); + EventLead captured = new EventLead(); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, existing.getUuid())).thenReturn(Optional.of(captured)); + + RegistrationService.RegisterResult r = service.register(req("Aisyah", MOBILE, EMAIL, null, null, 7L)); + + assertThat(r.outcome()).isEqualTo("ASSIGNED"); + assertThat(r.eventLeadUuid()).isEqualTo(String.valueOf(captured.getUuid())); + assertThat(captured.getSalespersonUserId()).isEqualTo(7L); + assertThat(captured.getUpdatedBy()).isEqualTo("qr"); + assertThat(captured.getUpdatedAt()).isNotNull(); + verify(eventLeadRepository).save(captured); + verify(statusChangeRepository, never()).save(any()); + } + + @Test + void alreadyCapturedWithSalespersonChangesNothing() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, null, null); + EventLead captured = new EventLead(); + captured.setSalespersonUserId(3L); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, existing.getUuid())).thenReturn(Optional.of(captured)); + + RegistrationService.RegisterResult r = service.register(req("Aisyah", MOBILE, EMAIL, null, null, 7L)); + + assertThat(r.outcome()).isEqualTo("ALREADY_CAPTURED"); + assertThat(captured.getSalespersonUserId()).isEqualTo(3L); + assertThat(captured.getUpdatedAt()).isNull(); + verify(eventLeadRepository, never()).save(any()); + verify(eventLeadRepository, never()).saveAndFlush(any()); + } + + @Test + void alreadyCapturedUnassignedWithNoSalespersonChangesNothing() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, null, null); + EventLead captured = new EventLead(); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, existing.getUuid())).thenReturn(Optional.of(captured)); + + assertThat(service.register(req("Aisyah", MOBILE, EMAIL, null, null, null)).outcome()).isEqualTo("ALREADY_CAPTURED"); + verify(eventLeadRepository, never()).save(any()); + } + + @Test + void uniqueKeyRaceRetriesInAFreshTransactionAndReportsAlreadyCaptured() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, null, null); + EventLead winner = new EventLead(); + winner.setSalespersonUserId(3L); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, existing.getUuid())) + .thenReturn(Optional.empty()).thenReturn(Optional.of(winner)); + when(eventLeadRepository.saveAndFlush(any(EventLead.class))).thenThrow(new DataIntegrityViolationException("uk_event_lead_event_lead")); + + RegistrationService.RegisterResult r = service.register(req("Aisyah", MOBILE, EMAIL, null, null, 7L)); + + assertThat(r.outcome()).isEqualTo("ALREADY_CAPTURED"); + assertThat(r.eventLeadUuid()).isEqualTo(String.valueOf(winner.getUuid())); + verify(eventLeadRepository, times(1)).saveAndFlush(any()); + verify(statusChangeRepository, never()).save(any()); + } + + @Test + void staffCaptureStillSourcesStaff() { + eventLeadService.capture(new EventLeadCaptureRequest(COMPANY, EVENT, null, "Aisyah", MOBILE, EMAIL, null, null, + 7L, null, null, List.of(), null, null, "staff1")); + + assertThat(savedEventLead().getSource()).isEqualTo("STAFF"); + } +} -- 2.54.1 From ab1643e36e443c365c60d37795108244ad1752a3 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:00:18 +0800 Subject: [PATCH 06/20] 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 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../CompanyPrivacyNoticeController.java | 37 +++++++ .../system/model/CompanyPrivacyNotice.java | 29 ++++++ .../repo/CompanyPrivacyNoticeRepository.java | 13 +++ .../service/CompanyPrivacyNoticeService.java | 48 +++++++++ .../CompanyPrivacyNoticeControllerTest.java | 99 +++++++++++++++++++ .../CompanyPrivacyNoticeServiceTest.java | 97 ++++++++++++++++++ 6 files changed, 323 insertions(+) create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/controller/CompanyPrivacyNoticeController.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/model/CompanyPrivacyNotice.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/repo/CompanyPrivacyNoticeRepository.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/service/CompanyPrivacyNoticeService.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/CompanyPrivacyNoticeControllerTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/service/CompanyPrivacyNoticeServiceTest.java diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/CompanyPrivacyNoticeController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/CompanyPrivacyNoticeController.java new file mode 100644 index 0000000..4dbc305 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/CompanyPrivacyNoticeController.java @@ -0,0 +1,37 @@ +package com.solvway.services.system.controller; + +import com.solvway.services.system.model.CompanyPrivacyNotice; +import com.solvway.services.system.service.CompanyPrivacyNoticeService; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestController +@RequestMapping("/company") +public class CompanyPrivacyNoticeController { + + public record NoticeRequest(String textEn, String textMs, String doneBy) {} + + private final CompanyPrivacyNoticeService service; + + public CompanyPrivacyNoticeController(CompanyPrivacyNoticeService service) { + this.service = service; + } + + @GetMapping("/{id}/privacyNotice") + public CompanyPrivacyNotice current(@PathVariable Long id) { + return service.current(id); + } + + @PostMapping("/{id}/privacyNotice") + public CompanyPrivacyNotice add(@PathVariable Long id, @RequestBody NoticeRequest body) { + return service.add(id, body.textEn(), body.textMs(), body.doneBy()); + } + + @ExceptionHandler({IllegalArgumentException.class, HttpMessageNotReadableException.class}) + public ResponseEntity> badRequest(RuntimeException e) { + return ResponseEntity.badRequest().body(Map.of("message", String.valueOf(e.getMessage()))); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/CompanyPrivacyNotice.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/CompanyPrivacyNotice.java new file mode 100644 index 0000000..1624244 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/CompanyPrivacyNotice.java @@ -0,0 +1,29 @@ +package com.solvway.services.system.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** Append-only privacy notice version; the newest row (highest id) of a company is current. */ +@Entity +@Table(name = "company_privacy_notice") +@Getter +@Setter +public class CompanyPrivacyNotice { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Long companyId; + + private String textEn; + + private String textMs; + + private String createdBy; + + private LocalDateTime createdAt; +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/CompanyPrivacyNoticeRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/CompanyPrivacyNoticeRepository.java new file mode 100644 index 0000000..8755b2e --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/CompanyPrivacyNoticeRepository.java @@ -0,0 +1,13 @@ +package com.solvway.services.system.repo; + +import com.solvway.services.system.model.CompanyPrivacyNotice; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface CompanyPrivacyNoticeRepository extends JpaRepository { + + Optional findFirstByCompanyIdOrderByIdDesc(Long companyId); +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/CompanyPrivacyNoticeService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/CompanyPrivacyNoticeService.java new file mode 100644 index 0000000..c2c3267 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/CompanyPrivacyNoticeService.java @@ -0,0 +1,48 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.CompanyPrivacyNotice; +import com.solvway.services.system.repo.CompanyPrivacyNoticeRepository; +import com.solvway.services.system.repo.CompanyRepository; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; + +@Service +public class CompanyPrivacyNoticeService { + + private static final int TEXT_MAX = 5000; + + private final CompanyPrivacyNoticeRepository notices; + private final CompanyRepository companies; + + public CompanyPrivacyNoticeService(CompanyPrivacyNoticeRepository notices, CompanyRepository companies) { + this.notices = notices; + this.companies = companies; + } + + public CompanyPrivacyNotice current(Long companyId) { + return notices.findFirstByCompanyIdOrderByIdDesc(companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No privacy notice")); + } + + /** Always inserts a new version; existing rows are never updated or deleted. */ + public CompanyPrivacyNotice add(Long companyId, String textEn, String textMs, String doneBy) { + if (!companies.existsById(companyId)) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Company not found"); + CompanyPrivacyNotice n = new CompanyPrivacyNotice(); + n.setCompanyId(companyId); + n.setTextEn(text(textEn, "English")); + n.setTextMs(text(textMs, "Bahasa Malaysia")); + n.setCreatedBy(doneBy); + n.setCreatedAt(LocalDateTime.now()); + return notices.save(n); + } + + private static String text(String raw, String language) { + String v = raw == null ? "" : raw.trim(); + if (v.isEmpty()) throw new IllegalArgumentException(language + " text is required"); + if (v.length() > TEXT_MAX) throw new IllegalArgumentException(language + " text must be at most " + TEXT_MAX + " characters"); + return v; + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/CompanyPrivacyNoticeControllerTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/CompanyPrivacyNoticeControllerTest.java new file mode 100644 index 0000000..67ec5d5 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/CompanyPrivacyNoticeControllerTest.java @@ -0,0 +1,99 @@ +package com.solvway.services.system.controller; + +import com.solvway.services.system.model.CompanyPrivacyNotice; +import com.solvway.services.system.service.CompanyPrivacyNoticeService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class CompanyPrivacyNoticeControllerTest { + + @Mock private CompanyPrivacyNoticeService service; + @InjectMocks private CompanyPrivacyNoticeController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + private static CompanyPrivacyNotice notice() { + CompanyPrivacyNotice n = new CompanyPrivacyNotice(); + n.setId(5L); + n.setCompanyId(1L); + n.setTextEn("en"); + n.setTextMs("ms"); + n.setCreatedBy("admin"); + n.setCreatedAt(LocalDateTime.of(2026, 12, 1, 9, 0)); + return n; + } + + @Test + void getReturnsCurrentNotice() throws Exception { + when(service.current(1L)).thenReturn(notice()); + + mvc.perform(get("/company/1/privacyNotice")).andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(5)).andExpect(jsonPath("$.companyId").value(1)) + .andExpect(jsonPath("$.textEn").value("en")).andExpect(jsonPath("$.textMs").value("ms")) + .andExpect(jsonPath("$.createdBy").value("admin")).andExpect(jsonPath("$.createdAt").exists()); + } + + @Test + void getWithNoneIs404() throws Exception { + when(service.current(1L)).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "No privacy notice")); + + mvc.perform(get("/company/1/privacyNotice")).andExpect(status().isNotFound()); + } + + @Test + void postAddsVersionAndReturnsIt() throws Exception { + when(service.add(1L, "en", "ms", "admin")).thenReturn(notice()); + + mvc.perform(post("/company/1/privacyNotice").contentType(MediaType.APPLICATION_JSON) + .content("{\"textEn\":\"en\",\"textMs\":\"ms\",\"doneBy\":\"admin\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(5)); + verify(service).add(1L, "en", "ms", "admin"); + } + + @Test + void invalidTextIs400WithMessage() throws Exception { + when(service.add(1L, "", "ms", null)).thenThrow(new IllegalArgumentException("English text is required")); + + mvc.perform(post("/company/1/privacyNotice").contentType(MediaType.APPLICATION_JSON) + .content("{\"textEn\":\"\",\"textMs\":\"ms\"}")) + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("English text is required")); + } + + @Test + void unknownCompanyIs404() throws Exception { + when(service.add(9L, "en", "ms", null)).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Company not found")); + + mvc.perform(post("/company/9/privacyNotice").contentType(MediaType.APPLICATION_JSON) + .content("{\"textEn\":\"en\",\"textMs\":\"ms\"}")) + .andExpect(status().isNotFound()); + } + + @Test + void missingBodyIs400() throws Exception { + mvc.perform(post("/company/1/privacyNotice").contentType(MediaType.APPLICATION_JSON).content("")) + .andExpect(status().isBadRequest()); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/CompanyPrivacyNoticeServiceTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/CompanyPrivacyNoticeServiceTest.java new file mode 100644 index 0000000..b4744df --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/CompanyPrivacyNoticeServiceTest.java @@ -0,0 +1,97 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.CompanyPrivacyNotice; +import com.solvway.services.system.repo.CompanyPrivacyNoticeRepository; +import com.solvway.services.system.repo.CompanyRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CompanyPrivacyNoticeServiceTest { + + @Mock private CompanyPrivacyNoticeRepository notices; + @Mock private CompanyRepository companies; + private CompanyPrivacyNoticeService service; + + @BeforeEach + void setUp() { + service = new CompanyPrivacyNoticeService(notices, companies); + when(companies.existsById(1L)).thenReturn(true); + when(notices.save(any(CompanyPrivacyNotice.class))).thenAnswer(i -> i.getArgument(0)); + } + + private static CompanyPrivacyNotice notice(Long id) { + CompanyPrivacyNotice n = new CompanyPrivacyNotice(); + n.setId(id); + n.setCompanyId(1L); + return n; + } + + private static void assertStatus(Throwable e, int code) { + assertThat(e).isInstanceOfSatisfying(ResponseStatusException.class, r -> assertThat(r.getStatusCode().value()).isEqualTo(code)); + } + + @Test + void currentIsTheNewestVersion() { + CompanyPrivacyNotice newest = notice(7L); + when(notices.findFirstByCompanyIdOrderByIdDesc(1L)).thenReturn(Optional.of(newest)); + + assertThat(service.current(1L)).isSameAs(newest); + } + + @Test + void currentWithNoNoticeIs404() { + when(notices.findFirstByCompanyIdOrderByIdDesc(1L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.current(1L)).satisfies(e -> assertStatus(e, 404)); + } + + @Test + void addInsertsANewRowTrimmedAndNeverTouchesOldOnes() { + CompanyPrivacyNotice saved = service.add(1L, " English ", " Bahasa ", "admin"); + + assertThat(saved.getId()).isNull(); // always a fresh insert, never an update of an existing row + assertThat(saved.getCompanyId()).isEqualTo(1L); + assertThat(saved.getTextEn()).isEqualTo("English"); + assertThat(saved.getTextMs()).isEqualTo("Bahasa"); + assertThat(saved.getCreatedBy()).isEqualTo("admin"); + assertThat(saved.getCreatedAt()).isNotNull(); + verify(notices).save(any(CompanyPrivacyNotice.class)); + } + + @Test + void bothTextsAreRequired() { + assertThatThrownBy(() -> service.add(1L, " ", "ms", "a")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> service.add(1L, "en", null, "a")).isInstanceOf(IllegalArgumentException.class); + verify(notices, never()).save(any()); + } + + @Test + void textsAreLimitedTo5000Characters() { + assertThat(service.add(1L, "e".repeat(5000), "m".repeat(5000), "a")).isNotNull(); + assertThatThrownBy(() -> service.add(1L, "e".repeat(5001), "ms", "a")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> service.add(1L, "en", "m".repeat(5001), "a")).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void addForUnknownCompanyIs404() { + assertThatThrownBy(() -> service.add(9L, "en", "ms", "a")).satisfies(e -> assertStatus(e, 404)); + verify(notices, never()).save(any()); + } +} -- 2.54.1 From cf8478d00c35f52219f00c804ca80c49e1e804bc Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:16:58 +0800 Subject: [PATCH 07/20] 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 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../api/RestApiCounterServiceConstants.java | 7 + .../api/RestApiSystemServiceConstants.java | 1 + .../admin/AdminCompanyController.java | 17 +- .../AdminRegistrationLinkController.java | 49 +++ .../PublicRegistrationController.java | 35 ++ .../api/dto/PublicRegistrationRequest.java | 8 + .../api/service/AdminCompanyService.java | 12 + .../api/service/AdminEventLeadService.java | 14 +- .../service/PublicRegistrationService.java | 171 +++++++++ .../api/service/RegistrationLinkService.java | 101 ++++++ .../api/useraccess/AppAccessAspect.java | 6 +- .../mobile/api/useraccess/Audited.java | 3 + .../admin/AdminCompanyPrivacyNoticeTest.java | 121 +++++++ .../AdminRegistrationLinkControllerTest.java | 66 ++++ .../PublicRegistrationControllerTest.java | 57 +++ .../PublicRegistrationServiceTest.java | 338 ++++++++++++++++++ .../service/PublicRegistrationWiringTest.java | 29 ++ .../service/RegistrationLinkServiceTest.java | 156 ++++++++ .../AppAccessAspectRegistrationAuditTest.java | 110 ++++++ 19 files changed, 1292 insertions(+), 9 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRegistrationLinkController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicRegistrationController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/PublicRegistrationRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/RegistrationLinkService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminCompanyPrivacyNoticeTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRegistrationLinkControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/publicapi/PublicRegistrationControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationWiringTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/RegistrationLinkServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectRegistrationAuditTest.java diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index 6cbe86c..ea6123d 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -55,4 +55,11 @@ public class RestApiCounterServiceConstants { //Member Voucher public static final String API_REST_COUNTER_MEMBER_VOUCHER_FIND_ELIGIBILITY="/counter/memberVoucher/findEligibility"; + + //Registration links and public self-registration + public static final String API_REST_COUNTER_REGISTRATION_LINK_FIND_BY_TOKEN="/counter/registrationLink/findByToken/{token}"; + public static final String API_REST_COUNTER_REGISTRATION_LINK_ENSURE="/counter/registrationLink/ensure"; + public static final String API_REST_COUNTER_REGISTRATION_LINK_SET_ENABLED="/counter/registrationLink/setEnabled"; + public static final String API_REST_COUNTER_REGISTRATION_LINK_MINE="/counter/registrationLink/mine"; + public static final String API_REST_COUNTER_REGISTRATION_REGISTER="/counter/registration/register"; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index 7f943aa..37b2d89 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -99,6 +99,7 @@ public class RestApiSystemServiceConstants { public static final String API_REST_COMPANY_FIND_BY_ID = "/company/findById/{id}"; public static final String API_REST_COMPANY_SAVE = "/company/save"; public static final String API_REST_COMPANY_RENAME_CODE = "/company/{id}/code"; + public static final String API_REST_COMPANY_PRIVACY_NOTICE = "/company/{id}/privacyNotice"; //LoginSecurity (admin sign-in lock check and history) public static final String API_REST_LOGIN_SECURITY_IS_LOCKED = "/loginSecurity/isLocked/{username}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java index 2c86c38..3533b3a 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java @@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -59,15 +60,29 @@ public class AdminCompanyController { return ResponseEntity.ok(companies.renameCode(id, body.get("code"))); } + @AppAuth + @GetMapping("/{id}/privacy-notice") + public ResponseEntity> privacyNotice(@PathVariable Long id) { + requireSuper(); + return ResponseEntity.ok(companies.privacyNotice(id)); + } + + @AppAuth + @PutMapping("/{id}/privacy-notice") + public ResponseEntity> savePrivacyNotice(@PathVariable Long id, @RequestBody Map body) { + return ResponseEntity.ok(companies.savePrivacyNotice(id, body, requireSuper().getUsername())); + } + /** Portal body is just {"message"}; the exception still reaches AppAccessAspect first, so the audit has the real status. */ @ExceptionHandler(CodedResponseStatusException.class) public ResponseEntity> upstream(CodedResponseStatusException e) { return ResponseEntity.status(e.getStatusCode()).body(Map.of("message", String.valueOf(e.getReason()))); } - private void requireSuper() { + private User requireSuper() { User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); scope.requireSuper(caller); + return caller; } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRegistrationLinkController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRegistrationLinkController.java new file mode 100644 index 0000000..ea3b23b --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRegistrationLinkController.java @@ -0,0 +1,49 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.mobile.api.useraccess.Audited; +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.service.RegistrationLinkService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** QR registration links for the admin portal. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +public class AdminRegistrationLinkController { + public record Toggle(Boolean enabled) {} + + private final RegistrationLinkService links; + + @AppAuth + @AdminModule("BO_EVENTS") + @GetMapping("/events/{uuid}/registration-links") + public ResponseEntity> links(@PathVariable String uuid) { + return ResponseEntity.ok(links.links(uuid)); + } + + @AppAuth + @AdminModule("BO_EVENTS") + @Audited(targetVariable = "uuid") + @PutMapping("/events/{uuid}/registration-links/{token}") + public ResponseEntity> setEnabled(@PathVariable String uuid, @PathVariable String token, @RequestBody Toggle body) { + return ResponseEntity.ok(links.setEnabled(uuid, token, body.enabled())); + } + + @AppAuth + @AdminModule(AdminModule.ANY_ADMIN) + @GetMapping("/my-registration-links") + public ResponseEntity>> mine() { + return ResponseEntity.ok(links.mine()); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicRegistrationController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicRegistrationController.java new file mode 100644 index 0000000..8200db3 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicRegistrationController.java @@ -0,0 +1,35 @@ +package com.solvway.mobile.api.controller.publicapi; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.PublicRegistrationRequest; +import com.solvway.mobile.api.service.PublicRegistrationService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +/** QR self-registration for walk-in visitors: no sign-in. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/public/registration") +@RequiredArgsConstructor +public class PublicRegistrationController { + private final PublicRegistrationService registration; + + @AppAuth(skipValidate = true) + @GetMapping("/{token}") + public ResponseEntity> page(@PathVariable String token) { + return ResponseEntity.ok(registration.page(token)); + } + + @AppAuth(skipValidate = true) + @PostMapping("/{token}") + public ResponseEntity> register(@PathVariable String token, @RequestBody PublicRegistrationRequest request) { + return ResponseEntity.ok(registration.register(token, request)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/PublicRegistrationRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/PublicRegistrationRequest.java new file mode 100644 index 0000000..04e9ae0 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/PublicRegistrationRequest.java @@ -0,0 +1,8 @@ +package com.solvway.mobile.api.dto; + +import java.util.List; + +/** A visitor's self-registration. {@code website} is the honeypot: real visitors never see or fill it. */ +public record PublicRegistrationRequest(String name, String mobile, String email, String companyName, String jobTitle, + List interestIds, Boolean consent, String website) { +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java index fc0bf3a..32d7350 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java @@ -46,6 +46,18 @@ public class AdminCompanyService { Map.of("code", code)).getBody()); } + public Map privacyNotice(Long id) { + return call(() -> restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE).replace("{id}", String.valueOf(id)), MAP).getBody()); + } + + public Map savePrivacyNotice(Long id, Map notice, String doneBy) { + Map body = new java.util.LinkedHashMap<>(); + body.put("textEn", notice.get("textEn")); + body.put("textMs", notice.get("textMs")); + body.put("doneBy", doneBy); + return call(() -> restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE).replace("{id}", String.valueOf(id)), MAP, body).getBody()); + } + private static T call(Supplier call) { try { return call.get(); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java index 01f13d8..36ffdc7 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -291,7 +291,7 @@ public class AdminEventLeadService { } /** Ids must be the company's interests; one newly added must be active, one already on the lead may stay. */ - private static List checkedInterests(Map> known, List requested, List current) { + static List checkedInterests(Map> known, List requested, List current) { List ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList())); for (Long id : ids) { Map interest = known.get(id); @@ -365,7 +365,7 @@ public class AdminEventLeadService { } /** id -> {id, name, active}, in the counter's order (sort order, then name). Interests are one shared list: the counter ignores the path company. */ - private Map> interests(Long companyId) { + Map> interests(Long companyId) { List> rows = restTemplateUtil.getForEntity( url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId == null ? 0L : companyId).getBody(); // ponytail: 0 when no company is known; drop the path variable when the counter does Map> out = new LinkedHashMap<>(); @@ -376,18 +376,18 @@ public class AdminEventLeadService { return out; } - private List teamIds(long eventUuid) { + List teamIds(long eventUuid) { List> rows = restTemplateUtil.getForEntity( url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID), MAP_LIST, eventUuid).getBody(); return rows == null ? List.of() : rows.stream().map(m -> ((Number) m.get("userId")).longValue()).toList(); } - private Map user(Long id) { + Map user(Long id) { return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody(); } /** The event, or 404 when it is missing or outside the caller's scope (staff: own company; super: the requested one, or any). */ - private CompanyEvent loadEvent(String uuid, Long requestedCompanyId) { + CompanyEvent loadEvent(String uuid, Long requestedCompanyId) { long id = parseOr(uuid, AdminEventLeadService::eventNotFound); CompanyEvent event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody(); if (event == null) throw eventNotFound(); @@ -396,7 +396,7 @@ public class AdminEventLeadService { return event; } - private User caller() { + User caller() { User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null); return caller; @@ -416,7 +416,7 @@ public class AdminEventLeadService { } } - private static boolean isActiveAdminOf(Map user, Long companyId) { + static boolean isActiveAdminOf(Map user, Long companyId) { return isActiveAdmin(user) && user.get("companyId") instanceof Number n && companyId != null && n.longValue() == companyId; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java new file mode 100644 index 0000000..70ed776 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java @@ -0,0 +1,171 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.dto.PublicRegistrationRequest; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +import java.time.Clock; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +import static com.solvway.mobile.api.service.AdminEventLeadService.error; +import static com.solvway.mobile.api.service.AdminEventLeadService.maxLength; +import static com.solvway.mobile.api.service.AdminEventLeadService.parseOr; +import static com.solvway.mobile.api.service.AdminEventLeadService.trimmed; + +/** + * Public QR self-registration: no sign-in, so every answer about a code that cannot be used is the same 404. + * Validation is the staff capture's (AdminEventLeadService helpers). Never log a visitor's name, mobile or email, or the token. + */ +@Service +@SuppressWarnings("unchecked") +public class PublicRegistrationService { + static final ZoneId MALAYSIA = ZoneId.of("Asia/Kuala_Lumpur"); + private static final int LOAD_LIMIT = 120; + private static final int SUBMIT_LIMIT = 60; + private static final long WINDOW_MINUTES = 10; + + private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + + private final RestTemplateCustomUtil rest; + private final AdminEventLeadService leads; + private final RedisTemplate redis; + private final Clock clock; + + @Autowired + public PublicRegistrationService(RestTemplateCustomUtil rest, AdminEventLeadService leads, RedisTemplate redis) { + this(rest, leads, redis, Clock.systemUTC()); + } + + PublicRegistrationService(RestTemplateCustomUtil rest, AdminEventLeadService leads, RedisTemplate redis, Clock clock) { + this.rest = rest; + this.leads = leads; + this.redis = redis; + this.clock = clock; + } + + /** What a valid code is for: the usable link, its event, the company's name and its current notice. */ + private record Open(Map link, CompanyEvent event, String companyName, Map notice) {} + + public Map page(String token) { + limit("reg:load:" + ip(), LOAD_LIMIT); + Open o = open(token); + CompanyEvent e = o.event(); + Map out = new LinkedHashMap<>(); + out.put("eventName", e.getName()); + out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString()); + out.put("endDate", e.getDateEnd().toLocalDate().toString()); + out.put("location", e.getLocation()); + out.put("companyName", o.companyName()); + out.put("notice", Map.of("id", o.notice().get("id"), "textEn", String.valueOf(o.notice().get("textEn")), "textMs", String.valueOf(o.notice().get("textMs")))); + out.put("interests", leads.interests(e.getCompanyId()).values().stream() + .filter(i -> Boolean.TRUE.equals(i.get("active"))).map(i -> Map.of("id", i.get("id"), "name", i.get("name"))).toList()); + return out; + } + + public Map register(String token, PublicRegistrationRequest r) { + limit("reg:load:" + ip(), LOAD_LIMIT); // counts token guessing by POST too + Open o = open(token); + CompanyEvent e = o.event(); + Map done = Map.of("eventName", String.valueOf(e.getName())); + if (r.website() != null && !r.website().isBlank()) return done; // honeypot: look like success, store nothing + limit("reg:submit:" + e.getUuid() + ":" + ip(), SUBMIT_LIMIT); + + String name = trimmed(r.name()); + String mobile = AdminEventLeadService.mobile(r.mobile()); + String email = AdminEventLeadService.email(r.email()); + List missing = new ArrayList<>(); + if (name == null) missing.add("name"); + if (mobile == null && email == null) { missing.add("mobile"); missing.add("email"); } + if (!missing.isEmpty()) throw AdminEventLeadService.required(missing); + maxLength("name", name, 100); + maxLength("email", email, 254); + String companyName = maxLength("companyName", trimmed(r.companyName()), 150); + String jobTitle = maxLength("jobTitle", trimmed(r.jobTitle()), 100); + List interestIds = AdminEventLeadService.checkedInterests(leads.interests(e.getCompanyId()), r.interestIds(), List.of()); + if (!Boolean.TRUE.equals(r.consent())) throw error(HttpStatus.BAD_REQUEST, "Please agree to the privacy notice", "CONSENT_REQUIRED", "consent"); + + Map body = new LinkedHashMap<>(); + body.put("companyId", e.getCompanyId()); + body.put("eventUuid", e.getUuid()); + body.put("salespersonUserId", salesperson(o.link(), e)); + body.put("name", name); + body.put("mobileE164", mobile); + body.put("email", email); + body.put("companyName", companyName); + body.put("jobTitle", jobTitle); + body.put("interestIds", interestIds); + body.put("consentNoticeId", o.notice().get("id")); + body.put("consentAt", LocalDateTime.now(clock.withZone(MALAYSIA)).toString()); + rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_REGISTER), MAP, body); + return done; + } + + /** The link's salesperson only while still on the event's team and an active admin of the company, else the event code's null. */ + private Long salesperson(Map link, CompanyEvent e) { + if (!(link.get("salespersonUserId") instanceof Number n)) return null; + long id = n.longValue(); + return leads.teamIds(e.getUuid()).contains(id) && AdminEventLeadService.isActiveAdminOf(found(() -> leads.user(id)), e.getCompanyId()) ? id : null; + } + + private Open open(String token) { + Map link = found(() -> rest.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_FIND_BY_TOKEN), MAP, token).getBody()); + if (link == null || !Boolean.TRUE.equals(link.get("enabled")) || !(link.get("eventUuid") instanceof Number uuid)) throw inactive(); + CompanyEvent e = found(() -> rest.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, uuid.longValue()).getBody()); + LocalDate today = LocalDate.now(clock.withZone(MALAYSIA)); + if (e == null || e.getEnabled() != GeneralEnum.FlagYesNo.Y || e.getDateEnd() == null || e.getDateEnd().toLocalDate().isBefore(today) + || e.getCompanyId() == null || !(link.get("companyId") instanceof Number c) || c.longValue() != e.getCompanyId()) throw inactive(); + Map company = found(() -> rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_BY_ID), MAP, e.getCompanyId()).getBody()); + if (company == null || !"A".equals(company.get("status"))) throw inactive(); + Map notice = found(() -> rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE), MAP, e.getCompanyId()).getBody()); + if (notice == null || notice.get("id") == null) throw inactive(); + return new Open(link, e, String.valueOf(company.get("name")), notice); + } + + /** A backend 404 and an empty body both mean "not there". */ + private static T found(Supplier call) { + try { + return call.get(); + } catch (HttpClientErrorException.NotFound e) { + return null; + } + } + + /** Fixed-window counter per key. ponytail: INCR then EXPIRE is not atomic; a crash between them leaves a key without expiry, move to a Lua script if that bites. */ + private void limit(String key, int max) { + Long n = redis.opsForValue().increment(key); + if (n != null && n == 1) redis.expire(key, WINDOW_MINUTES, TimeUnit.MINUTES); + if (n != null && n > max) throw error(HttpStatus.TOO_MANY_REQUESTS, "Too many registrations from this device. Try again later.", "TOO_MANY", null); + } + + private static String ip() { + return HttpReqRespUtils.getClientIpAddressIfServletRequestExist(); + } + + private static CodedResponseStatusException inactive() { + return error(HttpStatus.NOT_FOUND, "This code is no longer active.", "CODE_INACTIVE", null); + } + + private String url(String api) { + return rest.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/RegistrationLinkService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/RegistrationLinkService.java new file mode 100644 index 0000000..9eee59f --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/RegistrationLinkService.java @@ -0,0 +1,101 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +import java.time.Clock; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static com.solvway.mobile.api.service.AdminEventLeadService.error; + +/** Admin side of QR registration: an event's links (event code and one per team member), switching one off, and a salesperson's own links. */ +@Service +public class RegistrationLinkService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + + private final RestTemplateCustomUtil rest; + private final AdminEventLeadService leads; + private final Clock clock; + + @Autowired + public RegistrationLinkService(RestTemplateCustomUtil rest, AdminEventLeadService leads) { + this(rest, leads, Clock.systemUTC()); + } + + RegistrationLinkService(RestTemplateCustomUtil rest, AdminEventLeadService leads, Clock clock) { + this.rest = rest; + this.leads = leads; + this.clock = clock; + } + + public Map links(String eventUuid) { + CompanyEvent event = leads.loadEvent(eventUuid, null); + Map body = new LinkedHashMap<>(); + body.put("companyId", event.getCompanyId()); + body.put("eventUuid", event.getUuid()); + body.put("salespersonUserIds", leads.teamIds(event.getUuid())); + List> rows = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_ENSURE), MAP_LIST, body).getBody(); + Map out = new LinkedHashMap<>(); + List> members = new ArrayList<>(); + out.put("members", members); + for (Map row : rows == null ? List.>of() : rows) { + if (!(row.get("salespersonUserId") instanceof Number id)) { + out.put("event", Map.of("token", row.get("token"), "enabled", row.get("enabled"))); + continue; + } + Map u = leads.user(id.longValue()); + Map m = new LinkedHashMap<>(); + m.put("userId", id.longValue()); + m.put("name", u == null ? String.valueOf(id) : String.valueOf(u.get("name"))); + m.put("token", row.get("token")); + m.put("enabled", row.get("enabled")); + members.add(m); + } + return out; + } + + public Map setEnabled(String eventUuid, String token, Boolean enabled) { + if (enabled == null) throw AdminEventLeadService.required(List.of("enabled")); + User caller = leads.caller(); + CompanyEvent event = leads.loadEvent(eventUuid, null); + Map body = new LinkedHashMap<>(); + body.put("companyId", event.getCompanyId()); + body.put("eventUuid", event.getUuid()); + body.put("token", token); + body.put("enabled", enabled); + body.put("doneBy", caller.getUsername()); + try { + return rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_SET_ENABLED), MAP, body).getBody(); + } catch (HttpClientErrorException.NotFound e) { + throw error(HttpStatus.NOT_FOUND, "Registration link not found", "LINK_NOT_FOUND", null); + } + } + + /** The caller's own links for events still running; a user with no company (super admin) has none. */ + public List> mine() { + User caller = leads.caller(); + if (caller.getCompanyId() == null) return List.of(); + Map body = new LinkedHashMap<>(); + body.put("companyId", caller.getCompanyId()); + body.put("userId", caller.getId()); + body.put("today", LocalDate.now(clock.withZone(PublicRegistrationService.MALAYSIA)).toString()); + List> rows = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_MINE), MAP_LIST, body).getBody(); + return rows == null ? List.of() : rows; + } + + private String url(String api) { + return rest.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java index 712c0bd..8902947 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java @@ -187,7 +187,11 @@ public class AppAccessAspect { && request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) instanceof Map vars && !vars.isEmpty()) { Object last = null; - for (Object v : vars.values()) last = v; + if (audited != null && StringUtils.hasText(audited.targetVariable())) { + last = vars.get(audited.targetVariable()); + } else { + for (Object v : vars.values()) last = v; + } event.setTargetId(String.valueOf(last)); } event.setHttpStatus(status); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/Audited.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/Audited.java index 88170aa..fef0688 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/Audited.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/Audited.java @@ -22,4 +22,7 @@ public @interface Audited { /** False when the path variable is free text a person typed (e.g. a username from a failed sign-in): no target is recorded. */ boolean target() default true; + + /** Path variable to record as the target; empty means the last one. Set it when the last variable is a secret (e.g. a registration token). */ + String targetVariable() default ""; } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminCompanyPrivacyNoticeTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminCompanyPrivacyNoticeTest.java new file mode 100644 index 0000000..43bc4bb --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminCompanyPrivacyNoticeTest.java @@ -0,0 +1,121 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.service.AdminAuthenticationService; +import com.solvway.mobile.api.service.AdminCompanyService; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.HttpClientErrorException; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** Privacy notice endpoints of the Companies screen: super admin only. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminCompanyPrivacyNoticeTest { + + private static final String NOTICE = "/company/{id}/privacyNotice"; + private static final String BODY = "{\"textEn\":\"English\",\"textMs\":\"Malay\"}"; + + private final AdminCompanyService companies = mock(AdminCompanyService.class); + private final AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + private MockMvc mvc; + private MockedStatic http; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(new AdminCompanyController(companies, auth, new AdminCompanyScope())).build(); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + } + + @AfterEach + void close() { http.close(); } + + private void caller(Long companyId, long roleId) { + User u = new User(); + u.setCompanyId(companyId); + u.setUsername("root"); + Role r = new Role("R"); + r.setId(roleId); + u.setRoles(List.of(r)); + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + @Test + void handlersAreAuthenticated() throws Exception { + assertThat(AdminCompanyController.class.getDeclaredMethods()).filteredOn(m -> m.getName().toLowerCase().contains("privacy")) + .hasSize(2).allSatisfy(m -> assertThat(m.isAnnotationPresent(AppAuth.class)).isTrue()); + } + + @Test + void staff_get403_andNothingIsCalled() throws Exception { + caller(5L, 1); + mvc.perform(get("/api/admin/companies/5/privacy-notice")).andExpect(status().isForbidden()); + mvc.perform(put("/api/admin/companies/5/privacy-notice").contentType(MediaType.APPLICATION_JSON).content(BODY)).andExpect(status().isForbidden()); + verifyNoInteractions(companies); + } + + @Test + void superAdmin_getsAndSaves_withCallerAsDoneBy() throws Exception { + caller(null, 1); + when(companies.privacyNotice(5L)).thenReturn(Map.of("id", 9, "textEn", "English")); + when(companies.savePrivacyNotice(eq(5L), any(), eq("root"))).thenReturn(Map.of("id", 10, "textEn", "English")); + mvc.perform(get("/api/admin/companies/5/privacy-notice")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(9)); + mvc.perform(put("/api/admin/companies/5/privacy-notice").contentType(MediaType.APPLICATION_JSON).content(BODY)) + .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(10)); + verify(companies).savePrivacyNotice(eq(5L), eq(Map.of("textEn", "English", "textMs", "Malay")), eq("root")); + } + + // --- service --- + + private static HttpClientErrorException err(HttpStatus s, String body) { + return HttpClientErrorException.create(s, s.name(), null, body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); + } + + @Test + void service_sendsTextsAndDoneBy_andMapsUpstreamErrors() { + RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + AdminCompanyService service = new AdminCompanyService(rest); + when(rest.postForEntity(eq("/company/5/privacyNotice"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("id", 10))); + assertThat(service.savePrivacyNotice(5L, Map.of("textEn", "E", "textMs", "M"), "root")).containsEntry("id", 10); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/company/5/privacyNotice"), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("textEn", "E").containsEntry("textMs", "M").containsEntry("doneBy", "root"); + + when(rest.getForEntity(eq("/company/9/privacyNotice"), any(ParameterizedTypeReference.class))).thenThrow(err(HttpStatus.NOT_FOUND, "{}")); + assertThatThrownBy(() -> service.privacyNotice(9L)).isInstanceOfSatisfying(CodedResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRegistrationLinkControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRegistrationLinkControllerTest.java new file mode 100644 index 0000000..d9c456d --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRegistrationLinkControllerTest.java @@ -0,0 +1,66 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.service.RegistrationLinkService; +import com.solvway.mobile.api.useraccess.AdminModule; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class AdminRegistrationLinkControllerTest { + + private final RegistrationLinkService service = mock(RegistrationLinkService.class); + private final MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminRegistrationLinkController(service)).build(); + + private static Method handler(String name) { + return Arrays.stream(AdminRegistrationLinkController.class.getDeclaredMethods()).filter(m -> m.getName().equals(name)).findFirst().orElseThrow(); + } + + @Test + void everyHandlerIsAuthenticatedAndGated() { + for (Method m : AdminRegistrationLinkController.class.getDeclaredMethods()) { + if (m.isSynthetic() || !Modifier.isPublic(m.getModifiers())) continue; + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName()).isTrue(); + assertThat(m.isAnnotationPresent(AdminModule.class)).as(m.getName()).isTrue(); + } + assertThat(handler("links").getAnnotation(AdminModule.class).value()).containsExactly("BO_EVENTS"); + assertThat(handler("setEnabled").getAnnotation(AdminModule.class).value()).containsExactly("BO_EVENTS"); + assertThat(handler("mine").getAnnotation(AdminModule.class).value()).containsExactly(AdminModule.ANY_ADMIN); + } + + @Test + void links_get() throws Exception { + when(service.links("77")).thenReturn(Map.of("event", Map.of("token", "ev1", "enabled", true))); + mvc.perform(get("/api/admin/events/77/registration-links")).andExpect(status().isOk()).andExpect(jsonPath("$.event.token").value("ev1")); + } + + @Test + void toggle_put() throws Exception { + when(service.setEnabled("77", "t1", false)).thenReturn(Map.of("token", "t1", "enabled", false)); + mvc.perform(put("/api/admin/events/77/registration-links/t1").contentType(MediaType.APPLICATION_JSON).content("{\"enabled\":false}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.enabled").value(false)); + verify(service).setEnabled("77", "t1", false); + } + + @Test + void myLinks_get() throws Exception { + when(service.mine()).thenReturn(List.of(Map.of("token", "t1"))); + mvc.perform(get("/api/admin/my-registration-links")).andExpect(status().isOk()).andExpect(jsonPath("$[0].token").value("t1")); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/publicapi/PublicRegistrationControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/publicapi/PublicRegistrationControllerTest.java new file mode 100644 index 0000000..d9a59ef --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/publicapi/PublicRegistrationControllerTest.java @@ -0,0 +1,57 @@ +package com.solvway.mobile.api.controller.publicapi; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.PublicRegistrationRequest; +import com.solvway.mobile.api.service.PublicRegistrationService; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class PublicRegistrationControllerTest { + + private final PublicRegistrationService service = mock(PublicRegistrationService.class); + private final MockMvc mvc = MockMvcBuilders.standaloneSetup(new PublicRegistrationController(service)).build(); + + @Test + void everyHandlerSkipsSignIn() { + Method[] handlers = Arrays.stream(PublicRegistrationController.class.getDeclaredMethods()) + .filter(m -> !m.isSynthetic() && Modifier.isPublic(m.getModifiers())).toArray(Method[]::new); + assertThat(handlers).hasSize(2); + for (Method m : handlers) assertThat(m.getAnnotation(AppAuth.class).skipValidate()).as(m.getName()).isTrue(); + } + + @Test + void get_returnsThePage() throws Exception { + when(service.page("abc")).thenReturn(Map.of("eventName", "Fair")); + mvc.perform(get("/api/public/registration/abc")).andExpect(status().isOk()).andExpect(jsonPath("$.eventName").value("Fair")); + } + + @Test + void post_passesTheBodyAndReturnsEventName() throws Exception { + when(service.register(eq("abc"), any())).thenReturn(Map.of("eventName", "Fair")); + mvc.perform(post("/api/public/registration/abc").contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"A\",\"mobile\":\"0123\",\"consent\":true,\"interestIds\":[3],\"website\":\"\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.eventName").value("Fair")); + org.mockito.ArgumentCaptor c = org.mockito.ArgumentCaptor.forClass(PublicRegistrationRequest.class); + verify(service).register(eq("abc"), c.capture()); + assertThat(c.getValue().consent()).isTrue(); + assertThat(c.getValue().interestIds()).containsExactly(3L); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java new file mode 100644 index 0000000..1910476 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java @@ -0,0 +1,338 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.PublicRegistrationRequest; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class PublicRegistrationServiceTest { + + private static final String LINK = "/counter/registrationLink/findByToken/{token}"; + private static final String EVENT = "/counter/event/findByUuid/{uuid}"; + private static final String COMPANY_URL = "/company/findById/{id}"; + private static final String NOTICE = "/company/{id}/privacyNotice"; + private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}"; + private static final String USER = "/user/findById/{id}"; + private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}"; + private static final String REGISTER = "/counter/registration/register"; + private static final long EV = 3312726793093644288L; + private static final long COMPANY = 5L; + private static final String TOKEN = "abc123"; + + private RestTemplateCustomUtil rest; + private RedisTemplate redis; + private ValueOperations ops; + private MockedStatic http; + private PublicRegistrationService service; + + private static Clock at(String utc) { return Clock.fixed(Instant.parse(utc), ZoneOffset.UTC); } + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + redis = mock(RedisTemplate.class); + ops = mock(ValueOperations.class); + when(redis.opsForValue()).thenReturn(ops); + when(ops.increment(any())).thenReturn(1L); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getClientIpAddressIfServletRequestExist).thenReturn("1.2.3.4"); + AdminEventLeadService leads = new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope()); + service = new PublicRegistrationService(rest, leads, redis, at("2027-01-16T04:00:00Z")); + stubLink(true, 21L); + stubEvent(true, LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + stub(COMPANY_URL, COMPANY, new HashMap<>(Map.of("id", COMPANY, "name", "INS", "status", "A"))); + stub(NOTICE, COMPANY, Map.of("id", 9L, "textEn", "English notice", "textMs", "Notis")); + stub(TEAM, EV, List.of(Map.of("userId", 21L), Map.of("userId", 22L))); + stubUser(21L, true); + stubUser(22L, true); + stub(INTERESTS, COMPANY, List.of( + Map.of("id", 3L, "companyId", COMPANY, "name", "Cookware", "active", true, "sortOrder", 0), + Map.of("id", 5L, "companyId", COMPANY, "name", "Old", "active", false, "sortOrder", 1))); + when(rest.postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of())); + } + + @AfterEach + void close() { http.close(); } + + private void stub(String url, Object var, Object body) { + when(rest.getForEntity(eq(url), any(ParameterizedTypeReference.class), eq(var))).thenReturn(ResponseEntity.ok(body)); + } + + private void stubLink(boolean enabled, Long sales) { + Map l = new HashMap<>(); + l.put("token", TOKEN); + l.put("enabled", enabled); + l.put("eventUuid", EV); + l.put("companyId", COMPANY); + l.put("salespersonUserId", sales); + stub(LINK, TOKEN, l); + } + + private void stubEvent(boolean enabled, LocalDateTime end) { + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(COMPANY); + e.setUuid(EV); + e.setName("KL Food Fair 2027"); + e.setLocation("MITEC"); + e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0)); + e.setDateEnd(end); + e.setEnabled(enabled ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N); + stub(EVENT, EV, e); + } + + private void stubUser(long id, boolean enabled) { + Map u = new HashMap<>(); + u.put("id", id); + u.put("name", "Sales " + id); + u.put("type", "A"); + u.put("companyId", COMPANY); + u.put("enabled", enabled); + stub(USER, id, u); + } + + private static PublicRegistrationRequest req(String website, Boolean consent, List interests) { + return new PublicRegistrationRequest("Aisyah", "012-345 6789", "a@x.com", "Acme", "Chef", interests, consent, website); + } + + private static PublicRegistrationRequest ok() { return req(null, true, List.of(3L)); } + + private void assertInactive(Runnable r) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(e.getReason()).isEqualTo("This code is no longer active."); + assertThat(e.getBody().getProperties()).containsEntry("code", "CODE_INACTIVE"); + }); + } + + // --- GET --- + + @Test + void page_unknownToken_inactive() { + when(rest.getForEntity(eq(LINK), any(ParameterizedTypeReference.class), eq("nope"))) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); + assertInactive(() -> service.page("nope")); + } + + @Test + void page_switchedOffLink_inactive() { + stubLink(false, 21L); + assertInactive(() -> service.page(TOKEN)); + } + + @Test + void page_disabledEvent_inactive() { + stubEvent(false, LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + assertInactive(() -> service.page(TOKEN)); + } + + @Test + void page_endedEvent_inactive_atMalaysiaDateBoundary() { + // 2027-01-17 16:30 UTC is 2027-01-18 00:30 in Kuala Lumpur: the event ended on the 17th. + service = svc("2027-01-17T16:30:00Z"); + assertInactive(() -> service.page(TOKEN)); + } + + @Test + void page_lastDay_stillActive_beforeMalaysiaMidnight() { + // 2027-01-17 15:30 UTC is 2027-01-17 23:30 in Kuala Lumpur. + service = svc("2027-01-17T15:30:00Z"); + assertThat(service.page(TOKEN)).containsEntry("eventName", "KL Food Fair 2027"); + } + + @Test + void page_inactiveCompany_inactive() { + stub(COMPANY_URL, COMPANY, new HashMap<>(Map.of("id", COMPANY, "name", "INS", "status", "I"))); + assertInactive(() -> service.page(TOKEN)); + } + + @Test + void page_noNotice_inactive() { + when(rest.getForEntity(eq(NOTICE), any(ParameterizedTypeReference.class), eq(COMPANY))) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); + assertInactive(() -> service.page(TOKEN)); + } + + @Test + void page_active_payloadHasOnlyActiveInterests() { + Map p = service.page(TOKEN); + assertThat(p).containsEntry("eventName", "KL Food Fair 2027").containsEntry("startDate", "2027-01-15") + .containsEntry("endDate", "2027-01-17").containsEntry("location", "MITEC").containsEntry("companyName", "INS"); + assertThat((Map) p.get("notice")).containsEntry("id", 9L).containsEntry("textEn", "English notice").containsEntry("textMs", "Notis"); + assertThat((List>) p.get("interests")).containsExactly(Map.of("id", 3L, "name", "Cookware")); + } + + @Test + void page_limit_429_keyedByIp() { + when(ops.increment("reg:load:1.2.3.4")).thenReturn(121L); + assertThatThrownBy(() -> service.page(TOKEN)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS); + assertThat(e.getBody().getProperties()).containsEntry("code", "TOO_MANY"); + }); + when(ops.increment("reg:load:1.2.3.4")).thenReturn(120L); + assertThat(service.page(TOKEN)).containsKey("eventName"); + } + + @Test + void page_firstHit_setsTenMinuteWindow() { + service.page(TOKEN); + verify(redis).expire("reg:load:1.2.3.4", 10, TimeUnit.MINUTES); + } + + // --- POST --- + + private Map registered() { + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), body.capture()); + return (Map) body.getValue(); + } + + @Test + void register_inactiveCode_404_andNothingRegistered() { + stubLink(false, 21L); + assertInactive(() -> service.register(TOKEN, ok())); + verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any()); + } + + @Test + void register_honeypot_looksLikeSuccess_andRegistersNothing() { + assertThat(service.register(TOKEN, req("http://spam", true, List.of(3L)))).containsEntry("eventName", "KL Food Fair 2027"); + verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any()); + } + + @Test + void register_consentMissing_400_withField() { + for (Boolean c : new Boolean[]{null, false}) { + assertThatThrownBy(() -> service.register(TOKEN, req(null, c, List.of(3L)))).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(e.getBody().getProperties()).containsEntry("code", "CONSENT_REQUIRED"); + assertThat(String.valueOf(e.getBody().getProperties())).contains("consent"); + }); + } + verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any()); + } + + @Test + void register_validatesLikeStaffCapture() { + PublicRegistrationRequest noContact = new PublicRegistrationRequest("Aisyah", " ", null, null, null, List.of(), true, null); + assertThatThrownBy(() -> service.register(TOKEN, noContact)).isInstanceOf(CodedResponseStatusException.class) + .satisfies(e -> assertThat(((CodedResponseStatusException) e).getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST)); + PublicRegistrationRequest noName = new PublicRegistrationRequest(" ", "0123456789", null, null, null, List.of(), true, null); + assertThatThrownBy(() -> service.register(TOKEN, noName)).isInstanceOf(CodedResponseStatusException.class); + verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any()); + } + + @Test + void register_inactiveInterest_refused() { + assertThatThrownBy(() -> service.register(TOKEN, req(null, true, List.of(5L)))).isInstanceOfSatisfying(CodedResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST)); + verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any()); + } + + @Test + void register_happy_sendsNormalisedBody_withServerSideNoticeAndSalesperson() { + assertThat(service.register(TOKEN, ok())).containsEntry("eventName", "KL Food Fair 2027"); + Map b = registered(); + assertThat(b).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserId", 21L) + .containsEntry("name", "Aisyah").containsEntry("email", "a@x.com").containsEntry("companyName", "Acme") + .containsEntry("jobTitle", "Chef").containsEntry("interestIds", List.of(3L)).containsEntry("consentNoticeId", 9L); + assertThat(b.get("mobileE164")).isEqualTo("+60123456789"); + assertThat(b.get("consentAt")).isEqualTo("2027-01-16T12:00"); + } + + @Test + void register_salespersonNotOnTeam_isNull() { + stub(TEAM, EV, List.of(Map.of("userId", 22L))); + service.register(TOKEN, ok()); + assertThat(registered().get("salespersonUserId")).isNull(); + } + + @Test + void register_salespersonInactive_isNull() { + stubUser(21L, false); + service.register(TOKEN, ok()); + assertThat(registered().get("salespersonUserId")).isNull(); + } + + @Test + void register_eventCodeWithoutSalesperson_isNull() { + stubLink(true, null); + service.register(TOKEN, ok()); + assertThat(registered().get("salespersonUserId")).isNull(); + } + + @Test + void register_limit_429_keyedByEventAndIp() { + when(ops.increment("reg:submit:" + EV + ":1.2.3.4")).thenReturn(61L); + assertThatThrownBy(() -> service.register(TOKEN, ok())).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS); + assertThat(e.getReason()).isEqualTo("Too many registrations from this device. Try again later."); + assertThat(e.getBody().getProperties()).containsEntry("code", "TOO_MANY"); + }); + verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any()); + } + + @Test + void register_deletedSalesperson_isNull_not500() { + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L))) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); + service.register(TOKEN, ok()); + assertThat(registered().get("salespersonUserId")).isNull(); + } + + @Test + void register_inactiveToken_stillCountsAndEnforcesTheLoadLimit() { + stubLink(false, 21L); + assertInactive(() -> service.register(TOKEN, ok())); + verify(ops).increment("reg:load:1.2.3.4"); + when(ops.increment("reg:load:1.2.3.4")).thenReturn(121L); + assertThatThrownBy(() -> service.register(TOKEN, ok())).isInstanceOfSatisfying(CodedResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS)); + } + + @Test + void register_sameBodyWhateverTheCounterOutcome() { + for (String outcome : List.of("CREATED", "LINKED", "ALREADY_CAPTURED", "ASSIGNED")) { + when(rest.postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("outcome", outcome))); + assertThat(service.register(TOKEN, ok())).as(outcome).isEqualTo(Map.of("eventName", "KL Food Fair 2027")); + } + } + + private PublicRegistrationService svc(String utc) { + return new PublicRegistrationService(rest, new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope()), redis, at(utc)); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationWiringTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationWiringTest.java new file mode 100644 index 0000000..8030b6d --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationWiringTest.java @@ -0,0 +1,29 @@ +package com.solvway.mobile.api.service; + +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.data.redis.core.RedisTemplate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +/** Both new services have a test-clock constructor: Spring must still know which one to use, or mobile-api fails to start. */ +class PublicRegistrationWiringTest { + + @Test + @SuppressWarnings("unchecked") + void springCreatesBothServices() { + try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { + ctx.registerBean(RestTemplateCustomUtil.class, () -> mock(RestTemplateCustomUtil.class)); + ctx.registerBean(AdminAuthenticationService.class, () -> mock(AdminAuthenticationService.class)); + ctx.registerBean(RedisTemplate.class, () -> mock(RedisTemplate.class)); + ctx.registerBean(AdminCompanyScope.class); + ctx.register(AdminEventLeadService.class, PublicRegistrationService.class, RegistrationLinkService.class); + ctx.refresh(); + assertThat(ctx.getBean(PublicRegistrationService.class)).isNotNull(); + assertThat(ctx.getBean(RegistrationLinkService.class)).isNotNull(); + } + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/RegistrationLinkServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/RegistrationLinkServiceTest.java new file mode 100644 index 0000000..817bd44 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/RegistrationLinkServiceTest.java @@ -0,0 +1,156 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.ResponseEntity; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class RegistrationLinkServiceTest { + + private static final String EVENT = "/counter/event/findByUuid/{uuid}"; + private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}"; + private static final String USER = "/user/findById/{id}"; + private static final String ENSURE = "/counter/registrationLink/ensure"; + private static final String SET = "/counter/registrationLink/setEnabled"; + private static final String MINE = "/counter/registrationLink/mine"; + private static final long EV = 3312726793093644288L; + private static final long COMPANY = 5L; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private MockedStatic http; + private RegistrationLinkService service; + private User caller; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + caller = new User(); + caller.setId(21L); + caller.setUsername("sales1"); + caller.setCompanyId(COMPANY); + when(auth.loadUserByToken("tok")).thenReturn(caller); + AdminEventLeadService leads = new AdminEventLeadService(rest, auth, new AdminCompanyScope()); + service = new RegistrationLinkService(rest, leads, Clock.fixed(Instant.parse("2027-01-16T17:00:00Z"), ZoneOffset.UTC)); + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(COMPANY); + e.setUuid(EV); + e.setDateEnd(LocalDateTime.of(2027, 1, 20, 0, 0)); + e.setEnabled(GeneralEnum.FlagYesNo.Y); + when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e)); + when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), eq(EV))) + .thenReturn(ResponseEntity.ok(List.of(Map.of("userId", 21L), Map.of("userId", 22L)))); + stubUser(21L, "Sales One"); + stubUser(22L, "Sales Two"); + } + + @AfterEach + void close() { http.close(); } + + private void stubUser(long id, String name) { + Map u = new HashMap<>(Map.of("id", id, "name", name, "type", "A", "companyId", COMPANY, "enabled", true)); + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u)); + } + + private Map posted(String url) { + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(url), any(ParameterizedTypeReference.class), body.capture()); + return (Map) body.getValue(); + } + + @Test + void links_ensuresEventAndTeamLinks_andNamesMembers() { + Map eventRow = new HashMap<>(Map.of("token", "ev1", "enabled", true)); + List> rows = List.of(eventRow, + Map.of("token", "t21", "enabled", true, "salespersonUserId", 21L), + Map.of("token", "t22", "enabled", false, "salespersonUserId", 22L)); + when(rest.postForEntity(eq(ENSURE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(rows)); + + Map out = service.links(String.valueOf(EV)); + + assertThat((Map) out.get("event")).containsEntry("token", "ev1").containsEntry("enabled", true); + assertThat((List>) out.get("members")).containsExactly( + Map.of("userId", 21L, "name", "Sales One", "token", "t21", "enabled", true), + Map.of("userId", 22L, "name", "Sales Two", "token", "t22", "enabled", false)); + assertThat(posted(ENSURE)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserIds", List.of(21L, 22L)); + } + + @Test + void setEnabled_passesEventCompanyAndCallerUsername() { + when(rest.postForEntity(eq(SET), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("token", "t21", "enabled", false))); + assertThat(service.setEnabled(String.valueOf(EV), "t21", false)).containsEntry("enabled", false); + assertThat(posted(SET)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("token", "t21") + .containsEntry("enabled", false).containsEntry("doneBy", "sales1"); + } + + @Test + void mine_sendsCallerCompanyIdAndMalaysiaToday() { + when(rest.postForEntity(eq(MINE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(Map.of("token", "t21")))); + assertThat(service.mine()).hasSize(1); + // 2027-01-16 17:00 UTC is already 2027-01-17 in Kuala Lumpur. + assertThat(posted(MINE)).containsEntry("companyId", COMPANY).containsEntry("userId", 21L).containsEntry("today", "2027-01-17"); + } + + @Test + void mine_withoutCompany_isEmpty_andCallsNothing() { + caller.setCompanyId(null); + assertThat(service.mine()).isEmpty(); + org.mockito.Mockito.verify(rest, org.mockito.Mockito.never()).postForEntity(eq(MINE), any(ParameterizedTypeReference.class), any()); + } + + private void otherCompanyEvent() { + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(6L); + e.setUuid(EV); + e.setEnabled(GeneralEnum.FlagYesNo.Y); + when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e)); + } + + @Test + void links_eventInAnotherCompany_404() { + otherCompanyEvent(); + org.assertj.core.api.Assertions.assertThatThrownBy(() -> service.links(String.valueOf(EV))) + .isInstanceOfSatisfying(com.solvway.mobile.api.errorhandler.CodedResponseStatusException.class, + x -> assertThat(x.getStatusCode()).isEqualTo(org.springframework.http.HttpStatus.NOT_FOUND)); + org.mockito.Mockito.verify(rest, org.mockito.Mockito.never()).postForEntity(eq(ENSURE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void setEnabled_eventInAnotherCompany_404() { + otherCompanyEvent(); + org.assertj.core.api.Assertions.assertThatThrownBy(() -> service.setEnabled(String.valueOf(EV), "t21", false)) + .isInstanceOfSatisfying(com.solvway.mobile.api.errorhandler.CodedResponseStatusException.class, + x -> assertThat(x.getStatusCode()).isEqualTo(org.springframework.http.HttpStatus.NOT_FOUND)); + org.mockito.Mockito.verify(rest, org.mockito.Mockito.never()).postForEntity(eq(SET), any(ParameterizedTypeReference.class), any()); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectRegistrationAuditTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectRegistrationAuditTest.java new file mode 100644 index 0000000..6a415e1 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectRegistrationAuditTest.java @@ -0,0 +1,110 @@ +package com.solvway.mobile.api.useraccess; + +import com.google.cloud.spring.pubsub.core.PubSubTemplate; +import com.solvway.core.enums.JwtEnum.JwtCustomClaim; +import com.solvway.core.model.AuditEvent; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.core.utils.JwtTokenUtil; +import com.solvway.core.utils.PubSubUtil; +import com.solvway.mobile.api.config.AuthAppKeyConfig; +import com.solvway.mobile.api.config.PubSubConfig; +import com.solvway.mobile.api.controller.admin.AdminRegistrationLinkController; +import com.solvway.mobile.api.service.AuthenticationService; +import com.solvway.mobile.api.service.MemberService; +import com.solvway.mobile.api.service.UserService; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.reflect.MethodSignature; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.HandlerMapping; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** The registration token is a secret-ish link id: switching a link off is audited against the event, never the token. */ +class AppAccessAspectRegistrationAuditTest { + + private static final String API_KEY = "valid-api-key"; + private static final String TOK = "admin-tok"; + private static final String TOPIC = "audit-event-topic"; + + @AfterEach + void clear() { RequestContextHolder.resetRequestAttributes(); } + + @Test + @SuppressWarnings("unchecked") + void toggle_recordsTheEventUuid_neverTheToken() throws Throwable { + PubSubTemplate pubSubTemplate = mock(PubSubTemplate.class); + PubSubUtil pubSubUtil = mock(PubSubUtil.class); + JwtTokenUtil jwt = mock(JwtTokenUtil.class); + AdminSessionGuard guard = mock(AdminSessionGuard.class); + RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class); + ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class); + MethodSignature sig = mock(MethodSignature.class); + AuthAppKeyConfig cfg = new AuthAppKeyConfig(); + cfg.setList(List.of(API_KEY)); + PubSubConfig pubSubConfig = mock(PubSubConfig.class); + pubSubConfig.auditEventTopic = TOPIC; + AppAccessAspect aspect = new AppAccessAspect(mock(MemberService.class), mock(UserService.class), pubSubConfig, + pubSubTemplate, pubSubUtil, cfg, mock(AuthenticationService.class), jwt, guard, rest); + + MockHttpServletRequest req = new MockHttpServletRequest("PUT", "/api/admin/events/3312726793093644288/registration-links/SECRETTOKEN"); + req.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/admin/events/{uuid}/registration-links/{token}"); + Map vars = new LinkedHashMap<>(); + vars.put("uuid", "3312726793093644288"); + vars.put("token", "SECRETTOKEN"); + req.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, vars); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req)); + + Method m = Arrays.stream(AdminRegistrationLinkController.class.getMethods()).filter(x -> x.getName().equals("setEnabled")).findFirst().orElseThrow(); + when(joinPoint.getSignature()).thenReturn(sig); + when(sig.getMethod()).thenReturn(m); + when(sig.toShortString()).thenReturn("AdminRegistrationLinkController.setEnabled()"); + User u = new User(); + u.setEnabled(true); + u.setUsername("alice"); + u.setCompanyId(7L); + Role r = new Role(); + r.setId(1L); + u.getRoles().add(r); + when(guard.check(eq(TOK), any(Boolean.class))).thenReturn(u); + when(rest.getForEntity(any(), any(ParameterizedTypeReference.class), eq("BO"))) + .thenReturn(ResponseEntity.ok(List.of(Map.of("name", "BO_EVENTS", "roles", List.of(Map.of("id", 1)))))); + when(joinPoint.proceed()).thenReturn(ResponseEntity.ok("x")); + + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + h.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(API_KEY); + h.when(HttpReqRespUtils::getJwtToken).thenReturn(TOK); + when(jwt.isTokenExpired(TOK)).thenReturn(false); + when(jwt.getCustomClaimFromToken(TOK, JwtCustomClaim.USERTYPE)).thenReturn("A"); + aspect.appAccessAuthCheck(joinPoint); + } + + ArgumentCaptor captor = ArgumentCaptor.forClass(Object.class); + verify(pubSubUtil).publishMessage(eq(pubSubTemplate), eq(TOPIC), captor.capture()); + AuditEvent e = (AuditEvent) captor.getValue(); + assertThat(e.getTargetId()).isEqualTo("3312726793093644288"); + assertThat(String.valueOf(e.getPathTemplate()) + e.getTargetId() + e.getChanges()).doesNotContain("SECRETTOKEN"); + } +} -- 2.54.1 From ffda35b7850127e39f7af8b6a96e1c3f034f47c4 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:16:59 +0800 Subject: [PATCH 08/20] docs(openspec): POST counts against the QR page-load limit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-qr-self-registration/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/add-qr-self-registration/design.md b/openspec/changes/add-qr-self-registration/design.md index d629e0b..c0f3261 100644 --- a/openspec/changes/add-qr-self-registration/design.md +++ b/openspec/changes/add-qr-self-registration/design.md @@ -46,7 +46,7 @@ All bodies are JSON. `companyId` is always a concrete company, set by mobile-api 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`. + - 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; -- 2.54.1 From 6ebfbfb1ac637b29071ef17e83d834346f1cc245 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:18:30 +0800 Subject: [PATCH 09/20] docs: tick QR registration wave 1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-qr-self-registration/tasks.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openspec/changes/add-qr-self-registration/tasks.md b/openspec/changes/add-qr-self-registration/tasks.md index af26461..7b31985 100644 --- a/openspec/changes/add-qr-self-registration/tasks.md +++ b/openspec/changes/add-qr-self-registration/tasks.md @@ -21,7 +21,7 @@ Waves: ## 2. services-counter -- [ ] 2.1 Registration links and the registration capture (decision 2). +- [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; @@ -40,7 +40,7 @@ Waves: ## 3. services-system -- [ ] 3.1 Company privacy notice versions (decision 3). +- [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. @@ -49,7 +49,7 @@ Waves: ## 4. mobile-api -- [ ] 4.1 Public registration endpoints and the admin link and notice endpoints (decision 4). +- [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`; -- 2.54.1 From 5036196031681d60a158a21c83c190c2eb384abb Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:26:09 +0800 Subject: [PATCH 10/20] docs(openspec): gateway access for the public QR flow (task 4.2) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-qr-self-registration/design.md | 18 +++++++++++++++++- .../changes/add-qr-self-registration/tasks.md | 9 +++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/openspec/changes/add-qr-self-registration/design.md b/openspec/changes/add-qr-self-registration/design.md index c0f3261..5ff4fe1 100644 --- a/openspec/changes/add-qr-self-registration/design.md +++ b/openspec/changes/add-qr-self-registration/design.md @@ -83,7 +83,22 @@ Admin: - **"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 +### 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. @@ -93,3 +108,4 @@ Admin: - 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. +- 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. diff --git a/openspec/changes/add-qr-self-registration/tasks.md b/openspec/changes/add-qr-self-registration/tasks.md index 7b31985..d124e41 100644 --- a/openspec/changes/add-qr-self-registration/tasks.md +++ b/openspec/changes/add-qr-self-registration/tasks.md @@ -61,6 +61,15 @@ Waves: - Scope: `solvway-mobile-api/src/**` - Verify: `mvn -T 1C -q -pl solvway-mobile-api verify` +- [ ] 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 - [ ] 5.1 Public page, proxy, middleware, event QR card, My QR codes, Companies privacy notice (decision 5). -- 2.54.1 From 1a7c542f5e48ab2c6ffddaddec2eee8a1a91ef41 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:33:04 +0800 Subject: [PATCH 11/20] docs(openspec): QR rate-limit key is the last X-Forwarded-For hop Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-qr-self-registration/design.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/add-qr-self-registration/design.md b/openspec/changes/add-qr-self-registration/design.md index 5ff4fe1..750b4a2 100644 --- a/openspec/changes/add-qr-self-registration/design.md +++ b/openspec/changes/add-qr-self-registration/design.md @@ -76,7 +76,7 @@ Admin: - **`/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. + - 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. @@ -106,6 +106,6 @@ mobile-api forwards the caller's JWT to the gateway, and a visitor has none, so ## 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 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 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. -- 2.54.1 From eff4899c0d94c5d442ea420e5de70d79c0852830 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:37:51 +0800 Subject: [PATCH 12/20] 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 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../solvway/gateway/filter/JWTAuthFilter.java | 20 +++ ...TAuthFilterPublicRegistrationPathTest.java | 95 ++++++++++++++ .../api/RestApiSystemServiceConstants.java | 1 + .../service/PublicRegistrationService.java | 13 +- .../PublicRegistrationSalespersonTest.java | 121 ++++++++++++++++++ .../PublicRegistrationServiceTest.java | 12 +- .../system/controller/UserController.java | 8 ++ .../UserControllerActiveAdminOfTest.java | 69 ++++++++++ 8 files changed, 329 insertions(+), 10 deletions(-) create mode 100644 solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationSalespersonTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveAdminOfTest.java diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java index 68dba3e..0944b3d 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java @@ -19,6 +19,7 @@ import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; @@ -28,6 +29,9 @@ import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; @Component public class JWTAuthFilter implements GlobalFilter, Ordered { @@ -36,6 +40,21 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { private static final String WWW_AUTH_HEADER = "WWW-Authenticate"; + /** Public QR registration page: mobile-api reads these for a visitor with no user token. Anchored, exact method and path. */ + private static final List> PUBLIC_REGISTRATION = List.of( + publicPath(HttpMethod.GET, "/counter/registrationLink/findByToken/[A-Za-z0-9_-]{22}"), + publicPath(HttpMethod.GET, "/counter/event/findByUuid/\\d+"), + publicPath(HttpMethod.GET, "/counter/interest/findByCompany/\\d+"), + publicPath(HttpMethod.GET, "/counter/eventSalesperson/findByEventUuid/\\d+"), + publicPath(HttpMethod.GET, "/company/findById/\\d+"), + publicPath(HttpMethod.GET, "/company/\\d+/privacyNotice"), + publicPath(HttpMethod.GET, "/user/\\d+/activeAdminOf/\\d+"), + publicPath(HttpMethod.POST, "/counter/registration/register")); + + private static Map.Entry publicPath(HttpMethod method, String regex) { + return Map.entry(method, Pattern.compile(regex)); + } + @Value("${auth.api-key.third-party-api-key:''}") private String thirdPartyApiKey; @@ -136,6 +155,7 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { // Co-Lite admin sign-in: lock check and its recording run before the user has a token || (url.matches("/loginSecurity/isLocked/[^/]+") && !url.contains("..")) || url.equals("/loginSecurity/record") + || PUBLIC_REGISTRATION.stream().anyMatch(p -> p.getKey().equals(exchange.getRequest().getMethod()) && p.getValue().matcher(url).matches()) || url.contains("/geoLocationHierarchy/findByFirstLevelLocation") || url.contains("/geoLocationHierarchy/findAllByParentId") // public content - no JWT required diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java new file mode 100644 index 0000000..bea7a77 --- /dev/null +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java @@ -0,0 +1,95 @@ +package com.solvway.gateway.filter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.gateway.model.AuthAppKey; +import com.solvway.gateway.model.AuthAppKeyMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.test.util.ReflectionTestUtils; +import reactor.core.publisher.Mono; + +import java.net.InetSocketAddress; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.assertj.core.api.Assertions.assertThat; + +/** The public QR registration page reads a few things and posts one registration without a user token; nothing else opens. */ +class JWTAuthFilterPublicRegistrationPathTest { + + private static final String KEY = "gateway-test-key"; + private static final String TOKEN = "2lvFUDqc0zSu5X-6qvZE1g"; + + private JWTAuthFilter filter; + + @BeforeEach + void setUp() throws Exception { + AuthAppKey key = new ObjectMapper().readValue( + "{\"key\":\"" + KEY + "\",\"type\":\"BO\",\"ipList\":[\"0.0.0.0/0\"],\"allowList\":[\"/\"]}", + AuthAppKey.class); + AuthAppKeyMap map = new AuthAppKeyMap(); + map.add(KEY, key); + filter = new JWTAuthFilter(); + ReflectionTestUtils.setField(filter, "authAppKeyMap", map); + } + + private MockServerWebExchange call(HttpMethod method, String path) { + return MockServerWebExchange.from(MockServerHttpRequest.method(method, path) + .header("api-key", KEY) + .remoteAddress(new InetSocketAddress("127.0.0.1", 40000))); + } + + private boolean passes(MockServerWebExchange exchange) { + AtomicBoolean called = new AtomicBoolean(false); + GatewayFilterChain chain = ex -> { + called.set(true); + return Mono.empty(); + }; + filter.filter(exchange, chain).block(); + return called.get(); + } + + @Test + void publicRegistrationPathsNeedNoUserToken() { + for (String[] c : new String[][] { + {"GET", "/counter/registrationLink/findByToken/" + TOKEN}, + {"GET", "/counter/event/findByUuid/3312726793093644288"}, + {"GET", "/counter/interest/findByCompany/5"}, + {"GET", "/counter/eventSalesperson/findByEventUuid/3312726793093644288"}, + {"GET", "/company/findById/2"}, + {"GET", "/company/2/privacyNotice"}, + {"GET", "/user/21/activeAdminOf/5"}, + {"POST", "/counter/registration/register"} }) { + assertThat(passes(call(HttpMethod.valueOf(c[0]), c[1]))).as(c[0] + " " + c[1]).isTrue(); + } + } + + @Test + void everythingElseStillNeedsAToken() { + for (String[] c : new String[][] { + {"POST", "/company/1/privacyNotice"}, + {"GET", "/user/findById/1"}, + {"POST", "/counter/registrationLink/ensure"}, + {"GET", "/counter/registrationLink/findByToken/" + TOKEN + "/x"}, + {"GET", "/counter/registrationLink/findByToken/short"}, + {"GET", "/counter/registrationLink/findByToken/" + TOKEN + "a"}, + {"GET", "/counter/registrationLink/findByToken/../x/" + TOKEN}, + {"POST", "/counter/event/findByUuid/1"}, + {"GET", "/counter/event/findByUuid/1/x"}, + {"GET", "/counter/event/findByUuid/abc"}, + {"GET", "/x/company/findById/2"}, + {"GET", "/company/findById/2/x"}, + {"GET", "/user/1/activeAdminOf/2/x"}, + {"POST", "/user/1/activeAdminOf/2"}, + {"GET", "/counter/registration/register"}, + {"POST", "/counter/registration/register/x"} }) { + MockServerWebExchange ex = call(HttpMethod.valueOf(c[0]), c[1]); + assertThat(passes(ex)).as(c[0] + " " + c[1]).isFalse(); + assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED); + } + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index 37b2d89..942cf85 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -6,6 +6,7 @@ public class RestApiSystemServiceConstants { public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}"; public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}"; + public static final String API_REST_SYSTEM_USER_ACTIVE_ADMIN_OF = "/user/{id}/activeAdminOf/{companyId}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY = "/user/findByEmailAndCompanyId/{email}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java index 70ed776..adc8568 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java @@ -14,6 +14,7 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; import java.time.Clock; import java.time.LocalDate; @@ -44,6 +45,7 @@ public class PublicRegistrationService { private static final long WINDOW_MINUTES = 10; private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference BOOL = new ParameterizedTypeReference<>() {}; private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; private final RestTemplateCustomUtil rest; @@ -124,7 +126,16 @@ public class PublicRegistrationService { private Long salesperson(Map link, CompanyEvent e) { if (!(link.get("salespersonUserId") instanceof Number n)) return null; long id = n.longValue(); - return leads.teamIds(e.getUuid()).contains(id) && AdminEventLeadService.isActiveAdminOf(found(() -> leads.user(id)), e.getCompanyId()) ? id : null; + return leads.teamIds(e.getUuid()).contains(id) && Boolean.TRUE.equals(activeAdminOf(id, e.getCompanyId())) ? id : null; + } + + /** The user record is closed to visitors, so ask the one yes/no endpoint. Any failure means "no salesperson", never a 500. */ + private Boolean activeAdminOf(long userId, Long companyId) { + try { + return rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_ACTIVE_ADMIN_OF), BOOL, userId, companyId).getBody(); + } catch (RestClientException e) { + return false; + } } private Open open(String token) { diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationSalespersonTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationSalespersonTest.java new file mode 100644 index 0000000..1e5e42e --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationSalespersonTest.java @@ -0,0 +1,121 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.PublicRegistrationRequest; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** The visitor has no token, so the salesperson check must use the open activeAdminOf call, never the closed findById. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class PublicRegistrationSalespersonTest { + + private static final String ACTIVE_ADMIN_OF = "/user/{id}/activeAdminOf/{companyId}"; + private static final String FIND_BY_ID = "/user/findById/{id}"; + private static final long EV = 3312726793093644288L; + private static final long COMPANY = 5L; + private static final String TOKEN = "abc123"; + + private RestTemplateCustomUtil rest; + private MockedStatic http; + private PublicRegistrationService service; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + RedisTemplate redis = mock(RedisTemplate.class); + ValueOperations ops = mock(ValueOperations.class); + when(redis.opsForValue()).thenReturn(ops); + when(ops.increment(any())).thenReturn(1L); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getClientIpAddressIfServletRequestExist).thenReturn("1.2.3.4"); + AdminEventLeadService leads = new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope()); + service = new PublicRegistrationService(rest, leads, redis, Clock.fixed(Instant.parse("2027-01-16T04:00:00Z"), ZoneOffset.UTC)); + + Map link = new HashMap<>(Map.of("token", TOKEN, "enabled", true, "eventUuid", EV, "companyId", COMPANY, "salespersonUserId", 21L)); + stub("/counter/registrationLink/findByToken/{token}", TOKEN, link); + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(COMPANY); + e.setUuid(EV); + e.setName("KL Food Fair 2027"); + e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + e.setEnabled(GeneralEnum.FlagYesNo.Y); + stub("/counter/event/findByUuid/{uuid}", EV, e); + stub("/company/findById/{id}", COMPANY, new HashMap<>(Map.of("id", COMPANY, "name", "INS", "status", "A"))); + stub("/company/{id}/privacyNotice", COMPANY, Map.of("id", 9L, "textEn", "en", "textMs", "ms")); + stub("/counter/eventSalesperson/findByEventUuid/{eventUuid}", EV, List.of(Map.of("userId", 21L))); + stub("/counter/interest/findByCompany/{companyId}", COMPANY, List.of(Map.of("id", 3L, "companyId", COMPANY, "name", "Cookware", "active", true, "sortOrder", 0))); + when(rest.postForEntity(eq("/counter/registration/register"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of())); + } + + @AfterEach + void close() { http.close(); } + + private void stub(String url, Object var, Object body) { + when(rest.getForEntity(eq(url), any(ParameterizedTypeReference.class), eq(var))).thenReturn(ResponseEntity.ok(body)); + } + + private Object registeredSalesperson() { + service.register(TOKEN, new PublicRegistrationRequest("Aisyah", "012-345 6789", "a@x.com", "Acme", "Chef", List.of(3L), true, null)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/counter/registration/register"), any(ParameterizedTypeReference.class), body.capture()); + verify(rest, never()).getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), any()); + return ((Map) body.getValue()).get("salespersonUserId"); + } + + @Test + void activeAdminOf_true_keepsTheSalesperson() { + when(rest.getForEntity(eq(ACTIVE_ADMIN_OF), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))).thenReturn(ResponseEntity.ok(true)); + assertThat(registeredSalesperson()).isEqualTo(21L); + } + + @Test + void activeAdminOf_false_isNull() { + when(rest.getForEntity(eq(ACTIVE_ADMIN_OF), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))).thenReturn(ResponseEntity.ok(false)); + assertThat(registeredSalesperson()).isNull(); + } + + @Test + void activeAdminOf_404_isNull_not500() { + when(rest.getForEntity(eq(ACTIVE_ADMIN_OF), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); + assertThat(registeredSalesperson()).isNull(); + } + + @Test + void activeAdminOf_otherFailure_isNull_not500() { + when(rest.getForEntity(eq(ACTIVE_ADMIN_OF), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))) + .thenThrow(HttpClientErrorException.create(HttpStatus.UNAUTHORIZED, "no", null, null, null)); + assertThat(registeredSalesperson()).isNull(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java index 1910476..1ff5a11 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java @@ -46,7 +46,7 @@ class PublicRegistrationServiceTest { private static final String COMPANY_URL = "/company/findById/{id}"; private static final String NOTICE = "/company/{id}/privacyNotice"; private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}"; - private static final String USER = "/user/findById/{id}"; + private static final String USER = "/user/{id}/activeAdminOf/{companyId}"; private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}"; private static final String REGISTER = "/counter/registration/register"; private static final long EV = 3312726793093644288L; @@ -116,13 +116,7 @@ class PublicRegistrationServiceTest { } private void stubUser(long id, boolean enabled) { - Map u = new HashMap<>(); - u.put("id", id); - u.put("name", "Sales " + id); - u.put("type", "A"); - u.put("companyId", COMPANY); - u.put("enabled", enabled); - stub(USER, id, u); + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id), eq(COMPANY))).thenReturn(ResponseEntity.ok(enabled)); } private static PublicRegistrationRequest req(String website, Boolean consent, List interests) { @@ -308,7 +302,7 @@ class PublicRegistrationServiceTest { @Test void register_deletedSalesperson_isNull_not500() { - when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L))) + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))) .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); service.register(TOKEN, ok()); assertThat(registered().get("salespersonUserId")).isNull(); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java index 03de28c..b7febbb 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java @@ -225,6 +225,14 @@ public class UserController { return user.isPresent() ? user.get() : null; } + /** True only for an enabled admin of that company; open to the public registration page, so it exposes nothing else of the user. */ + @GetMapping("/{id}/activeAdminOf/{companyId}") + public boolean activeAdminOf(@PathVariable("id") Long id, @PathVariable("companyId") Long companyId) { + return userService.findById(id) + .filter(u -> u.getType() == UserType.A && u.isEnabled() && companyId.equals(u.getCompanyId())) + .isPresent(); + } + @RequestMapping("/findByEmail/{email}") public User findByEmail(@PathVariable("email") String email) { User user = userService.findByEmail(email); diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveAdminOfTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveAdminOfTest.java new file mode 100644 index 0000000..ef84331 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveAdminOfTest.java @@ -0,0 +1,69 @@ +package com.solvway.services.system.controller; + +import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.model.User; +import com.solvway.services.system.service.UserService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class UserControllerActiveAdminOfTest { + + @Mock private UserService userService; + @InjectMocks private UserController controller; + + private void stored(UserType type, Long companyId, boolean enabled) { + User u = new User(); + u.setType(type); + u.setCompanyId(companyId); + u.setEnabled(enabled); + when(userService.findById(7L)).thenReturn(Optional.of(u)); + } + + @Test + void enabledAdminOfTheCompany_isTrue() { + stored(UserType.A, 2L, true); + assertThat(controller.activeAdminOf(7L, 2L)).isTrue(); + } + + @Test + void otherCompany_isFalse() { + stored(UserType.A, 3L, true); + assertThat(controller.activeAdminOf(7L, 2L)).isFalse(); + } + + @Test + void companylessAdmin_isFalse() { + stored(UserType.A, null, true); + assertThat(controller.activeAdminOf(7L, 2L)).isFalse(); + } + + @Test + void disabled_isFalse() { + stored(UserType.A, 2L, false); + assertThat(controller.activeAdminOf(7L, 2L)).isFalse(); + } + + @Test + void nonAdminType_isFalse() { + stored(UserType.D, 2L, true); + assertThat(controller.activeAdminOf(7L, 2L)).isFalse(); + } + + @Test + void unknownUser_isFalse() { + when(userService.findById(8L)).thenReturn(Optional.empty()); + assertThat(controller.activeAdminOf(8L, 2L)).isFalse(); + } +} -- 2.54.1 From f13dac58a483a5152910a27bef92a453ef04e6a6 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:37:51 +0800 Subject: [PATCH 13/20] docs(openspec): gateway bypass risks; tick 4.2 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-qr-self-registration/design.md | 2 +- openspec/changes/add-qr-self-registration/tasks.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/add-qr-self-registration/design.md b/openspec/changes/add-qr-self-registration/design.md index 750b4a2..e2f8da8 100644 --- a/openspec/changes/add-qr-self-registration/design.md +++ b/openspec/changes/add-qr-self-registration/design.md @@ -108,4 +108,4 @@ mobile-api forwards the caller's JWT to the gateway, and a visitor has none, so - 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 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. +- 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/tasks.md b/openspec/changes/add-qr-self-registration/tasks.md index d124e41..eb09674 100644 --- a/openspec/changes/add-qr-self-registration/tasks.md +++ b/openspec/changes/add-qr-self-registration/tasks.md @@ -61,7 +61,7 @@ Waves: - Scope: `solvway-mobile-api/src/**` - Verify: `mvn -T 1C -q -pl solvway-mobile-api verify` -- [ ] 4.2 Gateway access for the public flow (decision 6), found by the live check. +- [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; -- 2.54.1 From 08c45e9109ac5797e9c85bfd5a4becf4fadc95c9 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:57:18 +0800 Subject: [PATCH 14/20] feat(portal): QR self-registration page, event QR card, My QR codes, privacy notice editor The public /r/ 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 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../companies/[id]/privacy-notice/route.ts | 29 +++ .../registration-links/[token]/route.ts | 17 ++ .../events/[uuid]/registration-links/route.ts | 13 ++ .../app/api/my-registration-links/route.ts | 12 ++ .../public/registration/[token]/route.test.ts | 47 +++++ .../api/public/registration/[token]/route.ts | 35 ++++ .../app/api/registrationAdminRoutes.test.ts | 43 +++++ .../app/companies/page.privacy.test.tsx | 74 ++++++++ solvway-admin-portal/app/companies/page.tsx | 73 ++++++++ .../app/Header.changePassword.test.tsx | 2 +- .../app/components/app/Header.tsx | 3 + .../events/RegistrationQrCard.test.tsx | 47 +++++ .../components/events/RegistrationQrCard.tsx | 61 +++++++ .../registration/QrCodeItem.test.tsx | 52 ++++++ .../components/registration/QrCodeItem.tsx | 69 +++++++ .../app/events/[uuid]/page.tsx | 6 + .../app/lib/i18n/defaultMessages.ts | 35 ++++ solvway-admin-portal/app/lib/routeGuard.ts | 3 +- .../app/lib/services/adminRegistration.ts | 41 +++++ .../lib/services/publicRegistration.test.ts | 32 ++++ .../app/lib/services/publicRegistration.ts | 47 +++++ solvway-admin-portal/app/my-qr/page.test.tsx | 34 ++++ solvway-admin-portal/app/my-qr/page.tsx | 37 ++++ .../app/r/[token]/page.test.tsx | 165 +++++++++++++++++ solvway-admin-portal/app/r/[token]/page.tsx | 169 ++++++++++++++++++ .../middleware.public.test.ts | 26 +++ 26 files changed, 1170 insertions(+), 2 deletions(-) create mode 100644 solvway-admin-portal/app/api/companies/[id]/privacy-notice/route.ts create mode 100644 solvway-admin-portal/app/api/events/[uuid]/registration-links/[token]/route.ts create mode 100644 solvway-admin-portal/app/api/events/[uuid]/registration-links/route.ts create mode 100644 solvway-admin-portal/app/api/my-registration-links/route.ts create mode 100644 solvway-admin-portal/app/api/public/registration/[token]/route.test.ts create mode 100644 solvway-admin-portal/app/api/public/registration/[token]/route.ts create mode 100644 solvway-admin-portal/app/api/registrationAdminRoutes.test.ts create mode 100644 solvway-admin-portal/app/companies/page.privacy.test.tsx create mode 100644 solvway-admin-portal/app/components/events/RegistrationQrCard.test.tsx create mode 100644 solvway-admin-portal/app/components/events/RegistrationQrCard.tsx create mode 100644 solvway-admin-portal/app/components/registration/QrCodeItem.test.tsx create mode 100644 solvway-admin-portal/app/components/registration/QrCodeItem.tsx create mode 100644 solvway-admin-portal/app/lib/services/adminRegistration.ts create mode 100644 solvway-admin-portal/app/lib/services/publicRegistration.test.ts create mode 100644 solvway-admin-portal/app/lib/services/publicRegistration.ts create mode 100644 solvway-admin-portal/app/my-qr/page.test.tsx create mode 100644 solvway-admin-portal/app/my-qr/page.tsx create mode 100644 solvway-admin-portal/app/r/[token]/page.test.tsx create mode 100644 solvway-admin-portal/app/r/[token]/page.tsx create mode 100644 solvway-admin-portal/middleware.public.test.ts 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} +
+ )} +
+
+ +