Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9438fd8cf1 | ||
|
|
d532bdcda4 | ||
|
|
c6c220265f | ||
|
|
9163557945 | ||
|
|
2d1513aa80 | ||
|
|
adbbdc6185 | ||
|
|
08c45e9109 | ||
|
|
f13dac58a4 | ||
|
|
eff4899c0d | ||
|
|
1a7c542f5e | ||
|
|
5036196031 | ||
|
|
6ebfbfb1ac | ||
|
|
ffda35b785 | ||
|
|
cf8478d00c | ||
|
|
ab1643e36e | ||
|
|
85b40424ce | ||
|
|
9c9469f5e5 | ||
|
|
0345314c89 | ||
|
|
2842ef423f | ||
|
|
6fbbdaa3c5 | ||
|
|
065a8561e3 | ||
|
|
61d17d5e38 | ||
|
|
a8d42a8a25 |
No files matched your search
@@ -105,6 +105,15 @@ Run the three in order, with a user that may alter tables. File `03` ends every
|
||||
|
||||
Run the three in order before the new images go live: the new services-counter writes to the table from `01` on every capture and status edit, and fails without it. `01` needs a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the status history.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/2026-12-01-add-qr-self-registration/sql/01-registration-link.sql` | Creates `service-counter`.`registration_link` (QR registration codes) and adds `source`, `consent_at` and `consent_notice_id` to `event_lead`. Existing event leads become `STAFF`. DDL. |
|
||||
| `openspec/changes/archive/2026-12-01-add-qr-self-registration/sql/02-company-privacy-notice.sql` | Creates `service-system`.`company_privacy_notice` and gives every existing company the default English and Bahasa Malaysia privacy notice, with the company's name filled in. DDL. |
|
||||
|
||||
Run both before the new images go live: the new services-counter reads the new `event_lead` columns on every lead query and fails without them. Both need a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the codes, the notices and the consent records.
|
||||
|
||||
**Review the privacy notice before go-live.** The seeded text is a starting template written for the PDPA, not legal advice. INS and CV should each have theirs checked; a super admin changes it under **Companies → Privacy notice**. A company with no notice has no working QR codes.
|
||||
|
||||
**Database user:**
|
||||
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
|
||||
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
|
||||
@@ -236,6 +245,8 @@ Generate each random value separately, for example with `openssl rand -base64 48
|
||||
|
||||
Route `co-lite.containerverse.dev` to the `admin-portal` Service on port 3000, with TLS. Only the admin portal is public: the browser talks to the portal, and the portal talks to `mobile-api` inside the cluster. Do not expose `mobile-api`, `api-gateway` or the services.
|
||||
|
||||
QR registration pages (`/r/<code>`) are served by the admin portal on the same host, so nothing new is routed. mobile-api rate-limits visitors by the address the portal sends: the last entry of `X-Forwarded-For`, which is the one Traefik adds. That works whether Traefik appends to or replaces the header. If another proxy or load balancer sits in front of Traefik, the last entry is that proxy's address and every visitor shares one limit; the portal's `clientIp` would then have to change (or use the PROXY protocol). If the portal sees no `X-Forwarded-For` and no `X-Real-Ip` at all, every visitor shares the portal pod's limit.
|
||||
|
||||
## 9. Secret templates
|
||||
|
||||
There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files.
|
||||
@@ -302,6 +313,9 @@ data:
|
||||
- **Sign-in lockout.** 5 failed sign-ins within 15 minutes lock a username, even with the right password, until 15 minutes after the first of those failures, and unknown usernames are counted too. Anyone who knows a username can therefore lock it on purpose. An admin with **Login security** can unlock it at once (Locked tab), and can change the limits there. If every super admin is locked, wait out the period. The lock check fails open: if `service-system` is down, sign-in still works without the lockout.
|
||||
- **Companies and super admins.** INS and CV each see only their own leads, events, event leads, users, emails, login history and audit log. Staff sign in with their company code, username and password. A super admin leaves Company blank, sees every company (with a company picker in the header), and is the only one who can manage companies, roles, interests, lockout settings and password rules. Changing a company's code renames its staff's sign-in names and signs them out; deactivating a company blocks its staff from signing in. Emails sent from public forms and other system emails have no company, so only super admins see them. Do not give a company's old code to another company while sessions opened under the old code may still be valid: such a session token would resolve to the new company's user of the same name. When in doubt, never reuse a code.
|
||||
- **Lead dashboard.** Users whose role has the Dashboard module see lead captures, wins, conversion and overdue follow-ups on the home page, for this month, last month or a custom range of up to two years in Malaysian time. A lead counts as converted when its status at an event is WON. Wins and days to win come from the status history, which starts with this release; for older leads it is approximate (see section 3).
|
||||
- **QR self-registration.** Visitors scan a code and register themselves as a lead at an event. Each event has an event code, and each team member has a personal code that assigns the visitor to them; staff with Events see and switch them off on the event page, and every staff user finds their own under **My QR codes** in the user menu. Codes work until the event's end date (Malaysian time). A registration never edits an existing lead: differences go into that event lead's notes for staff to check. Each visitor IP may load 120 registration pages in 10 minutes across all events, and submit 60 registrations per event in 10 minutes; there is no CAPTCHA. For a reprintable code with scan counts, paste the code's link into the dynamic-qr console and print that code instead; no visitor data reaches dynamic-qr.
|
||||
- **Gateway paths open to the public registration.** The internal gateway lets a few exact read paths and the registration write through without a user token, so mobile-api can serve visitors who are not signed in. Keep the gateway unexposed (above); the design notes in the change folder list the paths and the risk.
|
||||
- **Time zone.** The Java images run with `TZ=Asia/Kuala_Lumpur` (set in the `docker-java-21` base image), and stored times such as capture, consent and notice times are Malaysian local time. Do not override `TZ` on the services.
|
||||
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
|
||||
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
|
||||
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# QR Self-Registration — Design
|
||||
|
||||
Date: 2026-12-01. Status: draft for approval (owner answers of 2026-12-01 folded in).
|
||||
|
||||
## Why
|
||||
|
||||
Co-Lite is a lead-generation system for INS and CV. At events, staff type each visitor's details into Event Leads today. A walk-in visitor should instead scan a QR code at the booth or on a salesperson's phone, register themselves in under a minute, and become a lead that staff follow up. That removes typing at a busy booth, captures more visitors, and credits the salesperson who brought the visitor in.
|
||||
|
||||
Decided with the owner on 2026-12-01:
|
||||
- **Who scans:** walk-in visitors with no account register themselves as leads.
|
||||
- **No member app.** Co-Lite is a lead-generation system.
|
||||
- **Codes:** one QR per event (banner) plus a personal QR per salesperson per event. A personal code assigns the lead to that salesperson.
|
||||
- **dynamic-qr:** loose integration only. Co-Lite makes its own registration links and QR images. An admin who wants a repointable printed code with scan statistics pastes the Co-Lite link into the dynamic-qr console and prints that code. No API integration, and no personal data ever reaches dynamic-qr.
|
||||
|
||||
## Goals
|
||||
|
||||
- A public, phone-first registration page per event. It shows the event's name, dates and location (the "event details" purpose), a short form, and a thank-you page.
|
||||
- A registration creates or links the lead and creates the event lead, with the same rules as staff capture.
|
||||
- Event banner codes and personal salesperson codes. Staff can show, download, copy and switch off each code.
|
||||
- Consent under Malaysia's PDPA is recorded for every self-registration.
|
||||
- Abuse limits on the public page.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- A member app, member accounts, check-in for members, rewards or vouchers.
|
||||
- Calling the dynamic-qr API (option 2, later if admins print many codes).
|
||||
- Showing the registration source on the Event Leads and dashboard screens. The data is stored; a later change can show it.
|
||||
- Several languages on the public page. It is English with message keys, so it can be translated later.
|
||||
- Confirmation emails or WhatsApp to the visitor.
|
||||
- Removing the unused customer portal (`solvway-customer-portal`). That is a later clean-up.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
- Revealing whether a person already exists. Every successful registration gets the same thank-you page.
|
||||
- A guessable link, such as an event id in the URL.
|
||||
- A public endpoint that reaches company data beyond one event's name, dates, location and the active interests.
|
||||
|
||||
## Approaches considered (where the public page lives)
|
||||
|
||||
1. **A public route in the admin portal (chosen).** `/r/{token}` is excluded from the admin sign-in guard. The admin portal is already deployed behind Traefik, so there is nothing new to deploy. A separate hostname, for example `join.`, can point at the same app later.
|
||||
2. **The existing customer portal.** It is the untouched Tastefully member portal (login, vouchers, draws). It is not deployed and not built in CI, so it would need a new image, CI step and clean-up for one page.
|
||||
3. **A new small public app.** The cleanest separation, but it is a new deployable for one page.
|
||||
|
||||
## The visitor's flow
|
||||
|
||||
1. The visitor scans a code. It holds `https://<admin portal host>/r/<token>`.
|
||||
2. The page shows the event name, dates and location, then a form:
|
||||
- name (required), mobile, email (at least one of the two), company, job title;
|
||||
- interests (active ones, optional);
|
||||
- a PDPA consent tick box with the company's notice, which must be ticked.
|
||||
3. Submit. The page always shows "Thank you, you're registered for <event>", unless input is invalid (field errors) or the code is not active.
|
||||
4. A code that is unknown, switched off, belongs to an event that is disabled or has ended, or belongs to a salesperson no longer on the team shows "This code is no longer active." It shows no event details.
|
||||
|
||||
## What a registration does
|
||||
|
||||
Normalisation is the same as staff capture (event-lead-capture spec): mobile becomes E.164, email is lower-cased, and the same limits and errors apply. Matching is stricter, because anyone can type someone else's mobile or email into a public form (owner decision 2026-12-01):
|
||||
- **Match by mobile first, then by email.** The match is within the event's company. When the mobile matches one lead and the email another, the mobile match wins. Among several matches on the same key, the newest wins.
|
||||
- **A matched lead is never edited.** The registration links to it as EXISTING. Any submitted value that differs from the lead's is written into the event lead's notes ("Registered by QR with: name …, email …") for staff to review.
|
||||
- **No match** creates a new lead (NEW) with the submitted values.
|
||||
- **Already captured at this event:** nothing changes, with one exception. When the existing event lead has no salesperson and the visitor came through a personal code whose salesperson is still an active team member, that salesperson is assigned. The visitor sees the same thank-you page either way.
|
||||
- **The event lead:**
|
||||
- status OPEN;
|
||||
- salesperson = the code's salesperson when they are still an active user on the event's active team, otherwise none (Unassigned);
|
||||
- the chosen interests;
|
||||
- `source` = `QR`;
|
||||
- `consent_at` = now;
|
||||
- `consent_notice_id` = the notice version shown;
|
||||
- `captured_by` = `qr`.
|
||||
- **Status history:** null → OPEN, by `qr`.
|
||||
|
||||
## Codes and their management
|
||||
|
||||
- **Data:** table `service-counter.registration_link`:
|
||||
- `id`, `company_id`, `event_uuid`, `salesperson_user_id` (NULL for the event code);
|
||||
- `token` (22-character random URL-safe string from 128 random bits, unique);
|
||||
- `enabled`, `created_by`, `created_at`, `updated_by`, `updated_at`.
|
||||
|
||||
One row per event code and per salesperson per event, created on first use.
|
||||
- **Event page** (users with `BO_EVENTS`): a "Registration QR" section with:
|
||||
- the event code: QR image, copy link, download PNG, and an on/off switch;
|
||||
- each active team member's personal code, with the same controls, so admins can print lanyard cards.
|
||||
|
||||
Staff without edit rights (read-only event view) see the codes but not the switch.
|
||||
- **"My QR codes" page** for any signed-in staff user. It lists the events where they are an active team member and the event has not ended, with their personal code each. It is gated `ANY_ADMIN`, and it only ever shows the caller's own codes.
|
||||
- **When a code works:** the code is enabled, the event is enabled, its end date (Malaysia) has not passed, and the event's company has a privacy notice. Visitors can register before the event starts. A personal code whose salesperson has left the team or been deactivated keeps working, and its registrations arrive Unassigned, so printed cards never lose leads.
|
||||
- **Company scope:** as everywhere. Staff see their company's events; super admins see all.
|
||||
|
||||
## Consent (PDPA)
|
||||
|
||||
- **Bilingual notice.** The Personal Data Protection Act 2010 (s.7) requires the notice in Bahasa Malaysia and English. The form shows both, with a required tick box.
|
||||
- **One notice per company, versioned.** Table `service-system.company_privacy_notice`: `id`, `company_id`, `text_en`, `text_ms`, `created_by`, `created_at`. It is append-only, and the newest row is the current notice.
|
||||
- A super admin edits it on the Companies page. Saving adds a new row.
|
||||
- The change's SQL seeds INS and CV with the default below, with the company name filled in.
|
||||
- **What a registration records:** `event_lead.consent_at` and `event_lead.consent_notice_id`, so staff can show exactly what a person agreed to.
|
||||
- **A company with no notice row has no working codes.**
|
||||
- **The default text is a starting template, not legal advice.** INS and CV should have it reviewed before go-live.
|
||||
|
||||
Default notice (English); `{company}` is the company's name:
|
||||
|
||||
> **Privacy notice.** {company} collects the details you enter on this form (your name, mobile number, email, company, job title and interests) to contact you about our products, services and events, including by phone, SMS, WhatsApp and email. Your details are used only by {company} and the service providers who run this system for us, and are not sold to anyone. We keep them for as long as you remain a contact of ours or until you ask us to delete them. You may ask to see or correct your details, or withdraw this consent, at any time by contacting {company}. Giving your details is voluntary, but without them we cannot follow up with you.
|
||||
>
|
||||
> ☐ I agree to {company} using my details as described above.
|
||||
|
||||
Default notice (Bahasa Malaysia):
|
||||
|
||||
> **Notis privasi.** {company} mengumpul butiran yang anda masukkan dalam borang ini (nama, nombor telefon bimbit, e-mel, syarikat, jawatan dan minat anda) untuk menghubungi anda mengenai produk, perkhidmatan dan acara kami, termasuk melalui telefon, SMS, WhatsApp dan e-mel. Butiran anda hanya digunakan oleh {company} dan pembekal perkhidmatan yang mengendalikan sistem ini bagi pihak kami, dan tidak dijual kepada sesiapa. Kami menyimpannya selagi anda kekal sebagai kenalan kami atau sehingga anda meminta kami memadamnya. Anda boleh meminta untuk melihat atau membetulkan butiran anda, atau menarik balik persetujuan ini, pada bila-bila masa dengan menghubungi {company}. Pemberian butiran adalah secara sukarela, tetapi tanpanya kami tidak dapat menghubungi anda.
|
||||
>
|
||||
> ☐ Saya bersetuju {company} menggunakan butiran saya seperti yang diterangkan di atas.
|
||||
|
||||
## Abuse limits
|
||||
|
||||
- Each client IP may submit at most 60 registrations per event per 10 minutes (Redis counter in mobile-api), so a busy booth on shared venue Wi-Fi is not locked out. Over the limit the visitor sees "Too many registrations from this device. Try again later."
|
||||
- The visitor's IP is read the same way the audit log reads the client IP.
|
||||
- The thank-you page has a "Register another person" button for a kiosk tablet at the booth.
|
||||
- The form has a hidden honeypot field. A submission that fills it is answered with the normal thank-you page and saves nothing.
|
||||
- Each IP may make at most 120 page loads (`GET /r/{token}` data) per 10 minutes, to slow token guessing. With 128-bit tokens, guessing is not a practical risk anyway.
|
||||
- `ponytail:` no CAPTCHA. Add one if the limits prove too weak at a real event.
|
||||
|
||||
## API
|
||||
|
||||
- **Public, mobile-api:** `@AppAuth(skipValidate = true)`; the portal's server sends the api-key.
|
||||
- `GET /api/public/registration/{token}` returns `{eventName, startDate, endDate, location, companyCode, interests:[{id,name}]}`, or 404 `CODE_INACTIVE`.
|
||||
- `POST /api/public/registration/{token}` with `{name, mobile, email, companyName, jobTitle, interestIds, consent, website}` (`website` is the honeypot). It returns 200 `{eventName}`, 400 with field errors, 404 `CODE_INACTIVE`, or 429 `TOO_MANY`.
|
||||
- **Admin, mobile-api:**
|
||||
- `GET /api/admin/events/{uuid}/registration-links` (`BO_EVENTS`) returns the event code and the team members' codes, each `{salesperson|null, token, enabled}`. Missing rows are created.
|
||||
- `PUT /api/admin/events/{uuid}/registration-links/{token}` with `{enabled}` (`BO_EVENTS`, write).
|
||||
- `GET /api/admin/my-registration-links` (`ANY_ADMIN`) returns the caller's own codes for current events.
|
||||
- **services-counter:** endpoints for the link lookup and creation and for the self-registration capture, reusing `EventLeadService.capture` with `source` and `consent_at`.
|
||||
- **Routing:** the portal's server calls mobile-api directly with the api-key it already holds (`MOBILE_API_KEY`), as for every other call. The registration token never goes into the audit log as a target; the event uuid is recorded instead.
|
||||
- **Portal:**
|
||||
- public route `/r/[token]` and its proxy `app/api/public/registration/[token]`, both excluded from the admin auth middleware;
|
||||
- the QR images, rendered in the browser with `qrcode.react` (the library babyboo's portal already uses; one new dependency);
|
||||
- the portal builds the link from its own origin, so no new setting is needed.
|
||||
|
||||
## Data changes
|
||||
|
||||
- New table `registration_link` (above).
|
||||
- `event_lead`: add `source` varchar(8) NOT NULL DEFAULT 'STAFF' (`STAFF` | `QR`), `consent_at` datetime NULL and `consent_notice_id` bigint NULL.
|
||||
- New table `service-system.company_privacy_notice` (above), seeded with the default notice for INS and CV.
|
||||
- Companies page: a "Privacy notice" section (English and Bahasa Malaysia) for super admins.
|
||||
- Nothing is backfilled. Existing event leads are `STAFF`.
|
||||
|
||||
## Calls made (for the owner to check)
|
||||
|
||||
1. The public page lives on the admin portal at `/r/<token>`, not the customer portal.
|
||||
2. Personal codes are per salesperson per event, not one code per person for all events. Each lead then lands at the right event.
|
||||
3. A personal code keeps working after its salesperson leaves the team, but its registrations arrive Unassigned.
|
||||
4. Codes work from creation until the event's end date. There is no "reopen". Extend the event's end date instead.
|
||||
5. The limits: 60 registrations per IP per event and 120 page loads per IP per 10 minutes. There is also a honeypot field, and no CAPTCHA.
|
||||
6. A visitor already captured with no salesperson who scans a personal code is assigned to that salesperson.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- The exact layout and copy of the public page (mobile first, readable outdoors, large tap targets).
|
||||
- How the portal proxy passes the visitor's IP to mobile-api, matching what the audit log already uses for the client IP.
|
||||
- The PNG download size and file name.
|
||||
@@ -253,3 +253,51 @@ USE `service-system`;
|
||||
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard');
|
||||
|
||||
-- add-qr-self-registration/sql/01-registration-link.sql
|
||||
USE `service-counter`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `registration_link` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NOT NULL,
|
||||
`event_uuid` bigint NOT NULL,
|
||||
`salesperson_user_id` bigint NULL,
|
||||
`token` varchar(32) NOT NULL,
|
||||
`enabled` bit(1) NOT NULL DEFAULT b'1',
|
||||
`created_by` varchar(255) NULL,
|
||||
`created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_by` varchar(255) NULL,
|
||||
`updated_at` datetime NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_registration_link_token` (`token`),
|
||||
KEY `idx_registration_link_event` (`event_uuid`, `salesperson_user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
ALTER TABLE `event_lead`
|
||||
ADD COLUMN `source` varchar(8) NOT NULL DEFAULT 'STAFF' AFTER `lead_type`,
|
||||
ADD COLUMN `consent_at` datetime NULL AFTER `notes`,
|
||||
ADD COLUMN `consent_notice_id` bigint NULL AFTER `consent_at`;
|
||||
|
||||
-- add-qr-self-registration/sql/02-company-privacy-notice.sql
|
||||
USE `service-system`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `company_privacy_notice` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NOT NULL,
|
||||
`text_en` text NOT NULL,
|
||||
`text_ms` text NOT NULL,
|
||||
`created_by` varchar(255) NULL,
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_company_privacy_notice_company` (`company_id`, `id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- created_at in Malaysian time, like the rows the services write (the server clock may be UTC).
|
||||
INSERT INTO `company_privacy_notice` (`company_id`, `text_en`, `text_ms`, `created_by`, `created_at`)
|
||||
SELECT c.`id`,
|
||||
REPLACE('{company} collects the details you enter on this form (your name, mobile number, email, company, job title and interests) to contact you about our products, services and events, including by phone, SMS, WhatsApp and email. Your details are used only by {company} and the service providers who run this system for us, and are not sold to anyone. We keep them for as long as you remain a contact of ours or until you ask us to delete them. You may ask to see or correct your details, or withdraw this consent, at any time by contacting {company}. Giving your details is voluntary, but without them we cannot follow up with you.', '{company}', c.`name`),
|
||||
REPLACE('{company} mengumpul butiran yang anda masukkan dalam borang ini (nama, nombor telefon bimbit, e-mel, syarikat, jawatan dan minat anda) untuk menghubungi anda mengenai produk, perkhidmatan dan acara kami, termasuk melalui telefon, SMS, WhatsApp dan e-mel. Butiran anda hanya digunakan oleh {company} dan pembekal perkhidmatan yang mengendalikan sistem ini bagi pihak kami, dan tidak dijual kepada sesiapa. Kami menyimpannya selagi anda kekal sebagai kenalan kami atau sehingga anda meminta kami memadamnya. Anda boleh meminta untuk melihat atau membetulkan butiran anda, atau menarik balik persetujuan ini, pada bila-bila masa dengan menghubungi {company}. Pemberian butiran adalah secara sukarela, tetapi tanpanya kami tidak dapat menghubungi anda.', '{company}', c.`name`),
|
||||
'default',
|
||||
DATE_ADD(UTC_TIMESTAMP(), INTERVAL 8 HOUR)
|
||||
FROM `company` c
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `company_privacy_notice` n WHERE n.`company_id` = c.`id`);
|
||||
File renamed without changes.
@@ -0,0 +1,113 @@
|
||||
## Context
|
||||
|
||||
Approved product design: `docs/superpowers/specs/2026-12-01-qr-self-registration-design.md`. That covers the flow, the matching rules, the consent and the default notice text, the abuse limits and the calls made. This file fixes the technical contracts so services-counter, services-system and mobile-api can be built in parallel, and the portal after them.
|
||||
|
||||
Facts relied on:
|
||||
- Staff capture: mobile-api `AdminEventLeadService.capture` normalises and validates, then posts to services-counter `/counter/eventLead/capture`. On an existing lead, counter `EventLeadService.capture` fills blank fields (`fillBlank`), which registrations must not do.
|
||||
- An event's team is the rows of `event_salesperson` (`/counter/eventSalesperson/findByEventUuid`). An "active member" is an enabled admin user of the event's company (`AdminEventLeadService.isActiveAdminOf`).
|
||||
- `AppAccessAspect` audits admin paths only (`isAdminPath()`), so public endpoints never reach the audit log, and their token cannot either.
|
||||
- A public mobile-api endpoint is `@AppAuth(skipValidate = true)`: it needs the api-key header and no JWT. The portal's server already sends `MOBILE_API_KEY` on every call.
|
||||
- The portal middleware guards every page and `/api/*` route except static files.
|
||||
- `HttpReqRespUtils.getClientIpAddressIfServletRequestExist()` is how the audit log reads the client IP (it checks `X-Forwarded-For` first).
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. Data (SQL in `sql/`)
|
||||
|
||||
- `service-counter.registration_link`: `id` bigint PK auto, `company_id` bigint NOT NULL, `event_uuid` bigint NOT NULL, `salesperson_user_id` bigint NULL, `token` varchar(32) NOT NULL UNIQUE, `enabled` bit NOT NULL default 1, `created_by`, `created_at`, `updated_by`, `updated_at`. Key `(event_uuid, salesperson_user_id)`. MySQL allows several NULLs in a unique key, so services-counter enforces "one event code per event" when it creates rows, and an `ensure` race is settled by re-reading after the insert.
|
||||
- `service-counter.event_lead`: add `source` varchar(8) NOT NULL DEFAULT 'STAFF', `consent_at` datetime NULL, `consent_notice_id` bigint NULL.
|
||||
- `service-system.company_privacy_notice`: `id` bigint PK auto, `company_id` bigint NOT NULL, `text_en` text NOT NULL, `text_ms` text NOT NULL, `created_by` varchar(255), `created_at` datetime NOT NULL; key `(company_id, id)`. The newest row per company is current. Seeded for every existing company with the default text, `{company}` replaced by `company.name`.
|
||||
- Token: 16 bytes from `SecureRandom`, base64url without padding (22 characters).
|
||||
|
||||
### 2. services-counter contract
|
||||
|
||||
All bodies are JSON. `companyId` is always a concrete company, set by mobile-api.
|
||||
|
||||
- `POST /counter/registrationLink/ensure` `{companyId, eventUuid, salespersonUserIds: [..]}` returns `[{eventUuid, salespersonUserId|null, token, enabled}]`. The event code comes first, then one per given salesperson in the given order; missing rows are created. 404 when the event is not in the company.
|
||||
- `POST /counter/registrationLink/setEnabled` `{companyId, eventUuid, token, enabled, doneBy}` returns the link. 404 when the token is not that event's in that company.
|
||||
- `GET /counter/registrationLink/findByToken/{token}` returns `{companyId, eventUuid, salespersonUserId|null, token, enabled}`, or 404.
|
||||
- `POST /counter/registrationLink/mine` `{companyId, userId, today}` (today is a Malaysian date) covers events of the company where `event_salesperson` has the user, `enabled = Y` and `DATE(date_end) >= today`. Missing personal links are created. It returns `[{eventUuid, eventName, startDate, endDate, location, token, enabled}]`, ordered by start date.
|
||||
- `POST /counter/registration/register` `{companyId, eventUuid, salespersonUserId|null, name, mobileE164, email, companyName, jobTitle, interestIds, consentNoticeId, consentAt}` returns `{outcome: CREATED|LINKED|ALREADY_CAPTURED|ASSIGNED, eventLeadUuid}`. It runs in one transaction:
|
||||
1. **Match.** Look for a lead in the company with `mobile_e164 = mobileE164` (newest id first), then with `email_normalised = email`.
|
||||
2. **New person.** No match creates a new lead and a NEW event lead.
|
||||
3. **Known person, not yet captured here.** The match is not edited. Its event lead is EXISTING, and its notes are `Registered by QR with: <field> <value>; …` for each submitted non-blank value that differs from the lead's (name, mobile, email, company, job title); the notes are null when nothing differs.
|
||||
4. **Already captured.** When the lead is already captured at the event (row exists, or the insert hits `uk_event_lead_event_lead`): if that event lead has no salesperson and `salespersonUserId` is set, assign it (`ASSIGNED`, `updated_by = qr`); otherwise change nothing (`ALREADY_CAPTURED`).
|
||||
5. **The new event lead:** `status OPEN`, `source QR`, `captured_by 'qr'`, `consent_at`, `consent_notice_id`, the interests, plus the status history row null → OPEN by `qr`.
|
||||
|
||||
`EventLeadService.capture` (staff) stays as it is and sets `source STAFF`.
|
||||
|
||||
### 3. services-system contract
|
||||
|
||||
- `GET /company/{id}/privacyNotice` returns the current `{id, companyId, textEn, textMs, createdBy, createdAt}`, or 404.
|
||||
- `POST /company/{id}/privacyNotice` `{textEn, textMs, doneBy}` adds a version and returns it. Both texts are required after trimming and at most 5000 characters each (400 otherwise). 404 for an unknown company.
|
||||
|
||||
### 4. mobile-api contract
|
||||
|
||||
Public (`@AppAuth(skipValidate = true)`, controller `PublicRegistrationController` under `controller..`, path `/api/public/registration/{token}`):
|
||||
|
||||
- **`GET`:**
|
||||
- Page-load limit: Redis key `reg:load:<ip>`, at most 120 per 10 minutes, else 429 `TOO_MANY`. The POST counts against it too, before the code is checked, so guessing codes by POST is slowed as well.
|
||||
- A code works when all of these hold, otherwise 404 `CODE_INACTIVE` with message "This code is no longer active.":
|
||||
- the link exists and is enabled;
|
||||
- its event exists, is enabled and has `dateEnd`'s date (Malaysia) ≥ today;
|
||||
- the company is active (`status A`);
|
||||
- the company has a current notice.
|
||||
- Returns `{eventName, startDate, endDate, location, companyName, notice: {id, textEn, textMs}, interests: [{id, name}]}`, where interests are the active ones.
|
||||
- **`POST`** with `{name, mobile, email, companyName, jobTitle, interestIds, consent, website}`:
|
||||
- The code checks are the same as for `GET`.
|
||||
- A non-blank `website` (honeypot) returns 200 `{eventName}` without saving.
|
||||
- Submission limit: Redis key `reg:submit:<eventUuid>:<ip>`, at most 60 per 10 minutes, else 429 `TOO_MANY`.
|
||||
- Validation is the same as staff capture (required name, mobile or email, lengths, normalisation, interests must be active ones of the company), and `consent` must be true (field `consent`, code `CONSENT_REQUIRED`). Field errors use the existing `details.field` shape.
|
||||
- Salesperson: the link's salesperson when they are on the event's team and are an active admin of the company, else null.
|
||||
- The notice is the current notice at submit time; the client never chooses it.
|
||||
- Calls counter `register` and returns 200 `{eventName}` whatever the outcome.
|
||||
- **Limits:** they count only requests that reach the check. The limit message is "Too many registrations from this device. Try again later."
|
||||
|
||||
Admin:
|
||||
- `GET /api/admin/events/{uuid}/registration-links` (`BO_EVENTS`; event loaded through the company scope) returns `{event: {token, enabled}, members: [{userId, name, username, token, enabled}]}` for every team row, with names resolved per id.
|
||||
- `PUT /api/admin/events/{uuid}/registration-links/{token}` (`BO_EVENTS`) with `{enabled}` returns the link.
|
||||
- `GET /api/admin/my-registration-links` (`ANY_ADMIN`) returns the caller's own links from counter `mine` (Malaysian today). A caller with no company gets `[]`.
|
||||
- `GET` and `PUT /api/admin/companies/{id}/privacy-notice` are super-admin only (`AdminCompanyScope.requireSuper`) and pass through to services-system. `PUT` takes `{textEn, textMs}`.
|
||||
|
||||
### 5. Portal
|
||||
|
||||
- **Dependency:** `qrcode.react` (the same major as babyboo's portal).
|
||||
- **Middleware:** `/r/:token` and `/api/public/:path*` skip the sign-in check. This is security code, so it gets the minimum change and a test that a public path is reachable signed out while admin paths still redirect.
|
||||
- **`/r/[token]`:**
|
||||
- A client page built from the existing UI components, mobile first, without the admin shell (no sidebar or header).
|
||||
- States: loading, inactive, form, field errors, too-many, thank-you with "Register another person".
|
||||
- It uses the proxy `app/api/public/registration/[token]/route.ts` (GET and POST). The proxy sends the visitor IP to mobile-api as `X-Forwarded-For`, set to the last hop of the incoming header (the address the ingress added, the same rule as `X-Client-Ip`), so a visitor cannot choose their own rate-limit key.
|
||||
- **Event edit page:** a "Registration QR" card with:
|
||||
- the event code and every member's code: QR image (`QRCodeSVG`), the link built from `window.location.origin + /r/<token>`, copy, download PNG (`QRCodeCanvas` → `toDataURL`, file `<event>-<name|event>-qr.png`), and an on/off switch;
|
||||
- a note that the link can be pasted into dynamic-qr for a printed code.
|
||||
- **"My QR codes" page** `/my-qr`: reached from the header user menu, shown to every staff user, listing the caller's codes. It is not a module, so `ROUTE_MODULES` leaves it unmapped and any signed-in user may open it.
|
||||
- **Companies page (super admin):** a "Privacy notice" editor with the English and Bahasa Malaysia text areas, save, and "last changed by/at".
|
||||
|
||||
### 6. Gateway access without a user token (added after the live check)
|
||||
|
||||
mobile-api forwards the caller's JWT to the gateway, and a visitor has none, so the gateway's `JWTAuthFilter` refused every call the public flow makes (401). The gateway is internal only (`docs/deployment.md`), and the earlier sign-in work set the precedent of exact, anchored bypass paths.
|
||||
|
||||
- **Bypass only these, each for one HTTP method, with anchored patterns (no `contains`):**
|
||||
- GET `/counter/registrationLink/findByToken/<22 url-safe chars>`
|
||||
- GET `/counter/event/findByUuid/<digits>`
|
||||
- GET `/counter/interest/findByCompany/<digits>`
|
||||
- GET `/counter/eventSalesperson/findByEventUuid/<digits>`
|
||||
- GET `/company/findById/<digits>`
|
||||
- GET `/company/<digits>/privacyNotice` (the POST that saves a notice still needs a token)
|
||||
- GET `/user/<digits>/activeAdminOf/<digits>`
|
||||
- POST `/counter/registration/register`
|
||||
- **`/user/findById` stays closed.** It returns the whole user record, password hashes included. services-system gets `GET /user/{id}/activeAdminOf/{companyId}`, which answers only `true` or `false` (type A, enabled, same company; false for an unknown user), and the public salesperson check uses it.
|
||||
|
||||
### 7. Rejected
|
||||
|
||||
- Matching and capture in mobile-api with two counter calls: not atomic, and it races the unique key.
|
||||
- A notice text copied onto every event lead: a version id is enough and keeps rows small.
|
||||
|
||||
## Risks
|
||||
|
||||
- Shared venue NAT: 60 submissions per event per 10 minutes from one IP may still be hit at a very busy booth. The message tells the visitor to try later. Raise the limit if it happens.
|
||||
- The visitor IP is the last `X-Forwarded-For` hop, which is right whether Traefik appends to or replaces the header. Behind a second proxy in front of Traefik it would be that proxy's address; the deployment notes say so.
|
||||
- The default notice is a template; INS and CV must review it.
|
||||
- The registration code appears in request logs (mobile-api's response-time log and the gateway's request log). It is printed on the QR code anyway, and the audit log records the event instead; mask the path segment if that ever matters.
|
||||
- The event page loads each team member's user record one call at a time (N+1). Teams are small; batch it if they grow.
|
||||
- The gateway bypass (decision 6) lets any holder of a gateway api-key read those records and register a lead without a user token. The gateway is not exposed outside the cluster, and the paths are exact, so the exposure is limited to callers that already hold a server api-key. Such a caller could post registrations straight to services-counter, skipping mobile-api's code, consent and rate-limit checks: choose the company, event and salesperson, and learn from the outcome whether a mobile or email is already a lead. It could also read whole event records and test user ids against `activeAdminOf`. Narrower projections or a service-to-service credential would close this if the gateway is ever exposed.
|
||||
@@ -0,0 +1,29 @@
|
||||
## Why
|
||||
|
||||
Co-Lite is a lead-generation system for INS and CV (the owner dropped the member app on 2026-12-01). At events, staff type every visitor in by hand. Walk-in visitors should scan a QR code, register themselves, and land in Event Leads and the dashboard, credited to the salesperson whose code they scanned. Approved design: `docs/superpowers/specs/2026-12-01-qr-self-registration-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- A public, phone-first registration page `/r/<token>` on the admin portal. It shows the event's details, a short form and a bilingual PDPA consent, and every successful submit gets the same thank-you page.
|
||||
- A registration links to an existing lead without editing it (differences go to the event lead's notes), or creates a new lead. It creates an OPEN event lead with `source = QR` and the consent record.
|
||||
- Registration codes: one per event and one per salesperson per event. Staff with `BO_EVENTS` see, download, copy and switch off codes on the event page. Every staff user sees their own codes on a new "My QR codes" page.
|
||||
- Each company's privacy notice is versioned and edited by super admins on the Companies page. INS and CV are seeded with a default English and Bahasa Malaysia notice. A company without a notice has no working codes.
|
||||
- Abuse limits: per IP per event for submissions and per IP for page loads, plus a honeypot field.
|
||||
- The admin portal gains `qrcode.react` (already used by babyboo's portal) to draw the codes.
|
||||
- dynamic-qr: no code integration. An admin may paste a Co-Lite link into dynamic-qr's console for a repointable printed code.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `qr-registration`: registration codes, the public registration page and its rules, consent and privacy notices, and abuse limits.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
## Impact
|
||||
|
||||
- `service-counter`: new table `registration_link`; `event_lead` gains `source`, `consent_at` and `consent_notice_id`.
|
||||
- `service-system`: new table `company_privacy_notice`, seeded for INS and CV.
|
||||
- `solvway-services-counter`, `solvway-services-system`, `solvway-mobile-api` (public `/api/public/registration/**`, admin link and notice endpoints), `solvway-admin-portal` (public route outside the admin sign-in guard, event QR section, My QR codes, Companies notice).
|
||||
- New public, unauthenticated surface: covered by the abuse limits and the anti-goals in the design.
|
||||
- `docs/deployment.md`: the SQL, and a note that the default notice must be reviewed.
|
||||
@@ -0,0 +1,127 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Registration codes
|
||||
|
||||
The system SHALL give every event one registration code and one personal code per member of the event's team. A code SHALL be an unguessable token in a link of the form `/r/<token>`. Staff with `BO_EVENTS` SHALL see each code of an event of their company as a QR image, copy its link, download it as an image, and switch it off or on. Every staff user SHALL see their own personal codes for events of their company that have not ended.
|
||||
|
||||
#### Scenario: Event page codes
|
||||
|
||||
- **GIVEN** event `KL Expo` with `sales1` and `sales2` on its team
|
||||
- **WHEN** a user with `BO_EVENTS` opens the event
|
||||
- **THEN** the event's code and the personal codes of `sales1` and `sales2` are shown, each with its QR image and link
|
||||
|
||||
#### Scenario: Own codes
|
||||
|
||||
- **GIVEN** `sales1` is on the team of `KL Expo`, which ends tomorrow, and of `Penang Fair`, which ended last week
|
||||
- **WHEN** `sales1` opens My QR codes
|
||||
- **THEN** only the personal code for `KL Expo` is listed
|
||||
|
||||
#### Scenario: Switch a code off
|
||||
|
||||
- **WHEN** staff switch off the event code of `KL Expo`
|
||||
- **THEN** scanning that code shows that it is no longer active
|
||||
- **AND** the personal codes still work
|
||||
|
||||
### Requirement: When a code works
|
||||
|
||||
A code SHALL work only while it is switched on, its event is enabled, the event's end date in Malaysia time has not passed, and the event's company has a privacy notice. An inactive or unknown code SHALL show "This code is no longer active." and no event details. A personal code whose salesperson is no longer an active member of the event's team SHALL keep working, and its registrations SHALL have no salesperson.
|
||||
|
||||
#### Scenario: Ended event
|
||||
|
||||
- **GIVEN** `Penang Fair` ended yesterday
|
||||
- **WHEN** a visitor scans its code
|
||||
- **THEN** the page says the code is no longer active and shows no event details
|
||||
|
||||
#### Scenario: Salesperson left the team
|
||||
|
||||
- **GIVEN** `sales2` was removed from the team of `KL Expo`
|
||||
- **WHEN** a visitor registers through `sales2`'s code
|
||||
- **THEN** the registration succeeds and the event lead has no salesperson
|
||||
|
||||
### Requirement: Public registration
|
||||
|
||||
The registration page SHALL show the event's name, dates and location, and a form for name (required), mobile and email (at least one), company, job title, the company's active interests, and the privacy notice consent (required). Inputs SHALL be normalised and limited as in staff capture. Every accepted submission SHALL show the same thank-you page naming the event, with a button to register another person, whether or not the person was already known.
|
||||
|
||||
#### Scenario: Register
|
||||
|
||||
- **WHEN** a visitor scans the code of `KL Expo`, enters name `Aisyah`, mobile `012-345 6701` and ticks the consent
|
||||
- **THEN** the thank-you page names `KL Expo`
|
||||
- **AND** staff see `Aisyah` with mobile `+60123456701` in the event's leads as NEW and OPEN
|
||||
|
||||
#### Scenario: Missing consent or contact
|
||||
|
||||
- **WHEN** a visitor submits without ticking the consent, or without a mobile and an email
|
||||
- **THEN** nothing is saved and the page shows the error under the field
|
||||
|
||||
#### Scenario: Known person gets the same answer
|
||||
|
||||
- **GIVEN** a lead with mobile `+60123456701` exists in the company
|
||||
- **WHEN** a visitor registers with that mobile
|
||||
- **THEN** the page shows the same thank-you page as for a new person
|
||||
|
||||
### Requirement: Registration matching
|
||||
|
||||
A registration SHALL match a lead of the event's company by mobile first and then by email, the newest lead winning among several. A matched lead SHALL NOT be edited: it SHALL be linked as EXISTING, with every submitted value that differs from the lead's written into the event lead's notes. Without a match a new lead SHALL be created as NEW.
|
||||
|
||||
#### Scenario: Existing lead not edited
|
||||
|
||||
- **GIVEN** lead `Aisyah` with mobile `+60123456701` and no email
|
||||
- **WHEN** a visitor registers as `Aisyah Rahman` with that mobile and email `a@example.test`
|
||||
- **THEN** lead `Aisyah` still has no email and its name is unchanged
|
||||
- **AND** the new event lead is EXISTING and its notes list the submitted name and email
|
||||
|
||||
#### Scenario: Mobile beats email
|
||||
|
||||
- **GIVEN** lead `A` has mobile `+60123456701` and lead `B` has email `b@example.test`
|
||||
- **WHEN** a visitor registers with that mobile and that email
|
||||
- **THEN** the registration is linked to lead `A`
|
||||
|
||||
### Requirement: Registration of a person already captured
|
||||
|
||||
When the matched lead is already captured at the event, a registration SHALL change nothing, except that an event lead with no salesperson SHALL get the salesperson of a personal code whose salesperson is an active member of the event's team.
|
||||
|
||||
#### Scenario: Already captured, unassigned
|
||||
|
||||
- **GIVEN** `Aisyah` is captured at `KL Expo` with no salesperson
|
||||
- **WHEN** she registers again through `sales1`'s personal code and `sales1` is on the team
|
||||
- **THEN** her event lead's salesperson becomes `sales1` and nothing else changes
|
||||
|
||||
### Requirement: Registration record
|
||||
|
||||
An event lead created by a registration SHALL have status OPEN, source QR, captured by `qr`, the consent time and the privacy notice version shown, the chosen interests, and the code's salesperson when that salesperson is an active member of the event's team. Event leads captured by staff SHALL have source STAFF. The status history SHALL record the first status by `qr`.
|
||||
|
||||
#### Scenario: Personal code assigns
|
||||
|
||||
- **WHEN** a visitor registers through `sales1`'s personal code for `KL Expo`
|
||||
- **THEN** the event lead's salesperson is `sales1`, its source is QR and it records the consent time and notice version
|
||||
|
||||
### Requirement: Privacy notice
|
||||
|
||||
Each company SHALL have a privacy notice in English and Bahasa Malaysia, kept as versions: saving a change SHALL add a new version and keep the old ones. Only a super admin SHALL edit it, on the Companies page. The registration page SHALL show the company's current notice in both languages. INS and CV SHALL start with the default notice of the design, with the company's name filled in.
|
||||
|
||||
#### Scenario: Edit the notice
|
||||
|
||||
- **GIVEN** CV's notice is version 3
|
||||
- **WHEN** a super admin changes CV's English text and saves
|
||||
- **THEN** CV's registration pages show the new text
|
||||
- **AND** event leads registered before still point to version 3
|
||||
|
||||
#### Scenario: Not a super admin
|
||||
|
||||
- **WHEN** company staff call the privacy notice update endpoint
|
||||
- **THEN** it responds 403
|
||||
|
||||
### Requirement: Registration abuse limits
|
||||
|
||||
The system SHALL accept at most 60 registrations per client IP per event in 10 minutes and serve at most 120 registration page loads per client IP in 10 minutes, answering above either limit with "Too many registrations from this device. Try again later." A submission that fills the hidden honeypot field SHALL get the normal thank-you page and save nothing.
|
||||
|
||||
#### Scenario: Too many submissions
|
||||
|
||||
- **GIVEN** 60 registrations for `KL Expo` from one IP in the last 10 minutes
|
||||
- **WHEN** the 61st arrives from that IP
|
||||
- **THEN** nothing is saved and the page shows the too-many message
|
||||
|
||||
#### Scenario: Honeypot
|
||||
|
||||
- **WHEN** a submission fills the hidden field
|
||||
- **THEN** the thank-you page shows and no lead or event lead is saved
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Co-Lite change add-qr-self-registration: registration codes and the source/consent of event leads (design decision 1).
|
||||
-- Target: `service-counter`. Additive only. Run before the new images go live. Needs a user that may alter tables.
|
||||
USE `service-counter`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `registration_link` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NOT NULL,
|
||||
`event_uuid` bigint NOT NULL,
|
||||
`salesperson_user_id` bigint NULL,
|
||||
`token` varchar(32) NOT NULL,
|
||||
`enabled` bit(1) NOT NULL DEFAULT b'1',
|
||||
`created_by` varchar(255) NULL,
|
||||
`created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_by` varchar(255) NULL,
|
||||
`updated_at` datetime NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_registration_link_token` (`token`),
|
||||
KEY `idx_registration_link_event` (`event_uuid`, `salesperson_user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
ALTER TABLE `event_lead`
|
||||
ADD COLUMN `source` varchar(8) NOT NULL DEFAULT 'STAFF' AFTER `lead_type`,
|
||||
ADD COLUMN `consent_at` datetime NULL AFTER `notes`,
|
||||
ADD COLUMN `consent_notice_id` bigint NULL AFTER `consent_at`;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Co-Lite change add-qr-self-registration: versioned privacy notice per company, seeded with the default text.
|
||||
-- Target: `service-system`. Additive only. The default notice is a template, not legal advice: INS and CV should have it
|
||||
-- reviewed, then a super admin saves the reviewed text on the Companies page (which adds a new version).
|
||||
USE `service-system`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `company_privacy_notice` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NOT NULL,
|
||||
`text_en` text NOT NULL,
|
||||
`text_ms` text NOT NULL,
|
||||
`created_by` varchar(255) NULL,
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_company_privacy_notice_company` (`company_id`, `id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- created_at in Malaysian time, like the rows the services write (the server clock may be UTC).
|
||||
INSERT INTO `company_privacy_notice` (`company_id`, `text_en`, `text_ms`, `created_by`, `created_at`)
|
||||
SELECT c.`id`,
|
||||
REPLACE('{company} collects the details you enter on this form (your name, mobile number, email, company, job title and interests) to contact you about our products, services and events, including by phone, SMS, WhatsApp and email. Your details are used only by {company} and the service providers who run this system for us, and are not sold to anyone. We keep them for as long as you remain a contact of ours or until you ask us to delete them. You may ask to see or correct your details, or withdraw this consent, at any time by contacting {company}. Giving your details is voluntary, but without them we cannot follow up with you.', '{company}', c.`name`),
|
||||
REPLACE('{company} mengumpul butiran yang anda masukkan dalam borang ini (nama, nombor telefon bimbit, e-mel, syarikat, jawatan dan minat anda) untuk menghubungi anda mengenai produk, perkhidmatan dan acara kami, termasuk melalui telefon, SMS, WhatsApp dan e-mel. Butiran anda hanya digunakan oleh {company} dan pembekal perkhidmatan yang mengendalikan sistem ini bagi pihak kami, dan tidak dijual kepada sesiapa. Kami menyimpannya selagi anda kekal sebagai kenalan kami atau sehingga anda meminta kami memadamnya. Anda boleh meminta untuk melihat atau membetulkan butiran anda, atau menarik balik persetujuan ini, pada bila-bila masa dengan menghubungi {company}. Pemberian butiran adalah secara sukarela, tetapi tanpanya kami tidak dapat menghubungi anda.', '{company}', c.`name`),
|
||||
'default',
|
||||
DATE_ADD(UTC_TIMESTAMP(), INTERVAL 8 HOUR)
|
||||
FROM `company` c
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `company_privacy_notice` n WHERE n.`company_id` = c.`id`);
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Co-Lite change add-qr-self-registration: rollback. Deletes the codes, the notices and the consent records.
|
||||
USE `service-system`;
|
||||
DROP TABLE IF EXISTS `company_privacy_notice`;
|
||||
|
||||
USE `service-counter`;
|
||||
DROP TABLE IF EXISTS `registration_link`;
|
||||
ALTER TABLE `event_lead` DROP COLUMN `consent_notice_id`, DROP COLUMN `consent_at`, DROP COLUMN `source`;
|
||||
@@ -0,0 +1,97 @@
|
||||
# Tasks
|
||||
|
||||
Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-01-qr-self-registration-design.md` (product).
|
||||
|
||||
Waves:
|
||||
- Wave 0 (serial, controller): 1.1 and 1.2 touch hotspots (SQL, seed, `package.json`).
|
||||
- Wave 1 (parallel, 3 implementers): 2.1, 3.1 and 4.1 build against the fixed contracts in design decisions 2 to 4. Each touches one module only.
|
||||
- Wave 2 (serial): 5.1, the portal, which also touches the middleware (security).
|
||||
- Wave 3 (serial, controller): 6.1.
|
||||
|
||||
## 1. Data and dependency
|
||||
|
||||
- [x] 1.1 SQL `sql/01`, `02`, `99`; mirror 01 and 02 in `local/seed/03-colite.sql`; apply 01 and 02 to the local database.
|
||||
- Depends on: none
|
||||
- Scope: `local/seed/**`, `openspec/changes/add-qr-self-registration/sql/**`
|
||||
- Verify: `SELECT` shows the table, the new `event_lead` columns, and one notice per company with the company name filled in.
|
||||
- [x] 1.2 Portal: add `qrcode.react` (same major as babyboo's portal).
|
||||
- Depends on: none
|
||||
- Scope: `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`
|
||||
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
|
||||
|
||||
## 2. services-counter
|
||||
|
||||
- [x] 2.1 Registration links and the registration capture (decision 2).
|
||||
- Tests first:
|
||||
- `ensure` creates the event code and missing personal codes once, keeps order, and makes 22-character unique tokens;
|
||||
- `setEnabled` refuses another company's or another event's token;
|
||||
- `findByToken` returns the link, or 404;
|
||||
- `mine` lists only enabled, not-ended events where the user is on the team, creating missing links;
|
||||
- `register`:
|
||||
- new person → NEW, OPEN, QR, `qr`, consent fields, interests, history null → OPEN by `qr`;
|
||||
- known by mobile → EXISTING, lead unchanged, notes list only differing submitted values (null when none);
|
||||
- mobile beats email when they match different leads;
|
||||
- newest lead wins among several;
|
||||
- already captured: unassigned + salesperson → ASSIGNED; otherwise ALREADY_CAPTURED with nothing changed;
|
||||
- the unique-key race → treated as already captured;
|
||||
- staff capture still sets `source STAFF`.
|
||||
- Scope: `solvway-services-counter/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
|
||||
|
||||
## 3. services-system
|
||||
|
||||
- [x] 3.1 Company privacy notice versions (decision 3).
|
||||
- Tests first:
|
||||
- GET returns the newest version, 404 when none;
|
||||
- POST adds a version, keeps older ones, trims, requires both texts, at most 5000 characters each, 404 for an unknown company.
|
||||
- Scope: `solvway-services-system/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-services-system verify`
|
||||
|
||||
## 4. mobile-api
|
||||
|
||||
- [x] 4.1 Public registration endpoints and the admin link and notice endpoints (decision 4).
|
||||
- Tests first:
|
||||
- **GET code checks:** inactive for each failing condition (unknown, switched off, event disabled, ended, company inactive, no notice); the active payload includes only active interests;
|
||||
- **POST rejections:** honeypot → 200 and no counter call; consent missing → 400 `CONSENT_REQUIRED` on field `consent`;
|
||||
- **POST validation:** same field rules as staff capture; an inactive interest is refused;
|
||||
- **POST salesperson:** the code's salesperson is passed when active on the team, null otherwise;
|
||||
- **POST notice:** the current notice id comes from the server;
|
||||
- **Limits:** 120 page loads per IP and 60 submissions per IP per event per 10 minutes → 429 `TOO_MANY` (Redis mocked); the IP comes from `HttpReqRespUtils.getClientIpAddressIfServletRequestExist`;
|
||||
- **Admin:** links endpoint scoped by company and gated `BO_EVENTS`; toggle; my links for the caller only and `[]` without a company; privacy notice GET/PUT super-admin only (403 for staff).
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
|
||||
|
||||
- [x] 4.2 Gateway access for the public flow (decision 6), found by the live check.
|
||||
- Depends on: 4.1
|
||||
- Tests first:
|
||||
- gateway: each decision-6 path passes without a user token for its method; POST `/company/1/privacyNotice`, GET `/user/findById/1`, POST `/counter/registrationLink/ensure` and a path with an extra segment still get 401;
|
||||
- services-system: `activeAdminOf` is true only for an enabled type-A user of that company, false otherwise and for an unknown user;
|
||||
- mobile-api: the public salesperson check uses `activeAdminOf` and never `findById`.
|
||||
- Scope: `solvway-api-gateway/src/**`, `solvway-services-system/src/**`, `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-api-gateway,solvway-services-system,solvway-mobile-api verify`
|
||||
|
||||
## 5. Portal
|
||||
|
||||
- [x] 5.1 Public page, proxy, middleware, event QR card, My QR codes, Companies privacy notice (decision 5).
|
||||
- Depends on: 1.2 and the contracts of 4.1
|
||||
- Tests first:
|
||||
- middleware: `/r/x` and `/api/public/registration/x` pass signed out, and `/events` still redirects;
|
||||
- proxy forwards GET and POST with the client IP;
|
||||
- public page: inactive message, the form with both notice texts, required consent, field errors, too-many, thank-you with "Register another person" resetting the form, honeypot field hidden from people and from assistive technology;
|
||||
- event QR card: codes, copy, switch (hidden without write access), download;
|
||||
- My QR codes: list and empty state;
|
||||
- Companies notice editor: super admin only, save, error;
|
||||
- the hard-coded copy sweep stays green.
|
||||
- Scope: `solvway-admin-portal/app/**`, `solvway-admin-portal/middleware.ts`, `solvway-admin-portal/middleware*.test.ts`
|
||||
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
|
||||
|
||||
## 6. Release
|
||||
|
||||
- [x] 6.1 `docs/deployment.md` (SQL, notice review, the Traefik `X-Forwarded-For` note, dynamic-qr usage); live check on the local stack; Playwright at 1280 and 360 px:
|
||||
- a visitor registers through an event code and a personal code;
|
||||
- the inactive, consent and too-many paths;
|
||||
- staff toggle a code and see My QR codes;
|
||||
- a super admin edits a notice.
|
||||
- Depends on: 1.1 to 5.1
|
||||
- Scope: `docs/deployment.md`, `openspec/changes/add-qr-self-registration/tasks.md`
|
||||
- Verify: the three Maven modules and the portal verify.
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-01
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -150,3 +150,24 @@ The system SHALL let staff with `BO_EVENT_LEADS` change an event lead's salesper
|
||||
- **GIVEN** an event lead tagged `Cookware`, and `Cookware` is then deactivated
|
||||
- **WHEN** staff change the lead's status
|
||||
- **THEN** the save succeeds and the lead is still tagged `Cookware`
|
||||
|
||||
### Requirement: Event lead status history
|
||||
|
||||
The system SHALL record every change of an event lead's status with the previous status, the new status, the time and the user who made it. Capturing an event lead SHALL record its first status with no previous status, at the capture time. An edit that leaves the status unchanged SHALL record nothing. The history SHALL never be edited or deleted through the application.
|
||||
|
||||
#### Scenario: Capture records the first status
|
||||
|
||||
- **WHEN** staff capture a lead at an event with no status chosen
|
||||
- **THEN** the history holds one entry from no status to OPEN at the capture time, by that user
|
||||
|
||||
#### Scenario: Status change recorded
|
||||
|
||||
- **GIVEN** an OPEN event lead
|
||||
- **WHEN** staff change its status to CONTACTED and later to WON
|
||||
- **THEN** the history holds OPEN to CONTACTED and CONTACTED to WON, each with its time and user
|
||||
|
||||
#### Scenario: Edit without a status change
|
||||
|
||||
- **GIVEN** a CONTACTED event lead
|
||||
- **WHEN** staff change only its temperature and notes
|
||||
- **THEN** no history entry is added
|
||||
@@ -0,0 +1,158 @@
|
||||
# lead-dashboard Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Show managers on the back-office home page how many leads each period, event, salesperson and interest produced and how many converted (status WON), so marketing can see which events turn visitors into customers.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Dashboard access
|
||||
|
||||
The system SHALL show the lead dashboard on the back-office home page to users granted the `BO_DASHBOARD` module, and SHALL show users without it the welcome message instead of a not-authorised page. The dashboard endpoint SHALL answer 403 to a user without `BO_DASHBOARD`. The sidebar SHALL show a Dashboard link to users with the module.
|
||||
|
||||
#### Scenario: Granted user
|
||||
|
||||
- **GIVEN** a role holding `BO_DASHBOARD` is assigned to `sales1`
|
||||
- **WHEN** `sales1` signs in
|
||||
- **THEN** the home page shows the lead dashboard and the sidebar shows Dashboard
|
||||
|
||||
#### Scenario: User without the module
|
||||
|
||||
- **WHEN** a user without `BO_DASHBOARD` opens the home page or calls the dashboard endpoint
|
||||
- **THEN** the page shows the welcome message and the endpoint responds 403
|
||||
|
||||
### Requirement: Dashboard period
|
||||
|
||||
The dashboard SHALL cover a period of whole days in Malaysia time (Asia/Kuala_Lumpur): this month up to today (the default), last month, or a custom range from one date to another, both included. A range whose start is after its end, or that spans more than 731 days, SHALL be refused with a message. The trend SHALL be counted by day for a period of up to 62 days and by month for a longer one, and SHALL list every day or month in the period, with zero where nothing happened.
|
||||
|
||||
#### Scenario: Default period
|
||||
|
||||
- **WHEN** a user opens the dashboard on 2026-12-10
|
||||
- **THEN** it covers 2026-12-01 to 2026-12-10, with one trend point per day
|
||||
|
||||
#### Scenario: Long range counted by month
|
||||
|
||||
- **WHEN** the user picks 2026-01-01 to 2026-12-31
|
||||
- **THEN** the trend has one point per month, January to December
|
||||
|
||||
#### Scenario: Day boundary in Malaysia time
|
||||
|
||||
- **GIVEN** a lead captured at 2026-11-30 23:30 Malaysia time
|
||||
- **WHEN** the user views 2026-11-01 to 2026-11-30
|
||||
- **THEN** the capture is counted on 30 November
|
||||
|
||||
#### Scenario: Reversed range
|
||||
|
||||
- **WHEN** the user picks a start date after the end date
|
||||
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
|
||||
|
||||
#### Scenario: Range too long
|
||||
|
||||
- **WHEN** the user picks 2024-01-01 to 2026-12-31
|
||||
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
|
||||
|
||||
### Requirement: Capture figures
|
||||
|
||||
For the chosen period the dashboard SHALL show the captures (event leads captured in the period, so a person captured at two events counts twice), the new leads (captures whose lead type is NEW), the conversion rate (the share of the period's captures whose current status is WON, shown as a dash when there are no captures), a funnel of the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST) and the captures in the trend.
|
||||
|
||||
#### Scenario: Conversion of the period's captures
|
||||
|
||||
- **GIVEN** 10 leads captured in November, 3 of them now WON and 2 LOST
|
||||
- **WHEN** the user views November
|
||||
- **THEN** captures show 10, conversion rate 30%, and the funnel shows WON 3 and LOST 2
|
||||
|
||||
#### Scenario: No captures
|
||||
|
||||
- **WHEN** the user views a period with no captures
|
||||
- **THEN** captures show 0 and the conversion rate shows a dash
|
||||
|
||||
### Requirement: Win figures
|
||||
|
||||
The dashboard SHALL count as won in the period every event lead whose current status is WON and whose latest change to WON falls in the period, whenever it was captured. It SHALL show that count, the wins in the trend, and the median of whole days from capture to the latest change to WON over those event leads, shown as a dash when there are none.
|
||||
|
||||
#### Scenario: Win of an older capture
|
||||
|
||||
- **GIVEN** a lead captured in October and changed to WON on 5 November
|
||||
- **WHEN** the user views November
|
||||
- **THEN** won in period counts it and the November captures do not
|
||||
|
||||
#### Scenario: Reopened lead
|
||||
|
||||
- **GIVEN** a lead changed to WON on 3 November, back to QUALIFIED on 4 November, and to WON again on 20 November
|
||||
- **WHEN** the user views 1 to 10 November
|
||||
- **THEN** won in period does not count it, because its latest change to WON is 20 November
|
||||
|
||||
#### Scenario: Median days to win
|
||||
|
||||
- **GIVEN** three leads won in November, 2, 5 and 30 days after capture
|
||||
- **WHEN** the user views November
|
||||
- **THEN** median days to win shows 5
|
||||
|
||||
### Requirement: Overdue follow-ups
|
||||
|
||||
The dashboard SHALL show the event leads that are not WON or LOST and whose next follow-up date is before today in Malaysia time, whatever the chosen period.
|
||||
|
||||
#### Scenario: Overdue counted regardless of period
|
||||
|
||||
- **GIVEN** an OPEN lead captured in August with next follow-up 2026-12-01
|
||||
- **WHEN** the user views November on 2026-12-05
|
||||
- **THEN** overdue follow-ups count it
|
||||
|
||||
### Requirement: Breakdown by event
|
||||
|
||||
The dashboard SHALL list each event with captures in the period, most captures first, with its captures, new leads, won and conversion rate, and each row SHALL open that event's leads listing.
|
||||
|
||||
#### Scenario: Event drill-down
|
||||
|
||||
- **WHEN** the user selects an event row
|
||||
- **THEN** that event's leads listing opens
|
||||
|
||||
### Requirement: Breakdown by salesperson
|
||||
|
||||
The dashboard SHALL list, for the period's captures, each salesperson's assigned, worked (status other than OPEN), won, lost and conversion rate, with their current overdue follow-ups, and SHALL show captures with no salesperson as Unassigned.
|
||||
|
||||
#### Scenario: Salesperson row
|
||||
|
||||
- **GIVEN** in November `sales1` was assigned 4 captures: 1 OPEN, 1 CONTACTED, 1 WON and 1 LOST
|
||||
- **WHEN** the user views November
|
||||
- **THEN** sales1's row shows assigned 4, worked 3, won 1, lost 1 and conversion rate 25%
|
||||
|
||||
#### Scenario: Unassigned captures
|
||||
|
||||
- **GIVEN** 2 November captures have no salesperson
|
||||
- **WHEN** the user views November
|
||||
- **THEN** an Unassigned row shows assigned 2
|
||||
|
||||
### Requirement: Breakdown by interest
|
||||
|
||||
The dashboard SHALL list each interest with the period's captures tagged with it and how many of them are now WON. A capture with two interests SHALL count under both.
|
||||
|
||||
#### Scenario: Two interests
|
||||
|
||||
- **GIVEN** a November capture tagged `Cookware` and `Kitchen appliances`, now WON
|
||||
- **WHEN** the user views November
|
||||
- **THEN** both interests count 1 capture and 1 won
|
||||
|
||||
### Requirement: Phone width
|
||||
|
||||
The dashboard SHALL be usable on a 360 px wide screen without sideways scrolling.
|
||||
|
||||
#### Scenario: Phone
|
||||
|
||||
- **WHEN** a user opens the dashboard at 360 px
|
||||
- **THEN** the tiles stack and the breakdowns show as cards
|
||||
|
||||
### Requirement: Dashboard company scope
|
||||
|
||||
The dashboard SHALL count only the records of the caller's company for company staff. A super admin SHALL see every company's records by default and SHALL be able to narrow the dashboard to one company with the company picker; while all companies are shown, the by-event list SHALL show each event's company.
|
||||
|
||||
#### Scenario: Staff see their company
|
||||
|
||||
- **GIVEN** leads captured at INS and at CV events in November
|
||||
- **WHEN** an INS user with `BO_DASHBOARD` views November
|
||||
- **THEN** every figure counts INS records only
|
||||
|
||||
#### Scenario: Super admin picks a company
|
||||
|
||||
- **WHEN** a super admin picks CV in the company picker
|
||||
- **THEN** every figure counts CV records only
|
||||
@@ -0,0 +1,29 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id } = await params;
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/companies/${encodeURIComponent(id)}/privacy-notice`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id } = await params;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/companies/${encodeURIComponent(id)}/privacy-notice`, {
|
||||
method: "PUT",
|
||||
body,
|
||||
token,
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: { params: Promise<{ uuid: string; token: string }> }) {
|
||||
const session = await getToken();
|
||||
if (!session) return unauthorized();
|
||||
const { uuid, token } = await params;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const result = await callMobileApi<Record<string, unknown>>(
|
||||
`/api/admin/events/${encodeURIComponent(uuid)}/registration-links/${encodeURIComponent(token)}`,
|
||||
{ method: "PUT", body, token: session },
|
||||
);
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: { params: Promise<{ uuid: string }> }) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { uuid } = await params;
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/${encodeURIComponent(uuid)}/registration-links`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function GET() {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<unknown>("/api/admin/my-registration-links", { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
|
||||
import { GET, POST } from "./route";
|
||||
|
||||
type Req = Parameters<typeof GET>[0];
|
||||
const ctx = { params: Promise.resolve({ token: "tok/1" }) };
|
||||
const req = (init: RequestInit = {}) => new Request("http://localhost/api/public/registration/tok", init) as unknown as Req;
|
||||
|
||||
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { eventName: "Expo" } }));
|
||||
|
||||
describe("/api/public/registration/[token]", () => {
|
||||
it("GET forwards without a session and with the visitor IP", async () => {
|
||||
const res = await GET(req({ headers: { "x-forwarded-for": "203.0.113.7" } }), ctx);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ eventName: "Expo" });
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/registration/tok%2F1", {
|
||||
headers: { "X-Forwarded-For": "203.0.113.7" },
|
||||
});
|
||||
});
|
||||
|
||||
it("POST forwards the body and drops client-written X-Forwarded-For entries and sends only the last hop", async () => {
|
||||
const body = { name: "A", website: "" };
|
||||
await POST(req({ method: "POST", body: JSON.stringify(body), headers: { "x-forwarded-for": "6.6.6.6, 203.0.113.7" } }), ctx);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/registration/tok%2F1", {
|
||||
method: "POST",
|
||||
body,
|
||||
headers: { "X-Forwarded-For": "203.0.113.7" },
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to X-Real-Ip and sends no header when no address is known", async () => {
|
||||
await GET(req({ headers: { "x-real-ip": "192.0.2.9" } }), ctx);
|
||||
expect(mocks.callMobileApi.mock.calls[0][1].headers).toEqual({ "X-Forwarded-For": "192.0.2.9" });
|
||||
await GET(req(), ctx);
|
||||
expect(mocks.callMobileApi.mock.calls[1][1].headers).toEqual({});
|
||||
});
|
||||
|
||||
it("passes upstream failures with status and code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Too many registrations from this device. Try again later.", status: 429, code: "TOO_MANY" });
|
||||
const res = await POST(req({ method: "POST", body: "{}" }), ctx);
|
||||
expect(res.status).toBe(429);
|
||||
expect(((await res.json()) as Record<string, unknown>).code).toBe("TOO_MANY");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { clientIp } from "@/app/lib/server/clientContext";
|
||||
import { errorResponse } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// Public (signed-out) proxy for the QR registration page: no session token.
|
||||
// X-Forwarded-For is rebuilt from clientIp(req) only (the LAST hop, same trusted rule as X-Client-Ip):
|
||||
// client-written entries in an incoming header are never forwarded, so the rate-limit key cannot be spoofed.
|
||||
type Ctx = { params: Promise<{ token: string }> };
|
||||
|
||||
function forwardedFor(req: NextRequest): Record<string, string> {
|
||||
const xff = clientIp(req);
|
||||
return xff ? { "X-Forwarded-For": xff } : {};
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Ctx) {
|
||||
const { token } = await params;
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
|
||||
headers: forwardedFor(req),
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: Ctx) {
|
||||
const { token } = await params;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
|
||||
method: "POST",
|
||||
body,
|
||||
headers: forwardedFor(req),
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET as getLinks } from "./events/[uuid]/registration-links/route";
|
||||
import { PUT as putLink } from "./events/[uuid]/registration-links/[token]/route";
|
||||
import { GET as getMine } from "./my-registration-links/route";
|
||||
import { GET as getNotice, PUT as putNotice } from "./companies/[id]/privacy-notice/route";
|
||||
|
||||
const req = (init?: RequestInit) => new Request("http://localhost/x", init) as never;
|
||||
const p = <T,>(v: T) => ({ params: Promise.resolve(v) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { ok: 1 } });
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("registration admin proxies", () => {
|
||||
it("require a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
for (const res of [await getLinks(req(), p({ uuid: "e" })), await getMine(), await getNotice(req(), p({ id: "1" }))]) {
|
||||
expect(res.status).toBe(401);
|
||||
}
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forward to the admin endpoints with the token", async () => {
|
||||
await getLinks(req(), p({ uuid: "e1" }));
|
||||
await putLink(req({ method: "PUT", body: '{"enabled":false}' }), p({ uuid: "e1", token: "t1" }));
|
||||
await getMine();
|
||||
await getNotice(req(), p({ id: "2" }));
|
||||
await putNotice(req({ method: "PUT", body: '{"textEn":"a","textMs":"b"}' }), p({ id: "2" }));
|
||||
expect(mocks.callMobileApi.mock.calls).toEqual([
|
||||
["/api/admin/events/e1/registration-links", { token: "jwt" }],
|
||||
["/api/admin/events/e1/registration-links/t1", { method: "PUT", body: { enabled: false }, token: "jwt" }],
|
||||
["/api/admin/my-registration-links", { token: "jwt" }],
|
||||
["/api/admin/companies/2/privacy-notice", { token: "jwt" }],
|
||||
["/api/admin/companies/2/privacy-notice", { method: "PUT", body: { textEn: "a", textMs: "b" }, token: "jwt" }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ isSuper: true, apiGet: vi.fn(), getPrivacyNotice: vi.fn(), savePrivacyNotice: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ loading: false, isSuper: mocks.isSuper }) }));
|
||||
vi.mock("@/app/lib/services/adminRegistration", () => ({
|
||||
getPrivacyNotice: mocks.getPrivacyNotice,
|
||||
savePrivacyNotice: mocks.savePrivacyNotice,
|
||||
}));
|
||||
|
||||
import CompaniesPage from "./page";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
|
||||
mocks.getPrivacyNotice.mockReset().mockResolvedValue({ id: 3, companyId: 1, textEn: "Old EN", textMs: "Old MS", createdBy: "boss", createdAt: "2026-11-30T10:00:00" });
|
||||
mocks.savePrivacyNotice.mockReset().mockResolvedValue({ id: 4, companyId: 1, textEn: "x", textMs: "y", createdBy: "boss", createdAt: "2026-12-01T09:30:00" });
|
||||
mocks.isSuper = true;
|
||||
});
|
||||
|
||||
async function openEditor() {
|
||||
render(<CompaniesPage />);
|
||||
const row = (await screen.findByText("Insight")).closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: "Privacy notice" }));
|
||||
}
|
||||
|
||||
describe("Companies privacy notice editor", () => {
|
||||
it("loads both languages and shows who changed it last", async () => {
|
||||
await openEditor();
|
||||
expect(await screen.findByDisplayValue("Old EN")).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue("Old MS")).toBeInTheDocument();
|
||||
expect(screen.getByText(/boss/)).toBeInTheDocument();
|
||||
expect(mocks.getPrivacyNotice).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it("saves the edited text", async () => {
|
||||
await openEditor();
|
||||
const en = await screen.findByLabelText("English");
|
||||
await userEvent.clear(en);
|
||||
await userEvent.type(en, "New EN");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save notice" }));
|
||||
await waitFor(() => expect(mocks.savePrivacyNotice).toHaveBeenCalledWith(1, { textEn: "New EN", textMs: "Old MS" }));
|
||||
});
|
||||
|
||||
it("shows the server error and starts empty when there is no notice", async () => {
|
||||
mocks.getPrivacyNotice.mockResolvedValue(null);
|
||||
mocks.savePrivacyNotice.mockRejectedValue(new ApiError("Notice text is required.", 400, { error: "Notice text is required." }));
|
||||
await openEditor();
|
||||
const en = (await screen.findByLabelText("English")) as HTMLTextAreaElement;
|
||||
expect(en.value).toBe("");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save notice" }));
|
||||
expect(await screen.findByText("Notice text is required.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not crash when the notice has no createdAt or createdBy", async () => {
|
||||
mocks.getPrivacyNotice.mockResolvedValue({ id: 3, companyId: 1, textEn: "Old EN", textMs: "Old MS" });
|
||||
await openEditor();
|
||||
expect(await screen.findByDisplayValue("Old EN")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Last changed/i)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not offer the editor to a non-super admin", async () => {
|
||||
mocks.isSuper = false;
|
||||
render(<CompaniesPage />);
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Privacy notice" })).toBeNull());
|
||||
expect(mocks.getPrivacyNotice).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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<PrivacyNotice | null>(null);
|
||||
const [textEn, setTextEn] = useState("");
|
||||
const [textMs, setTextMs] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
getPrivacyNotice(company.id!)
|
||||
.then((n) => {
|
||||
setNotice(n);
|
||||
setTextEn(n?.textEn ?? "");
|
||||
setTextMs(n?.textMs ?? "");
|
||||
})
|
||||
.catch(() => setError(t("PrivLoadFailed")));
|
||||
}, [company.id, t]);
|
||||
|
||||
async function save(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setSaving(true);
|
||||
try {
|
||||
setNotice(await savePrivacyNotice(company.id!, { textEn, textMs }));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error && err.message ? err.message : t("PrivSaveFailed"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("PrivNotice")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{error && (
|
||||
<div className="text-sm text-destructive" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={save} className="space-y-4" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="notice-en">{t("RegNoticeEn")}</Label>
|
||||
<textarea id="notice-en" className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm" rows={5} value={textEn} onChange={(e) => setTextEn(e.target.value)} disabled={saving} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="notice-ms">{t("RegNoticeMs")}</Label>
|
||||
<textarea id="notice-ms" className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm" rows={5} value={textMs} onChange={(e) => setTextMs(e.target.value)} disabled={saving} />
|
||||
</div>
|
||||
{notice?.createdAt && notice.createdBy && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("PrivLastChanged", { user: notice.createdBy, date: notice.createdAt.replace("T", " ").slice(0, 16) })}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("PrivSave")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function CompaniesPageContent() {
|
||||
const t = useT();
|
||||
const [companies, setCompanies] = useState<AdminCompany[]>([]);
|
||||
@@ -121,6 +189,7 @@ function CompaniesPageContent() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [dialog, setDialog] = useState<DialogState | null>(null);
|
||||
const [noticeFor, setNoticeFor] = useState<AdminCompany | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const size = pageSize ?? MIN_PAGE_SIZE;
|
||||
@@ -165,6 +234,9 @@ function CompaniesPageContent() {
|
||||
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "code", company: row.original })}>
|
||||
{t("CompChangeCode")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setNoticeFor(row.original)}>
|
||||
{t("PrivNotice")}
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -200,6 +272,7 @@ function CompaniesPageContent() {
|
||||
empty={<EmptyState title={t("CompNone")} />}
|
||||
/>
|
||||
|
||||
{noticeFor && <PrivacyNoticeDialog company={noticeFor} onClose={() => setNoticeFor(null)} />}
|
||||
{dialog && <CompanyDialog state={dialog} onClose={() => setDialog(null)} onSaved={refetch} />}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -31,7 +31,7 @@ describe("Header: change password", () => {
|
||||
render(<Header />);
|
||||
await userEvent.click(screen.getByRole("button", { name: /admin user/i }));
|
||||
const items = (await screen.findAllByRole("menuitem")).map((i) => i.textContent);
|
||||
expect(items).toEqual(["Change password", "Logout"]);
|
||||
expect(items).toEqual(["My QR codes", "Change password", "Logout"]);
|
||||
});
|
||||
|
||||
it("blocks empty fields and mismatched passwords without calling the server", async () => {
|
||||
|
||||
@@ -108,6 +108,9 @@ export default function Header() {
|
||||
<span className="block text-sm font-medium">{name}</span>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => router.push("/my-qr")}>
|
||||
{t("QrMyTitle")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setChangingPassword(true)}>
|
||||
<KeyRound aria-hidden="true" className="size-4" />
|
||||
{t("PwdChangeMenu")}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { forwardRef } from "react";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getEventLinks: vi.fn(), setLinkEnabled: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminRegistration", () => mocks);
|
||||
vi.mock("qrcode.react", () => ({
|
||||
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
|
||||
QRCodeCanvas: forwardRef<HTMLCanvasElement>(function QRCodeCanvas(_, ref) {
|
||||
return <canvas ref={ref} />;
|
||||
}),
|
||||
}));
|
||||
|
||||
import { RegistrationQrCard } from "./RegistrationQrCard";
|
||||
|
||||
const links = {
|
||||
event: { token: "ev1", enabled: true },
|
||||
members: [
|
||||
{ userId: 5, name: "Aini", username: "aini@cv", token: "m1", enabled: false },
|
||||
{ userId: 6, name: "Bob", username: "", token: "m2", enabled: true },
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getEventLinks.mockReset().mockResolvedValue(links);
|
||||
mocks.setLinkEnabled.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("RegistrationQrCard", () => {
|
||||
it("lists the event code and each team member code with a QR", async () => {
|
||||
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
|
||||
await screen.findByText("Aini (aini@cv)");
|
||||
const values = screen.getAllByTestId("qr-svg").map((e) => e.getAttribute("data-value"));
|
||||
expect(values).toEqual([`${window.location.origin}/r/ev1`, `${window.location.origin}/r/m1`, `${window.location.origin}/r/m2`]);
|
||||
expect(screen.getByText(/dynamic-qr/)).toBeTruthy();
|
||||
expect(mocks.getEventLinks).toHaveBeenCalledWith("u1");
|
||||
});
|
||||
|
||||
it("labels a member without a username by name only", async () => {
|
||||
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
|
||||
await screen.findByText("Bob");
|
||||
expect(screen.queryByText(/\(\)/)).toBeNull();
|
||||
});
|
||||
|
||||
it("names the PNG download after the event and the member's name and username", async () => {
|
||||
const user = userEvent.setup();
|
||||
const names: string[] = [];
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue("data:image/png;base64,");
|
||||
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) {
|
||||
names.push(this.download);
|
||||
});
|
||||
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
|
||||
await screen.findByText("Aini (aini@cv)");
|
||||
await user.click(screen.getAllByRole("button", { name: "Download PNG" })[1]);
|
||||
expect(names).toEqual(["expo-aini-aini-cv-qr.png"]);
|
||||
});
|
||||
|
||||
it("toggles a code through the API", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
|
||||
await screen.findByText("Aini (aini@cv)");
|
||||
await user.click(screen.getAllByRole("switch")[1]);
|
||||
await waitFor(() => expect(mocks.setLinkEnabled).toHaveBeenCalledWith("u1", "m1", true));
|
||||
});
|
||||
|
||||
it("hides the switches without write access", async () => {
|
||||
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite={false} />);
|
||||
await screen.findByText("Aini (aini@cv)");
|
||||
expect(screen.queryAllByRole("switch")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { QrCodeItem } from "@/app/components/registration/QrCodeItem";
|
||||
import { getEventLinks, setLinkEnabled, type EventLinks } from "@/app/lib/services/adminRegistration";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
export function RegistrationQrCard({ eventUuid, eventName, canWrite }: { eventUuid: string; eventName: string; canWrite: boolean }) {
|
||||
const t = useT();
|
||||
const [links, setLinks] = useState<EventLinks | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
getEventLinks(eventUuid)
|
||||
.then((l) => !cancelled && setLinks(l))
|
||||
.catch(() => !cancelled && setError(t("QrLoadFailed")));
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [eventUuid, t]);
|
||||
|
||||
async function toggle(token: string, enabled: boolean) {
|
||||
setError(null);
|
||||
try {
|
||||
await setLinkEnabled(eventUuid, token, enabled);
|
||||
setLinks((l) =>
|
||||
l && {
|
||||
event: l.event.token === token ? { ...l.event, enabled } : l.event,
|
||||
members: l.members.map((m) => (m.token === token ? { ...m, enabled } : m)),
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
setError(t("QrSaveFailed"));
|
||||
}
|
||||
}
|
||||
|
||||
const onToggle = (token: string) => (canWrite ? (on: boolean) => toggle(token, on) : undefined);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("QrCardTitle")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">{t("QrNote")}</p>
|
||||
{error && <ErrorState message={error} />}
|
||||
{links && (
|
||||
<>
|
||||
<QrCodeItem label={t("QrEventCode")} eventName={eventName} token={links.event.token} enabled={links.event.enabled} onToggle={onToggle(links.event.token)} />
|
||||
{links.members.map((m) => {
|
||||
const label = m.username ? `${m.name} (${m.username})` : m.name;
|
||||
return (
|
||||
<QrCodeItem key={m.token} label={label} eventName={eventName} fileLabel={label} token={m.token} enabled={m.enabled} onToggle={onToggle(m.token)} />
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { forwardRef } from "react";
|
||||
|
||||
vi.mock("qrcode.react", () => ({
|
||||
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
|
||||
QRCodeCanvas: forwardRef<HTMLCanvasElement, { value: string }>(function C({ value }, ref) {
|
||||
return <canvas ref={(el) => { if (el) el.toDataURL = () => "data:image/png;base64,AAA"; if (typeof ref === "function") ref(el); else if (ref) ref.current = el; }} data-value={value} />;
|
||||
}),
|
||||
}));
|
||||
|
||||
import { QrCodeItem } from "./QrCodeItem";
|
||||
|
||||
let clicked: HTMLAnchorElement | undefined;
|
||||
beforeEach(() => {
|
||||
clicked = undefined;
|
||||
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) { clicked = this; });
|
||||
});
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe("QrCodeItem", () => {
|
||||
it("renders the QR for the origin link, copies it and downloads a slugified PNG", async () => {
|
||||
const user = userEvent.setup(); // installs a clipboard stub on navigator
|
||||
const writeText = vi.spyOn(navigator.clipboard, "writeText");
|
||||
const link = `${window.location.origin}/r/abc`;
|
||||
render(<QrCodeItem label="Aini Binti" eventName="Expo 2026!" fileLabel="Aini Binti" token="abc" enabled />);
|
||||
expect(screen.getByTestId("qr-svg").getAttribute("data-value")).toBe(link);
|
||||
expect(screen.getByText(link)).toBeTruthy();
|
||||
await user.click(screen.getByRole("button", { name: "Copy link" }));
|
||||
expect(writeText).toHaveBeenCalledWith(link);
|
||||
await user.click(screen.getByRole("button", { name: "Download PNG" }));
|
||||
expect(clicked?.download).toBe("expo-2026-aini-binti-qr.png");
|
||||
expect(clicked?.href).toBe("data:image/png;base64,AAA");
|
||||
});
|
||||
|
||||
it("uses event as the file name part when there is no member", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QrCodeItem label="Event code" eventName="Expo" token="abc" enabled />);
|
||||
await user.click(screen.getByRole("button", { name: "Download PNG" }));
|
||||
expect(clicked?.download).toBe("expo-event-qr.png");
|
||||
});
|
||||
|
||||
it("shows a switch only when a toggle handler is given", async () => {
|
||||
const onToggle = vi.fn();
|
||||
const { rerender } = render(<QrCodeItem label="x" eventName="E" token="t" enabled onToggle={onToggle} />);
|
||||
await userEvent.click(screen.getByRole("switch"));
|
||||
expect(onToggle).toHaveBeenCalledWith(false);
|
||||
rerender(<QrCodeItem label="x" eventName="E" token="t" enabled />);
|
||||
expect(screen.queryByRole("switch")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { QRCodeCanvas, QRCodeSVG } from "qrcode.react";
|
||||
import { Copy, Download } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Switch } from "@/app/components/ui/switch";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
||||
|
||||
/** One registration code: QR, link, copy, PNG download and (when onToggle is given) an on/off switch. */
|
||||
export function QrCodeItem({
|
||||
label,
|
||||
eventName,
|
||||
fileLabel,
|
||||
token,
|
||||
enabled,
|
||||
onToggle,
|
||||
}: {
|
||||
label: string;
|
||||
eventName: string;
|
||||
/** Member name for the download file name; omit for the event code. */
|
||||
fileLabel?: string;
|
||||
token: string;
|
||||
enabled: boolean;
|
||||
onToggle?: (enabled: boolean) => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const canvas = useRef<HTMLCanvasElement>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const link = `${window.location.origin}/r/${token}`;
|
||||
|
||||
async function copy() {
|
||||
await navigator.clipboard.writeText(link);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
|
||||
function download() {
|
||||
if (!canvas.current) return;
|
||||
const a = document.createElement("a");
|
||||
a.href = canvas.current.toDataURL("image/png");
|
||||
a.download = `${slug(eventName)}-${slug(fileLabel || "event")}-qr.png`;
|
||||
a.click();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 rounded-lg border p-4 sm:flex-row sm:items-center">
|
||||
<QRCodeSVG value={link} size={128} className="shrink-0" />
|
||||
<QRCodeCanvas ref={canvas} value={link} size={512} className="hidden" />
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
<p className="break-all text-xs text-muted-foreground">{link}</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={copy}>
|
||||
<Copy aria-hidden="true" className="size-4" />
|
||||
{copied ? t("QrCopied") : t("QrCopy")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={download}>
|
||||
<Download aria-hidden="true" className="size-4" />
|
||||
{t("QrDownload")}
|
||||
</Button>
|
||||
{onToggle && <Switch checked={enabled} onCheckedChange={onToggle} aria-label={t("QrEnabled")} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { Alert, AlertDescription } from "@/app/components/ui/alert";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RegistrationQrCard } from "@/app/components/events/RegistrationQrCard";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { getAdminEvent, saveAdminEvent } from "@/app/lib/services/adminEvents";
|
||||
@@ -18,6 +20,7 @@ function EditEventPageContent() {
|
||||
const { uuid } = useParams<{ uuid: string }>();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const { hasModule } = useAdminAuth();
|
||||
const [event, setEvent] = useState<AdminEvent | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [notFound, setNotFound] = useState(false);
|
||||
@@ -114,6 +117,9 @@ function EditEventPageContent() {
|
||||
)}
|
||||
|
||||
<EventForm initial={event} onSubmit={handleSubmit} submitLabel={t("Save")} />
|
||||
|
||||
{/* ponytail: no read-only role for events yet; the events module is the write gate for the code switches. */}
|
||||
<RegistrationQrCard eventUuid={event.uuid} eventName={event.name} canWrite={hasModule("BO_EVENTS")} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -463,4 +463,41 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
PwdRule_SYMBOLIC_LENGTH_MAX: "Maximum symbols",
|
||||
PwdRule_NO_OTHER_LANGUAGE: "Latin characters only",
|
||||
PwdRule_SPACE_NOT_ALLOWED: "No spaces",
|
||||
// QR self-registration (public page, QR cards, privacy notice)
|
||||
RegInactive: "This code is no longer active.",
|
||||
RegLoadFailed: "Could not load this page. Try again later.",
|
||||
RegName: "Your name",
|
||||
RegMobile: "Mobile number",
|
||||
RegEmail: "Email",
|
||||
RegCompany: "Company",
|
||||
RegJobTitle: "Job title",
|
||||
RegInterests: "Interests (optional)",
|
||||
RegNoticeEn: "English",
|
||||
RegNoticeMs: "Bahasa Malaysia",
|
||||
RegConsentEn: "I agree to {company} using my details as described above.",
|
||||
RegConsentMs: "Saya bersetuju {company} menggunakan butiran saya seperti yang diterangkan di atas.",
|
||||
RegSubmit: "Register",
|
||||
RegAnother: "Register another person",
|
||||
RegThanks: "Thank you, you're registered for {event}",
|
||||
RegNameRequired: "Enter your name.",
|
||||
RegContactRequired: "Enter a mobile number or an email.",
|
||||
RegTooMany: "Too many registrations from this device. Try again later.",
|
||||
RegFailed: "Could not register. Try again.",
|
||||
QrCardTitle: "Registration QR",
|
||||
QrEventCode: "Event code",
|
||||
QrCopy: "Copy link",
|
||||
QrCopied: "Link copied",
|
||||
QrDownload: "Download PNG",
|
||||
QrEnabled: "Enabled",
|
||||
QrNote: "Paste the link into the dynamic-qr console to get a QR that can be changed later.",
|
||||
QrLoadFailed: "Could not load registration codes.",
|
||||
QrSaveFailed: "Could not change the code.",
|
||||
QrMyTitle: "My QR codes",
|
||||
QrSwitchedOff: "Switched off",
|
||||
QrMyNone: "You have no registration codes yet.",
|
||||
PrivNotice: "Privacy notice",
|
||||
PrivSave: "Save notice",
|
||||
PrivSaveFailed: "Could not save the notice.",
|
||||
PrivLoadFailed: "Could not load the notice.",
|
||||
PrivLastChanged: "Last changed by {user} on {date}",
|
||||
};
|
||||
@@ -8,8 +8,9 @@
|
||||
// resetPasswordRequired); it is reached right after login, so it stays public.
|
||||
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forgot-password"]);
|
||||
|
||||
// /r/<token> is the QR self-registration page: visitors are not signed in. (A prefix, so PUBLIC_PATHS stays exact.)
|
||||
export function isPublicPath(pathname: string): boolean {
|
||||
return PUBLIC_PATHS.has(pathname);
|
||||
return PUBLIC_PATHS.has(pathname) || /^\/r\/[^/]+$/.test(pathname);
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
@@ -24,7 +25,7 @@ export function guardDecision(pathname: string, session: SessionState | null): s
|
||||
return isPublicPath(pathname) ? null : "/login";
|
||||
}
|
||||
// A pending reset confines the session to the set-password form (/login stays reachable).
|
||||
if (session?.resetRequired && pathname !== "/reset-password" && pathname !== "/login") {
|
||||
if (session?.resetRequired && !/^\/r\/[^/]+$/.test(pathname) && pathname !== "/reset-password" && pathname !== "/login") {
|
||||
return "/reset-password";
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { ApiError, apiGet, apiPut } from "@/app/lib/clientApi";
|
||||
|
||||
export interface RegistrationLink {
|
||||
token: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
export interface EventLinks {
|
||||
event: RegistrationLink;
|
||||
members: (RegistrationLink & { userId: number; name: string; username: string })[];
|
||||
}
|
||||
export interface MyLink extends RegistrationLink {
|
||||
eventUuid: string;
|
||||
eventName: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
location: string;
|
||||
}
|
||||
export interface PrivacyNotice {
|
||||
id: number;
|
||||
companyId: number;
|
||||
textEn: string;
|
||||
textMs: string;
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export const getEventLinks = (uuid: string) => apiGet<EventLinks>(`/api/events/${encodeURIComponent(uuid)}/registration-links`);
|
||||
export const setLinkEnabled = (uuid: string, token: string, enabled: boolean) =>
|
||||
apiPut(`/api/events/${encodeURIComponent(uuid)}/registration-links/${encodeURIComponent(token)}`, { enabled });
|
||||
export const getMyLinks = () => apiGet<MyLink[]>("/api/my-registration-links");
|
||||
|
||||
export async function getPrivacyNotice(companyId: number): Promise<PrivacyNotice | null> {
|
||||
try {
|
||||
return await apiGet<PrivacyNotice>(`/api/companies/${companyId}/privacy-notice`);
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 404) return null; // no notice published yet
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
export const savePrivacyNotice = (companyId: number, body: { textEn: string; textMs: string }) =>
|
||||
apiPut<PrivacyNotice>(`/api/companies/${companyId}/privacy-notice`, body);
|
||||
@@ -0,0 +1,32 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { getRegistration, submitRegistration } from "./publicRegistration";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const body = { name: "A", mobile: "", email: "a@b.co", companyName: "", jobTitle: "", interestIds: [], consent: true, website: "" };
|
||||
|
||||
describe("publicRegistration service", () => {
|
||||
const originalLocation = window.location;
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, "location", { value: { ...window.location, assign: vi.fn() }, writable: true, configurable: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
Object.defineProperty(window, "location", { value: originalLocation, writable: true, configurable: true });
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("never sends a visitor to the admin login on a 401", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockImplementation(async () => new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 })));
|
||||
await expect(getRegistration("t")).rejects.toMatchObject({ status: 401 });
|
||||
await expect(submitRegistration("t", body)).rejects.toBeInstanceOf(ApiError);
|
||||
expect(window.location.assign).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("posts JSON and returns the parsed body", async () => {
|
||||
const f = vi.fn().mockResolvedValue(new Response(JSON.stringify({ eventName: "Expo" }), { status: 200 }));
|
||||
vi.stubGlobal("fetch", f);
|
||||
expect(await submitRegistration("a/b", body)).toEqual({ eventName: "Expo" });
|
||||
expect(f.mock.calls[0][0]).toBe("/api/public/registration/a%2Fb");
|
||||
expect(f.mock.calls[0][1].method).toBe("POST");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
export interface RegistrationInfo {
|
||||
eventName: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
location: string;
|
||||
companyName: string;
|
||||
notice: { id: number; textEn: string; textMs: string };
|
||||
interests: { id: number; name: string }[];
|
||||
}
|
||||
|
||||
export interface RegistrationBody {
|
||||
name: string;
|
||||
mobile: string;
|
||||
email: string;
|
||||
companyName: string;
|
||||
jobTitle: string;
|
||||
interestIds: number[];
|
||||
consent: boolean;
|
||||
website: string;
|
||||
}
|
||||
|
||||
const url = (token: string) => `/api/public/registration/${encodeURIComponent(token)}`;
|
||||
|
||||
// Plain fetch on purpose: clientApi redirects a 401 to the admin /login, which a visitor must never see.
|
||||
async function call<T>(token: string, init?: RequestInit): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url(token), { ...init, headers: init?.body ? { "Content-Type": "application/json" } : {} });
|
||||
} catch {
|
||||
throw new ApiError("Request failed", 0);
|
||||
}
|
||||
const text = await res.text();
|
||||
let data: unknown;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : undefined;
|
||||
} catch {
|
||||
data = undefined;
|
||||
}
|
||||
if (!res.ok) throw new ApiError(`Request failed (${res.status})`, res.status, data);
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export const getRegistration = (token: string) => call<RegistrationInfo>(token);
|
||||
export const submitRegistration = (token: string, body: RegistrationBody) =>
|
||||
call<{ eventName: string }>(token, { method: "POST", body: JSON.stringify(body) });
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getMyLinks: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminRegistration", () => mocks);
|
||||
vi.mock("qrcode.react", () => ({
|
||||
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
|
||||
QRCodeCanvas: () => <canvas />,
|
||||
}));
|
||||
|
||||
import MyQrPage from "./page";
|
||||
|
||||
beforeEach(() => mocks.getMyLinks.mockReset());
|
||||
|
||||
describe("My QR codes", () => {
|
||||
it("lists the caller's codes with event, dates, location and QR", async () => {
|
||||
mocks.getMyLinks.mockResolvedValue([
|
||||
{ eventUuid: "u1", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", token: "t1", enabled: true },
|
||||
]);
|
||||
render(<MyQrPage />);
|
||||
await screen.findByText("Expo 2026");
|
||||
expect(screen.getByText(/KLCC/)).toBeTruthy();
|
||||
expect(screen.getByText(/2026-12-01/)).toBeTruthy();
|
||||
expect(screen.getByTestId("qr-svg").getAttribute("data-value")).toBe(`${window.location.origin}/r/t1`);
|
||||
expect(screen.getByRole("button", { name: "Copy link" })).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Download PNG" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("marks a switched-off code", async () => {
|
||||
mocks.getMyLinks.mockResolvedValue([
|
||||
{ eventUuid: "u1", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", token: "t1", enabled: false },
|
||||
]);
|
||||
render(<MyQrPage />);
|
||||
await screen.findByText("Switched off");
|
||||
});
|
||||
|
||||
it("shows an empty state", async () => {
|
||||
mocks.getMyLinks.mockResolvedValue([]);
|
||||
render(<MyQrPage />);
|
||||
await screen.findByText("You have no registration codes yet.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { QrCodeItem } from "@/app/components/registration/QrCodeItem";
|
||||
import { getMyLinks, type MyLink } from "@/app/lib/services/adminRegistration";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
// Any signed-in staff user; deliberately not in ROUTE_MODULES. Read-only: no on/off switch.
|
||||
export default function MyQrPage() {
|
||||
const t = useT();
|
||||
const [links, setLinks] = useState<MyLink[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
getMyLinks().then(setLinks).catch(() => setError(t("QrLoadFailed")));
|
||||
}, [t]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("QrMyTitle")} />
|
||||
{error && <ErrorState message={error} />}
|
||||
{links?.length === 0 && <EmptyState title={t("QrMyNone")} />}
|
||||
<div className="space-y-3">
|
||||
{links?.map((l) => (
|
||||
<div key={l.token} className="space-y-1">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{l.startDate} - {l.endDate} | {l.location}
|
||||
</p>
|
||||
{!l.enabled && <Badge variant="warning">{t("QrSwitchedOff")}</Badge>}
|
||||
<QrCodeItem label={l.eventName} eventName={l.eventName} token={l.token} enabled={l.enabled} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getRegistration: vi.fn(), submitRegistration: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/publicRegistration", () => mocks);
|
||||
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "tok1" }) }));
|
||||
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import RegisterPage from "./page";
|
||||
|
||||
const info = {
|
||||
eventName: "Expo 2026",
|
||||
startDate: "2026-12-01",
|
||||
endDate: "2026-12-02",
|
||||
location: "KLCC",
|
||||
companyName: "INS",
|
||||
notice: { id: 7, textEn: "We keep your data safe.", textMs: "Data anda selamat." },
|
||||
interests: [{ id: 1, name: "Skincare" }, { id: 2, name: "Wellness" }],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getRegistration.mockReset().mockResolvedValue(info);
|
||||
mocks.submitRegistration.mockReset().mockResolvedValue({ eventName: "Expo 2026" });
|
||||
});
|
||||
|
||||
async function ready() {
|
||||
render(<RegisterPage />);
|
||||
await screen.findByLabelText("Your name");
|
||||
}
|
||||
|
||||
describe("/r/[token] public page", () => {
|
||||
it("shows a loading state, then the event, notice in both languages and the form", async () => {
|
||||
render(<RegisterPage />);
|
||||
expect(screen.getByRole("status")).toBeTruthy();
|
||||
await screen.findByText("Expo 2026");
|
||||
expect(screen.getByText("We keep your data safe.")).toBeTruthy();
|
||||
expect(screen.getByText("Data anda selamat.")).toBeTruthy();
|
||||
expect(screen.getByLabelText("Skincare")).toBeTruthy();
|
||||
expect(mocks.getRegistration).toHaveBeenCalledWith("tok1");
|
||||
});
|
||||
|
||||
it("shows the consent tick box text in English and Bahasa Malaysia with the company name", async () => {
|
||||
await ready();
|
||||
const box = screen.getByRole("checkbox", { name: /I agree to INS using my details as described above\./ });
|
||||
expect(box).toBeTruthy();
|
||||
expect(screen.getByText("Saya bersetuju INS menggunakan butiran saya seperti yang diterangkan di atas.")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows only the inactive message, no event details, when the code is off", async () => {
|
||||
mocks.getRegistration.mockRejectedValue(new ApiError("x", 404, { code: "CODE_INACTIVE" }));
|
||||
render(<RegisterPage />);
|
||||
await screen.findByText("This code is no longer active.");
|
||||
expect(screen.queryByText("Expo 2026")).toBeNull();
|
||||
expect(screen.queryByLabelText("Your name")).toBeNull();
|
||||
});
|
||||
|
||||
it("hides the honeypot from people and assistive tech", async () => {
|
||||
await ready();
|
||||
const hp = document.querySelector('input[name="website"]') as HTMLInputElement;
|
||||
expect(hp).toBeTruthy();
|
||||
expect(hp.tabIndex).toBe(-1);
|
||||
expect(hp.getAttribute("autocomplete")).toBe("off");
|
||||
expect(hp.closest("[aria-hidden='true']")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("submits the form, then shows thank-you and lets another person register", async () => {
|
||||
const user = userEvent.setup();
|
||||
await ready();
|
||||
await user.type(screen.getByLabelText("Your name"), "Aini");
|
||||
await user.type(screen.getByLabelText("Mobile number"), "0123456789");
|
||||
await user.type(screen.getByLabelText("Company"), "Acme");
|
||||
await user.type(screen.getByLabelText("Job title"), "Buyer");
|
||||
await user.click(screen.getByLabelText("Wellness"));
|
||||
await user.click(screen.getByLabelText(/I agree to INS using my details as described above\./));
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
await screen.findByText("Thank you, you're registered for Expo 2026");
|
||||
expect(mocks.submitRegistration).toHaveBeenCalledWith("tok1", {
|
||||
name: "Aini", mobile: "0123456789", email: "", companyName: "Acme", jobTitle: "Buyer",
|
||||
interestIds: [2], consent: true, website: "",
|
||||
});
|
||||
await user.click(screen.getByRole("button", { name: "Register another person" }));
|
||||
const name = (await screen.findByLabelText("Your name")) as HTMLInputElement;
|
||||
expect(name.value).toBe("");
|
||||
expect((screen.getByLabelText(/I agree to INS using my details as described above\./) as HTMLElement).getAttribute("aria-checked")).toBe("false");
|
||||
expect((screen.getByLabelText("Wellness") as HTMLElement).getAttribute("aria-checked")).toBe("false");
|
||||
expect((document.querySelector('input[name="website"]') as HTMLInputElement).value).toBe("");
|
||||
});
|
||||
|
||||
it("clears a filled honeypot too when registering another person", async () => {
|
||||
const user = userEvent.setup();
|
||||
await ready();
|
||||
await user.type(document.querySelector('input[name="website"]') as HTMLInputElement, "spam");
|
||||
await user.type(screen.getByLabelText("Your name"), "Aini");
|
||||
await user.type(screen.getByLabelText("Email"), "a@b.co");
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
await user.click(await screen.findByRole("button", { name: "Register another person" }));
|
||||
await screen.findByLabelText("Your name");
|
||||
expect((document.querySelector('input[name="website"]') as HTMLInputElement).value).toBe("");
|
||||
});
|
||||
|
||||
it("asks for a name and a mobile or email before calling the API", async () => {
|
||||
const user = userEvent.setup();
|
||||
await ready();
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
expect(screen.getByText("Enter your name.")).toBeTruthy();
|
||||
expect(screen.getByText("Enter a mobile number or an email.")).toBeTruthy();
|
||||
expect(mocks.submitRegistration).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a server field error under the field", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.submitRegistration.mockRejectedValue(
|
||||
new ApiError("x", 400, { code: "VALIDATION", details: { field: "consent", code: "CONSENT_REQUIRED" }, error: "Consent is required." }),
|
||||
);
|
||||
await ready();
|
||||
await user.type(screen.getByLabelText("Your name"), "Aini");
|
||||
await user.type(screen.getByLabelText("Email"), "a@b.co");
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
const msg = await screen.findByText("Consent is required.");
|
||||
const box = screen.getByLabelText(/I agree to INS using my details as described above\./);
|
||||
expect(box.getAttribute("aria-describedby")).toBe(msg.id);
|
||||
expect(box.getAttribute("aria-invalid")).toBe("true");
|
||||
});
|
||||
|
||||
it("shows the form-level error for a field the page does not render", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.submitRegistration.mockRejectedValue(
|
||||
new ApiError("x", 400, { code: "VALIDATION", details: { field: "interestIds" }, error: "Unknown interest." }),
|
||||
);
|
||||
await ready();
|
||||
await user.type(screen.getByLabelText("Your name"), "Aini");
|
||||
await user.type(screen.getByLabelText("Email"), "a@b.co");
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
expect((await screen.findByRole("alert")).textContent).toBe("Unknown interest.");
|
||||
});
|
||||
|
||||
it("shows a generic error, not the server text, for a 401", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.submitRegistration.mockRejectedValue(new ApiError("Unauthorized", 401, { error: "Unauthorized" }));
|
||||
await ready();
|
||||
await user.type(screen.getByLabelText("Your name"), "Aini");
|
||||
await user.type(screen.getByLabelText("Email"), "a@b.co");
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
expect((await screen.findByRole("alert")).textContent).toBe("Could not register. Try again.");
|
||||
});
|
||||
|
||||
it("gives inputs, buttons and checkbox rows large tap targets", async () => {
|
||||
await ready();
|
||||
expect(screen.getByLabelText("Your name").className).toContain("h-11");
|
||||
expect(screen.getByRole("button", { name: "Register" }).className).toContain("h-11");
|
||||
for (const l of ["Wellness", /I agree to INS using my details/]) {
|
||||
const label = document.querySelector(`label[for="${screen.getByLabelText(l).id}"]`)!;
|
||||
expect(label.className).toContain("w-full");
|
||||
expect(label.className).toContain("min-h-11");
|
||||
}
|
||||
});
|
||||
|
||||
it("shows too-many and inactive messages from submit", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.submitRegistration.mockRejectedValueOnce(new ApiError("x", 429, { code: "TOO_MANY" }));
|
||||
await ready();
|
||||
await user.type(screen.getByLabelText("Your name"), "Aini");
|
||||
await user.type(screen.getByLabelText("Email"), "a@b.co");
|
||||
await user.click(screen.getByLabelText(/I agree to INS using my details as described above\./));
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
await screen.findByText("Too many registrations from this device. Try again later.");
|
||||
mocks.submitRegistration.mockRejectedValueOnce(new ApiError("x", 404, { code: "CODE_INACTIVE" }));
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
await waitFor(() => expect(screen.getByText("This code is no longer active.")).toBeTruthy());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Checkbox } from "@/app/components/ui/checkbox";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { getRegistration, submitRegistration, type RegistrationInfo } from "@/app/lib/services/publicRegistration";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const EMPTY = { name: "", mobile: "", email: "", companyName: "", jobTitle: "", interestIds: [] as number[], consent: false, website: "" };
|
||||
// Fields the form renders; a server error for any other field goes to the form-level alert.
|
||||
const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"];
|
||||
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
|
||||
const BOX = "size-6";
|
||||
type Phase = "loading" | "inactive" | "form" | "done";
|
||||
|
||||
function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
|
||||
if (!(err instanceof ApiError)) return {};
|
||||
const d = (err.data ?? {}) as { code?: string; error?: string; details?: { field?: string } };
|
||||
return { status: err.status, code: d.code, error: d.error, field: d.details?.field };
|
||||
}
|
||||
|
||||
// Public, signed-out, mobile-first page (no admin shell: AppShell skips it via isPublicPath).
|
||||
export default function RegisterPage() {
|
||||
const t = useT();
|
||||
const { token } = useParams<{ token: string }>();
|
||||
const [phase, setPhase] = useState<Phase>("loading");
|
||||
const [info, setInfo] = useState<RegistrationInfo | null>(null);
|
||||
const [form, setForm] = useState(EMPTY);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
getRegistration(token)
|
||||
.then((i) => {
|
||||
setInfo(i);
|
||||
setPhase("form");
|
||||
})
|
||||
.catch((err) => {
|
||||
if (apiData(err).code === "CODE_INACTIVE") setPhase("inactive");
|
||||
else {
|
||||
setFormError(apiData(err).code === "TOO_MANY" ? t("RegTooMany") : t("RegLoadFailed"));
|
||||
setPhase("form");
|
||||
}
|
||||
});
|
||||
}, [token, t]);
|
||||
|
||||
const set = (patch: Partial<typeof EMPTY>) => setForm((f) => ({ ...f, ...patch }));
|
||||
|
||||
async function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
const errs: Record<string, string> = {};
|
||||
if (!form.name.trim()) errs.name = t("RegNameRequired");
|
||||
if (!form.mobile.trim() && !form.email.trim()) errs.mobile = t("RegContactRequired");
|
||||
setErrors(errs);
|
||||
setFormError(null);
|
||||
if (Object.keys(errs).length) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await submitRegistration(token, {
|
||||
...form,
|
||||
name: form.name.trim(),
|
||||
mobile: form.mobile.trim(),
|
||||
email: form.email.trim(),
|
||||
companyName: form.companyName.trim(),
|
||||
jobTitle: form.jobTitle.trim(),
|
||||
});
|
||||
setPhase("done");
|
||||
} catch (err) {
|
||||
const { status, code, error, field } = apiData(err);
|
||||
if (code === "CODE_INACTIVE") setPhase("inactive");
|
||||
else if (code === "TOO_MANY") setFormError(t("RegTooMany"));
|
||||
else if (status === 400 && error && field && FIELDS.includes(field)) setErrors({ [field]: error });
|
||||
else setFormError(status === 400 && error ? error : t("RegFailed"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const field = (id: keyof typeof EMPTY, label: string, type = "text") => (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`reg-${id}`}>{label}</Label>
|
||||
<Input id={`reg-${id}`} className="h-11" type={type} value={String(form[id])} onChange={(e) => set({ [id]: e.target.value })} disabled={saving} aria-invalid={!!errors[id]} aria-describedby={errors[id] ? `reg-${id}-error` : undefined} />
|
||||
{errors[id] && <p id={`reg-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>}
|
||||
</div>
|
||||
);
|
||||
|
||||
let body;
|
||||
if (phase === "loading") body = <p role="status">{t("UiLoading")}</p>;
|
||||
else if (phase === "inactive") body = <p role="alert">{t("RegInactive")}</p>;
|
||||
else if (phase === "done") {
|
||||
body = (
|
||||
<div className="space-y-4">
|
||||
<p role="status" className="text-lg font-medium">{t("RegThanks", { event: info?.eventName ?? "" })}</p>
|
||||
<Button
|
||||
className="h-11"
|
||||
onClick={() => {
|
||||
setForm(EMPTY);
|
||||
setErrors({});
|
||||
setPhase("form");
|
||||
}}
|
||||
>
|
||||
{t("RegAnother")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
body = (
|
||||
<form onSubmit={submit} className="space-y-4" noValidate>
|
||||
{info && (
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">{info.eventName}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{info.companyName} | {info.startDate} - {info.endDate} | {info.location}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
|
||||
{info && (
|
||||
<>
|
||||
{field("name", t("RegName"))}
|
||||
{field("mobile", t("RegMobile"), "tel")}
|
||||
{field("email", t("RegEmail"), "email")}
|
||||
{field("companyName", t("RegCompany"))}
|
||||
{field("jobTitle", t("RegJobTitle"))}
|
||||
{info.interests.length > 0 && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
|
||||
{info.interests.map((i) => (
|
||||
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
|
||||
<Checkbox
|
||||
className={BOX}
|
||||
id={`reg-interest-${i.id}`}
|
||||
checked={form.interestIds.includes(i.id)}
|
||||
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
|
||||
/>
|
||||
{i.name}
|
||||
</Label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
<div className="space-y-2 rounded-md border p-3 text-sm">
|
||||
<h2 className="font-medium">{t("RegNoticeEn")}</h2>
|
||||
<p className="whitespace-pre-line">{info.notice.textEn}</p>
|
||||
<h2 className="font-medium">{t("RegNoticeMs")}</h2>
|
||||
<p className="whitespace-pre-line">{info.notice.textMs}</p>
|
||||
</div>
|
||||
<Label htmlFor="reg-consent" className={ROW}>
|
||||
<Checkbox id="reg-consent" className={BOX} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
|
||||
<span>
|
||||
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
|
||||
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
|
||||
</span>
|
||||
</Label>
|
||||
{errors.consent && <p id="reg-consent-error" className="text-sm text-destructive">{errors.consent}</p>}
|
||||
{/* Honeypot: people never see or reach it; bots fill it and the server drops the submission. */}
|
||||
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
|
||||
<input name="website" tabIndex={-1} autoComplete="off" value={form.website} onChange={(e) => set({ website: e.target.value })} />
|
||||
</div>
|
||||
<Button type="submit" className="h-11 w-full" disabled={saving}>{t("RegSubmit")}</Button>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
return <main className="mx-auto w-full max-w-md px-4 py-6">{body}</main>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { guardDecision } from "./app/lib/routeGuard";
|
||||
import { middleware } from "./middleware";
|
||||
|
||||
// add-qr-self-registration: the QR landing page and its proxy are reachable signed out; admin paths still are not.
|
||||
const get = (path: string) => middleware(new NextRequest(new URL(path, "https://portal.test")));
|
||||
|
||||
describe("middleware: public registration paths", () => {
|
||||
it("lets a signed-out visitor open /r/<token>", async () => {
|
||||
const res = await get("/r/abc123");
|
||||
expect(res.headers.get("x-middleware-next")).toBe("1");
|
||||
expect(res.headers.get("location")).toBeNull();
|
||||
});
|
||||
|
||||
it("lets a signed-out visitor reach the public registration proxy", async () => {
|
||||
const res = await get("/api/public/registration/abc123");
|
||||
expect(res.headers.get("x-middleware-next")).toBe("1");
|
||||
});
|
||||
|
||||
it("still redirects a signed-out visitor from admin paths", async () => {
|
||||
for (const path of ["/events", "/my-qr", "/r", "/r/"]) {
|
||||
const res = await get(path);
|
||||
expect(res.headers.get("location"), path).toContain("/login");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("routeGuard: /r/<token> with a pending password reset", () => {
|
||||
it("stays reachable; admin paths still go to /reset-password", () => {
|
||||
const s = { present: true, resetRequired: true };
|
||||
expect(guardDecision("/r/abc123", s)).toBeNull();
|
||||
expect(guardDecision("/events", s)).toBe("/reset-password");
|
||||
expect(guardDecision("/r", s)).toBe("/reset-password");
|
||||
});
|
||||
});
|
||||
Generated
+10
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<Map.Entry<HttpMethod, Pattern>> 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<HttpMethod, Pattern> 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
|
||||
|
||||
+95
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
@@ -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";
|
||||
}
|
||||
+2
@@ -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}";
|
||||
@@ -99,6 +100,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}";
|
||||
|
||||
+16
-1
@@ -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<Map<String, Object>> privacyNotice(@PathVariable Long id) {
|
||||
requireSuper();
|
||||
return ResponseEntity.ok(companies.privacyNotice(id));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PutMapping("/{id}/privacy-notice")
|
||||
public ResponseEntity<Map<String, Object>> savePrivacyNotice(@PathVariable Long id, @RequestBody Map<String, Object> 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<Map<String, String>> 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;
|
||||
}
|
||||
}
|
||||
+49
@@ -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<Map<String, Object>> 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<Map<String, Object>> 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<List<Map<String, Object>>> mine() {
|
||||
return ResponseEntity.ok(links.mine());
|
||||
}
|
||||
}
|
||||
+35
@@ -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<Map<String, Object>> page(@PathVariable String token) {
|
||||
return ResponseEntity.ok(registration.page(token));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/{token}")
|
||||
public ResponseEntity<Map<String, Object>> register(@PathVariable String token, @RequestBody PublicRegistrationRequest request) {
|
||||
return ResponseEntity.ok(registration.register(token, request));
|
||||
}
|
||||
}
|
||||
+8
@@ -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<Long> interestIds, Boolean consent, String website) {
|
||||
}
|
||||
+12
@@ -46,6 +46,18 @@ public class AdminCompanyService {
|
||||
Map.of("code", code)).getBody());
|
||||
}
|
||||
|
||||
public Map<String, Object> privacyNotice(Long id) {
|
||||
return call(() -> restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE).replace("{id}", String.valueOf(id)), MAP).getBody());
|
||||
}
|
||||
|
||||
public Map<String, Object> savePrivacyNotice(Long id, Map<String, Object> notice, String doneBy) {
|
||||
Map<String, Object> 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> T call(Supplier<T> call) {
|
||||
try {
|
||||
return call.get();
|
||||
|
||||
+7
-7
@@ -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<Long> checkedInterests(Map<Long, Map<String, Object>> known, List<Long> requested, List<Long> current) {
|
||||
static List<Long> checkedInterests(Map<Long, Map<String, Object>> known, List<Long> requested, List<Long> current) {
|
||||
List<Long> ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList()));
|
||||
for (Long id : ids) {
|
||||
Map<String, Object> 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<Long, Map<String, Object>> interests(Long companyId) {
|
||||
Map<Long, Map<String, Object>> interests(Long companyId) {
|
||||
List<Map<String, Object>> 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<Long, Map<String, Object>> out = new LinkedHashMap<>();
|
||||
@@ -376,18 +376,18 @@ public class AdminEventLeadService {
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<Long> teamIds(long eventUuid) {
|
||||
List<Long> teamIds(long eventUuid) {
|
||||
List<Map<String, Object>> 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<String, Object> user(Long id) {
|
||||
Map<String, Object> 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<String, Object> user, Long companyId) {
|
||||
static boolean isActiveAdminOf(Map<String, Object> user, Long companyId) {
|
||||
return isActiveAdmin(user) && user.get("companyId") instanceof Number n && companyId != null && n.longValue() == companyId;
|
||||
}
|
||||
|
||||
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
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 org.springframework.web.client.RestClientException;
|
||||
|
||||
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<CompanyEvent> EVENT = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Boolean> BOOL = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final AdminEventLeadService leads;
|
||||
private final RedisTemplate<String, Object> redis;
|
||||
private final Clock clock;
|
||||
|
||||
@Autowired
|
||||
public PublicRegistrationService(RestTemplateCustomUtil rest, AdminEventLeadService leads, RedisTemplate<String, Object> redis) {
|
||||
this(rest, leads, redis, Clock.systemUTC());
|
||||
}
|
||||
|
||||
PublicRegistrationService(RestTemplateCustomUtil rest, AdminEventLeadService leads, RedisTemplate<String, Object> 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<String, Object> link, CompanyEvent event, String companyName, Map<String, Object> notice) {}
|
||||
|
||||
public Map<String, Object> page(String token) {
|
||||
limit("reg:load:" + ip(), LOAD_LIMIT);
|
||||
Open o = open(token);
|
||||
CompanyEvent e = o.event();
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> 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<String> 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<Long> 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<String, Object> 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<String, Object> link, CompanyEvent e) {
|
||||
if (!(link.get("salespersonUserId") instanceof Number n)) return null;
|
||||
long id = n.longValue();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/** The gateway lets only this token shape through unsigned; anything else would come back 401 and surface as a 500. */
|
||||
private static final java.util.regex.Pattern TOKEN_SHAPE = java.util.regex.Pattern.compile("[A-Za-z0-9_-]{22}");
|
||||
|
||||
private Open open(String token) {
|
||||
if (token == null || !TOKEN_SHAPE.matcher(token).matches()) throw inactive();
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> 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> T found(Supplier<T> 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);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
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<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> 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<String, Object> links(String eventUuid) {
|
||||
CompanyEvent event = leads.loadEvent(eventUuid, null);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", event.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("salespersonUserIds", leads.teamIds(event.getUuid()));
|
||||
List<Map<String, Object>> rows = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_ENSURE), MAP_LIST, body).getBody();
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
List<Map<String, Object>> members = new ArrayList<>();
|
||||
out.put("members", members);
|
||||
for (Map<String, Object> row : rows == null ? List.<Map<String, Object>>of() : rows) {
|
||||
if (!(row.get("salespersonUserId") instanceof Number id)) {
|
||||
out.put("event", Map.of("token", row.get("token"), "enabled", row.get("enabled")));
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> u = leads.user(id.longValue());
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("userId", id.longValue());
|
||||
m.put("name", u == null ? String.valueOf(id) : String.valueOf(u.get("name")));
|
||||
m.put("username", u == null || u.get("username") == null ? "" : String.valueOf(u.get("username")));
|
||||
m.put("token", row.get("token"));
|
||||
m.put("enabled", row.get("enabled"));
|
||||
members.add(m);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> 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<String, Object> 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<Map<String, Object>> mine() {
|
||||
User caller = leads.caller();
|
||||
if (caller.getCompanyId() == null) return List.of();
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("userId", caller.getId());
|
||||
body.put("today", LocalDate.now(clock.withZone(PublicRegistrationService.MALAYSIA)).toString());
|
||||
List<Map<String, Object>> 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);
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -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);
|
||||
|
||||
@@ -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 "";
|
||||
}
|
||||
+121
@@ -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<HttpReqRespUtils> 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<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq("/company/5/privacyNotice"), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) 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));
|
||||
}
|
||||
}
|
||||
+66
@@ -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"));
|
||||
}
|
||||
}
|
||||
+57
@@ -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<PublicRegistrationRequest> 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);
|
||||
}
|
||||
}
|
||||
+121
@@ -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 = "abcDEF123_-abcDEF123_-";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private PublicRegistrationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
RedisTemplate<String, Object> redis = mock(RedisTemplate.class);
|
||||
ValueOperations<String, Object> 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<String, Object> 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<Object> 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<String, Object>) 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();
|
||||
}
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
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.verifyNoInteractions;
|
||||
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/{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;
|
||||
private static final long COMPANY = 5L;
|
||||
private static final String TOKEN = "abcDEF123_-abcDEF123_-";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private RedisTemplate<String, Object> redis;
|
||||
private ValueOperations<String, Object> ops;
|
||||
private MockedStatic<HttpReqRespUtils> 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<String, Object> 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) {
|
||||
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<Long> 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_tokenShapeTheGatewayRefuses_inactive_withoutBackendCall() {
|
||||
for (String bad : List.of("x", "short-link", TOKEN.substring(1), TOKEN + "A", TOKEN.substring(1) + "!")) {
|
||||
assertInactive(() -> service.page(bad));
|
||||
assertInactive(() -> service.register(bad, ok()));
|
||||
}
|
||||
verifyNoInteractions(rest);
|
||||
}
|
||||
|
||||
@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<String, Object> 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<String, Object>) p.get("notice")).containsEntry("id", 9L).containsEntry("textEn", "English notice").containsEntry("textMs", "Notis");
|
||||
assertThat((List<Map<String, Object>>) 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<String, Object> registered() {
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), body.capture());
|
||||
return (Map<String, Object>) 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<String, Object> 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), eq(COMPANY)))
|
||||
.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));
|
||||
}
|
||||
}
|
||||
+29
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
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<HttpReqRespUtils> 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<String, Object> u = new HashMap<>(Map.of("id", id, "name", name, "username", "sales" + id, "type", "A", "companyId", COMPANY, "enabled", true));
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private Map<String, Object> posted(String url) {
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(url), any(ParameterizedTypeReference.class), body.capture());
|
||||
return (Map<String, Object>) body.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void links_ensuresEventAndTeamLinks_andNamesMembers() {
|
||||
Map<String, Object> eventRow = new HashMap<>(Map.of("token", "ev1", "enabled", true));
|
||||
List<Map<String, Object>> 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<String, Object> out = service.links(String.valueOf(EV));
|
||||
|
||||
assertThat((Map<String, Object>) out.get("event")).containsEntry("token", "ev1").containsEntry("enabled", true);
|
||||
assertThat((List<Map<String, Object>>) out.get("members")).containsExactly(
|
||||
Map.of("userId", 21L, "name", "Sales One", "username", "sales21", "token", "t21", "enabled", true),
|
||||
Map.of("userId", 22L, "name", "Sales Two", "username", "sales22", "token", "t22", "enabled", false));
|
||||
assertThat(posted(ENSURE)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserIds", List.of(21L, 22L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void links_memberWithoutUsername_getsEmptyUsername() {
|
||||
Map<String, Object> u = new HashMap<>(Map.of("id", 21L, "name", "Sales One", "type", "A", "companyId", COMPANY, "enabled", true));
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L))).thenReturn(ResponseEntity.ok(u));
|
||||
when(rest.postForEntity(eq(ENSURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(List.of(Map.of("token", "t21", "enabled", true, "salespersonUserId", 21L))));
|
||||
|
||||
List<Map<String, Object>> members = (List<Map<String, Object>>) service.links(String.valueOf(EV)).get("members");
|
||||
|
||||
assertThat(members.get(0)).containsEntry("username", "");
|
||||
}
|
||||
|
||||
@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());
|
||||
}
|
||||
}
|
||||
+110
@@ -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<String, String> 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<HttpReqRespUtils> 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<Object> 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");
|
||||
}
|
||||
}
|
||||
+46
@@ -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<RegistrationLinkService.LinkView> 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<RegistrationLinkService.MineRow> mine(@RequestBody RegistrationLinkService.MineRequest req) {
|
||||
return linkService.mine(req);
|
||||
}
|
||||
|
||||
@PostMapping("/registration/register")
|
||||
public RegistrationService.RegisterResult register(@RequestBody RegistrationService.RegisterRequest req) {
|
||||
return registrationService.register(req);
|
||||
}
|
||||
}
|
||||
+7
@@ -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();
|
||||
|
||||
|
||||
+40
@@ -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;
|
||||
}
|
||||
+1
@@ -12,6 +12,7 @@ import java.util.Optional;
|
||||
@Repository
|
||||
public interface EventRepository extends JpaRepository<Event,Long> , JpaRepositoryCustom<Event>{
|
||||
Optional<Event> findByUuid(long uuid);
|
||||
java.util.List<Event> findByCompanyIdAndUuidIn(Long companyId, java.util.Collection<Long> uuids);
|
||||
Optional<Event> findTop1ByDateStartLessThanEqualAndDateEndGreaterThanEqualAndEnabledOrderByDateStartDesc(LocalDateTime dateStart, LocalDateTime dateEnd, GeneralEnum.FlagYesNo enabled);
|
||||
}
|
||||
|
||||
|
||||
+2
@@ -13,6 +13,8 @@ import java.util.List;
|
||||
public interface EventSalespersonRepository extends JpaRepository<EventSalesperson, Long> {
|
||||
List<EventSalesperson> findByEventUuid(long eventUuid);
|
||||
|
||||
List<EventSalesperson> findByCompanyIdAndUserId(long companyId, long userId);
|
||||
|
||||
@Modifying
|
||||
@Query("delete from EventSalesperson e where e.eventUuid = :eventUuid")
|
||||
void deleteByEventUuid(@Param("eventUuid") long eventUuid);
|
||||
|
||||
+4
@@ -19,6 +19,10 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
|
||||
List<Lead> findMatches(@Param("companyId") long companyId, @Param("mobile") String mobile,
|
||||
@Param("email") String email, Pageable pageable);
|
||||
|
||||
Optional<Lead> findFirstByCompanyIdAndMobileE164OrderByIdDesc(long companyId, String mobileE164);
|
||||
|
||||
Optional<Lead> findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(long companyId, String emailNormalised);
|
||||
|
||||
Optional<Lead> findByUuidAndCompanyId(long uuid, long companyId);
|
||||
|
||||
Optional<Lead> findByUuid(long uuid);
|
||||
|
||||
+17
@@ -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<RegistrationLink, Long> {
|
||||
Optional<RegistrationLink> findByToken(String token);
|
||||
|
||||
Optional<RegistrationLink> findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(long eventUuid, long salespersonUserId);
|
||||
|
||||
List<RegistrationLink> findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(long eventUuid);
|
||||
}
|
||||
+2
-2
@@ -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<Long> saveInterests(long eventLeadId, long companyId, List<Long> requested) {
|
||||
public List<Long> saveInterests(long eventLeadId, long companyId, List<Long> requested) {
|
||||
List<Long> ids = requested == null ? List.of() : requested.stream().filter(Objects::nonNull).distinct().toList();
|
||||
if (!ids.isEmpty()) {
|
||||
eventLeadInterestRepository.saveAll(ids.stream().map(id -> {
|
||||
|
||||
+128
@@ -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<Long> 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<LinkView> ensure(EnsureRequest req) {
|
||||
requireEvent(req.companyId(), req.eventUuid());
|
||||
List<RegistrationLink> 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<MineRow> mine(MineRequest req) {
|
||||
LocalDate today = LocalDate.parse(req.today());
|
||||
List<Long> 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() != null && !e.getDateEnd().toLocalDate().isBefore(today))
|
||||
.sorted(Comparator.comparing(Event::getDateStart, Comparator.nullsLast(Comparator.naturalOrder())))
|
||||
.map(e -> {
|
||||
RegistrationLink l = personal(req.companyId(), e.getUuid(), req.userId());
|
||||
return new MineRow(String.valueOf(e.getUuid()), e.getName(), e.getDateStart() == null ? null : 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<RegistrationLink> 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());
|
||||
}
|
||||
}
|
||||
+123
@@ -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<Long> 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<Lead> 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<EventLead> 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<String> 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<String> parts, String label, String submitted, String current) {
|
||||
if (submitted != null && !submitted.isBlank() && !submitted.equals(current)) parts.add(label + " " + submitted);
|
||||
}
|
||||
}
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
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<RegistrationLinkService.LinkView> 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<RegistrationLink> 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<RegistrationLinkService.LinkView> 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<RegistrationLinkService.LinkView> 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<RegistrationLinkService.LinkView> 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 mineSkipsUndatedEndAndSortsUndatedStartLast() {
|
||||
EventSalesperson r1 = new EventSalesperson(); r1.setEventUuid(1L);
|
||||
EventSalesperson r2 = new EventSalesperson(); r2.setEventUuid(2L);
|
||||
EventSalesperson r3 = new EventSalesperson(); r3.setEventUuid(3L);
|
||||
when(eventSalespersonRepository.findByCompanyIdAndUserId(COMPANY, 7L)).thenReturn(List.of(r1, r2, r3));
|
||||
Event noStart = event(1L, COMPANY, "NoStart", null, LocalDateTime.of(2026, 12, 12, 18, 0), GeneralEnum.FlagYesNo.Y);
|
||||
Event noEnd = event(2L, COMPANY, "NoEnd", LocalDateTime.of(2026, 12, 3, 9, 0), null, GeneralEnum.FlagYesNo.Y);
|
||||
Event dated = event(3L, COMPANY, "Dated", LocalDateTime.of(2026, 12, 5, 9, 0), LocalDateTime.of(2026, 12, 6, 9, 0), GeneralEnum.FlagYesNo.Y);
|
||||
when(eventRepository.findByCompanyIdAndUuidIn(eq(COMPANY), anyCollection())).thenReturn(List.of(noStart, noEnd, dated));
|
||||
when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(anyLong(), eq(7L))).thenReturn(Optional.of(link(7L, "T", true)));
|
||||
|
||||
List<RegistrationLinkService.MineRow> out = service.mine(new RegistrationLinkService.MineRequest(COMPANY, 7L, "2026-12-01"));
|
||||
|
||||
assertThat(out).extracting(RegistrationLinkService.MineRow::eventName).containsExactly("Dated", "NoStart");
|
||||
assertThat(out.get(1).startDate()).isNull();
|
||||
}
|
||||
|
||||
@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<RegistrationLinkService.MineRow> 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());
|
||||
}
|
||||
}
|
||||
+264
@@ -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<EventLead> 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<Lead> 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<EventLeadStatusChange> 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<Iterable<EventLeadInterest>> 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");
|
||||
}
|
||||
}
|
||||
+37
@@ -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<Map<String, String>> badRequest(RuntimeException e) {
|
||||
return ResponseEntity.badRequest().body(Map.of("message", String.valueOf(e.getMessage())));
|
||||
}
|
||||
}
|
||||
+8
@@ -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);
|
||||
|
||||
+29
@@ -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;
|
||||
}
|
||||
+13
@@ -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<CompanyPrivacyNotice, Long> {
|
||||
|
||||
Optional<CompanyPrivacyNotice> findFirstByCompanyIdOrderByIdDesc(Long companyId);
|
||||
}
|
||||
+48
@@ -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;
|
||||
}
|
||||
}
|
||||
+99
@@ -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());
|
||||
}
|
||||
}
|
||||
+69
@@ -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();
|
||||
}
|
||||
}
|
||||
+97
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user