Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbe48c2db9 | ||
|
|
39139ed7b1 | ||
|
|
5e5762cdcb | ||
|
|
41c616b3f6 | ||
|
|
ff4b12c2e9 | ||
|
|
3ab1a0e0e3 | ||
|
|
5583cf5897 | ||
|
|
03b85737d7 | ||
|
|
9438fd8cf1 | ||
|
|
d532bdcda4 | ||
|
|
c6c220265f | ||
|
|
9163557945 | ||
|
|
2d1513aa80 | ||
|
|
adbbdc6185 | ||
|
|
08c45e9109 | ||
|
|
f13dac58a4 | ||
|
|
eff4899c0d | ||
|
|
1a7c542f5e | ||
|
|
5036196031 | ||
|
|
6ebfbfb1ac | ||
|
|
ffda35b785 | ||
|
|
cf8478d00c | ||
|
|
ab1643e36e | ||
|
|
85b40424ce | ||
|
|
9c9469f5e5 | ||
|
|
0345314c89 | ||
|
|
2842ef423f | ||
|
|
6fbbdaa3c5 | ||
|
|
065a8561e3 | ||
|
|
61d17d5e38 | ||
|
|
a8d42a8a25 | ||
|
|
07c3ecb7ad | ||
|
|
ee5fe6d15b | ||
|
|
db7f218a71 | ||
|
|
0a5d5a229b | ||
|
|
5ffd4176ec | ||
|
|
5eead327a6 | ||
|
|
7ff5c77b78 | ||
|
|
a482a3a6d0 | ||
|
|
8d5f3747bf | ||
|
|
8177c08540 | ||
|
|
044b746f0b | ||
|
|
5b63e19550 | ||
|
|
a2a369aa19 | ||
|
|
6a512bea8e | ||
|
|
05ff2e9b74 | ||
|
|
b6b05f12df | ||
|
|
a1aa906a66 |
No files matched your search
@@ -97,6 +97,29 @@ After running `04`, `SELECT LENGTH(password) FROM \`service-system\`.\`user\` WH
|
||||
|
||||
Run the three in order, with a user that may alter tables. File `03` ends every admin session: everyone signs in again, staff with company `ins`. `99-rollback.sql` in the same folder undoes the three. It fails on the username unique key once two companies have a user with the same username; rename one of them first.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/01-status-change.sql` | Creates `service-counter`.`event_lead_status_change` (every event-lead status change with its time and user) and an index on `event_lead` for the dashboard. DDL. |
|
||||
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/02-status-change-backfill.sql` | Gives event leads captured before this release a history: OPEN at capture, and the current status at the last update. These times are approximate. Safe to run twice. |
|
||||
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/03-dashboard-module.sql` | Adds the Dashboard back-office module (`BO_DASHBOARD`). No role gets it; super admins grant it under Roles. |
|
||||
|
||||
Run the three in order before the new images go live: the new services-counter writes to the table from `01` on every capture and status edit, and fails without it. `01` needs a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the status history.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/2026-12-01-add-qr-self-registration/sql/01-registration-link.sql` | Creates `service-counter`.`registration_link` (QR registration codes) and adds `source`, `consent_at` and `consent_notice_id` to `event_lead`. Existing event leads become `STAFF`. DDL. |
|
||||
| `openspec/changes/archive/2026-12-01-add-qr-self-registration/sql/02-company-privacy-notice.sql` | Creates `service-system`.`company_privacy_notice` and gives every existing company the default English and Bahasa Malaysia privacy notice, with the company's name filled in. DDL. |
|
||||
|
||||
Run both before the new images go live: the new services-counter reads the new `event_lead` columns on every lead query and fails without them. Both need a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the codes, the notices and the consent records.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/2026-12-01-uppercase-company-codes/sql/01-uppercase-codes.sql` | Turns every company code and every staff login name to capitals (`ins` becomes `INS`, `sales9@cv` becomes `sales9@CV`). Safe to run twice. |
|
||||
|
||||
Run it when the new services-system and mobile-api go live. Staff who are signed in keep working until their session needs a refresh, then sign in again. Sign-in still ignores case, so staff may keep typing `ins` or `cv`. `99-rollback.sql` in the same folder turns codes and login names back to lowercase.
|
||||
|
||||
**Review the privacy notice before go-live.** The seeded text is a starting template written for the PDPA, not legal advice. INS and CV should each have theirs checked; a super admin changes it under **Companies → Privacy notice**. A company with no notice has no working QR codes.
|
||||
|
||||
**Database user:**
|
||||
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
|
||||
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
|
||||
@@ -228,6 +251,8 @@ Generate each random value separately, for example with `openssl rand -base64 48
|
||||
|
||||
Route `co-lite.containerverse.dev` to the `admin-portal` Service on port 3000, with TLS. Only the admin portal is public: the browser talks to the portal, and the portal talks to `mobile-api` inside the cluster. Do not expose `mobile-api`, `api-gateway` or the services.
|
||||
|
||||
QR registration pages (`/r/<code>`) are served by the admin portal on the same host, so nothing new is routed. mobile-api rate-limits visitors by the address the portal sends: the last entry of `X-Forwarded-For`, which is the one Traefik adds. That works whether Traefik appends to or replaces the header. If another proxy or load balancer sits in front of Traefik, the last entry is that proxy's address and every visitor shares one limit; the portal's `clientIp` would then have to change (or use the PROXY protocol). If the portal sees no `X-Forwarded-For` and no `X-Real-Ip` at all, every visitor shares the portal pod's limit.
|
||||
|
||||
## 9. Secret templates
|
||||
|
||||
There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files.
|
||||
@@ -293,6 +318,10 @@ data:
|
||||
- **No email provider yet.** Staff onboarding does not need one: the admin types each new user's first password, and "Set temporary password" on a user's page unlocks a user who forgot theirs. Both force a password change at the next sign-in. Forgot-password and "Send password reset" still create an email with a temporary password. Nobody receives it, but `service-email` saves every email first, so a super admin (or a role granted Emails) can read it under **Emails** and pass the password on in person. The user must change it at the next sign-in. Grant Emails narrowly: it shows every saved email, including other users' temporary passwords, member email-verification codes, and contact or distributor form submissions with the sender's personal 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,103 @@
|
||||
# Lead Dashboard — Design
|
||||
|
||||
Date: 2026-12-01. Status: draft for approval.
|
||||
|
||||
## Why
|
||||
|
||||
Co-Lite exists to generate leads for INS and CV marketing. Managers need to see which events, salespeople and interests produce leads and which of those leads convert. Today the portal home page is a welcome line, and the system keeps only each event lead's current status, so it cannot say when a lead was won or how long it took.
|
||||
|
||||
## Goals
|
||||
|
||||
- A dashboard on the portal home page showing lead capture and conversion for a chosen period.
|
||||
- Record every event-lead status change with its time, so the dashboard can count wins in a period and time to win.
|
||||
- Gate the dashboard with a new ACL module, `BO_DASHBOARD`, assigned to roles like every other module.
|
||||
- Company scoping as everywhere else: staff see their company, super admins see all or the one picked.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- New lead statuses or a pipeline editor. The existing statuses stay: OPEN, CONTACTED, QUALIFIED, WON, LOST.
|
||||
- Member-app conversion (option 2). It comes later as its own change.
|
||||
- Showing the status timeline on the lead or event-lead screens. The data will exist; a later change can show it.
|
||||
- Excel export of the dashboard.
|
||||
- Demographics (age, gender, state) as in the legacy event statistics: Co-Lite leads carry none of those fields.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
- Numbers that disagree with the Leads and Event Leads listings for the same filter.
|
||||
- SQL built by string replacement (the legacy report service does this; it is an injection risk).
|
||||
- A slow home page: every user lands there after sign-in.
|
||||
|
||||
## Definitions
|
||||
|
||||
- **Capture:** one event lead (a person captured at one event). A person captured at two events is two captures. Conversion is per capture, because the question is which events convert.
|
||||
- **Won:** an event lead whose current status is WON.
|
||||
- **Won in period:** a won event lead whose latest change into WON falls in the period.
|
||||
- **Conversion rate:** of the captures made in the period, the share that are now WON.
|
||||
- **Days to win:** from capture to the latest change into WON, in whole days. Reported as the median.
|
||||
- **Overdue follow-up:** an event lead that is not WON or LOST and whose next follow-up date is before today. This is a current count, not tied to the period.
|
||||
- **Clock:** Asia/Kuala_Lumpur, as in the legacy dashboard.
|
||||
|
||||
## What the dashboard shows
|
||||
|
||||
- **Period:** This month (the default), Last month, or a custom range. A range of up to 62 days is charted by day; a longer one by month (legacy rule).
|
||||
- **Company picker:** the existing picker, for super admins only.
|
||||
- **Tiles:**
|
||||
- Captures.
|
||||
- New leads (lead type NEW).
|
||||
- Won in period.
|
||||
- Conversion rate.
|
||||
- Median days to win.
|
||||
- Overdue follow-ups.
|
||||
- **Funnel:** the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST).
|
||||
- **Trend chart:** captures and wins per day or month.
|
||||
- **By event:** each event with captures in the period.
|
||||
- Columns: event, captures, new, won, conversion rate.
|
||||
- A super admin viewing all companies also gets a Company column.
|
||||
- Each row links to that event's leads.
|
||||
- **By salesperson:** for the period's captures, per salesperson.
|
||||
- Columns: assigned, worked (status beyond OPEN), won, lost, conversion rate, overdue follow-ups.
|
||||
- Captures with no salesperson appear as an "Unassigned" row.
|
||||
- **By interest:** per interest, the captures and wins. A capture with two interests counts under both.
|
||||
- **Phone width:** tiles stack, and the tables become cards, as on the other listings.
|
||||
|
||||
## Status timing
|
||||
|
||||
- **New table** `event_lead_status_change` in services-counter, append-only. Columns:
|
||||
- `id`, `company_id`, `event_lead_id`;
|
||||
- `from_status` (null for the first row), `to_status`;
|
||||
- `changed_at`, `changed_by`.
|
||||
- **Capture** writes the first row: null → initial status, at `captured_at`.
|
||||
- **An edit that changes status** writes one row in the same transaction. An edit that keeps the status writes nothing.
|
||||
- **Backfill** for existing event leads, in the change's SQL:
|
||||
- one row null → OPEN at `captured_at`;
|
||||
- when the current status is not OPEN, a second row OPEN → status at `updated_at`, or at `captured_at` when `updated_at` is null.
|
||||
|
||||
These times are approximate, and the deployment notes say so.
|
||||
|
||||
## Access
|
||||
|
||||
- **New module** `BO_DASHBOARD`, type M, URL `/`, id `40050000`. The sidebar shows a "Dashboard" link.
|
||||
- **The home page** shows the dashboard to users with `BO_DASHBOARD`. Everyone else sees today's welcome, not a not-authorised page, because every user lands at home after sign-in.
|
||||
- **The endpoint** answers 403 without the module.
|
||||
- **Super admins** pass as they do for every module.
|
||||
|
||||
## Approach
|
||||
|
||||
Aggregate in services-counter SQL:
|
||||
- services-counter gets one endpoint, `/counter/dashboard/leads`. It takes `companyId` (null = all), `from`, `to` and the bucket, and runs grouped native queries with bind parameters over `event_lead`, `event_lead_status_change`, `event_lead_interest` and `event`.
|
||||
- mobile-api adds `GET /api/admin/dashboard/leads` under `@AdminModule("BO_DASHBOARD")`. It applies the company scope, resolves salesperson names in one batch call to services-system, and returns one JSON payload.
|
||||
|
||||
Rejected:
|
||||
- **Aggregating in mobile-api from paged listings:** too many calls, and it gets slower as leads grow.
|
||||
- **A separate report service like legacy:** a new deployable for one screen.
|
||||
|
||||
## Portal
|
||||
|
||||
- **Charts:** add `recharts` and copy babyboo's `chart.tsx` wrapper. babyboo already uses both, and the look then matches.
|
||||
- **The funnel and tables** use existing components (Card, Table, data-table).
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- Indexes for the dashboard queries, chosen from EXPLAIN on realistic local data: likely `event_lead(company_id, captured_at)` and `event_lead_status_change(event_lead_id, changed_at)`.
|
||||
- Exact tile layout and copy.
|
||||
- Message keys for every label (English, as for other screens).
|
||||
@@ -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.
|
||||
@@ -185,8 +185,8 @@ ALTER TABLE `company`
|
||||
ADD COLUMN `code` varchar(20) NULL AFTER `name`,
|
||||
ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`;
|
||||
|
||||
UPDATE `company` SET `name` = 'INS', `code` = 'ins' WHERE `id` = 1;
|
||||
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'cv', 'A');
|
||||
UPDATE `company` SET `name` = 'INS', `code` = 'INS' WHERE `id` = 1;
|
||||
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'CV', 'A');
|
||||
|
||||
ALTER TABLE `company`
|
||||
MODIFY COLUMN `code` varchar(20) NOT NULL,
|
||||
@@ -226,5 +226,78 @@ DROP PROCEDURE `colite_check_admin_usernames`;
|
||||
UPDATE `user` u SET u.`company_id` = NULL
|
||||
WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||
|
||||
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins')
|
||||
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@INS')
|
||||
WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||
|
||||
-- add-lead-dashboard/sql/01-status-change.sql (02 backfill has nothing to do on an empty volume)
|
||||
USE `service-counter`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `event_lead_status_change` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NOT NULL,
|
||||
`event_lead_id` bigint NOT NULL,
|
||||
`from_status` varchar(10) NULL,
|
||||
`to_status` varchar(10) NOT NULL,
|
||||
`changed_at` datetime NOT NULL,
|
||||
`changed_by` varchar(255) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_elsc_event_lead` (`event_lead_id`, `changed_at`),
|
||||
KEY `idx_elsc_company_to_changed` (`company_id`, `to_status`, `changed_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Dashboard capture query: captures by company and capture time.
|
||||
ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_captured` (`company_id`, `captured_at`);
|
||||
|
||||
-- add-lead-dashboard/sql/03-dashboard-module.sql
|
||||
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,95 @@
|
||||
## Context
|
||||
|
||||
Approved product design: `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md` (definitions, figures, access). This file fixes the technical contract so the services-counter, mobile-api and portal tasks can be built in parallel.
|
||||
|
||||
Facts the design relies on:
|
||||
- `event_lead.status` already holds OPEN / CONTACTED / QUALIFIED / WON / LOST (event-lead-capture). Only the current value is stored.
|
||||
- `event_lead.captured_at` and `updated_at` are `LocalDateTime.now()` in the services-counter JVM, i.e. wall time in the JVM's default zone (UTC in the containers). There is no zone column.
|
||||
- services-counter has no database tests; every existing test is a Mockito unit test.
|
||||
- Salesperson names live in services-system; mobile-api already resolves them per user id with a per-request map (`AdminLeadService.salesperson`).
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. Status history table
|
||||
|
||||
`service-counter.event_lead_status_change`:
|
||||
- columns `id` bigint PK auto, `company_id` bigint NOT NULL, `event_lead_id` bigint NOT NULL, `from_status` varchar(10) NULL, `to_status` varchar(10) NOT NULL, `changed_at` datetime NOT NULL, `changed_by` varchar(255) NULL;
|
||||
- key `idx_elsc_event_lead (event_lead_id, changed_at)` and key `idx_elsc_company_to_changed (company_id, to_status, changed_at)`.
|
||||
|
||||
`EventLeadService.capture` saves one row (null → initial status, `changed_at` = the event lead's `captured_at`, `changed_by` = doneBy) in the capture transaction. `update` saves one row when the requested status differs from the stored one (`changed_at` = the new `updated_at`). Entity `EventLeadStatusChange`, repository `EventLeadStatusChangeRepository`. Nothing deletes or updates these rows.
|
||||
|
||||
Backfill (`sql/02-status-change-backfill.sql`, idempotent: only event leads with no history rows):
|
||||
- one row null → OPEN at `captured_at`, `changed_by` = `captured_by`;
|
||||
- where `status <> 'OPEN'`, one row OPEN → status at `COALESCE(updated_at, captured_at)`, `changed_by` = `COALESCE(updated_by, captured_by)`.
|
||||
|
||||
### 2. Aggregate in Java over lean rows, not in SQL
|
||||
|
||||
services-counter runs three plain native queries with bind parameters and aggregates the rows in a pure Java class (`LeadDashboardCalculator`), which is unit-tested without a database:
|
||||
1. **Captures:** event leads with `captured_at` in [fromUtc, toUtc) and the company filter, joined to `event` for name and company: `event_lead.id, event_uuid, event name, company_id, salesperson_user_id, lead_type, status, captured_at`.
|
||||
2. **Wins:** event leads with `status = 'WON'` whose latest history row with `to_status = 'WON'` has `changed_at` in [fromUtc, toUtc): `event_lead.id, captured_at, won_at`.
|
||||
3. **Overdue:** `salesperson_user_id, COUNT(*)` for status not in (WON, LOST) and `next_follow_up_date < today`, grouped by salesperson.
|
||||
|
||||
Interests for the captures come from the existing `EventLeadInterestRepository.findByIdEventLeadIdIn`, in chunks of 1000 ids, and interest names from `InterestRepository`.
|
||||
|
||||
Rejected: one grouped SQL query per figure. Its correctness could only be checked against a live database (no DB tests here), and adding Testcontainers is a new build dependency for one screen.
|
||||
|
||||
`ponytail:` row volume is one row per capture in the period. Fine for thousands per period; move the sums into SQL when one company captures hundreds of thousands of leads a year.
|
||||
|
||||
### 3. Time zone
|
||||
|
||||
mobile-api turns the period into dates; services-counter turns `[from 00:00, to+1 00:00)` in Asia/Kuala_Lumpur into the JVM default zone's wall time for the queries, and turns each stored time back to a Malaysian date for bucketing. "Today" for overdue is today in Asia/Kuala_Lumpur.
|
||||
|
||||
### 4. services-counter contract
|
||||
|
||||
`POST /counter/dashboard/leads` (route already under `/counter/**`), body:
|
||||
|
||||
```json
|
||||
{ "companyId": 2, "from": "2026-11-01", "to": "2026-11-30", "bucket": "DAY" }
|
||||
```
|
||||
|
||||
`companyId` null = all companies. `bucket` is `DAY` or `MONTH`. `from` after `to` → 400 `INVALID_PERIOD`. Response:
|
||||
|
||||
```json
|
||||
{
|
||||
"captures": 10, "newLeads": 6, "wonInPeriod": 3, "medianDaysToWin": 5, "overdueFollowUps": 4,
|
||||
"funnel": { "OPEN": 3, "CONTACTED": 1, "QUALIFIED": 1, "WON": 3, "LOST": 2 },
|
||||
"trend": [ { "bucket": "2026-11-01", "captures": 2, "wins": 0 } ],
|
||||
"events": [ { "eventUuid": "123", "name": "KL Expo", "companyId": 2, "captures": 10, "newLeads": 6, "won": 3 } ],
|
||||
"salespeople": [ { "userId": 7, "assigned": 4, "worked": 3, "won": 1, "lost": 1, "overdue": 2 } ],
|
||||
"interests": [ { "interestId": 5, "name": "Cookware", "captures": 4, "won": 1 } ]
|
||||
}
|
||||
```
|
||||
|
||||
- `medianDaysToWin` is null when there are no wins; with an even count it is the lower middle value (whole days).
|
||||
- `trend` lists every bucket in the period, zero-filled; a month bucket is the month's first day.
|
||||
- `events` is ordered by captures descending, then name; `salespeople` by assigned descending, with `userId` null for Unassigned; `salespeople` also includes a salesperson with overdue follow-ups but no captures in the period (assigned 0). `interests` by captures descending, then name.
|
||||
- `eventUuid` is a string (JavaScript loses precision on snowflake ids).
|
||||
|
||||
Rates are not sent; the portal divides.
|
||||
|
||||
### 5. mobile-api contract
|
||||
|
||||
`GET /api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2` under `@AdminModule("BO_DASHBOARD")`:
|
||||
- `from`/`to` optional; when absent, from = first day of the current Malaysian month, to = today (Malaysia).
|
||||
- Bad date format, from after to, or a range of more than 731 days (two years) → 400 `INVALID_PERIOD` (ProblemDetail: `code`, `detail`). The cap keeps one request from building an unbounded bucket list in services-counter, which also refuses a range over 731 days.
|
||||
- bucket = `DAY` when `to - from + 1 <= 62` days, else `MONTH`.
|
||||
- company from `AdminCompanyScope.scope(caller, companyId)`.
|
||||
- Response: the counter response plus `from`, `to`, `bucket`, and each salesperson row gains `name` (the user's name, or null for Unassigned and for a user that no longer exists). Salesperson names are resolved with the existing per-request map pattern.
|
||||
|
||||
### 6. Module
|
||||
|
||||
`service-system.module` row `(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard')`. No role grant: super admins grant it under Roles. Id 40050000 sorts it first in the sidebar, which orders by module id. The portal's route gate (`ROUTE_MODULES`) does not list `/`: the home page itself decides between the dashboard and the welcome, using `hasModule("BO_DASHBOARD")`.
|
||||
|
||||
### 7. Portal
|
||||
|
||||
- `recharts` added to `package.json`; `app/components/ui/chart.tsx` copied from babyboo's portal.
|
||||
- `app/lib/services/adminDashboard.ts`: types for decision 5 and `getLeadDashboard({from, to, companyId})`.
|
||||
- `app/page.tsx`: welcome for users without the module; otherwise the dashboard with a period control (This month / Last month / Custom with the existing date picker), the company picker for super admins (via `useCompanyScope`), tiles, funnel bars, a recharts line or bar chart of captures and wins, and three tables (cards below `md`). Event rows link to `/event-leads/{eventUuid}`. The Company column on the event table shows only when `showCompanyColumn`.
|
||||
- Rates show as whole percent; a null median or zero captures shows "–".
|
||||
- All labels are message keys with English defaults, as on other screens.
|
||||
|
||||
## Risks
|
||||
|
||||
- Backfilled history times are approximate (deployment notes say so).
|
||||
- A lead whose status was set by a direct DB edit has no history row for that change; the dashboard then misses that win. Nothing in the app does this.
|
||||
- `captured_at` stored in the JVM zone: if production pods ever run in a different zone from when rows were written, older rows shift. Same risk already exists for every listing.
|
||||
@@ -0,0 +1,33 @@
|
||||
## Why
|
||||
|
||||
Co-Lite exists to generate leads for INS and CV marketing. Managers need to see which events, salespeople and interests produce leads and which of those leads convert (status WON). Today the portal home page is a welcome line, and the system keeps only each event lead's current status, so it cannot say when a lead was won or how long it took. Approved design: `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Every event-lead status change is recorded with its time and who made it. Capture records the first status. Existing event leads are backfilled with approximate times.
|
||||
- A lead dashboard on the portal home page for a chosen period (this month, last month, or a custom range):
|
||||
- tiles: captures, new leads, won in period, conversion rate, median days to win, overdue follow-ups;
|
||||
- a status funnel;
|
||||
- a trend of captures and wins;
|
||||
- tables by event, by salesperson and by interest.
|
||||
- A new back-office module `BO_DASHBOARD` gates the dashboard. Users without it keep the welcome page.
|
||||
- Company scoping as on every other admin screen.
|
||||
- The admin portal gains the `recharts` dependency (already used by babyboo's portal) for the trend chart.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `lead-dashboard`: the dashboard, its definitions, period rules, access and company scope.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `event-lead-capture`: adds the status change history requirement.
|
||||
|
||||
## Impact
|
||||
|
||||
- Database `service-counter`: new table `event_lead_status_change`, a backfill, and an index on `event_lead`. `service-system`: one `module` row. SQL in `sql/`, mirrored in `local/seed/03-colite.sql`.
|
||||
- `solvway-services-counter`: history writes on capture and edit; a new dashboard endpoint.
|
||||
- `solvway-mobile-api`: `GET /api/admin/dashboard/leads`.
|
||||
- `solvway-admin-portal`: home page, sidebar link, `recharts`.
|
||||
- `docs/deployment.md`: the new SQL files.
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### 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,152 @@
|
||||
## ADDED 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,19 @@
|
||||
-- Co-Lite change add-lead-dashboard: event lead status history (design decision 1).
|
||||
-- Target: `service-counter`. Additive only. Run before the new images go live (services-counter writes this table), then 02.
|
||||
USE `service-counter`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `event_lead_status_change` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NOT NULL,
|
||||
`event_lead_id` bigint NOT NULL,
|
||||
`from_status` varchar(10) NULL,
|
||||
`to_status` varchar(10) NOT NULL,
|
||||
`changed_at` datetime NOT NULL,
|
||||
`changed_by` varchar(255) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_elsc_event_lead` (`event_lead_id`, `changed_at`),
|
||||
KEY `idx_elsc_company_to_changed` (`company_id`, `to_status`, `changed_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Dashboard capture query: captures by company and capture time.
|
||||
ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_captured` (`company_id`, `captured_at`);
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
-- Co-Lite change add-lead-dashboard: history for event leads captured before the history existed.
|
||||
-- Target: `service-counter`. Idempotent: touches only event leads with no history row. Times are approximate:
|
||||
-- the first status at capture, the current status (if not OPEN) at the last update.
|
||||
USE `service-counter`;
|
||||
|
||||
INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`)
|
||||
SELECT el.company_id, el.id, NULL, 'OPEN', el.captured_at, el.captured_by
|
||||
FROM `event_lead` el
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id);
|
||||
|
||||
INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`)
|
||||
SELECT el.company_id, el.id, 'OPEN', el.status, COALESCE(el.updated_at, el.captured_at), COALESCE(el.updated_by, el.captured_by)
|
||||
FROM `event_lead` el
|
||||
WHERE el.status <> 'OPEN'
|
||||
AND NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id AND s.to_status = el.status);
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Co-Lite change add-lead-dashboard: the Dashboard back-office module (area BO).
|
||||
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
|
||||
-- No role grant: super admins see every module; they grant BO_DASHBOARD to other roles under Roles.
|
||||
USE `service-system`;
|
||||
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard');
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Co-Lite change add-lead-dashboard: rollback. Drops the status history (its data is lost).
|
||||
USE `service-system`;
|
||||
DELETE FROM `modules_roles` WHERE `module_id` = 40050000;
|
||||
DELETE FROM `module` WHERE `id` = 40050000;
|
||||
|
||||
USE `service-counter`;
|
||||
ALTER TABLE `event_lead` DROP KEY `idx_event_lead_company_captured`;
|
||||
DROP TABLE IF EXISTS `event_lead_status_change`;
|
||||
@@ -0,0 +1,63 @@
|
||||
# Tasks
|
||||
|
||||
Design: `design.md` (technical contract) and `docs/superpowers/specs/2026-12-01-lead-dashboard-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 4 and 5. Scopes do not overlap: each touches one module.
|
||||
- Wave 2 (serial, controller): 5.1.
|
||||
|
||||
## 1. Data, module and chart dependency
|
||||
|
||||
- [x] 1.1 SQL `sql/01..03` and `99-rollback.sql`; mirror 01 and 03 in `local/seed/03-colite.sql` (02 has nothing to backfill on an empty volume); apply 01, 02 and 03 to the local database.
|
||||
- Depends on: none
|
||||
- Scope: `local/seed/**`, `openspec/changes/add-lead-dashboard/sql/**`
|
||||
- Verify: `SELECT` shows the table, the index, the backfilled rows and the module row.
|
||||
- [x] 1.2 Portal: add `recharts` (same major as babyboo's portal) with `npm install`, and copy babyboo's `app/components/ui/chart.tsx`.
|
||||
- Depends on: none
|
||||
- Scope: `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`, `solvway-admin-portal/app/components/ui/chart.tsx`
|
||||
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
|
||||
|
||||
## 2. services-counter
|
||||
|
||||
- [x] 2.1 Status history writes (decision 1) and the dashboard endpoint (decisions 2 to 4).
|
||||
- Tests first:
|
||||
- capture saves one history row null → initial status at the capture time, by doneBy;
|
||||
- update saves one row when the status changes and none when it stays;
|
||||
- the calculator, from in-memory rows: captures, new leads, funnel, won in period (latest WON only), median days (odd, even, none), overdue per salesperson, Unassigned, salesperson with overdue only, interest double-count, event ordering, zero-filled day and month trend, Malaysia day boundary from JVM-zone times;
|
||||
- the endpoint rejects from after to with 400 `INVALID_PERIOD` and passes a null company as all companies.
|
||||
- Scope: `solvway-services-counter/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
|
||||
|
||||
## 3. mobile-api
|
||||
|
||||
- [x] 3.1 `GET /api/admin/dashboard/leads` (decision 5).
|
||||
- Tests first:
|
||||
- default period is this Malaysian month to today; DAY bucket up to 62 days, MONTH above;
|
||||
- bad date and from after to → 400 `INVALID_PERIOD`;
|
||||
- staff are scoped to their company, a super admin's `companyId` is passed through, null for all;
|
||||
- salesperson names resolved, null for Unassigned and for a missing user;
|
||||
- the endpoint is gated by `BO_DASHBOARD` (aspect test with the annotation).
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
|
||||
|
||||
## 4. Portal
|
||||
|
||||
- [x] 4.1 Home page dashboard (decision 7).
|
||||
- Tests first:
|
||||
- without `BO_DASHBOARD` the welcome shows and the dashboard API is not called;
|
||||
- with it: tiles, funnel, chart container, the three tables with Unassigned, whole-percent rates and "–" for null median and zero captures;
|
||||
- period presets send the right `from`/`to`; a reversed custom range shows the error message;
|
||||
- a super admin's picker sends `companyId` and shows the Company column only for all companies;
|
||||
- an event row links to `/event-leads/{eventUuid}`;
|
||||
- the hard-coded copy sweep stays green (labels as message keys).
|
||||
- Includes the Next proxy route `app/api/dashboard/leads/route.ts` (added after review: the first plan left it out).
|
||||
- Scope: `solvway-admin-portal/app/api/dashboard/**`, `solvway-admin-portal/app/page.tsx`, `solvway-admin-portal/app/page*.test.tsx`, `solvway-admin-portal/app/components/dashboard/**`, `solvway-admin-portal/app/lib/services/adminDashboard*.ts`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`
|
||||
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
|
||||
|
||||
## 5. Release
|
||||
|
||||
- [x] 5.1 `docs/deployment.md` lists the SQL; live check against the local stack (seeded INS and CV event leads with status changes), and Playwright at 1280 and 360 px for a granted user, a user without the module, and a super admin switching company.
|
||||
- Depends on: 1.1 to 4.1
|
||||
- Scope: `docs/deployment.md`, `openspec/changes/add-lead-dashboard/tasks.md`
|
||||
- Verify: full `mvn -T 1C -q verify` of the three touched Maven modules and the portal verify.
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-01
|
||||
@@ -0,0 +1,113 @@
|
||||
## Context
|
||||
|
||||
Approved product design: `docs/superpowers/specs/2026-12-01-qr-self-registration-design.md`. That covers the flow, the matching rules, the consent and the default notice text, the abuse limits and the calls made. This file fixes the technical contracts so services-counter, services-system and mobile-api can be built in parallel, and the portal after them.
|
||||
|
||||
Facts relied on:
|
||||
- Staff capture: mobile-api `AdminEventLeadService.capture` normalises and validates, then posts to services-counter `/counter/eventLead/capture`. On an existing lead, counter `EventLeadService.capture` fills blank fields (`fillBlank`), which registrations must not do.
|
||||
- An event's team is the rows of `event_salesperson` (`/counter/eventSalesperson/findByEventUuid`). An "active member" is an enabled admin user of the event's company (`AdminEventLeadService.isActiveAdminOf`).
|
||||
- `AppAccessAspect` audits admin paths only (`isAdminPath()`), so public endpoints never reach the audit log, and their token cannot either.
|
||||
- A public mobile-api endpoint is `@AppAuth(skipValidate = true)`: it needs the api-key header and no JWT. The portal's server already sends `MOBILE_API_KEY` on every call.
|
||||
- The portal middleware guards every page and `/api/*` route except static files.
|
||||
- `HttpReqRespUtils.getClientIpAddressIfServletRequestExist()` is how the audit log reads the client IP (it checks `X-Forwarded-For` first).
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. Data (SQL in `sql/`)
|
||||
|
||||
- `service-counter.registration_link`: `id` bigint PK auto, `company_id` bigint NOT NULL, `event_uuid` bigint NOT NULL, `salesperson_user_id` bigint NULL, `token` varchar(32) NOT NULL UNIQUE, `enabled` bit NOT NULL default 1, `created_by`, `created_at`, `updated_by`, `updated_at`. Key `(event_uuid, salesperson_user_id)`. MySQL allows several NULLs in a unique key, so services-counter enforces "one event code per event" when it creates rows, and an `ensure` race is settled by re-reading after the insert.
|
||||
- `service-counter.event_lead`: add `source` varchar(8) NOT NULL DEFAULT 'STAFF', `consent_at` datetime NULL, `consent_notice_id` bigint NULL.
|
||||
- `service-system.company_privacy_notice`: `id` bigint PK auto, `company_id` bigint NOT NULL, `text_en` text NOT NULL, `text_ms` text NOT NULL, `created_by` varchar(255), `created_at` datetime NOT NULL; key `(company_id, id)`. The newest row per company is current. Seeded for every existing company with the default text, `{company}` replaced by `company.name`.
|
||||
- Token: 16 bytes from `SecureRandom`, base64url without padding (22 characters).
|
||||
|
||||
### 2. services-counter contract
|
||||
|
||||
All bodies are JSON. `companyId` is always a concrete company, set by mobile-api.
|
||||
|
||||
- `POST /counter/registrationLink/ensure` `{companyId, eventUuid, salespersonUserIds: [..]}` returns `[{eventUuid, salespersonUserId|null, token, enabled}]`. The event code comes first, then one per given salesperson in the given order; missing rows are created. 404 when the event is not in the company.
|
||||
- `POST /counter/registrationLink/setEnabled` `{companyId, eventUuid, token, enabled, doneBy}` returns the link. 404 when the token is not that event's in that company.
|
||||
- `GET /counter/registrationLink/findByToken/{token}` returns `{companyId, eventUuid, salespersonUserId|null, token, enabled}`, or 404.
|
||||
- `POST /counter/registrationLink/mine` `{companyId, userId, today}` (today is a Malaysian date) covers events of the company where `event_salesperson` has the user, `enabled = Y` and `DATE(date_end) >= today`. Missing personal links are created. It returns `[{eventUuid, eventName, startDate, endDate, location, token, enabled}]`, ordered by start date.
|
||||
- `POST /counter/registration/register` `{companyId, eventUuid, salespersonUserId|null, name, mobileE164, email, companyName, jobTitle, interestIds, consentNoticeId, consentAt}` returns `{outcome: CREATED|LINKED|ALREADY_CAPTURED|ASSIGNED, eventLeadUuid}`. It runs in one transaction:
|
||||
1. **Match.** Look for a lead in the company with `mobile_e164 = mobileE164` (newest id first), then with `email_normalised = email`.
|
||||
2. **New person.** No match creates a new lead and a NEW event lead.
|
||||
3. **Known person, not yet captured here.** The match is not edited. Its event lead is EXISTING, and its notes are `Registered by QR with: <field> <value>; …` for each submitted non-blank value that differs from the lead's (name, mobile, email, company, job title); the notes are null when nothing differs.
|
||||
4. **Already captured.** When the lead is already captured at the event (row exists, or the insert hits `uk_event_lead_event_lead`): if that event lead has no salesperson and `salespersonUserId` is set, assign it (`ASSIGNED`, `updated_by = qr`); otherwise change nothing (`ALREADY_CAPTURED`).
|
||||
5. **The new event lead:** `status OPEN`, `source QR`, `captured_by 'qr'`, `consent_at`, `consent_notice_id`, the interests, plus the status history row null → OPEN by `qr`.
|
||||
|
||||
`EventLeadService.capture` (staff) stays as it is and sets `source STAFF`.
|
||||
|
||||
### 3. services-system contract
|
||||
|
||||
- `GET /company/{id}/privacyNotice` returns the current `{id, companyId, textEn, textMs, createdBy, createdAt}`, or 404.
|
||||
- `POST /company/{id}/privacyNotice` `{textEn, textMs, doneBy}` adds a version and returns it. Both texts are required after trimming and at most 5000 characters each (400 otherwise). 404 for an unknown company.
|
||||
|
||||
### 4. mobile-api contract
|
||||
|
||||
Public (`@AppAuth(skipValidate = true)`, controller `PublicRegistrationController` under `controller..`, path `/api/public/registration/{token}`):
|
||||
|
||||
- **`GET`:**
|
||||
- Page-load limit: Redis key `reg:load:<ip>`, at most 120 per 10 minutes, else 429 `TOO_MANY`. The POST counts against it too, before the code is checked, so guessing codes by POST is slowed as well.
|
||||
- A code works when all of these hold, otherwise 404 `CODE_INACTIVE` with message "This code is no longer active.":
|
||||
- the link exists and is enabled;
|
||||
- its event exists, is enabled and has `dateEnd`'s date (Malaysia) ≥ today;
|
||||
- the company is active (`status A`);
|
||||
- the company has a current notice.
|
||||
- Returns `{eventName, startDate, endDate, location, companyName, notice: {id, textEn, textMs}, interests: [{id, name}]}`, where interests are the active ones.
|
||||
- **`POST`** with `{name, mobile, email, companyName, jobTitle, interestIds, consent, website}`:
|
||||
- The code checks are the same as for `GET`.
|
||||
- A non-blank `website` (honeypot) returns 200 `{eventName}` without saving.
|
||||
- Submission limit: Redis key `reg:submit:<eventUuid>:<ip>`, at most 60 per 10 minutes, else 429 `TOO_MANY`.
|
||||
- Validation is the same as staff capture (required name, mobile or email, lengths, normalisation, interests must be active ones of the company), and `consent` must be true (field `consent`, code `CONSENT_REQUIRED`). Field errors use the existing `details.field` shape.
|
||||
- Salesperson: the link's salesperson when they are on the event's team and are an active admin of the company, else null.
|
||||
- The notice is the current notice at submit time; the client never chooses it.
|
||||
- Calls counter `register` and returns 200 `{eventName}` whatever the outcome.
|
||||
- **Limits:** they count only requests that reach the check. The limit message is "Too many registrations from this device. Try again later."
|
||||
|
||||
Admin:
|
||||
- `GET /api/admin/events/{uuid}/registration-links` (`BO_EVENTS`; event loaded through the company scope) returns `{event: {token, enabled}, members: [{userId, name, username, token, enabled}]}` for every team row, with names resolved per id.
|
||||
- `PUT /api/admin/events/{uuid}/registration-links/{token}` (`BO_EVENTS`) with `{enabled}` returns the link.
|
||||
- `GET /api/admin/my-registration-links` (`ANY_ADMIN`) returns the caller's own links from counter `mine` (Malaysian today). A caller with no company gets `[]`.
|
||||
- `GET` and `PUT /api/admin/companies/{id}/privacy-notice` are super-admin only (`AdminCompanyScope.requireSuper`) and pass through to services-system. `PUT` takes `{textEn, textMs}`.
|
||||
|
||||
### 5. Portal
|
||||
|
||||
- **Dependency:** `qrcode.react` (the same major as babyboo's portal).
|
||||
- **Middleware:** `/r/:token` and `/api/public/:path*` skip the sign-in check. This is security code, so it gets the minimum change and a test that a public path is reachable signed out while admin paths still redirect.
|
||||
- **`/r/[token]`:**
|
||||
- A client page built from the existing UI components, mobile first, without the admin shell (no sidebar or header).
|
||||
- States: loading, inactive, form, field errors, too-many, thank-you with "Register another person".
|
||||
- It uses the proxy `app/api/public/registration/[token]/route.ts` (GET and POST). The proxy sends the visitor IP to mobile-api as `X-Forwarded-For`, set to the last hop of the incoming header (the address the ingress added, the same rule as `X-Client-Ip`), so a visitor cannot choose their own rate-limit key.
|
||||
- **Event edit page:** a "Registration QR" card with:
|
||||
- the event code and every member's code: QR image (`QRCodeSVG`), the link built from `window.location.origin + /r/<token>`, copy, download PNG (`QRCodeCanvas` → `toDataURL`, file `<event>-<name|event>-qr.png`), and an on/off switch;
|
||||
- a note that the link can be pasted into dynamic-qr for a printed code.
|
||||
- **"My QR codes" page** `/my-qr`: reached from the header user menu, shown to every staff user, listing the caller's codes. It is not a module, so `ROUTE_MODULES` leaves it unmapped and any signed-in user may open it.
|
||||
- **Companies page (super admin):** a "Privacy notice" editor with the English and Bahasa Malaysia text areas, save, and "last changed by/at".
|
||||
|
||||
### 6. Gateway access without a user token (added after the live check)
|
||||
|
||||
mobile-api forwards the caller's JWT to the gateway, and a visitor has none, so the gateway's `JWTAuthFilter` refused every call the public flow makes (401). The gateway is internal only (`docs/deployment.md`), and the earlier sign-in work set the precedent of exact, anchored bypass paths.
|
||||
|
||||
- **Bypass only these, each for one HTTP method, with anchored patterns (no `contains`):**
|
||||
- GET `/counter/registrationLink/findByToken/<22 url-safe chars>`
|
||||
- GET `/counter/event/findByUuid/<digits>`
|
||||
- GET `/counter/interest/findByCompany/<digits>`
|
||||
- GET `/counter/eventSalesperson/findByEventUuid/<digits>`
|
||||
- GET `/company/findById/<digits>`
|
||||
- GET `/company/<digits>/privacyNotice` (the POST that saves a notice still needs a token)
|
||||
- GET `/user/<digits>/activeAdminOf/<digits>`
|
||||
- POST `/counter/registration/register`
|
||||
- **`/user/findById` stays closed.** It returns the whole user record, password hashes included. services-system gets `GET /user/{id}/activeAdminOf/{companyId}`, which answers only `true` or `false` (type A, enabled, same company; false for an unknown user), and the public salesperson check uses it.
|
||||
|
||||
### 7. Rejected
|
||||
|
||||
- Matching and capture in mobile-api with two counter calls: not atomic, and it races the unique key.
|
||||
- A notice text copied onto every event lead: a version id is enough and keeps rows small.
|
||||
|
||||
## Risks
|
||||
|
||||
- Shared venue NAT: 60 submissions per event per 10 minutes from one IP may still be hit at a very busy booth. The message tells the visitor to try later. Raise the limit if it happens.
|
||||
- The visitor IP is the last `X-Forwarded-For` hop, which is right whether Traefik appends to or replaces the header. Behind a second proxy in front of Traefik it would be that proxy's address; the deployment notes say so.
|
||||
- The default notice is a template; INS and CV must review it.
|
||||
- The registration code appears in request logs (mobile-api's response-time log and the gateway's request log). It is printed on the QR code anyway, and the audit log records the event instead; mask the path segment if that ever matters.
|
||||
- The event page loads each team member's user record one call at a time (N+1). Teams are small; batch it if they grow.
|
||||
- The gateway bypass (decision 6) lets any holder of a gateway api-key read those records and register a lead without a user token. The gateway is not exposed outside the cluster, and the paths are exact, so the exposure is limited to callers that already hold a server api-key. Such a caller could post registrations straight to services-counter, skipping mobile-api's code, consent and rate-limit checks: choose the company, event and salesperson, and learn from the outcome whether a mobile or email is already a lead. It could also read whole event records and test user ids against `activeAdminOf`. Narrower projections or a service-to-service credential would close this if the gateway is ever exposed.
|
||||
@@ -0,0 +1,29 @@
|
||||
## Why
|
||||
|
||||
Co-Lite is a lead-generation system for INS and CV (the owner dropped the member app on 2026-12-01). At events, staff type every visitor in by hand. Walk-in visitors should scan a QR code, register themselves, and land in Event Leads and the dashboard, credited to the salesperson whose code they scanned. Approved design: `docs/superpowers/specs/2026-12-01-qr-self-registration-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- A public, phone-first registration page `/r/<token>` on the admin portal. It shows the event's details, a short form and a bilingual PDPA consent, and every successful submit gets the same thank-you page.
|
||||
- A registration links to an existing lead without editing it (differences go to the event lead's notes), or creates a new lead. It creates an OPEN event lead with `source = QR` and the consent record.
|
||||
- Registration codes: one per event and one per salesperson per event. Staff with `BO_EVENTS` see, download, copy and switch off codes on the event page. Every staff user sees their own codes on a new "My QR codes" page.
|
||||
- Each company's privacy notice is versioned and edited by super admins on the Companies page. INS and CV are seeded with a default English and Bahasa Malaysia notice. A company without a notice has no working codes.
|
||||
- Abuse limits: per IP per event for submissions and per IP for page loads, plus a honeypot field.
|
||||
- The admin portal gains `qrcode.react` (already used by babyboo's portal) to draw the codes.
|
||||
- dynamic-qr: no code integration. An admin may paste a Co-Lite link into dynamic-qr's console for a repointable printed code.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `qr-registration`: registration codes, the public registration page and its rules, consent and privacy notices, and abuse limits.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
## Impact
|
||||
|
||||
- `service-counter`: new table `registration_link`; `event_lead` gains `source`, `consent_at` and `consent_notice_id`.
|
||||
- `service-system`: new table `company_privacy_notice`, seeded for INS and CV.
|
||||
- `solvway-services-counter`, `solvway-services-system`, `solvway-mobile-api` (public `/api/public/registration/**`, admin link and notice endpoints), `solvway-admin-portal` (public route outside the admin sign-in guard, event QR section, My QR codes, Companies notice).
|
||||
- New public, unauthenticated surface: covered by the abuse limits and the anti-goals in the design.
|
||||
- `docs/deployment.md`: the SQL, and a note that the default notice must be reviewed.
|
||||
+127
@@ -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
|
||||
+24
@@ -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`;
|
||||
+25
@@ -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.
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-01
|
||||
@@ -0,0 +1,27 @@
|
||||
## Why
|
||||
|
||||
Company codes are stored and shown in lowercase (`ins`, `cv`). The owner wants them in capitals (`INS`, `CV`), and the Companies screen cannot change `cv` to `CV`: the portal treats a case-only change as no change, and services-system lowercases every code it saves.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Company codes are stored and shown in capitals: 2 to 20 characters of `A-Z`, `0-9` and `-`. Any code entered is turned to capitals before it is checked and saved.
|
||||
- Sign-in keeps ignoring case: staff can type `cv`, `Cv` or `CV`.
|
||||
- Staff login names follow the code (`sales9@CV`).
|
||||
- A one-off SQL turns the existing codes and staff login names to capitals.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `company-scoping`: the code format of the Companies requirement becomes capitals.
|
||||
|
||||
## Impact
|
||||
|
||||
- **services-system:** `CompanyService` code validation and normalisation.
|
||||
- **mobile-api:** the admin login builds the login name with the code in capitals.
|
||||
- **portal:** the Companies code fields show and send capitals. A case-only rename is no longer treated as no change.
|
||||
- **Data:** `sql/01-uppercase-codes.sql` on `service-system`. Signed-in staff must sign in again after it runs, as after any code change.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Spec Delta
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Companies
|
||||
|
||||
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of capital letters, digits and hyphens. A code entered in any case SHALL be stored in capitals, and codes SHALL be compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
|
||||
|
||||
#### Scenario: Create a company
|
||||
|
||||
- **WHEN** a super admin creates company `CV` with code `cv`
|
||||
- **THEN** it is listed as active with code `CV`
|
||||
- **AND** staff can be created in it
|
||||
|
||||
#### Scenario: Duplicate code
|
||||
|
||||
- **GIVEN** a company with code `INS`
|
||||
- **WHEN** a super admin creates or renames another company to code `ins`
|
||||
- **THEN** the save is refused and the code is reported as taken
|
||||
|
||||
#### Scenario: Not a super admin
|
||||
|
||||
- **WHEN** company staff open the Companies page or call a companies endpoint
|
||||
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||
|
||||
#### Scenario: Sign-in ignores case
|
||||
|
||||
- **GIVEN** company code `CV` and its user `sales9`
|
||||
- **WHEN** they sign in with company `cv`
|
||||
- **THEN** they are signed in as `sales9` of CV
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Co-Lite change uppercase-company-codes: company codes and staff login names in capitals.
|
||||
-- Target: `service-system`. Signed-in staff must sign in again afterwards. Idempotent.
|
||||
USE `service-system`;
|
||||
|
||||
UPDATE `user` u JOIN `company` c ON c.`id` = u.`company_id`
|
||||
SET u.`username` = CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', UPPER(c.`code`))
|
||||
WHERE u.`type` = 'A' AND u.`username` LIKE CONCAT('%@', c.`code`) AND BINARY u.`username` <> BINARY CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', UPPER(c.`code`));
|
||||
|
||||
UPDATE `company` SET `code` = UPPER(`code`) WHERE BINARY `code` <> BINARY UPPER(`code`);
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Co-Lite change uppercase-company-codes: rollback to lowercase codes and login names.
|
||||
USE `service-system`;
|
||||
|
||||
UPDATE `user` u JOIN `company` c ON c.`id` = u.`company_id`
|
||||
SET u.`username` = CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', LOWER(c.`code`))
|
||||
WHERE u.`type` = 'A' AND u.`username` LIKE CONCAT('%@', c.`code`);
|
||||
|
||||
UPDATE `company` SET `code` = LOWER(`code`);
|
||||
@@ -0,0 +1,33 @@
|
||||
# Tasks
|
||||
|
||||
Serial. One implementer, in this session.
|
||||
|
||||
## 1. Data
|
||||
|
||||
- [x] 1.1 `sql/01-uppercase-codes.sql` and `sql/99-rollback.sql`; change the codes in `local/seed/03-colite.sql` to `INS` and `CV` (the `@ins` login names it builds follow); apply 01 to the local database.
|
||||
- Depends on: none
|
||||
- Scope: `local/seed/**`, `openspec/changes/uppercase-company-codes/sql/**`
|
||||
- Verify: `SELECT code FROM company` gives `INS`, `CV`; staff login names end in `@INS` or `@CV`.
|
||||
|
||||
## 2. Backend
|
||||
|
||||
- [x] 2.1 services-system `CompanyService` stores codes in capitals (`^[A-Z0-9-]{2,20}$`, entered value trimmed and turned to capitals); mobile-api admin login and forgot-password build the login name with the code in capitals.
|
||||
- Depends on: 1.1
|
||||
- Tests first: create with `cv` stores `CV`; rename `cv` to `CV` on a company whose code is `cv` succeeds; `ins` is taken when `INS` exists; an invalid code is refused; login with company `cv` looks up `user@CV`.
|
||||
- Scope: `solvway-services-system/src/**`, `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-services-system,solvway-mobile-api verify`
|
||||
|
||||
## 3. Portal
|
||||
|
||||
- [x] 3.1 Companies: code inputs show capitals as typed and the rename compares case-sensitively, so `cv` to `CV` is a change.
|
||||
- Depends on: 2.1
|
||||
- Tests first: typing `cv` shows `CV`; renaming `cv` to `CV` sends the request.
|
||||
- Scope: `solvway-admin-portal/app/**`
|
||||
- Verify: `cd solvway-admin-portal && npm run lint; echo L=$?; npx tsc --noEmit; echo T=$?; npx vitest run; echo V=$?`
|
||||
|
||||
## 4. Release
|
||||
|
||||
- [x] 4.1 `docs/deployment.md` notes the SQL and that staff sign in again; Playwright: Companies shows `INS` and `CV`, sign in as `sales9` with company `cv` works.
|
||||
- Depends on: 3.1
|
||||
- Scope: `docs/deployment.md`, `openspec/changes/uppercase-company-codes/tasks.md`
|
||||
- Verify: the 2.1 and 3.1 verifies.
|
||||
@@ -132,3 +132,20 @@ An audit event and a login-history record SHALL belong to the company of the use
|
||||
|
||||
- **WHEN** someone fails to sign in with a company code that does not exist
|
||||
- **THEN** the login-history record has no company and only super admins see it
|
||||
|
||||
### Requirement: Invalid admins fail closed
|
||||
|
||||
The system SHALL refuse every company-scoped request from an admin with no company who is not a super admin, and SHALL grant a company user who holds the super admin role only the modules and records their company and other roles allow.
|
||||
|
||||
#### Scenario: Admin without a company who is not a super admin
|
||||
|
||||
- **GIVEN** an admin user with no company and no super admin role
|
||||
- **WHEN** they open Leads, Events, Users or any other company-scoped list or record
|
||||
- **THEN** the request is refused with 403
|
||||
- **AND** no company's records are returned
|
||||
|
||||
#### Scenario: Company user still holding the super admin role
|
||||
|
||||
- **GIVEN** a user of INS who holds the super admin role and a role granting only Leads
|
||||
- **WHEN** they open Users or another super admin's email
|
||||
- **THEN** the request is refused with 403
|
||||
@@ -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,133 @@
|
||||
# qr-registration Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Walk-in visitors scan an event or salesperson QR code and register themselves as a lead, with recorded PDPA consent, abuse limits and staff tools to show, print and switch off codes.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Registration codes
|
||||
|
||||
The system SHALL give every event one registration code and one personal code per member of the event's team. A code SHALL be an unguessable token in a link of the form `/r/<token>`. Staff with `BO_EVENTS` SHALL see each code of an event of their company as a QR image, copy its link, download it as an image, and switch it off or on. Every staff user SHALL see their own personal codes for events of their company that have not ended.
|
||||
|
||||
#### Scenario: Event page codes
|
||||
|
||||
- **GIVEN** event `KL Expo` with `sales1` and `sales2` on its team
|
||||
- **WHEN** a user with `BO_EVENTS` opens the event
|
||||
- **THEN** the event's code and the personal codes of `sales1` and `sales2` are shown, each with its QR image and link
|
||||
|
||||
#### Scenario: Own codes
|
||||
|
||||
- **GIVEN** `sales1` is on the team of `KL Expo`, which ends tomorrow, and of `Penang Fair`, which ended last week
|
||||
- **WHEN** `sales1` opens My QR codes
|
||||
- **THEN** only the personal code for `KL Expo` is listed
|
||||
|
||||
#### Scenario: Switch a code off
|
||||
|
||||
- **WHEN** staff switch off the event code of `KL Expo`
|
||||
- **THEN** scanning that code shows that it is no longer active
|
||||
- **AND** the personal codes still work
|
||||
|
||||
### Requirement: When a code works
|
||||
|
||||
A code SHALL work only while it is switched on, its event is enabled, the event's end date in Malaysia time has not passed, and the event's company has a privacy notice. An inactive or unknown code SHALL show "This code is no longer active." and no event details. A personal code whose salesperson is no longer an active member of the event's team SHALL keep working, and its registrations SHALL have no salesperson.
|
||||
|
||||
#### Scenario: Ended event
|
||||
|
||||
- **GIVEN** `Penang Fair` ended yesterday
|
||||
- **WHEN** a visitor scans its code
|
||||
- **THEN** the page says the code is no longer active and shows no event details
|
||||
|
||||
#### Scenario: Salesperson left the team
|
||||
|
||||
- **GIVEN** `sales2` was removed from the team of `KL Expo`
|
||||
- **WHEN** a visitor registers through `sales2`'s code
|
||||
- **THEN** the registration succeeds and the event lead has no salesperson
|
||||
|
||||
### Requirement: Public registration
|
||||
|
||||
The registration page SHALL show the event's name, dates and location, and a form for name (required), mobile and email (at least one), company, job title, the company's active interests, and the privacy notice consent (required). Inputs SHALL be normalised and limited as in staff capture. Every accepted submission SHALL show the same thank-you page naming the event, with a button to register another person, whether or not the person was already known.
|
||||
|
||||
#### Scenario: Register
|
||||
|
||||
- **WHEN** a visitor scans the code of `KL Expo`, enters name `Aisyah`, mobile `012-345 6701` and ticks the consent
|
||||
- **THEN** the thank-you page names `KL Expo`
|
||||
- **AND** staff see `Aisyah` with mobile `+60123456701` in the event's leads as NEW and OPEN
|
||||
|
||||
#### Scenario: Missing consent or contact
|
||||
|
||||
- **WHEN** a visitor submits without ticking the consent, or without a mobile and an email
|
||||
- **THEN** nothing is saved and the page shows the error under the field
|
||||
|
||||
#### Scenario: Known person gets the same answer
|
||||
|
||||
- **GIVEN** a lead with mobile `+60123456701` exists in the company
|
||||
- **WHEN** a visitor registers with that mobile
|
||||
- **THEN** the page shows the same thank-you page as for a new person
|
||||
|
||||
### Requirement: Registration matching
|
||||
|
||||
A registration SHALL match a lead of the event's company by mobile first and then by email, the newest lead winning among several. A matched lead SHALL NOT be edited: it SHALL be linked as EXISTING, with every submitted value that differs from the lead's written into the event lead's notes. Without a match a new lead SHALL be created as NEW.
|
||||
|
||||
#### Scenario: Existing lead not edited
|
||||
|
||||
- **GIVEN** lead `Aisyah` with mobile `+60123456701` and no email
|
||||
- **WHEN** a visitor registers as `Aisyah Rahman` with that mobile and email `a@example.test`
|
||||
- **THEN** lead `Aisyah` still has no email and its name is unchanged
|
||||
- **AND** the new event lead is EXISTING and its notes list the submitted name and email
|
||||
|
||||
#### Scenario: Mobile beats email
|
||||
|
||||
- **GIVEN** lead `A` has mobile `+60123456701` and lead `B` has email `b@example.test`
|
||||
- **WHEN** a visitor registers with that mobile and that email
|
||||
- **THEN** the registration is linked to lead `A`
|
||||
|
||||
### Requirement: Registration of a person already captured
|
||||
|
||||
When the matched lead is already captured at the event, a registration SHALL change nothing, except that an event lead with no salesperson SHALL get the salesperson of a personal code whose salesperson is an active member of the event's team.
|
||||
|
||||
#### Scenario: Already captured, unassigned
|
||||
|
||||
- **GIVEN** `Aisyah` is captured at `KL Expo` with no salesperson
|
||||
- **WHEN** she registers again through `sales1`'s personal code and `sales1` is on the team
|
||||
- **THEN** her event lead's salesperson becomes `sales1` and nothing else changes
|
||||
|
||||
### Requirement: Registration record
|
||||
|
||||
An event lead created by a registration SHALL have status OPEN, source QR, captured by `qr`, the consent time and the privacy notice version shown, the chosen interests, and the code's salesperson when that salesperson is an active member of the event's team. Event leads captured by staff SHALL have source STAFF. The status history SHALL record the first status by `qr`.
|
||||
|
||||
#### Scenario: Personal code assigns
|
||||
|
||||
- **WHEN** a visitor registers through `sales1`'s personal code for `KL Expo`
|
||||
- **THEN** the event lead's salesperson is `sales1`, its source is QR and it records the consent time and notice version
|
||||
|
||||
### Requirement: Privacy notice
|
||||
|
||||
Each company SHALL have a privacy notice in English and Bahasa Malaysia, kept as versions: saving a change SHALL add a new version and keep the old ones. Only a super admin SHALL edit it, on the Companies page. The registration page SHALL show the company's current notice in both languages. INS and CV SHALL start with the default notice of the design, with the company's name filled in.
|
||||
|
||||
#### Scenario: Edit the notice
|
||||
|
||||
- **GIVEN** CV's notice is version 3
|
||||
- **WHEN** a super admin changes CV's English text and saves
|
||||
- **THEN** CV's registration pages show the new text
|
||||
- **AND** event leads registered before still point to version 3
|
||||
|
||||
#### Scenario: Not a super admin
|
||||
|
||||
- **WHEN** company staff call the privacy notice update endpoint
|
||||
- **THEN** it responds 403
|
||||
|
||||
### Requirement: Registration abuse limits
|
||||
|
||||
The system SHALL accept at most 60 registrations per client IP per event in 10 minutes and serve at most 120 registration page loads per client IP in 10 minutes, answering above either limit with "Too many registrations from this device. Try again later." A submission that fills the hidden honeypot field SHALL get the normal thank-you page and save nothing.
|
||||
|
||||
#### Scenario: Too many submissions
|
||||
|
||||
- **GIVEN** 60 registrations for `KL Expo` from one IP in the last 10 minutes
|
||||
- **WHEN** the 61st arrives from that IP
|
||||
- **THEN** nothing is saved and the page shows the too-many message
|
||||
|
||||
#### Scenario: Honeypot
|
||||
|
||||
- **WHEN** a submission fills the hidden field
|
||||
- **THEN** the thank-you page shows and no lead or event lead is saved
|
||||
@@ -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,38 @@
|
||||
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 } from "./route";
|
||||
|
||||
type Req = Parameters<typeof GET>[0];
|
||||
const req = (url: string) => new Request(`http://localhost${url}`) as unknown as Req;
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { captures: 1 } });
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
|
||||
});
|
||||
|
||||
describe("/api/dashboard/leads", () => {
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await GET(req("/api/dashboard/leads"));
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards the query string to mobile-api", async () => {
|
||||
const res = await GET(req("/api/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ captures: 1 });
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2", { token: "jwt-abc" });
|
||||
});
|
||||
|
||||
it("passes an upstream INVALID_PERIOD with its code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Start date must be on or before end date.", status: 400, code: "INVALID_PERIOD" });
|
||||
const res = await GET(req("/api/dashboard/leads?from=2026-11-30&to=2026-11-01"));
|
||||
expect(res.status).toBe(400);
|
||||
expect(((await res.json()) as Record<string, unknown>).code).toBe("INVALID_PERIOD");
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
|
||||
// Proxy for /api/admin/dashboard/leads; mobile-api owns period validation and the BO_DASHBOARD guard.
|
||||
export async function GET(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<unknown>(`/api/admin/dashboard/leads${new URL(req.url).search}`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: { params: Promise<{ uuid: string; token: string }> }) {
|
||||
const session = await getToken();
|
||||
if (!session) return unauthorized();
|
||||
const { uuid, token } = await params;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const result = await callMobileApi<Record<string, unknown>>(
|
||||
`/api/admin/events/${encodeURIComponent(uuid)}/registration-links/${encodeURIComponent(token)}`,
|
||||
{ method: "PUT", body, token: session },
|
||||
);
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: { params: Promise<{ uuid: string }> }) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { uuid } = await params;
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/${encodeURIComponent(uuid)}/registration-links`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function GET() {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<unknown>("/api/admin/my-registration-links", { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
|
||||
import { GET, POST } from "./route";
|
||||
|
||||
type Req = Parameters<typeof GET>[0];
|
||||
const ctx = { params: Promise.resolve({ token: "tok/1" }) };
|
||||
const req = (init: RequestInit = {}) => new Request("http://localhost/api/public/registration/tok", init) as unknown as Req;
|
||||
|
||||
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { eventName: "Expo" } }));
|
||||
|
||||
describe("/api/public/registration/[token]", () => {
|
||||
it("GET forwards without a session and with the visitor IP", async () => {
|
||||
const res = await GET(req({ headers: { "x-forwarded-for": "203.0.113.7" } }), ctx);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ eventName: "Expo" });
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/registration/tok%2F1", {
|
||||
headers: { "X-Forwarded-For": "203.0.113.7" },
|
||||
});
|
||||
});
|
||||
|
||||
it("POST forwards the body and drops client-written X-Forwarded-For entries and sends only the last hop", async () => {
|
||||
const body = { name: "A", website: "" };
|
||||
await POST(req({ method: "POST", body: JSON.stringify(body), headers: { "x-forwarded-for": "6.6.6.6, 203.0.113.7" } }), ctx);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/registration/tok%2F1", {
|
||||
method: "POST",
|
||||
body,
|
||||
headers: { "X-Forwarded-For": "203.0.113.7" },
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to X-Real-Ip and sends no header when no address is known", async () => {
|
||||
await GET(req({ headers: { "x-real-ip": "192.0.2.9" } }), ctx);
|
||||
expect(mocks.callMobileApi.mock.calls[0][1].headers).toEqual({ "X-Forwarded-For": "192.0.2.9" });
|
||||
await GET(req(), ctx);
|
||||
expect(mocks.callMobileApi.mock.calls[1][1].headers).toEqual({});
|
||||
});
|
||||
|
||||
it("passes upstream failures with status and code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Too many registrations from this device. Try again later.", status: 429, code: "TOO_MANY" });
|
||||
const res = await POST(req({ method: "POST", body: "{}" }), ctx);
|
||||
expect(res.status).toBe(429);
|
||||
expect(((await res.json()) as Record<string, unknown>).code).toBe("TOO_MANY");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { clientIp } from "@/app/lib/server/clientContext";
|
||||
import { errorResponse } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// Public (signed-out) proxy for the QR registration page: no session token.
|
||||
// X-Forwarded-For is rebuilt from clientIp(req) only (the LAST hop, same trusted rule as X-Client-Ip):
|
||||
// client-written entries in an incoming header are never forwarded, so the rate-limit key cannot be spoofed.
|
||||
type Ctx = { params: Promise<{ token: string }> };
|
||||
|
||||
function forwardedFor(req: NextRequest): Record<string, string> {
|
||||
const xff = clientIp(req);
|
||||
return xff ? { "X-Forwarded-For": xff } : {};
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Ctx) {
|
||||
const { token } = await params;
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
|
||||
headers: forwardedFor(req),
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: Ctx) {
|
||||
const { token } = await params;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
|
||||
method: "POST",
|
||||
body,
|
||||
headers: forwardedFor(req),
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET as getLinks } from "./events/[uuid]/registration-links/route";
|
||||
import { PUT as putLink } from "./events/[uuid]/registration-links/[token]/route";
|
||||
import { GET as getMine } from "./my-registration-links/route";
|
||||
import { GET as getNotice, PUT as putNotice } from "./companies/[id]/privacy-notice/route";
|
||||
|
||||
const req = (init?: RequestInit) => new Request("http://localhost/x", init) as never;
|
||||
const p = <T,>(v: T) => ({ params: Promise.resolve(v) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { ok: 1 } });
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("registration admin proxies", () => {
|
||||
it("require a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
for (const res of [await getLinks(req(), p({ uuid: "e" })), await getMine(), await getNotice(req(), p({ id: "1" }))]) {
|
||||
expect(res.status).toBe(401);
|
||||
}
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forward to the admin endpoints with the token", async () => {
|
||||
await getLinks(req(), p({ uuid: "e1" }));
|
||||
await putLink(req({ method: "PUT", body: '{"enabled":false}' }), p({ uuid: "e1", token: "t1" }));
|
||||
await getMine();
|
||||
await getNotice(req(), p({ id: "2" }));
|
||||
await putNotice(req({ method: "PUT", body: '{"textEn":"a","textMs":"b"}' }), p({ id: "2" }));
|
||||
expect(mocks.callMobileApi.mock.calls).toEqual([
|
||||
["/api/admin/events/e1/registration-links", { token: "jwt" }],
|
||||
["/api/admin/events/e1/registration-links/t1", { method: "PUT", body: { enabled: false }, token: "jwt" }],
|
||||
["/api/admin/my-registration-links", { token: "jwt" }],
|
||||
["/api/admin/companies/2/privacy-notice", { token: "jwt" }],
|
||||
["/api/admin/companies/2/privacy-notice", { method: "PUT", body: { textEn: "a", textMs: "b" }, token: "jwt" }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth
|
||||
import CompaniesPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "INS", status: "A" }]);
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
|
||||
});
|
||||
@@ -24,7 +24,7 @@ describe("CompaniesPage fixes", () => {
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Change code" }));
|
||||
const input = screen.getByLabelText("New code");
|
||||
await userEvent.clear(input);
|
||||
await userEvent.type(input, " INS ");
|
||||
await userEvent.type(input, " ins ");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Confirm" }));
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("alert")).toBeInTheDocument();
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ isSuper: true, apiGet: vi.fn(), getPrivacyNotice: vi.fn(), savePrivacyNotice: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ loading: false, isSuper: mocks.isSuper }) }));
|
||||
vi.mock("@/app/lib/services/adminRegistration", () => ({
|
||||
getPrivacyNotice: mocks.getPrivacyNotice,
|
||||
savePrivacyNotice: mocks.savePrivacyNotice,
|
||||
}));
|
||||
|
||||
import CompaniesPage from "./page";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
|
||||
mocks.getPrivacyNotice.mockReset().mockResolvedValue({ id: 3, companyId: 1, textEn: "Old EN", textMs: "Old MS", createdBy: "boss", createdAt: "2026-11-30T10:00:00" });
|
||||
mocks.savePrivacyNotice.mockReset().mockResolvedValue({ id: 4, companyId: 1, textEn: "x", textMs: "y", createdBy: "boss", createdAt: "2026-12-01T09:30:00" });
|
||||
mocks.isSuper = true;
|
||||
});
|
||||
|
||||
async function openEditor() {
|
||||
render(<CompaniesPage />);
|
||||
const row = (await screen.findByText("Insight")).closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: "Privacy notice" }));
|
||||
}
|
||||
|
||||
describe("Companies privacy notice editor", () => {
|
||||
it("loads both languages and shows who changed it last", async () => {
|
||||
await openEditor();
|
||||
expect(await screen.findByDisplayValue("Old EN")).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue("Old MS")).toBeInTheDocument();
|
||||
expect(screen.getByText(/boss/)).toBeInTheDocument();
|
||||
expect(mocks.getPrivacyNotice).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it("saves the edited text", async () => {
|
||||
await openEditor();
|
||||
const en = await screen.findByLabelText("English");
|
||||
await userEvent.clear(en);
|
||||
await userEvent.type(en, "New EN");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save notice" }));
|
||||
await waitFor(() => expect(mocks.savePrivacyNotice).toHaveBeenCalledWith(1, { textEn: "New EN", textMs: "Old MS" }));
|
||||
});
|
||||
|
||||
it("shows the server error and starts empty when there is no notice", async () => {
|
||||
mocks.getPrivacyNotice.mockResolvedValue(null);
|
||||
mocks.savePrivacyNotice.mockRejectedValue(new ApiError("Notice text is required.", 400, { error: "Notice text is required." }));
|
||||
await openEditor();
|
||||
const en = (await screen.findByLabelText("English")) as HTMLTextAreaElement;
|
||||
expect(en.value).toBe("");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save notice" }));
|
||||
expect(await screen.findByText("Notice text is required.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not crash when the notice has no createdAt or createdBy", async () => {
|
||||
mocks.getPrivacyNotice.mockResolvedValue({ id: 3, companyId: 1, textEn: "Old EN", textMs: "Old MS" });
|
||||
await openEditor();
|
||||
expect(await screen.findByDisplayValue("Old EN")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Last changed/i)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not offer the editor to a non-super admin", async () => {
|
||||
mocks.isSuper = false;
|
||||
render(<CompaniesPage />);
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Privacy notice" })).toBeNull());
|
||||
expect(mocks.getPrivacyNotice).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
@@ -38,7 +39,7 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
|
||||
if ((mode === "code" ? newCode : form.code).trim() === "" && (mode === "code" || !form.id)) {
|
||||
return setError(t("CompCodeRequired"));
|
||||
}
|
||||
if (mode === "code" && newCode.trim().toLowerCase() === company.code.toLowerCase()) {
|
||||
if (mode === "code" && newCode.trim().toUpperCase() === company.code) {
|
||||
return setError(t("CompCodeUnchanged"));
|
||||
}
|
||||
setError(null);
|
||||
@@ -73,7 +74,7 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
|
||||
<p className="text-sm">{t("CompChangeCodeWarning")}</p>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company-new-code">{t("CompNewCode")}</Label>
|
||||
<Input id="company-new-code" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
|
||||
<Input id="company-new-code" className="uppercase" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
@@ -85,7 +86,7 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
|
||||
{!form.id && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company-code">{t("Code")}</Label>
|
||||
<Input id="company-code" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
|
||||
<Input id="company-code" className="uppercase" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-1.5">
|
||||
@@ -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} />}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import CompaniesPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 2, name: "Clever", code: "cv", status: "A" }]);
|
||||
mocks.apiPost.mockReset().mockResolvedValue({ id: 2, code: "CV" });
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
|
||||
});
|
||||
|
||||
async function openChangeCode() {
|
||||
render(<CompaniesPage />);
|
||||
const row = (await screen.findByText("Clever")).closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /change code/i }));
|
||||
return screen.getByLabelText("New code");
|
||||
}
|
||||
|
||||
describe("CompaniesPage company codes in capitals", () => {
|
||||
it("treats a change of case as a change and posts it", async () => {
|
||||
const code = await openChangeCode();
|
||||
await userEvent.clear(code);
|
||||
await userEvent.type(code, "CV");
|
||||
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
|
||||
await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies/2/code", { code: "CV" }));
|
||||
});
|
||||
|
||||
it("still refuses the same code typed in any case", async () => {
|
||||
mocks.apiGet.mockResolvedValue([{ id: 2, name: "Clever", code: "CV", status: "A" }]);
|
||||
const code = await openChangeCode();
|
||||
await userEvent.clear(code);
|
||||
await userEvent.type(code, "cv");
|
||||
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
|
||||
expect(await screen.findByRole("alert")).toBeInTheDocument();
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows code inputs in capitals", async () => {
|
||||
const code = await openChangeCode();
|
||||
expect(code).toHaveClass("uppercase");
|
||||
await userEvent.keyboard("{Escape}");
|
||||
await userEvent.click(screen.getByRole("button", { name: /add company/i }));
|
||||
expect(screen.getByLabelText("Code")).toHaveClass("uppercase");
|
||||
});
|
||||
});
|
||||
@@ -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,60 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||||
import { EmptyState } from "@/app/components/ui/states";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
||||
import { cn } from "@/app/lib/utils";
|
||||
|
||||
export interface DashColumn<R> {
|
||||
label: string;
|
||||
numeric?: boolean;
|
||||
cell: (row: R) => ReactNode;
|
||||
}
|
||||
|
||||
/** A titled table that stacks into label/value cards below md (one DOM, CSS only). */
|
||||
export function DashTable<R>({ title, empty, columns, rows, rowKey }: {
|
||||
title: string;
|
||||
empty: string;
|
||||
columns: DashColumn<R>[];
|
||||
rows: R[];
|
||||
rowKey: (row: R) => string;
|
||||
}) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">{title}</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
{rows.length === 0 ? (
|
||||
<EmptyState title={empty} className="py-6" />
|
||||
) : (
|
||||
<Table aria-label={title} className="max-md:block">
|
||||
<TableHeader className="max-md:hidden">
|
||||
<TableRow>
|
||||
{columns.map((c) => (
|
||||
<TableHead key={c.label} className={cn(c.numeric && "text-right")}>{c.label}</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="max-md:block max-md:[&_tr:last-child]:border">
|
||||
{rows.map((row) => (
|
||||
<TableRow key={rowKey(row)} className="max-md:mb-3 max-md:block max-md:rounded-lg max-md:border max-md:p-2">
|
||||
{columns.map((c) => (
|
||||
<TableCell
|
||||
key={c.label}
|
||||
data-label={c.label}
|
||||
className={cn(
|
||||
"max-md:flex max-md:justify-between max-md:gap-4 max-md:whitespace-normal max-md:px-1 max-md:py-1",
|
||||
"max-md:before:font-medium max-md:before:text-muted-foreground max-md:before:content-[attr(data-label)]",
|
||||
c.numeric && "text-right tabular max-md:text-left",
|
||||
)}
|
||||
>
|
||||
{c.cell(row)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||||
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/app/components/ui/chart";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { getLeadDashboard, type LeadDashboard } from "@/app/lib/services/adminDashboard";
|
||||
import { DashTable, type DashColumn } from "./DashTable";
|
||||
|
||||
type Preset = "this" | "last" | "custom";
|
||||
type Range = { from?: string; to?: string };
|
||||
|
||||
const DASH = "–";
|
||||
const pct = (num: number, den: number) => (den > 0 ? `${Math.round((num / den) * 100)}%` : DASH);
|
||||
|
||||
/** First and last day of the previous calendar month, as seen in Kuala Lumpur right now. */
|
||||
function lastMonthRange(): Range {
|
||||
const today = new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
|
||||
const [y, m] = today.split("-").map(Number);
|
||||
const py = m === 1 ? y - 1 : y;
|
||||
const pm = m === 1 ? 12 : m - 1;
|
||||
const mm = String(pm).padStart(2, "0");
|
||||
const lastDay = new Date(Date.UTC(y, m - 1, 0)).getUTCDate();
|
||||
return { from: `${py}-${mm}-01`, to: `${py}-${mm}-${lastDay}` };
|
||||
}
|
||||
|
||||
function bucketLabel(bucket: string, kind: "DAY" | "MONTH"): string {
|
||||
const [y, m, d] = bucket.split("-");
|
||||
if (kind === "DAY") return `${d}/${m}`;
|
||||
return new Date(Date.UTC(Number(y), Number(m) - 1, 1)).toLocaleString("en-GB", { month: "short", year: "numeric", timeZone: "UTC" });
|
||||
}
|
||||
|
||||
function Tile({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div role="group" aria-label={label} className="rounded-xl border bg-card p-4">
|
||||
<div className="text-sm text-muted-foreground">{label}</div>
|
||||
<div className="mt-1 text-2xl font-semibold tabular">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LeadDashboard() {
|
||||
const t = useT();
|
||||
const { companyId, showCompanyColumn, codeOf } = useCompanyScope();
|
||||
const [preset, setPreset] = useState<Preset>("this");
|
||||
const [customFrom, setCustomFrom] = useState("");
|
||||
const [customTo, setCustomTo] = useState("");
|
||||
const [data, setData] = useState<LeadDashboard | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [refusedPeriod, setRefusedPeriod] = useState(false);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
|
||||
const range = useMemo<Range | null>(() => {
|
||||
if (preset === "this") return {};
|
||||
if (preset === "last") return lastMonthRange();
|
||||
return customFrom && customTo && customFrom <= customTo ? { from: customFrom, to: customTo } : null;
|
||||
}, [preset, customFrom, customTo]);
|
||||
const reversed = preset === "custom" && !!customFrom && !!customTo && customFrom > customTo;
|
||||
const from = range?.from;
|
||||
const to = range?.to;
|
||||
|
||||
useEffect(() => {
|
||||
if (!range) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets data/error before the period/company/reloadKey-triggered fetch below, which is the actual synchronization.
|
||||
setData(null);
|
||||
setError(null);
|
||||
getLeadDashboard({ from, to, companyId })
|
||||
.then((d) => { if (!cancelled) setData(d); })
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return;
|
||||
const refused = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "INVALID_PERIOD";
|
||||
setError(refused ? err.message : t("DashLoadFailed"));
|
||||
setRefusedPeriod(refused);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- `range` is derived from from/to.
|
||||
}, [from, to, companyId, reloadKey, !!range, t]);
|
||||
|
||||
const presets: [Preset, string][] = [["this", t("DashThisMonth")], ["last", t("DashLastMonth")], ["custom", t("DashCustom")]];
|
||||
const chartConfig = { captures: { label: t("DashCaptures"), color: "var(--chart-1)" }, wins: { label: t("DashWins"), color: "var(--chart-2)" } } satisfies ChartConfig;
|
||||
|
||||
const eventCols: DashColumn<LeadDashboard["events"][number]>[] = [
|
||||
{ label: t("DashEvent"), cell: (r) => <Link href={`/event-leads/${r.eventUuid}`} className="font-medium text-primary underline-offset-4 hover:underline">{r.name}</Link> },
|
||||
...(showCompanyColumn ? [{ label: t("Company"), cell: (r: { companyId: number }) => codeOf(r.companyId) }] : []),
|
||||
{ label: t("DashCaptures"), numeric: true, cell: (r) => r.captures },
|
||||
{ label: t("LeadNew"), numeric: true, cell: (r) => r.newLeads },
|
||||
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
|
||||
{ label: t("DashConversion"), numeric: true, cell: (r) => pct(r.won, r.captures) },
|
||||
];
|
||||
const salesCols: DashColumn<LeadDashboard["salespeople"][number]>[] = [
|
||||
{ label: t("DashSalesperson"), cell: (r) => (r.userId == null ? t("DashUnassigned") : r.name ?? t("DashUnknownUser")) },
|
||||
{ label: t("DashAssigned"), numeric: true, cell: (r) => r.assigned },
|
||||
{ label: t("DashWorked"), numeric: true, cell: (r) => r.worked },
|
||||
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
|
||||
{ label: t("LeadLost"), numeric: true, cell: (r) => r.lost },
|
||||
{ label: t("DashConversion"), numeric: true, cell: (r) => pct(r.won, r.assigned) },
|
||||
{ label: t("DashOverdueShort"), numeric: true, cell: (r) => r.overdue },
|
||||
];
|
||||
const interestCols: DashColumn<LeadDashboard["interests"][number]>[] = [
|
||||
{ label: t("DashInterest"), cell: (r) => r.name },
|
||||
{ label: t("DashCaptures"), numeric: true, cell: (r) => r.captures },
|
||||
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
|
||||
];
|
||||
|
||||
const funnelRows: [keyof LeadDashboard["funnel"], string][] = [
|
||||
["OPEN", t("LeadOpen")], ["CONTACTED", t("LeadContacted")], ["QUALIFIED", t("LeadQualified")], ["WON", t("LeadWon")], ["LOST", t("LeadLost")],
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
{presets.map(([key, label]) => (
|
||||
<Button key={key} variant={preset === key ? "default" : "outline"} aria-pressed={preset === key} onClick={() => setPreset(key)}>{label}</Button>
|
||||
))}
|
||||
{preset === "custom" && (
|
||||
<>
|
||||
<DatePicker aria-label={t("DashFrom")} value={customFrom} onChange={setCustomFrom} className="w-40" />
|
||||
<DatePicker aria-label={t("DashTo")} value={customTo} onChange={setCustomTo} className="w-40" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{reversed && <p role="alert" className="text-sm text-destructive">{t("DashRangeReversed")}</p>}
|
||||
|
||||
{range && error && <ErrorState message={error} onRetry={refusedPeriod ? undefined : () => setReloadKey((k) => k + 1)} />}
|
||||
{range && !error && !data && <Skeleton className="h-40 w-full" />}
|
||||
|
||||
{range && data && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3 lg:grid-cols-6">
|
||||
<Tile label={t("DashCaptures")} value={String(data.captures)} />
|
||||
<Tile label={t("DashNewLeads")} value={String(data.newLeads)} />
|
||||
<Tile label={t("DashWonInPeriod")} value={String(data.wonInPeriod)} />
|
||||
<Tile label={t("DashConversionRate")} value={pct(data.funnel.WON, data.captures)} />
|
||||
<Tile label={t("DashMedianDays")} value={data.medianDaysToWin == null ? DASH : String(data.medianDaysToWin)} />
|
||||
<Tile label={t("DashOverdue")} value={String(data.overdueFollowUps)} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">{t("DashFunnel")}</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<ul aria-label={t("DashLeadFunnelLabel")} className="space-y-2">
|
||||
{funnelRows.map(([key, label]) => {
|
||||
const max = Math.max(1, ...Object.values(data.funnel));
|
||||
return (
|
||||
<li key={key} className="flex items-center gap-2 text-sm">
|
||||
<span className="w-24 shrink-0">{label}</span>
|
||||
<span className="h-4 min-w-0 flex-1"><span className="block h-full rounded bg-primary" style={{ width: `${(data.funnel[key] / max) * 100}%` }} /></span>
|
||||
<span className="w-10 shrink-0 text-right tabular">{data.funnel[key]}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">{t("DashTrend")}</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<ChartContainer config={chartConfig} role="img" aria-label={t("DashTrend")} className="aspect-auto h-56 w-full">
|
||||
<BarChart data={data.trend.map((p) => ({ ...p, label: bucketLabel(p.bucket, data.bucket) }))}>
|
||||
<CartesianGrid vertical={false} />
|
||||
<XAxis dataKey="label" tickLine={false} axisLine={false} />
|
||||
<YAxis allowDecimals={false} width={32} tickLine={false} axisLine={false} />
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Bar dataKey="captures" fill="var(--color-captures)" radius={2} />
|
||||
<Bar dataKey="wins" fill="var(--color-wins)" radius={2} />
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<DashTable title={t("DashByEvent")} empty={t("DashEmpty")} columns={eventCols} rows={data.events} rowKey={(r) => r.eventUuid} />
|
||||
<DashTable title={t("DashBySalesperson")} empty={t("DashEmpty")} columns={salesCols} rows={data.salespeople} rowKey={(r) => String(r.userId)} />
|
||||
<DashTable title={t("DashByInterest")} empty={t("DashEmpty")} columns={interestCols} rows={data.interests} rowKey={(r) => String(r.interestId)} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
import * as React from "react"
|
||||
import * as RechartsPrimitive from "recharts"
|
||||
import type { TooltipValueType } from "recharts"
|
||||
|
||||
import { cn } from "@/app/lib/utils"
|
||||
|
||||
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||
const THEMES = { light: "", dark: ".dark" } as const
|
||||
|
||||
const INITIAL_DIMENSION = { width: 320, height: 200 } as const
|
||||
type TooltipNameType = number | string
|
||||
|
||||
export type ChartConfig = Record<
|
||||
string,
|
||||
{
|
||||
label?: React.ReactNode
|
||||
icon?: React.ComponentType
|
||||
} & (
|
||||
| { color?: string; theme?: never }
|
||||
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
||||
)
|
||||
>
|
||||
|
||||
type ChartContextProps = {
|
||||
config: ChartConfig
|
||||
}
|
||||
|
||||
const ChartContext = React.createContext<ChartContextProps | null>(null)
|
||||
|
||||
function useChart() {
|
||||
const context = React.useContext(ChartContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useChart must be used within a <ChartContainer />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function ChartContainer({
|
||||
id,
|
||||
className,
|
||||
children,
|
||||
config,
|
||||
initialDimension = INITIAL_DIMENSION,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
config: ChartConfig
|
||||
children: React.ComponentProps<
|
||||
typeof RechartsPrimitive.ResponsiveContainer
|
||||
>["children"]
|
||||
initialDimension?: {
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
}) {
|
||||
const uniqueId = React.useId()
|
||||
const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`
|
||||
|
||||
return (
|
||||
<ChartContext.Provider value={{ config }}>
|
||||
<div
|
||||
data-slot="chart"
|
||||
data-chart={chartId}
|
||||
className={cn(
|
||||
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-none [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChartStyle id={chartId} config={config} />
|
||||
<RechartsPrimitive.ResponsiveContainer
|
||||
initialDimension={initialDimension}
|
||||
>
|
||||
{children}
|
||||
</RechartsPrimitive.ResponsiveContainer>
|
||||
</div>
|
||||
</ChartContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||
const colorConfig = Object.entries(config).filter(
|
||||
([, config]) => config.theme ?? config.color
|
||||
)
|
||||
|
||||
if (!colorConfig.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<style
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: Object.entries(THEMES)
|
||||
.map(
|
||||
([theme, prefix]) => `
|
||||
${prefix} [data-chart=${id}] {
|
||||
${colorConfig
|
||||
.map(([key, itemConfig]) => {
|
||||
const color =
|
||||
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
|
||||
itemConfig.color
|
||||
return color ? ` --color-${key}: ${color};` : null
|
||||
})
|
||||
.join("\n")}
|
||||
}
|
||||
`
|
||||
)
|
||||
.join("\n"),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartTooltip = RechartsPrimitive.Tooltip
|
||||
|
||||
function ChartTooltipContent({
|
||||
active,
|
||||
payload,
|
||||
className,
|
||||
indicator = "dot",
|
||||
hideLabel = false,
|
||||
hideIndicator = false,
|
||||
label,
|
||||
labelFormatter,
|
||||
labelClassName,
|
||||
formatter,
|
||||
color,
|
||||
nameKey,
|
||||
labelKey,
|
||||
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
||||
React.ComponentProps<"div"> & {
|
||||
hideLabel?: boolean
|
||||
hideIndicator?: boolean
|
||||
indicator?: "line" | "dot" | "dashed"
|
||||
nameKey?: string
|
||||
labelKey?: string
|
||||
} & Omit<
|
||||
RechartsPrimitive.DefaultTooltipContentProps<
|
||||
TooltipValueType,
|
||||
TooltipNameType
|
||||
>,
|
||||
"accessibilityLayer"
|
||||
>) {
|
||||
const { config } = useChart()
|
||||
|
||||
const tooltipLabel = React.useMemo(() => {
|
||||
if (hideLabel || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [item] = payload
|
||||
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const value =
|
||||
!labelKey && typeof label === "string"
|
||||
? (config[label]?.label ?? label)
|
||||
: itemConfig?.label
|
||||
|
||||
if (labelFormatter) {
|
||||
return (
|
||||
<div className={cn("font-medium", labelClassName)}>
|
||||
{labelFormatter(value, payload)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <div className={cn("font-medium", labelClassName)}>{value}</div>
|
||||
}, [
|
||||
label,
|
||||
labelFormatter,
|
||||
payload,
|
||||
hideLabel,
|
||||
labelClassName,
|
||||
config,
|
||||
labelKey,
|
||||
])
|
||||
|
||||
if (!active || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const nestLabel = payload.length === 1 && indicator !== "dot"
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{!nestLabel ? tooltipLabel : null}
|
||||
<div className="grid gap-1.5">
|
||||
{payload
|
||||
.filter((item) => item.type !== "none")
|
||||
.map((item, index) => {
|
||||
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const indicatorColor = color ?? item.payload?.fill ?? item.color
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={cn(
|
||||
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
|
||||
indicator === "dot" && "items-center"
|
||||
)}
|
||||
>
|
||||
{formatter && item?.value !== undefined && item.name ? (
|
||||
formatter(item.value, item.name, item, index, item.payload)
|
||||
) : (
|
||||
<>
|
||||
{itemConfig?.icon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
!hideIndicator && (
|
||||
<div
|
||||
className={cn(
|
||||
"shrink-0 rounded-[2px] border-[color:var(--color-border)] bg-[var(--color-bg)]",
|
||||
{
|
||||
"h-2.5 w-2.5": indicator === "dot",
|
||||
"w-1": indicator === "line",
|
||||
"w-0 border-[1.5px] border-dashed bg-transparent":
|
||||
indicator === "dashed",
|
||||
"my-0.5": nestLabel && indicator === "dashed",
|
||||
}
|
||||
)}
|
||||
style={
|
||||
{
|
||||
"--color-bg": indicatorColor,
|
||||
"--color-border": indicatorColor,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-1 justify-between leading-none",
|
||||
nestLabel ? "items-end" : "items-center"
|
||||
)}
|
||||
>
|
||||
<div className="grid gap-1.5">
|
||||
{nestLabel ? tooltipLabel : null}
|
||||
<span className="text-muted-foreground">
|
||||
{itemConfig?.label ?? item.name}
|
||||
</span>
|
||||
</div>
|
||||
{item.value != null && (
|
||||
<span className="font-mono font-medium text-foreground tabular-nums">
|
||||
{typeof item.value === "number"
|
||||
? item.value.toLocaleString()
|
||||
: String(item.value)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartLegend = RechartsPrimitive.Legend
|
||||
|
||||
function ChartLegendContent({
|
||||
className,
|
||||
hideIcon = false,
|
||||
payload,
|
||||
verticalAlign = "bottom",
|
||||
nameKey,
|
||||
}: React.ComponentProps<"div"> & {
|
||||
hideIcon?: boolean
|
||||
nameKey?: string
|
||||
} & RechartsPrimitive.DefaultLegendContentProps) {
|
||||
const { config } = useChart()
|
||||
|
||||
if (!payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-4",
|
||||
verticalAlign === "top" ? "pb-3" : "pt-3",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{payload
|
||||
.filter((item) => item.type !== "none")
|
||||
.map((item, index) => {
|
||||
const key = `${nameKey ?? item.dataKey ?? "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={cn(
|
||||
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
{itemConfig?.icon && !hideIcon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
<div
|
||||
className="h-2 w-2 shrink-0 rounded-[2px]"
|
||||
style={{
|
||||
backgroundColor: item.color,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{itemConfig?.label}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to extract item config from a payload.
|
||||
function getPayloadConfigFromPayload(
|
||||
config: ChartConfig,
|
||||
payload: unknown,
|
||||
key: string
|
||||
) {
|
||||
if (typeof payload !== "object" || payload === null) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const payloadPayload =
|
||||
"payload" in payload &&
|
||||
typeof payload.payload === "object" &&
|
||||
payload.payload !== null
|
||||
? payload.payload
|
||||
: undefined
|
||||
|
||||
let configLabelKey: string = key
|
||||
|
||||
if (
|
||||
key in payload &&
|
||||
typeof payload[key as keyof typeof payload] === "string"
|
||||
) {
|
||||
configLabelKey = payload[key as keyof typeof payload] as string
|
||||
} else if (
|
||||
payloadPayload &&
|
||||
key in payloadPayload &&
|
||||
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
|
||||
) {
|
||||
configLabelKey = payloadPayload[
|
||||
key as keyof typeof payloadPayload
|
||||
] as string
|
||||
}
|
||||
|
||||
return configLabelKey in config ? config[configLabelKey] : config[key]
|
||||
}
|
||||
|
||||
export {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
ChartLegend,
|
||||
ChartLegendContent,
|
||||
ChartStyle,
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { resolveMessage } from "./t";
|
||||
|
||||
// The sidebar labels the BO_DASHBOARD module by its name as a message key; without a default it shows the raw code.
|
||||
describe("BO_DASHBOARD label", () => {
|
||||
it("resolves to Dashboard with an empty catalog", () => {
|
||||
expect(resolveMessage({}, "BO_DASHBOARD")).toBe("Dashboard");
|
||||
});
|
||||
});
|
||||
@@ -117,6 +117,36 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
ModulesParent: "Parent",
|
||||
DashWelcome: "Welcome, {name}",
|
||||
DashWelcomeFallbackName: "admin",
|
||||
DashLeadFunnelLabel: "Lead funnel",
|
||||
DashThisMonth: "This month",
|
||||
DashLastMonth: "Last month",
|
||||
DashCustom: "Custom",
|
||||
DashFrom: "From",
|
||||
DashTo: "To",
|
||||
DashRangeReversed: "The start date must not be after the end date.",
|
||||
DashLoadFailed: "Could not load the dashboard.",
|
||||
DashCaptures: "Captures",
|
||||
DashNewLeads: "New leads",
|
||||
DashWonInPeriod: "Won in period",
|
||||
DashConversionRate: "Conversion rate",
|
||||
DashMedianDays: "Median days to win",
|
||||
DashOverdue: "Overdue follow-ups",
|
||||
DashFunnel: "Funnel",
|
||||
DashTrend: "Captures and wins over time",
|
||||
DashWins: "Wins",
|
||||
DashByEvent: "By event",
|
||||
DashBySalesperson: "By salesperson",
|
||||
DashByInterest: "By interest",
|
||||
DashEvent: "Event",
|
||||
DashSalesperson: "Salesperson",
|
||||
DashInterest: "Interest",
|
||||
DashAssigned: "Assigned",
|
||||
DashWorked: "Worked",
|
||||
DashConversion: "Conversion",
|
||||
DashOverdueShort: "Overdue",
|
||||
DashUnassigned: "Unassigned",
|
||||
DashUnknownUser: "Unknown user",
|
||||
DashEmpty: "No data for this period",
|
||||
Close: "Close",
|
||||
Enabled: "Enabled",
|
||||
Admin: "Admin",
|
||||
@@ -395,6 +425,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LsSettingsLoadFailed: "Failed to load the settings",
|
||||
LsSaveFailed: "Failed to save",
|
||||
BO_AUDIT_LOG: "Audit log",
|
||||
BO_DASHBOARD: "Dashboard",
|
||||
BO_LEADS_EDIT: "Lead editing",
|
||||
BO_LEADS_EXPORT: "Lead export",
|
||||
AuditWho: "Who",
|
||||
@@ -432,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;
|
||||
|
||||
@@ -18,7 +18,10 @@ const HTML_SINKS = [
|
||||
] as const;
|
||||
type Sink = (typeof HTML_SINKS)[number];
|
||||
|
||||
const SINK_ALLOWED: Record<string, Sink[]> = {};
|
||||
const SINK_ALLOWED: Record<string, Sink[]> = {
|
||||
// shadcn chart: a <style> built from the chart's own colour config (code constants), never from data.
|
||||
"components/ui/chart.tsx": ["dangerouslySetInnerHTML"],
|
||||
};
|
||||
|
||||
function sourceFiles(dir: string, out: string[] = []): string[] {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import { getLeadDashboard } from "./adminDashboard";
|
||||
|
||||
beforeEach(() => mocks.apiGet.mockReset().mockResolvedValue({}));
|
||||
|
||||
describe("adminDashboard", () => {
|
||||
it("sends no query string when no params are given", async () => {
|
||||
await getLeadDashboard({});
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/dashboard/leads");
|
||||
});
|
||||
|
||||
it("sends only the given params", async () => {
|
||||
await getLeadDashboard({ from: "2026-11-01", to: "2026-11-30", companyId: 2 });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2");
|
||||
await getLeadDashboard({ companyId: 3 });
|
||||
expect(mocks.apiGet).toHaveBeenLastCalledWith("/api/dashboard/leads?companyId=3");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { apiGet } from "@/app/lib/clientApi";
|
||||
|
||||
export interface LeadDashboard {
|
||||
from: string;
|
||||
to: string;
|
||||
bucket: "DAY" | "MONTH";
|
||||
captures: number;
|
||||
newLeads: number;
|
||||
wonInPeriod: number;
|
||||
medianDaysToWin: number | null;
|
||||
overdueFollowUps: number;
|
||||
funnel: { OPEN: number; CONTACTED: number; QUALIFIED: number; WON: number; LOST: number };
|
||||
trend: { bucket: string; captures: number; wins: number }[];
|
||||
events: { eventUuid: string; name: string; companyId: number; captures: number; newLeads: number; won: number }[];
|
||||
salespeople: { userId: number | null; name: string | null; assigned: number; worked: number; won: number; lost: number; overdue: number }[];
|
||||
interests: { interestId: number; name: string; captures: number; won: number }[];
|
||||
}
|
||||
|
||||
export interface LeadDashboardParams {
|
||||
from?: string;
|
||||
to?: string;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export function getLeadDashboard({ from, to, companyId }: LeadDashboardParams): Promise<LeadDashboard> {
|
||||
const qs = new URLSearchParams();
|
||||
if (from) qs.set("from", from);
|
||||
if (to) qs.set("to", to);
|
||||
if (companyId) qs.set("companyId", String(companyId));
|
||||
const s = qs.toString();
|
||||
return apiGet<LeadDashboard>(`/api/dashboard/leads${s ? `?${s}` : ""}`);
|
||||
}
|
||||
@@ -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,173 @@
|
||||
import { render, screen, waitFor, within, fireEvent } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getLeadDashboard: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
useCompanyScope: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminDashboard", () => ({ getLeadDashboard: mocks.getLeadDashboard }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import HomePage from "./page";
|
||||
|
||||
const DATA = {
|
||||
from: "2026-12-01", to: "2026-12-01", bucket: "DAY",
|
||||
captures: 40, newLeads: 25, wonInPeriod: 8, medianDaysToWin: 4.5, overdueFollowUps: 3,
|
||||
funnel: { OPEN: 11, CONTACTED: 12, QUALIFIED: 13, WON: 8, LOST: 6 },
|
||||
trend: [{ bucket: "2026-12-01", captures: 5, wins: 1 }],
|
||||
events: [{ eventUuid: "ev-1", name: "Expo KL", companyId: 2, captures: 20, newLeads: 10, won: 5 }],
|
||||
salespeople: [
|
||||
{ userId: null, name: null, assigned: 7, worked: 2, won: 1, lost: 0, overdue: 4 },
|
||||
{ userId: 9, name: null, assigned: 0, worked: 0, won: 0, lost: 0, overdue: 0 },
|
||||
{ userId: 5, name: "Sam", assigned: 10, worked: 6, won: 3, lost: 1, overdue: 2 },
|
||||
],
|
||||
interests: [{ interestId: 1, name: "Catering", captures: 15, won: 4 }],
|
||||
};
|
||||
const scope = (companyId?: number, showCompanyColumn = false) => ({
|
||||
companyId, companies: [], showCompanyColumn, codeOf: (id?: number | null) => (id === 2 ? "CV" : ""), setCompanyId: vi.fn(),
|
||||
});
|
||||
const tile = (name: string) => within(screen.getByRole("group", { name }));
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getLeadDashboard.mockReset().mockResolvedValue(DATA);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ name: "Alice", loading: false, isSuper: false, hasModule: (m: string) => m === "BO_DASHBOARD" });
|
||||
mocks.useCompanyScope.mockReset().mockReturnValue(scope());
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe("home page lead dashboard", () => {
|
||||
it("shows only the welcome and never calls the API without the module", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ name: "Alice", loading: false, hasModule: () => false });
|
||||
render(<HomePage />);
|
||||
expect(screen.getByText("Welcome, Alice")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
|
||||
expect(mocks.getLeadDashboard).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows the welcome plus tiles with the This month default (no from/to)", async () => {
|
||||
render(<HomePage />);
|
||||
expect(screen.getByText("Welcome, Alice")).toBeInTheDocument();
|
||||
await screen.findByRole("group", { name: "Captures" });
|
||||
expect(tile("Captures").getByText("40")).toBeInTheDocument();
|
||||
expect(tile("New leads").getByText("25")).toBeInTheDocument();
|
||||
expect(tile("Won in period").getByText("8")).toBeInTheDocument();
|
||||
expect(tile("Conversion rate").getByText("20%")).toBeInTheDocument();
|
||||
expect(tile("Median days to win").getByText("4.5")).toBeInTheDocument();
|
||||
expect(tile("Overdue follow-ups").getByText("3")).toBeInTheDocument();
|
||||
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: undefined });
|
||||
});
|
||||
|
||||
it("shows a dash for a null median and for zero captures", async () => {
|
||||
mocks.getLeadDashboard.mockResolvedValue({ ...DATA, captures: 0, medianDaysToWin: null });
|
||||
render(<HomePage />);
|
||||
await waitFor(() => expect(tile("Conversion rate").getByText("–")).toBeInTheDocument());
|
||||
expect(tile("Median days to win").getByText("–")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the funnel counts and the trend chart", async () => {
|
||||
const { container } = render(<HomePage />);
|
||||
const funnel = await screen.findByRole("list", { name: "Lead funnel" });
|
||||
const items = within(funnel).getAllByRole("listitem").map((li) => li.textContent);
|
||||
expect(items).toEqual(["Open11", "Contacted12", "Qualified13", "Won8", "Lost6"]);
|
||||
expect(container.querySelector('[data-slot="chart"]')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the by-event, by-salesperson and by-interest tables", async () => {
|
||||
render(<HomePage />);
|
||||
const ev = within(await screen.findByRole("table", { name: "By event" }));
|
||||
expect(ev.getByRole("link", { name: "Expo KL" })).toHaveAttribute("href", "/event-leads/ev-1");
|
||||
expect(ev.getByText("25%")).toBeInTheDocument();
|
||||
expect(ev.queryByText("Company")).not.toBeInTheDocument();
|
||||
const sp = within(screen.getByRole("table", { name: "By salesperson" }));
|
||||
expect(sp.getByText("Unassigned")).toBeInTheDocument();
|
||||
expect(sp.getByText("Unknown user")).toBeInTheDocument();
|
||||
expect(sp.getByText("Sam")).toBeInTheDocument();
|
||||
expect(sp.getByText("30%")).toBeInTheDocument();
|
||||
expect(sp.getAllByText("–").length).toBe(1);
|
||||
const rowText = (name: string) => Array.from(sp.getByText(name).closest("tr")!.querySelectorAll("td")).map((td) => td.textContent);
|
||||
expect(rowText("Unassigned")).toEqual(["Unassigned", "7", "2", "1", "0", "14%", "4"]);
|
||||
expect(rowText("Sam")).toEqual(["Sam", "10", "6", "3", "1", "30%", "2"]);
|
||||
const it = within(screen.getByRole("table", { name: "By interest" }));
|
||||
expect(it.getByText("Catering")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows empty-state lines for empty lists", async () => {
|
||||
mocks.getLeadDashboard.mockResolvedValue({ ...DATA, events: [], salespeople: [], interests: [] });
|
||||
render(<HomePage />);
|
||||
await waitFor(() => expect(screen.getAllByText("No data for this period")).toHaveLength(3));
|
||||
});
|
||||
|
||||
it("sends the previous Malaysian month for Last month", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"], now: new Date("2026-12-01T10:00:00+08:00") });
|
||||
render(<HomePage />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Last month" }));
|
||||
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-11-01", to: "2026-11-30", companyId: undefined }));
|
||||
});
|
||||
|
||||
it("uses Malaysian time near midnight UTC and across a year boundary", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"], now: new Date("2026-12-31T20:00:00Z") }); // 2027-01-01 04:00 in KL
|
||||
render(<HomePage />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Last month" }));
|
||||
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-12-01", to: "2026-12-31", companyId: undefined }));
|
||||
});
|
||||
|
||||
it("rejects a reversed custom range without calling the API", async () => {
|
||||
render(<HomePage />);
|
||||
await screen.findByRole("group", { name: "Captures" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Custom" }));
|
||||
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
|
||||
mocks.getLeadDashboard.mockClear();
|
||||
pickDate("From", "2026-11-20");
|
||||
pickDate("To", "2026-11-10");
|
||||
expect(await screen.findByText("The start date must not be after the end date.")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
|
||||
expect(mocks.getLeadDashboard).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sends a valid custom range", async () => {
|
||||
render(<HomePage />);
|
||||
await screen.findByRole("group", { name: "Captures" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Custom" }));
|
||||
pickDate("From", "2026-11-10");
|
||||
pickDate("To", "2026-11-20");
|
||||
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-11-10", to: "2026-11-20", companyId: undefined }));
|
||||
});
|
||||
|
||||
it("sends the picked company and shows no Company column", async () => {
|
||||
mocks.useCompanyScope.mockReturnValue(scope(2, false));
|
||||
render(<HomePage />);
|
||||
const ev = within(await screen.findByRole("table", { name: "By event" }));
|
||||
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: 2 });
|
||||
expect(ev.queryByText("Company")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("on All companies sends no companyId and shows the Company column with the code", async () => {
|
||||
mocks.useCompanyScope.mockReturnValue(scope(undefined, true));
|
||||
render(<HomePage />);
|
||||
const ev = within(await screen.findByRole("table", { name: "By event" }));
|
||||
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: undefined });
|
||||
expect(ev.getByText("Company")).toBeInTheDocument();
|
||||
expect(ev.getByText("CV")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the API message for INVALID_PERIOD", async () => {
|
||||
mocks.getLeadDashboard.mockRejectedValue(new ApiError("Start date must be on or before end date.", 400, { error: "Start date must be on or before end date.", code: "INVALID_PERIOD" }));
|
||||
render(<HomePage />);
|
||||
expect(await screen.findByText("Start date must be on or before end date.")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a retryable error for other failures", async () => {
|
||||
mocks.getLeadDashboard.mockRejectedValueOnce(new Error("boom"));
|
||||
render(<HomePage />);
|
||||
expect(await screen.findByText("Could not load the dashboard.")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
|
||||
await screen.findByRole("group", { name: "Captures" });
|
||||
expect(tile("Captures").getByText("40")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ name: "Alice" }) }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ name: "Alice", hasModule: () => false }) }));
|
||||
|
||||
import HomePage from "./page";
|
||||
|
||||
|
||||
@@ -2,16 +2,20 @@
|
||||
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { LeadDashboard } from "@/app/components/dashboard/LeadDashboard";
|
||||
|
||||
export default function HomePage() {
|
||||
const t = useT();
|
||||
const { name } = useAdminAuth();
|
||||
const { name, hasModule } = useAdminAuth();
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl">{t("BackOfficeTitle")}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })}
|
||||
</p>
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl">{t("BackOfficeTitle")}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })}
|
||||
</p>
|
||||
</div>
|
||||
{hasModule("BO_DASHBOARD") && <LeadDashboard />}
|
||||
</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
+398
-1
@@ -13,10 +13,12 @@
|
||||
"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",
|
||||
"react-dom": "^19.2.8",
|
||||
"recharts": "3.10.1",
|
||||
"tailwind-merge": "^3.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -3183,6 +3185,36 @@
|
||||
"integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@reduxjs/toolkit": {
|
||||
"version": "2.16.0",
|
||||
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.16.0.tgz",
|
||||
"integrity": "sha512-MZAZNNvsNJrMttw/+rfBhay3+/zxPZNmuK/lFmahE+SAJTemxW643i+USptYg69guUohrtUu/4/XXbocOxVFIA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"@standard-schema/utils": "^0.3.0",
|
||||
"immer": "^11.2.14",
|
||||
"redux": "^5.0.1",
|
||||
"redux-thunk": "^3.1.0",
|
||||
"reselect": "^5.1.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "*",
|
||||
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
|
||||
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"react-redux": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-android-arm-eabi": {
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz",
|
||||
@@ -3527,7 +3559,12 @@
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@standard-schema/utils": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
|
||||
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@swc/helpers": {
|
||||
@@ -3701,6 +3738,69 @@
|
||||
"assertion-error": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-array": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
|
||||
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-color": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
|
||||
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-ease": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
|
||||
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-interpolate": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
|
||||
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-color": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-path": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
|
||||
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-scale": {
|
||||
"version": "4.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
|
||||
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-time": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-shape": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz",
|
||||
"integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-path": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-time": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
|
||||
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-timer": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
|
||||
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/deep-eql": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||
@@ -3759,6 +3859,12 @@
|
||||
"@types/react": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/use-sync-external-store": {
|
||||
"version": "0.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
|
||||
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "8.72.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz",
|
||||
@@ -5236,6 +5342,127 @@
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/d3-array": {
|
||||
"version": "3.2.5",
|
||||
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.5.tgz",
|
||||
"integrity": "sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"internmap": "1 - 2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-color": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.1.tgz",
|
||||
"integrity": "sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-ease": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.2.tgz",
|
||||
"integrity": "sha512-B5znKqRmKROAN4oHWQ50W/qisVjA9GXh2WMsVKdFVp4DxWmcrOsweqgUOUVsv5th96kwaZlokU6SlV4J3gak1w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-format": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.3.tgz",
|
||||
"integrity": "sha512-+F+/49swqmGuQJmSKnVMIDH/QkEFV5li9QRj0xm/KhyAUBv099O5PrvpQFxBp24PYph17Mnvt9mjKQV0ii0nMA==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-interpolate": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.2.tgz",
|
||||
"integrity": "sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-color": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-path": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.1.tgz",
|
||||
"integrity": "sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-scale": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.3.tgz",
|
||||
"integrity": "sha512-66cWobCNzcMvlfoaDHCxuIv9TBUWG1BLOWdv9kHHFuCr1JdqAWPvTmsaEYDD5NRMyWZ5+7u0GqiCDfMXMqh3hg==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-array": "2.10.0 - 3",
|
||||
"d3-format": "1 - 3",
|
||||
"d3-interpolate": "1.2.0 - 3",
|
||||
"d3-time": "2.1.1 - 3",
|
||||
"d3-time-format": "2 - 4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-shape": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.1.tgz",
|
||||
"integrity": "sha512-dm2o+lbKdzg9tY7GEag/dB9hcbodLfwkE/DkvqbELJXaMz0yKzWWhZqhbI7CKubukA7HnRyz0avdtvi7EPxPvw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-path": "^3.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-time": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.1.tgz",
|
||||
"integrity": "sha512-Ze7rjrhMzdeulh0/hjcfFj7XLAHOfowtEMfsoG6DU866HPynQNW7Wfen6hzXcqKTv8XzxvF6Hzr5XD6bMHr2ug==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-array": "2 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-time-format": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.1.tgz",
|
||||
"integrity": "sha512-22XaqjyCjpqgda20erhsOjGmC3vvYwTNYniKAd45W5UWLDF43moeOuV9qYpRqobIlsnK0UhnKZjUUJm3VgORUA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-time": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-timer": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.2.tgz",
|
||||
"integrity": "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/damerau-levenshtein": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",
|
||||
@@ -5346,6 +5573,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/decimal.js-light": {
|
||||
"version": "2.5.1",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
|
||||
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/deep-is": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
|
||||
@@ -5698,6 +5931,18 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/es-toolkit": {
|
||||
"version": "1.53.2",
|
||||
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.53.2.tgz",
|
||||
"integrity": "sha512-iUqZ+NlwH4jUgRmXZUxFBsV/9762TQEa1O4IXLFBmDEjVHScBytKuseX23I0+v9ShZ5MYxEx6WKNzm6IPnex8g==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"docs",
|
||||
"benchmarks",
|
||||
"tests/types",
|
||||
"tests/browser-compat"
|
||||
]
|
||||
},
|
||||
"node_modules/escalade": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
||||
@@ -6147,6 +6392,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eventemitter3": {
|
||||
"version": "5.0.4",
|
||||
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
|
||||
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/expect-type": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
|
||||
@@ -6660,6 +6911,16 @@
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/immer": {
|
||||
"version": "11.2.14",
|
||||
"resolved": "https://registry.npmjs.org/immer/-/immer-11.2.14.tgz",
|
||||
"integrity": "sha512-Xujh/D+NWN1mM/eJb30ASOOTrI74DA6BV+SdkvfeIvHt8Pk70h0lP5l4LRIvBcEujxbw7LbVTFvcxgGg6pgvKA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/immer"
|
||||
}
|
||||
},
|
||||
"node_modules/import-fresh": {
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
|
||||
@@ -6712,6 +6973,15 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/internmap": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
|
||||
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/is-array-buffer": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
|
||||
@@ -8580,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",
|
||||
@@ -8725,6 +9004,36 @@
|
||||
"react": "^19.2.8"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "19.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz",
|
||||
"integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/react-redux": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.1.tgz",
|
||||
"integrity": "sha512-vxMLT0lalUjbZPkoTepWyKAZbjIIFssNx/CEL9lTfwQBU6XpkGSmCNdcCIrkOBUgB68uftZMnbXVb6DwGnhRKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/use-sync-external-store": "^0.0.6",
|
||||
"use-sync-external-store": "^1.4.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.2.25 || ^19",
|
||||
"react": "^18.0 || ^19",
|
||||
"redux": "^5.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"redux": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-remove-scroll": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",
|
||||
@@ -8801,6 +9110,36 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/recharts": {
|
||||
"version": "3.10.1",
|
||||
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.10.1.tgz",
|
||||
"integrity": "sha512-QXFrvt6IVcw7eeZCoyXTwkIJAX3Dv1nyVhMicXJ47GsGDDpcN8z6o644DibE9XjpBTThtsomLKnTV6lc+cVFUA==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"www"
|
||||
],
|
||||
"dependencies": {
|
||||
"@reduxjs/toolkit": "^1.9.0 || 2.x.x",
|
||||
"clsx": "^2.1.1",
|
||||
"decimal.js-light": "^2.5.1",
|
||||
"es-toolkit": "^1.39.3",
|
||||
"eventemitter3": "^5.0.1",
|
||||
"immer": "^11.1.8",
|
||||
"react-redux": "8.x.x || 9.x.x",
|
||||
"reselect": "5.2.0",
|
||||
"tiny-invariant": "^1.3.3",
|
||||
"use-sync-external-store": "^1.2.2",
|
||||
"victory-vendor": "^37.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/redent": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz",
|
||||
@@ -8815,6 +9154,21 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/redux": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
|
||||
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/redux-thunk": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
|
||||
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"redux": "^5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reflect.getprototypeof": {
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
|
||||
@@ -8869,6 +9223,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reselect": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",
|
||||
"integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/resolve": {
|
||||
"version": "2.0.0-next.7",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.7.tgz",
|
||||
@@ -9732,6 +10092,12 @@
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/tiny-invariant": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
|
||||
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
|
||||
@@ -10205,6 +10571,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/use-sync-external-store": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz",
|
||||
"integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/util-deprecate": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
@@ -10212,6 +10587,28 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/victory-vendor": {
|
||||
"version": "37.4.1",
|
||||
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.4.1.tgz",
|
||||
"integrity": "sha512-geV4p2GVfVM9lgm9ZRS3pvsbAPS+BUGhM9W9nPzPHTKi+/+KjNrFXdgP6KkG+XspNZuvcXmchcrtklfuQ4gniw==",
|
||||
"license": "MIT AND ISC AND BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@types/d3-array": "^3.0.3",
|
||||
"@types/d3-ease": "^3.0.0",
|
||||
"@types/d3-interpolate": "^3.0.1",
|
||||
"@types/d3-scale": "^4.0.2",
|
||||
"@types/d3-shape": "^3.1.0",
|
||||
"@types/d3-time": "^3.0.0",
|
||||
"@types/d3-timer": "^3.0.0",
|
||||
"d3-array": "^3.1.6",
|
||||
"d3-ease": "^3.0.1",
|
||||
"d3-interpolate": "^3.0.1",
|
||||
"d3-scale": "^4.0.2",
|
||||
"d3-shape": "^3.1.0",
|
||||
"d3-time": "^3.0.0",
|
||||
"d3-timer": "^3.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "8.3.8",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz",
|
||||
|
||||
@@ -19,10 +19,12 @@
|
||||
"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",
|
||||
"react-dom": "^19.2.8",
|
||||
"recharts": "3.10.1",
|
||||
"tailwind-merge": "^3.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -44,6 +44,7 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_LEAD_SEARCH="/counter/lead/search";
|
||||
public static final String API_REST_COUNTER_LEAD_DETAIL="/counter/lead/detail/{leadUuid}";
|
||||
public static final String API_REST_COUNTER_LEAD_UPDATE="/counter/lead/update";
|
||||
public static final String API_REST_COUNTER_DASHBOARD_LEADS="/counter/dashboard/leads";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{eventLeadUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update";
|
||||
@@ -54,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}";
|
||||
|
||||
+1
-1
@@ -207,7 +207,7 @@ public class AdminAuthController {
|
||||
if (!StringUtils.hasText(username) || username.contains("@")) {
|
||||
return null;
|
||||
}
|
||||
String code = company == null ? "" : company.trim().toLowerCase();
|
||||
String code = company == null ? "" : company.trim().toUpperCase(java.util.Locale.ROOT);
|
||||
return code.isEmpty() ? username.trim() : username.trim() + "@" + code;
|
||||
}
|
||||
}
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminDashboardService;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Lead dashboard. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/dashboard")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminDashboardController {
|
||||
private final AdminDashboardService adminDashboardService;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_DASHBOARD")
|
||||
@GetMapping("/leads")
|
||||
public ResponseEntity<Map<String, Object>> leads(@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminDashboardService.leads(from, to, companyId));
|
||||
}
|
||||
}
|
||||
+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();
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
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.useraccess.AdminCompanyScope;
|
||||
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 java.time.Clock;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
|
||||
|
||||
/** Lead dashboard for the admin portal: validates the period and company scope here; services-counter aggregates. */
|
||||
@Service
|
||||
@SuppressWarnings("unchecked")
|
||||
public class AdminDashboardService {
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ZoneId KL = ZoneId.of("Asia/Kuala_Lumpur");
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
private final AdminCompanyScope scope;
|
||||
private final Clock clock;
|
||||
|
||||
@Autowired
|
||||
public AdminDashboardService(RestTemplateCustomUtil restTemplateUtil, AdminAuthenticationService adminAuthenticationService, AdminCompanyScope scope) {
|
||||
this(restTemplateUtil, adminAuthenticationService, scope, Clock.systemUTC());
|
||||
}
|
||||
|
||||
AdminDashboardService(RestTemplateCustomUtil restTemplateUtil, AdminAuthenticationService adminAuthenticationService, AdminCompanyScope scope, Clock clock) {
|
||||
this.restTemplateUtil = restTemplateUtil;
|
||||
this.adminAuthenticationService = adminAuthenticationService;
|
||||
this.scope = scope;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public Map<String, Object> leads(String fromParam, String toParam, Long companyId) {
|
||||
Long company = scope.scope(caller(), companyId);
|
||||
LocalDate today = LocalDate.now(clock.withZone(KL));
|
||||
LocalDate from = date(fromParam, today.withDayOfMonth(1));
|
||||
LocalDate to = date(toParam, today);
|
||||
if (from.isAfter(to)) throw invalid("Start date must be on or before end date.");
|
||||
long days = ChronoUnit.DAYS.between(from, to) + 1;
|
||||
if (days > 731) throw invalid("The period can be at most 731 days.");
|
||||
String bucket = days <= 62 ? "DAY" : "MONTH";
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", company);
|
||||
body.put("from", from.toString());
|
||||
body.put("to", to.toString());
|
||||
body.put("bucket", bucket);
|
||||
Map<String, Object> res = restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_DASHBOARD_LEADS), MAP, body).getBody();
|
||||
|
||||
Map<String, Object> out = new LinkedHashMap<>(res == null ? Map.of() : res);
|
||||
out.put("from", from.toString());
|
||||
out.put("to", to.toString());
|
||||
out.put("bucket", bucket);
|
||||
Map<Long, Map<String, Object>> users = new HashMap<>();
|
||||
List<Map<String, Object>> rows = out.get("salespeople") == null ? List.of() : (List<Map<String, Object>>) out.get("salespeople");
|
||||
out.put("salespeople", rows.stream().map(r -> {
|
||||
Map<String, Object> m = new LinkedHashMap<>(r);
|
||||
m.put("name", r.get("userId") instanceof Number n ? name(n.longValue(), users) : null);
|
||||
return m;
|
||||
}).toList());
|
||||
return out;
|
||||
}
|
||||
|
||||
/** User name, or null when the user no longer exists; one lookup per distinct id per request. */
|
||||
private String name(long id, Map<Long, Map<String, Object>> users) {
|
||||
if (!users.containsKey(id)) { // computeIfAbsent would not cache a missing user
|
||||
users.put(id, restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody());
|
||||
}
|
||||
Map<String, Object> u = users.get(id);
|
||||
return u == null || u.get("name") == null ? null : String.valueOf(u.get("name"));
|
||||
}
|
||||
|
||||
private static LocalDate date(String s, LocalDate dflt) {
|
||||
if (s == null || s.isBlank()) return dflt;
|
||||
try {
|
||||
return LocalDate.parse(s.trim());
|
||||
} catch (DateTimeParseException e) {
|
||||
throw invalid("Dates must be yyyy-MM-dd.");
|
||||
}
|
||||
}
|
||||
|
||||
private static RuntimeException invalid(String message) {
|
||||
return error(HttpStatus.BAD_REQUEST, message, "INVALID_PERIOD", null);
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
|
||||
return caller;
|
||||
}
|
||||
}
|
||||
+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 "";
|
||||
}
|
||||
+7
-7
@@ -84,9 +84,9 @@ class AdminAuthControllerCompanyTest {
|
||||
|
||||
ArgumentCaptor<AuthRequest> sent = ArgumentCaptor.forClass(AuthRequest.class);
|
||||
verify(auth).getToken(sent.capture());
|
||||
assertThat(sent.getValue().getUsername()).isEqualTo("john@ins");
|
||||
verify(auth).isLocked("john@ins");
|
||||
verify(auth).record("john@ins", "LOGIN_SUCCESS", null);
|
||||
assertThat(sent.getValue().getUsername()).isEqualTo("john@INS");
|
||||
verify(auth).isLocked("john@INS");
|
||||
verify(auth).record("john@INS", "LOGIN_SUCCESS", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,7 +114,7 @@ class AdminAuthControllerCompanyTest {
|
||||
void login_wrongCompanyOrUnknownUser_isBadLogin() throws Exception {
|
||||
when(auth.getToken(any())).thenReturn(null);
|
||||
login("{\"company\":\"nope\",\"username\":\"john\",\"password\":\"pw\"}").andExpect(status().isUnauthorized());
|
||||
verify(auth).record("john@nope", "LOGIN_FAIL", null);
|
||||
verify(auth).record("john@NOPE", "LOGIN_FAIL", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -124,7 +124,7 @@ class AdminAuthControllerCompanyTest {
|
||||
|
||||
login("{\"company\":\"ins\",\"username\":\"john\",\"password\":\"pw\"}")
|
||||
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.message").value("Invalid username or password"));
|
||||
verify(auth).record("john@ins", "LOGIN_FAIL", null);
|
||||
verify(auth).record("john@INS", "LOGIN_FAIL", null);
|
||||
verify(authenticationService).logoutToken("tok");
|
||||
}
|
||||
|
||||
@@ -154,10 +154,10 @@ class AdminAuthControllerCompanyTest {
|
||||
mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"company\":\"INS\",\"username\":\"john\",\"email\":\"j@x.com\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.result").value("true"));
|
||||
verify(auth).resetAdminPassword("john@ins", "j@x.com");
|
||||
verify(auth).resetAdminPassword("john@INS", "j@x.com");
|
||||
|
||||
mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"company\":\"ins\",\"username\":\"a@b\",\"email\":\"j@x.com\"}")).andExpect(status().isOk());
|
||||
verify(auth, never()).resetAdminPassword(org.mockito.ArgumentMatchers.eq("a@b@ins"), anyString());
|
||||
verify(auth, never()).resetAdminPassword(org.mockito.ArgumentMatchers.eq("a@b@INS"), anyString());
|
||||
}
|
||||
}
|
||||
+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));
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminDashboardService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
class AdminDashboardControllerTest {
|
||||
|
||||
@Test
|
||||
void leadsNeedsBoDashboard() throws Exception {
|
||||
Method m = AdminDashboardController.class.getDeclaredMethod("leads", String.class, String.class, Long.class);
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).isTrue();
|
||||
assertThat(m.getAnnotation(AdminModule.class).value()).containsExactly("BO_DASHBOARD");
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesParams() throws Exception {
|
||||
AdminDashboardService s = mock(AdminDashboardService.class);
|
||||
when(s.leads("2026-11-01", "2026-11-30", 2L)).thenReturn(Map.of("bucket", "DAY"));
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminDashboardController(s)).build();
|
||||
mvc.perform(get("/api/admin/dashboard/leads").param("from", "2026-11-01").param("to", "2026-11-30").param("companyId", "2"))
|
||||
.andExpect(status().isOk()).andExpect(content().json("{\"bucket\":\"DAY\"}"));
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user