From 651c038dcba6dc4b0c67dc24059a0f5767324914 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 15:41:51 +0800 Subject: [PATCH 01/24] docs: event invitations, capacity and attendance design Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- ...-01-event-invitations-attendance-design.md | 217 ++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 docs/superpowers/specs/2026-12-01-event-invitations-attendance-design.md diff --git a/docs/superpowers/specs/2026-12-01-event-invitations-attendance-design.md b/docs/superpowers/specs/2026-12-01-event-invitations-attendance-design.md new file mode 100644 index 0000000..c5f7de8 --- /dev/null +++ b/docs/superpowers/specs/2026-12-01-event-invitations-attendance-design.md @@ -0,0 +1,217 @@ +# Event Invitations, Capacity and Attendance — Design + +Date: 2026-12-01. Status: draft for approval (owner answers of 2026-12-01, including the builder check, folded in). + +## Why + +Co-Lite will grow into an event platform with a member web portal. That portal is phase 2, after go-live. For go-live on 2027-01-15, INS and CV need to run an event end to end around event leads: + +- **Invite** known people before the event. +- **Know** who registered and who actually came. +- **Capture** walk-ins on the day. +- **Compare** the numbers with the event's capacity. + +The owner sees two goals: event leads, which this change serves, and registrations into the system, which is the phase-2 member portal. This change keeps them apart: nobody gets an account. + +Decided with the owner on 2026-12-01: + +- **Invitations are admin-only.** An admin creates the event and invites people. Salespeople do not send invitations, whether or not the event has a cap. +- **Named guest list (option B).** Each guest gets their own invite link. Invites go out by email now and by WhatsApp later. + - Co-Lite's email service already saves every email, and super admins read it under **Emails**. + - Mail is really delivered once SMTP is configured, with no change here. + - Every invite also has a copy link for sending by hand. +- **The guest list is separate from event leads (approach A).** A guest becomes an event lead only when they register or check in, so lead listings, the dashboard and conversion count real captures only. +- **Walk-ins are still captured on the day** through the event code and the salespeople's personal codes. These are the QR self-registration codes, now walk-in codes. +- **Code distribution, both ways:** + - salespeople share or show their own codes from their phones; + - admins print cards or copy all links. +- **Member registration is phase 2.** + +## Goals + +- **Event settings:** optional max capacity and optional invitation cap. +- **Guest list per event:** + - add guests one by one or by pasting a list; + - each guest has a personal invite link and moves Invited → Registered → Attended. +- **Sending:** "Send invite" by email, per guest or to every guest not yet sent, plus "Copy link". +- **Invite page:** "You're invited to ", with the guest's own details filled in, the privacy notice and consent. Submitting registers the guest and creates their event lead. +- **Check-in at the venue:** + - Each event gets a check-in code. A guest scans it, enters their mobile or email, and is marked attended. + - A guest's own invite link also turns into a check-in button on the event days. + - A person not on the list goes on to the walk-in form and is captured and attended at once. +- **Attendance on event leads:** a walk-in captured during the event, by staff or by walk-in code, counts as attended. +- **Numbers on the event page:** invited, registered, attended, walk-ins, against capacity and cap. +- **Distribution of walk-in codes:** + - **My QR codes:** a Share button and a full-screen QR, plus a "you have new event codes" notice. + - **Event page:** "Print cards" (lanyard cards, printed or saved as PDF by the browser) and "Copy all links". + +## Non-goals + +- Member accounts, sign-in for visitors, or a member portal (phase 2). +- Members inviting others, or chains of inviters. +- WhatsApp sending; it comes later through the same invite link. +- A real SMTP provider (deployment backlog). +- Reminders, RSVP "not coming", plus-ones, seat or table plans. +- Changing how walk-in codes register people, beyond the new attended mark. + +## Anti-goals + +- Invited-but-absent people counted as captures, leads or conversions. +- The system turning away a walk-in at the door. Staff decide that. +- A public page that reveals whether a person is on a guest list or is a lead, beyond what the check-in step must reveal (see Risks). +- Guessable invite or check-in links. + +## Approaches considered (where the guest list lives) + +1. **A separate guest list (chosen).** A new `event_guest` table per event. A guest links to an event lead once they register or check in. +2. **Guests as event leads with status "Invited".** It has fewer new parts. But every invitee shows in Event leads and the dashboard as a capture, which inflates captures and lowers conversion, and every listing and report would have to filter them out. + +## The guest list + +- **Table:** `service-counter.event_guest` with: + - `id`, `company_id`, `event_uuid`; + - `name`, `mobile_e164`, `email` (at least one of the two), `company_name`; + - `salesperson_user_id` (optional, from the event team); + - `token` (22 characters, URL-safe, 128 random bits, unique); + - `invited_at` (set when first sent or first copied), `invite_sent_count`; + - `registered_at`, `event_lead_id`; + - `created_by`, `created_at`, `updated_by`, `updated_at`. +- **Duplicates:** within one event, a mobile or email already on the list is refused. The message names the existing guest. +- **Input:** the same normalisation and validation as staff capture: E.164 mobile, lower-cased email, the same lengths. +- **Paste list:** one guest per line, as `name, mobile, email, company`. The admin sees a preview with per-line errors before saving. Lines with errors are skipped. +- **Removing a guest:** + - allowed while the guest is only Invited; + - a guest who has registered or attended cannot be removed, because their event lead exists. Staff manage it there. +- **Invitation cap:** the number of guests on the list may not exceed it. Adding beyond it is refused with "Invitation cap reached (N)". Lowering the cap below the current count is refused. + +## Invite and registration + +- **Invite page `/i/`:** + - It shows "You're invited to ": name, dates and location. + - The form is filled with the guest's details, which the guest may correct. It also has interests and the privacy notice with the bilingual consent tick, as on the QR page. +- **Submitting** runs the QR registration capture (`/counter/registration/register`) with the guest's salesperson, then sets `registered_at` and `event_lead_id`. + - The same matching rules apply: mobile first, then email, and an existing lead is never edited. + - The event lead's `source` is `INVITE`. + - A guest who registers twice sees the same thank-you page, and nothing changes the second time. +- **When the link stops working:** + - it works until the event's end date (Malaysia), and only while the event is enabled and the company has a privacy notice; + - otherwise it shows "This invitation is no longer active." +- **Capacity:** + - Registered guests plus walk-in event leads count against capacity. + - When capacity is reached before the event days, the invite page shows "This event is full", and new guest registrations are refused. On the event days (Malaysia, start date through end date) nothing is refused: check-in, invite registration and walk-ins always go through, because nobody is turned away at the door by the system. + - Staff can still add leads by hand, and walk-in codes are never blocked (anti-goal). +- **Email:** + - One email in both languages, English then Bahasa Malaysia, like the privacy notice. Guests have no language field. + - "Send invite" builds an email from a message template: subject "You're invited: ", the event details and the invite link. It goes through the existing email service, the same path as the public forms. + - It needs a guest email. Guests with only a mobile get "Copy link" only. + - "Send to all not yet sent" sends to every guest with an email and `invite_sent_count = 0`. + - Resending one guest is allowed and increments the count. + +## Check-in and attendance + +- **Check-in code:** one per event, a new `registration_link` kind or its own token (left to the builder), at `/c/`. Staff print it at the entrance. +- **Check-in page:** "Check in to ", with one field for mobile or email. + - **Found as a guest of this event:** + - **Registered:** set `attended_at` on the guest and on its event lead. Show "Welcome, . You're checked in." + - **Invited but not registered:** show the walk-in form, blank, with consent. The check-in page never shows a guest's details back to whoever typed a mobile or email. Submitting registers them, links their guest row and checks them in at once. + - **Found as an event lead of this event but not a guest** (a walk-in who registered by QR earlier): set `attended_at` on the event lead, and show the same welcome. + - **Not found:** show the walk-in form (the QR page form, unassigned). Submitting captures them and marks them attended. + - **Already checked in:** the same welcome again; nothing changes. +- **Check-in by invite link:** on the event days (Malaysia, from the start date through the end date), a registered guest's own `/i/` shows a "Check in" button instead of the form. +- **Guest status is derived, not copied.** A guest row links to its event lead (`event_lead_id`). Registered = linked; Attended = the linked event lead's `attended_at` is set. So a staff untick follows through, and there is no `attended_at` on the guest. +- **A guest who arrives another way is still linked.** When any capture creates or finds an event lead for this event (staff "Add lead", a walk-in code, the check-in walk-in form), an unlinked guest of the same event with the same mobile, or else the same email, is linked to it and its `registered_at` set. It then counts as a guest, not a walk-in. +- **Attended on event leads:** a new `event_lead.attended_at`. + - It is set by check-in. + - It is set at capture when a walk-in is captured during the event days, by staff "Add lead" or by a walk-in code. + - Before the event, a walk-in-code registration is registered only. + - Staff can tick or untick "Attended" on an event lead. +- **When check-in works:** only on the event days, Malaysia time. Outside them, `/c/` shows "Check-in opens on " or "This event has ended." + +## Event page + +- **Settings:** max capacity and invitation cap, both optional whole numbers. +- **"Guests" section:** + - the list with status (Invited / Registered / Attended), invite sent count, and the salesperson; + - Add guest, Paste list, Send invite, Send to all not yet sent, Copy link, Remove (Invited only). +- **Numbers strip:** invited N / cap, registered N, attended N, walk-ins N, total N / capacity. Here: + - attended = guests attended + walk-ins attended; + - walk-ins are event leads without a guest row. +- **Registration QR card:** + - gains the check-in code; + - gains "Print cards", a print-styled page with one card per team member (name, event, dates, QR and short link) plus the event and check-in codes; + - gains "Copy all links", a "name: link" list. +- **Event leads listing:** an "Attended" column and filter, and the source shown (Staff, QR, Invite). + +## My QR codes + +- **Share:** the browser's share sheet (`navigator.share`), falling back to copy. It sends the link with a short message: "Register for : ". +- **Show QR:** a full-screen QR for showing at the booth. +- **Notice:** after sign-in, "You have new event codes" when the user has a code they have not opened yet. The builder may simplify this to "added to an event team in the last 7 days". + +## Access + +- **New module `BO_EVENT_GUESTS` ("Event guests").** Only roles granted it can add, paste, remove and invite guests and set capacity and the invitation cap. It follows the existing split of Leads / Leads edit / Leads export. No role gets it by default; super admins grant it under Roles. +- **Everyone with `BO_EVENTS`** sees the guest list and the numbers on the event page, without the guest actions or the two settings. +- **Company scope** as everywhere. +- **Attended tick on an event lead:** `BO_EVENT_LEADS`, like the other event-lead edits. +- **Super admins:** as everywhere. + +## API (outline; the builder fixes the contracts in the OpenSpec design) + +- **services-counter:** + - guest CRUD, paste-import, mark-sent; + - invite lookup by token; + - register-by-invite (wraps the registration capture); + - check-in (by token or by mobile/email for an event); + - event `capacity` and `invitation_cap`; + - `event_lead.attended_at` and its set/clear; + - counts for the numbers strip. +- **mobile-api:** + - admin endpoints under `/api/admin/events/{uuid}/guests/**` and the event fields; + - public endpoints `/api/public/invite/{token}` (GET, POST, POST check-in) and `/api/public/check-in/{token}` (GET, POST lookup, POST walk-in), with the same limits as the QR page; + - the invite email. +- **Gateway:** exact public paths for the new public calls, as in QR decision 6. +- **Portal:** + - `/i/[token]` and `/c/[token]` public pages, with routeGuard public paths for both, including for a reset-pending session; + - the Guests section, the numbers strip, the print page, and the My QR codes additions. + +## Data changes + +- New table `event_guest`. +- `event`: add `capacity` int NULL and `invitation_cap` int NULL. +- `event_lead`: + - add `attended_at` datetime NULL; + - `source` gains `INVITE`; + - backfill: none, so existing leads count as not attended. +- Check-in codes: one per event (see above). +- An email message template for the invite, English and Bahasa Malaysia, in the existing message table. + +## Risks + +- **Check-in lookup.** The check-in page tells a person at the venue whether a mobile or email is registered for this event: they get a welcome with a first name, or a blank form. That is inherent to self check-in. It never shows other details, is limited to one event, is rate-limited, and is only open on the event days. +- **Check-in rate limit.** At a door rush everyone shares the venue Wi-Fi, so check-in lookups and submissions allow 300 per IP per event per 10 minutes (the walk-in page keeps 60). The page-load limit (120 per IP) does not apply to `/c/`. +- **Email delivery.** Until SMTP is set up, invite emails are only saved, so admins must use "Copy link" or read them under Emails. The event page says so. +- **Attendance counting.** Attendance by capture time counts a walk-in captured on the day as attended even if staff typed them in later from a business card. Staff can untick. + +## Calls made (for the owner to check) + +1. The invitation cap limits the number of guests on the list, not sign-ups. +2. Capacity blocks guest registrations only. Walk-ins and staff entries are never blocked; the numbers show when capacity is passed. +3. Registered guests and walk-ins both count toward capacity. +4. A guest may correct their details on the invite page, but a matched existing lead is still never edited; differences go into notes, as on the QR page. +5. Check-in opens only on the event days. +6. A walk-in captured during the event days counts as attended automatically. +7. Guests with only a mobile number get "Copy link" (for WhatsApp by hand) until WhatsApp sending exists. +8. The check-in page never shows a guest's details; an invited guest who has not registered gets a blank form. +9. Capacity never refuses anyone on the event days. +10. Invite emails are one bilingual email. +11. Guest status is derived from the linked event lead, and every capture route links a matching guest. +12. Check-in allows 300 per IP per event per 10 minutes. + +## Left to the builder + +- Whether check-in codes live in `registration_link` with a kind column or in their own table. +- The print page layout (A4 grid of lanyard cards) and the share message wording. +- The "new codes" notice rule. +- Indexes for the numbers queries. +- Message keys for all copy. -- 2.54.1 From a6bc7287e940815bdf6dad4f726c6fdcf6f831aa Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 16:00:54 +0800 Subject: [PATCH 02/24] docs(openspec): propose add-event-invitations Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-event-invitations/.openspec.yaml | 2 + .../changes/add-event-invitations/design.md | 196 ++++++++++++++++++ .../changes/add-event-invitations/proposal.md | 60 ++++++ .../specs/event-attendance/spec.md | 132 ++++++++++++ .../specs/event-invitations/spec.md | 192 +++++++++++++++++ .../specs/qr-registration/spec.md | 46 ++++ .../changes/add-event-invitations/tasks.md | 194 +++++++++++++++++ 7 files changed, 822 insertions(+) create mode 100644 openspec/changes/add-event-invitations/.openspec.yaml create mode 100644 openspec/changes/add-event-invitations/design.md create mode 100644 openspec/changes/add-event-invitations/proposal.md create mode 100644 openspec/changes/add-event-invitations/specs/event-attendance/spec.md create mode 100644 openspec/changes/add-event-invitations/specs/event-invitations/spec.md create mode 100644 openspec/changes/add-event-invitations/specs/qr-registration/spec.md create mode 100644 openspec/changes/add-event-invitations/tasks.md diff --git a/openspec/changes/add-event-invitations/.openspec.yaml b/openspec/changes/add-event-invitations/.openspec.yaml new file mode 100644 index 0000000..785b150 --- /dev/null +++ b/openspec/changes/add-event-invitations/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-01 diff --git a/openspec/changes/add-event-invitations/design.md b/openspec/changes/add-event-invitations/design.md new file mode 100644 index 0000000..cf9e350 --- /dev/null +++ b/openspec/changes/add-event-invitations/design.md @@ -0,0 +1,196 @@ +# Design + +## Context + +See proposal.md for the motivation. The product design is `docs/superpowers/specs/2026-12-01-event-invitations-attendance-design.md`. This change builds on `add-qr-self-registration` (archived 2026-12-01), which already provides: + +- **services-counter:** `RegistrationService.register` runs matching, the never-edit rule and the already-captured rule in one transaction with one retry. `EventLeadService.capture` is the staff path, and `EventLeadService.update` is the staff edit. +- **mobile-api:** `PublicRegistrationService` holds the token-shape check, `open()` checks, rate limits (`limit(key, max)`), last-hop IP, honeypot and consent. `AdminEventLeadService` holds the validation helpers. +- **gateway:** `JWTAuthFilter.PUBLIC_REGISTRATION` is a list of method and anchored-pattern pairs, and the public flow gets through only on those. +- **portal:** + - `/r/[token]` uses a non-redirecting fetch helper (`app/lib/services/publicRegistration.ts`); + - `routeGuard.isPublicPath` and the reset-pending exemption control access; + - `QrCodeItem` and `RegistrationQrCard` render codes; + - `/my-qr` lists a salesperson's codes. + +Emails are built in mobile-api as escaped HTML and sent with `EmailService.send(Email)` over Pub/Sub, as `PublicFormController` does. services-email saves every email, and super admins read them under Emails. `Email` has a `companyId`. + +The services run with `TZ=Asia/Kuala_Lumpur`, so every stored time is Malaysian local time. + +## Goals / Non-Goals + +**Goals:** +- One shared rule for "during the event days" and one shared rule for linking a guest. Every capture route uses both, so the numbers agree everywhere. +- Reuse the QR registration capture for invite and check-in registrations, rather than a third matching path. +- Keep the module-based access model: one new module, and no read-only flags. + +**Non-Goals:** +- A redesign of the existing screens. The new screens use the current components and will be restyled with the rest of the portal by the coming visual revamp. +- WhatsApp sending, reminders, RSVP declines. +- Backfilling attendance for existing event leads. + +## Decisions + +### 1. Data (SQL in `sql/`) + +- **`service-counter.event_guest`** columns: + - `id` bigint PK auto; + - `company_id` bigint NOT NULL; + - `event_uuid` bigint NOT NULL; + - `name` varchar(100) NOT NULL; + - `mobile_e164` varchar(20) NULL; + - `email` varchar(254) NULL; + - `company_name` varchar(150) NULL; + - `salesperson_user_id` bigint NULL; + - `token` varchar(32) NOT NULL UNIQUE; + - `invited_at` datetime NULL; + - `invite_sent_count` int NOT NULL DEFAULT 0; + - `registered_at` datetime NULL; + - `event_lead_id` bigint NULL; + - `created_by`, `created_at`, `updated_by`, `updated_at`. + + Keys: + - `uk_event_guest_mobile (event_uuid, mobile_e164)` and `uk_event_guest_email (event_uuid, email)`. MySQL allows several NULLs in a unique key, so a guest with only one of the two is fine. These keys enforce "no duplicate on the list" against races. + - `idx_event_guest_lead (event_lead_id)`. +- **`event`:** add + - `capacity` int NULL; + - `invitation_cap` int NULL; + - `checkin_token` varchar(32) NULL UNIQUE. It is created on first use, like registration links. + + Check-in codes live on the event row because there is exactly one per event. This is simpler than a kind column on `registration_link`, whose event-code lookups would then all need a filter. +- **`event_lead`:** add `attended_at` datetime NULL. `source` stays varchar(8), and `INVITE` fits. +- **`service-system.module`:** add `(41150000, 'BO_EVENT_GUESTS', 'Event guests', 'BO', 'M', 40000000, NULL, NULL)`. A NULL url keeps it out of the sidebar, like `BO_LEADS_EDIT` and `BO_LEADS_EXPORT`. No role gets it by default. +- **Seed:** `local/seed/03-colite.sql` mirrors 01 and 02. `99-rollback.sql` drops the table and columns and deletes the module row and its `modules_roles` rows. + +### 2. Shared rules in services-counter + +- **`EventDays.isDuring(event, now)`:** true when `now.toLocalDate()` (Malaysian time) is between `dateStart.toLocalDate()` and `dateEnd.toLocalDate()` inclusive. When `dateStart` is null, only the end counts. When `dateEnd` is null, it is false. This one static helper is used by: + - staff capture, QR register, invite register and check-in capture, to set `attended_at`; + - the capacity rule; + - the check-in window. +- **`GuestLinker.link(eventUuid, eventLead, lead)`:** called in the same transaction after any capture creates or finds an event lead. It finds an unlinked guest of the event by the lead's `mobile_e164`, else by `email_normalised`. It sets `event_lead_id` and `registered_at` (if empty). It is a no-op when the event lead is already linked to a guest. + - Called from `EventLeadService.capture` (staff), `RegistrationService.register` (QR, invite and check-in walk-in) and the invite register. + - The match is by the person's lead, not the submitted values, so a guest who corrected their mobile on the invite page is still linked by the invite token (see decision 3). +- **Attendance at capture:** + - a new event lead gets `attended_at = now` when `EventDays.isDuring`; + - an existing event lead found by the already-captured rule gets `attended_at` set only by an explicit check-in, never by a repeat registration. + +### 3. services-counter endpoints + +All bodies are JSON. `companyId` is always a concrete company, set by mobile-api. + +- **Guests:** + - `POST /counter/eventGuest/list {companyId, eventUuid}` returns `[{id, name, mobileE164, email, companyName, salespersonUserId, token, invitedAt, inviteSentCount, registeredAt, attended, eventLeadUuid}]`. `attended` is derived from the linked event lead's `attended_at`. The list is ordered by name. + - `POST /counter/eventGuest/add {companyId, eventUuid, guests:[{name, mobileE164, email, companyName, salespersonUserId}], doneBy}` returns `{added:[...], rejected:[{index, code, field, message}]}`. Values arrive normalised by mobile-api. + - Rejection codes: `DUPLICATE` (names the existing guest), `CAP_REACHED`, `NOT_ON_TEAM`. + - It saves the valid guests in input order up to the cap. + - It returns 404 when the event is not in the company. + - `POST /counter/eventGuest/remove {companyId, eventUuid, guestId, doneBy}` returns 409 `GUEST_REGISTERED` when the guest is linked. + - `POST /counter/eventGuest/markSent {companyId, eventUuid, guestIds, doneBy}` sets `invited_at` if empty and increments `invite_sent_count`. + - `GET /counter/eventGuest/findByToken/{token}` returns `{companyId, eventUuid, guestId, name, mobileE164, email, companyName, salespersonUserId, registered, attended}`, or 404. +- **Event settings:** `POST /counter/event/save` accepts `capacity` and `invitationCap`, each null or ≥ 1. It returns 409 `CAP_BELOW_GUESTS` when the cap is below the current guest count. +- **Invite registration:** `POST /counter/eventGuest/register {companyId, guestToken, name, mobileE164, email, companyName, jobTitle, interestIds, consentNoticeId, consentAt}` returns `{outcome, eventLeadUuid}`. + - **Capacity:** before the event days, it returns 409 `EVENT_FULL` when the guest is not yet registered and registered guests plus walk-ins ≥ capacity. + - **Capture:** it runs `RegistrationService.register` with source `INVITE` and the guest's salesperson, then links this guest row to the resulting event lead directly by token, not by matching. + - **Already registered:** a guest who is already registered gets `ALREADY_REGISTERED` and nothing changes. +- **Check-in:** + - `GET /counter/checkin/findEvent/{token}` returns `{companyId, eventUuid}`, or 404. + - `POST /counter/checkin/ensureToken {companyId, eventUuid}` returns `{token}`, creating it once. + - `POST /counter/checkin/lookup {companyId, eventUuid, mobileE164, email}` (exactly one of the two) returns `{result: CHECKED_IN | FORM, firstName}`. `firstName` is only present for CHECKED_IN. + - It matches an event lead of this event by the lead's mobile, else email. That covers registered guests and earlier registrants. + - When it matches, it sets `attended_at` if empty and returns CHECKED_IN. + - Otherwise (an invited-not-registered guest, or nobody) it returns FORM. + - `POST /counter/checkin/byGuest {companyId, guestToken}` covers the "Check in" button on `/i/`. It requires the guest to be registered and today to be an event day, sets `attended_at` and returns `{firstName}`. + - The walk-in form on `/c/` posts to `POST /counter/registration/register` with source `QR`, a new field `attend: true`, and no salesperson. `attend` sets `attended_at` even on an already-captured event lead. +- **Attendance edit:** `POST /counter/eventLead/update` accepts `attended` (boolean). True sets `attended_at = now` if empty; false clears it. +- **Numbers:** `POST /counter/event/attendance {companyId, eventUuid}` returns `{invited, cap, registered, attended, walkIns, total, capacity}`, using the counts defined in the spec. +- **New codes:** `POST /counter/registrationLink/mine` adds `addedAt` (the team row's `create_date_time`) to each entry. + +### 4. mobile-api contracts + +- **Admin, gated `BO_EVENTS` for reads and `BO_EVENT_GUESTS` for writes,** with the company scope via `loadEvent` as today: + - `GET /api/admin/events/{uuid}/guests` returns the list, with each `salespersonName` resolved. + - `POST /api/admin/events/{uuid}/guests` with `{guests:[{name, mobile, email, companyName, salespersonUserId}]}` returns `{added, rejected}`. + - The same endpoint serves single add and paste. The portal parses pasted lines into this shape and shows the preview from a dry-run flag, `?preview=true`, which validates and returns the result without saving. + - Validation and normalisation use the `AdminEventLeadService` helpers. `rejected[].field` names the field. + - `DELETE /api/admin/events/{uuid}/guests/{guestId}` + - `POST /api/admin/events/{uuid}/guests/send` with `{guestIds}` or `{allUnsent: true}` returns `{sent, skippedNoEmail}`. + - It builds one email per guest: escaped values, English then Bahasa Malaysia, and the link `/i/`. + - It sends with `companyId` = the event's company, then calls counter `markSent` for the sent ones. + - `ADMIN_PORTAL_BASE_URL` is a new mobile-api setting. Emails have no browser origin, unlike the QR card. + - `GET /api/admin/events/{uuid}/checkin` returns `{token}`, ensured. + - `GET /api/admin/events/{uuid}/attendance` returns the numbers. + - Event GET and PUT gain `capacity` and `invitationCap`. The PUT only changes them when the caller has `BO_EVENT_GUESTS`; otherwise it ignores them. + - The event-lead PUT accepts `attended`. + - The audit target is the event uuid for every guest endpoint. `@Audited(targetVariable = "uuid")` is used where a later path variable exists. +- **Public endpoints,** `@AppAuth(skipValidate = true)`, with token shape `[A-Za-z0-9_-]{22}` checked before any backend call: + - **Invite pages:** + - `GET /api/public/invite/{token}` returns `{eventName, startDate, endDate, location, companyName, notice, interests, guest:{name, mobile, email, companyName}, state: OPEN | REGISTERED | CHECKIN | CHECKED_IN}`. + - `CHECKIN` means registered on an event day. `CHECKED_IN` means registered and attended. + - Inactive gives 404 `INVITE_INACTIVE` ("This invitation is no longer active."). + - The guest's own details go only to their own token. + - `POST /api/public/invite/{token}` registers. It uses the same body, consent and honeypot as `/registration`. It returns 409 `EVENT_FULL` ("This event is full") and 200 `{eventName}` otherwise. + - `POST /api/public/invite/{token}/checkin` returns 200 `{firstName}`. + - **Check-in pages:** + - `GET /api/public/checkin/{token}` returns `{eventName, startDate, endDate, location, companyName, notice, interests, state: OPEN | NOT_YET | ENDED}`. + - `NOT_YET` and `ENDED` carry only `startDate`, not the other details. An unknown token gives 404 `CODE_INACTIVE`. + - `POST /api/public/checkin/{token}/lookup` with `{value}` (mobile or email, detected by the presence of `@`) returns `{result, firstName}`. + - `POST /api/public/checkin/{token}/register` takes the walk-in form and returns 200 `{eventName}` (counter register with `attend: true`). +- **Limits** (Redis keys, 10 minutes): + - `inv:load:` 120 and `inv:submit::` 60 for invites; + - `chk::` 300 for every check-in call. The check-in page does not count `reg:load`. + - Over the limit: 429 `TOO_MANY`. + +### 5. Gateway (decision 6 of the QR change, extended) + +Add these anchored method and path pairs: +- GET `/counter/eventGuest/findByToken/[A-Za-z0-9_-]{22}` +- POST `/counter/eventGuest/register` +- GET `/counter/checkin/findEvent/[A-Za-z0-9_-]{22}` +- POST `/counter/checkin/lookup` +- POST `/counter/checkin/byGuest` +- POST `/counter/event/attendance` (for the capacity check on the public invite) + +`/counter/registration/register` is already open. Everything else stays closed. + +### 6. Portal + +- **Public pages:** `/i/[token]` and `/c/[token]` are public in `routeGuard`, including the reset-pending exemption, using one shared pattern for `/r/`, `/i/` and `/c/`. Their proxies are `app/api/public/invite/[token]/**` and `app/api/public/checkin/[token]/**`, which send only the last X-Forwarded-For hop. They reuse the `/r/` form component (extract the form from `app/r/[token]/page.tsx` into a shared component, so the three pages share fields, consent, errors and thank-you). +- **Event page:** + - **Guests section:** a table with status badges, an Add guest dialog, a Paste list dialog with preview, send to one or to all unsent, copy link, and remove for Invited guests. Actions show only with `BO_EVENT_GUESTS`. + - **Numbers strip.** + - **Capacity and cap fields:** disabled without `BO_EVENT_GUESTS`. + - **Check-in code:** shown in the Registration QR card. + - **Print cards and Copy all links.** +- **Print page:** `/events/[uuid]/print` uses print CSS (A4, 2×4 cards). Its "Print" button calls `window.print()`, so no PDF library is needed. +- **My QR codes:** + - Share uses `navigator.share`, falling back to the clipboard. + - The full-screen view is a dialog with the QR sized to `min(90vw, 90vh)` on white. + - The notice is a banner in the shell after sign-in when any code's `addedAt` is within 7 days. It is dismissible, and the dismissal is stored in `localStorage` per code. +- **Event leads:** the listing gains an Attended column and filter and a Source column. The edit form gains an Attended checkbox. +- **`ROUTE_MODULES`:** `/events/[uuid]/print` maps to `BO_EVENTS`. + +### 7. Rejected + +- **Guests as event leads with status Invited.** It inflates captures and conversion (product design, approach 2). +- **A `kind` column on `registration_link` for check-in codes.** Every event-code query would need the filter; one column on the event is enough. +- **Server-side PDF generation for cards.** It adds a dependency; browser print to PDF covers it. +- **Storing `attended_at` on the guest.** Two sources of truth; it is derived from the event lead instead. + +## Risks / Trade-offs + +- **[Check-in reveals membership]** It reveals whether a mobile or email is registered for the event (welcome versus form). It is limited to the event days, one event and 300 per 10 minutes per IP, and shows a first name only. +- **[Wrong attendance]** A staff capture typed in later during the event days, for example from a business card, counts as attended. Staff can untick. +- **[Email delivery]** Until SMTP exists, invite emails are saved, not delivered. The Guests section states it, and Copy link always works. +- **[Gateway exposure]** New open paths let a holder of a gateway api-key read a guest by token and register or check in without a user token. Same accepted risk as QR decision 6: the gateway is internal only. +- **[Capacity race]** Two last-seat invite registrations at the same moment can both pass. This is accepted; capacity is a planning number, and it is never enforced on the day. +- **[ADMIN_PORTAL_BASE_URL]** A wrong value sends broken invite links. The deployment notes list it with the other required settings, and a startup log line prints it. + +## Migration Plan + +1. Run `sql/01-event-guests.sql` (DDL: table and columns) and `sql/02-event-guests-module.sql` before the new images. The new services-counter reads the new columns on every event and event-lead query. +2. Set `ADMIN_PORTAL_BASE_URL` on mobile-api. +3. Deploy services-counter, mobile-api, api-gateway and admin-portal together. +4. A super admin grants Event guests to the admin roles under Roles. + +Rollback: `sql/99-rollback.sql` drops the table and columns and deletes the module, losing guests and attendance marks. Redeploy the previous images. diff --git a/openspec/changes/add-event-invitations/proposal.md b/openspec/changes/add-event-invitations/proposal.md new file mode 100644 index 0000000..7cea812 --- /dev/null +++ b/openspec/changes/add-event-invitations/proposal.md @@ -0,0 +1,60 @@ +# Proposal + +## Why + +To run an event end to end at go-live (2027-01-15), INS and CV need to: + +- invite known people before the event; +- know who registered and who actually came; +- capture walk-ins on the day; +- compare these numbers with the event's capacity. + +Today Co-Lite only captures leads. It cannot invite anyone, and it cannot tell a registration from an attendance. The approved product design is `docs/superpowers/specs/2026-12-01-event-invitations-attendance-design.md`. + +## What Changes + +- **Event settings:** each event gains two optional numbers, a max capacity and an invitation cap. +- **Guest list per event:** a named list of invited people, kept separate from event leads. Each guest: + - has a personal invite link; + - moves through Invited → Registered → Attended, with the status derived from the linked event lead. +- **Invite sending:** admins send each guest an invite email in English and Bahasa Malaysia through the existing email service. Each guest also has a copy-link action for sending by WhatsApp by hand. +- **Public invite page `/i/`:** shows "You're invited", with the guest's details filled in and the privacy consent. Submitting registers the guest as an event lead with source `INVITE`. On the event days the page offers check-in instead. +- **Public check-in page `/c/`:** one per event, open only on the event days. + - A guest or earlier registrant enters a mobile or email and is checked in. + - Anyone else fills in the walk-in form and is captured and checked in at once. + - The page never shows a guest's details back to the person typing. +- **Attendance on event leads:** a new attended time, set by check-in or by a capture made during the event days. Staff can tick or untick it, and listings can filter on it. +- **A matching guest is linked whatever the route.** When any capture creates or finds an event lead for the event, a guest of that event with the same mobile or email is linked to it. +- **Capacity:** reaching capacity stops invite registrations before the event days. Nothing is refused on the event days. +- **Numbers on the event page:** invited (against the cap), registered, attended, walk-ins, and total (against capacity). +- **Walk-in code distribution:** + - My QR codes gains a share button, a full-screen QR, and a notice about new codes. + - The event page gains a printable sheet of cards and a copy-all-links action. +- **New back-office module `BO_EVENT_GUESTS`:** only roles granted it can manage guests, send invites, and set capacity and the cap. Everyone with `BO_EVENTS` can see the guest list and the numbers. +- **Internal gateway:** opens exact method and path pairs for the new public endpoints, as the QR change did. + +## Capabilities + +### New Capabilities + +- `event-invitations`: event capacity and invitation cap, the guest list, invite links and emails, and registration by invitation. +- `event-attendance`: the event check-in page, attended marks on event leads, guest linking across capture routes, and the event's attendance numbers. + +### Modified Capabilities + +- `qr-registration`: adds distribution of walk-in codes (share, full screen, new-code notice, printable cards, copy all). Walk-in registrations made during the event days count as attended. Existing requirements are unchanged. + +## Impact + +- **Data (services-counter):** + - new table `event_guest`; + - new columns `event.capacity` and `event.invitation_cap`; + - new column `event_lead.attended_at`; + - `event_lead.source` gains the value `INVITE`; + - check-in codes. +- **Data (services-system):** the new module row `BO_EVENT_GUESTS`. +- **services-counter:** guest, invite, check-in and attendance endpoints; changes to the staff and QR capture paths for attendance and guest linking. +- **mobile-api:** the admin guest endpoints and event fields, the public invite and check-in endpoints with rate limits, and the invite email. +- **api-gateway:** new public paths. +- **admin portal:** new pages and sections, including the public `/i/` and `/c/` pages, the Guests section, the numbers strip, the print sheet, the My QR codes additions, and the attended column and filter. +- **Deployment:** new SQL to run before the images go live. Invite emails are only saved until SMTP is configured. diff --git a/openspec/changes/add-event-invitations/specs/event-attendance/spec.md b/openspec/changes/add-event-invitations/specs/event-attendance/spec.md new file mode 100644 index 0000000..544d330 --- /dev/null +++ b/openspec/changes/add-event-invitations/specs/event-attendance/spec.md @@ -0,0 +1,132 @@ +# Spec Delta + +## Purpose + +Record who actually came to an event, through self check-in at the venue and capture during the event days, and show an event's invited, registered, attended and walk-in numbers against its capacity. + +## ADDED Requirements + +### Requirement: Check-in code + +Every event SHALL have one check-in code, a link of the form `/c/` with an unguessable token. Users with `BO_EVENTS` SHALL see it on the event page as a QR image, with copy link and image download, for printing at the entrance. + +#### Scenario: Code on the event page + +- **WHEN** a user with `BO_EVENTS` opens `KL Expo` +- **THEN** the page shows the check-in QR with copy link and download + +### Requirement: Check-in code availability + +The check-in code SHALL work only on the event days (Malaysia, from the start date through the end date), while the event is enabled and its company has a privacy notice. Before the event it SHALL show "Check-in opens on ". After the event it SHALL show "This event has ended." An unknown token or a disabled event SHALL show "This code is no longer active." None of these pages SHALL show any other event details. + +#### Scenario: Before the event + +- **GIVEN** `KL Expo` starts tomorrow +- **WHEN** a visitor opens its check-in link +- **THEN** the page says check-in opens on the start date + +#### Scenario: On the day + +- **GIVEN** today is the first day of `KL Expo` +- **WHEN** a visitor opens its check-in link +- **THEN** the page asks for a mobile or email + +### Requirement: Self check-in of a known person + +On the event days, the check-in page SHALL ask for one mobile or email, normalised as in staff capture. When the value matches a registered guest or an event lead of this event, that event lead SHALL be marked attended and the page SHALL show "Welcome, . You're checked in." Checking in again SHALL show the same welcome and change nothing. The page SHALL never show a guest's or lead's details other than the first name in the welcome. + +#### Scenario: Registered guest checks in + +- **GIVEN** `Tan Mei Ling` registered by invitation for `KL Expo` +- **WHEN** she enters `012-555 0101` on the check-in page on the event day +- **THEN** the page welcomes `Tan` and her event lead is attended +- **AND** the guest list shows her as Attended + +### Requirement: Self check-in of a walk-in + +When the value matches an invited guest who has not registered, or no one, the check-in page SHALL show the walk-in form, blank, with the privacy consent. An accepted submission SHALL capture the person with the QR registration rules and no salesperson, link a matching guest, mark the event lead attended, and show the checked-in page. + +#### Scenario: Invited but not registered + +- **GIVEN** `Lim Wei` is Invited but never registered +- **WHEN** he enters his mobile on the check-in page +- **THEN** a blank walk-in form with the consent is shown, not his details +- **AND** after he submits, he is Attended on the guest list + +#### Scenario: Unknown walk-in + +- **WHEN** a visitor whose mobile matches no one enters it and submits the walk-in form +- **THEN** an event lead is captured for them and marked attended + +### Requirement: Check-in by invite link + +On the event days, a registered guest's invite link SHALL show a "Check in" button instead of the registration form. Pressing it SHALL mark the guest's event lead attended and show the checked-in page. + +#### Scenario: Check in from the email + +- **GIVEN** `Tan Mei Ling` is registered and today is an event day +- **WHEN** she opens her invite link and presses Check in +- **THEN** she is Attended + +### Requirement: Attendance at capture + +Each event lead SHALL have an attended time. A staff capture, a walk-in code registration or a check-in-page capture made during the event days SHALL set it. A registration made before the event days SHALL NOT set it. Event leads that exist before this change SHALL count as not attended. + +#### Scenario: Walk-in on the day + +- **GIVEN** today is the first day of `KL Expo` +- **WHEN** staff capture a visitor at the booth +- **THEN** the event lead is attended + +#### Scenario: Early QR registration + +- **GIVEN** `KL Expo` starts next week +- **WHEN** a visitor registers through the event's walk-in code +- **THEN** the event lead is registered but not attended + +### Requirement: Attendance in staff screens + +Users who can edit event leads SHALL tick or untick Attended. The event leads listing SHALL show an Attended column and filter, and each event lead's source (Staff, QR, Invite). + +#### Scenario: Staff untick + +- **WHEN** staff untick Attended on an event lead linked to a guest +- **THEN** the guest list shows that guest as Registered + +### Requirement: Guest linking across routes + +A guest's status SHALL be derived from the event lead it is linked to: Registered when linked, Attended when that event lead is attended. Whenever a capture for an event creates or finds an event lead, by staff, walk-in code, invite or check-in, an unlinked guest of the same event SHALL be linked to it. The guest is matched by mobile first, else by email. The guest then SHALL count as a guest, not as a walk-in. + +#### Scenario: Guest captured by staff + +- **GIVEN** `Lim Wei` is Invited to `KL Expo` +- **WHEN** staff capture `Lim Wei` with his mobile at the booth on the event day +- **THEN** the guest list shows him as Attended +- **AND** he is not counted as a walk-in + +### Requirement: Event attendance numbers + +The event page SHALL show: + +- invited: the number of guests, against the invitation cap when set; +- registered: guests linked to an event lead; +- attended: attended event leads; +- walk-ins: event leads not linked to a guest; +- total: registered guests plus walk-ins, against capacity when set. + +The numbers SHALL agree with the guest list and the event leads listing. A total above capacity SHALL be shown, not hidden. + +#### Scenario: Numbers + +- **GIVEN** `KL Expo` has capacity 100, cap 50, 40 guests of whom 30 registered and 20 attended, plus 15 walk-ins of whom 15 attended +- **WHEN** an admin opens the event page +- **THEN** the event page shows invited 40 of 50, registered 30, attended 35, walk-ins 15, total 45 of 100 + +### Requirement: Check-in abuse limits + +The check-in endpoints SHALL allow at most 300 lookups and submissions per IP per event per 10 minutes, answering "Too many attempts. Try again later." beyond that. The IP SHALL be determined as on the QR page. The check-in page SHALL NOT count against the QR page-load limit. + +#### Scenario: Door rush + +- **WHEN** 200 guests check in from the venue Wi-Fi within 10 minutes +- **THEN** none of them is refused as too many diff --git a/openspec/changes/add-event-invitations/specs/event-invitations/spec.md b/openspec/changes/add-event-invitations/specs/event-invitations/spec.md new file mode 100644 index 0000000..e6d9be4 --- /dev/null +++ b/openspec/changes/add-event-invitations/specs/event-invitations/spec.md @@ -0,0 +1,192 @@ +# Spec Delta + +## Purpose + +Admins invite named guests to an event before it happens, each with a personal invite link, and see who registered, against an optional invitation cap and event capacity. + +## ADDED Requirements + +### Requirement: Event capacity and invitation cap + +An event SHALL have an optional max capacity and an optional invitation cap. Each SHALL be empty or a whole number of at least 1. Only users with `BO_EVENT_GUESTS` SHALL set them. Every user who can open the event SHALL see them. + +#### Scenario: Set both + +- **GIVEN** a user with `BO_EVENTS` and `BO_EVENT_GUESTS` +- **WHEN** they set capacity `200` and invitation cap `150` on `KL Expo` +- **THEN** the event shows capacity 200 and cap 150 + +#### Scenario: Without the guests module + +- **GIVEN** a user with `BO_EVENTS` only +- **WHEN** they open `KL Expo` +- **THEN** they see capacity and cap but cannot change them + +### Requirement: Guest list + +Each event SHALL have a guest list, kept separate from its event leads. A guest SHALL have a name (required), a mobile and an email (at least one of the two), an optional company and an optional salesperson from the event team. Inputs SHALL be normalised and limited as in staff capture. A guest SHALL NOT appear in event leads, lead listings or the dashboard until registered. + +#### Scenario: Add a guest + +- **WHEN** an admin adds guest `Tan Mei Ling` with mobile `012-555 0101` to `KL Expo` +- **THEN** the guest list shows `Tan Mei Ling` as Invited +- **AND** the event's leads do not include her + +### Requirement: Guest duplicates + +A mobile or email already on the event's guest list SHALL be refused with a message naming the existing guest. + +#### Scenario: Duplicate refused + +- **GIVEN** `Tan Mei Ling` with mobile `+60125550101` is on the list +- **WHEN** an admin adds another guest with mobile `0125550101` +- **THEN** it is refused with a message naming `Tan Mei Ling` + +### Requirement: Adding guests by paste + +Users with `BO_EVENT_GUESTS` SHALL add guests one at a time or by pasting a list of lines `name, mobile, email, company`. A pasted list SHALL show a preview with per-line errors and save only the valid lines. + +#### Scenario: Paste with errors + +- **WHEN** an admin pastes three lines, one of which has neither mobile nor email +- **THEN** the preview marks that line with its error +- **AND** saving adds the other two guests only + +### Requirement: Invitation cap enforcement + +When an event has an invitation cap, the number of guests on its list SHALL NOT exceed it. Adding a guest beyond the cap SHALL be refused with "Invitation cap reached (N)". A pasted list SHALL save valid lines only up to the cap and report the lines left out. Lowering the cap below the current number of guests SHALL be refused. + +#### Scenario: Cap reached + +- **GIVEN** `KL Expo` has cap 2 and two guests +- **WHEN** an admin adds a third guest +- **THEN** it is refused with "Invitation cap reached (2)" + +#### Scenario: Lower the cap too far + +- **GIVEN** `KL Expo` has five guests +- **WHEN** an admin sets the cap to 4 +- **THEN** the change is refused + +### Requirement: Guest removal + +A user with `BO_EVENT_GUESTS` SHALL be able to remove a guest who is only Invited. A guest who has registered or attended SHALL NOT be removable from the guest list. + +#### Scenario: Remove an invited guest + +- **WHEN** an admin removes an Invited guest +- **THEN** the guest is gone and their invite link shows that it is no longer active + +#### Scenario: Registered guest stays + +- **GIVEN** `Tan Mei Ling` has registered +- **THEN** no remove action is offered for her + +### Requirement: Invite links + +Every guest SHALL have a personal invite link of the form `/i/` with an unguessable token. Copying a guest's link SHALL be available to users with `BO_EVENT_GUESTS`. An invite link SHALL work only while: + +- the guest is on the list; +- the event is enabled; +- the event's end date in Malaysia time has not passed; +- the event's company has a privacy notice. + +Otherwise it SHALL show "This invitation is no longer active." and no event details. + +#### Scenario: Copy a link + +- **WHEN** an admin copies the invite link of `Tan Mei Ling` +- **THEN** the clipboard holds her `/i/` link + +#### Scenario: Ended event + +- **GIVEN** `Penang Fair` ended yesterday +- **WHEN** a guest opens their invite link +- **THEN** the page says the invitation is no longer active + +### Requirement: Invite email + +A user with `BO_EVENT_GUESTS` SHALL be able to send an invite email to one guest who has an email, or to every guest with an email who has not been sent one yet. The email SHALL be in English and Bahasa Malaysia and SHALL carry the event's name, dates and location and the guest's invite link. Values from the event and guest SHALL be escaped as text, never as markup. A guest with no email SHALL offer copy link only. + +#### Scenario: Send to all not yet sent + +- **GIVEN** three guests with an email, one already sent +- **WHEN** an admin chooses send to all not yet sent +- **THEN** two emails are saved + +### Requirement: Invite sending record + +Sending SHALL record that the guest was invited and how many times an invite was sent. The email SHALL belong to the event's company, so that company's users with Emails can see it. + +#### Scenario: Send to one + +- **WHEN** an admin sends an invite to `Tan Mei Ling`, who has an email +- **THEN** an email to her address with her invite link is saved by the email service +- **AND** her invite sent count is 1 + +### Requirement: Invite page + +The invite page SHALL show "You're invited to " with the event's name, dates and location. Its form SHALL be filled in with the guest's name, mobile, email and company, which the guest may correct. It SHALL offer the company's active interests and the privacy notice consent (required), as on the QR page. + +#### Scenario: Prefilled form + +- **WHEN** `Tan Mei Ling` opens her invite link before the event +- **THEN** the form shows her name and mobile, and the consent unticked + +### Requirement: Registration by invitation + +An accepted invite submission SHALL register the guest with the same normalisation, limits, matching and existing-lead rules as QR registration. The resulting event lead SHALL have source `INVITE` and the guest's salesperson. The guest SHALL become Registered and be linked to that event lead. Submitting again SHALL change nothing and SHALL show the same thank-you page. + +#### Scenario: Guest registers + +- **WHEN** `Tan Mei Ling` opens her invite link, ticks the consent and submits +- **THEN** the thank-you page names `KL Expo` +- **AND** she is Registered on the guest list +- **AND** an event lead with source INVITE exists for her + +#### Scenario: Guest already a lead elsewhere + +- **GIVEN** `Tan Mei Ling` is an existing lead with a different job title +- **WHEN** she registers by invitation with a new job title +- **THEN** her lead is not edited and the new job title is in the event lead's notes + +### Requirement: Capacity before the event + +When an event has a capacity, invite registrations SHALL be refused before the event days once the number of registered guests plus walk-in event leads reaches it. A refused registration SHALL show "This event is full". On the event days (Malaysia, from the start date through the end date) no registration or check-in SHALL be refused for capacity. Staff capture SHALL never be refused for capacity. + +#### Scenario: Full before the event + +- **GIVEN** `KL Expo` starts next week, has capacity 2, and two registered guests +- **WHEN** a third guest submits their invite +- **THEN** the page says the event is full and nothing is saved + +#### Scenario: Not refused on the day + +- **GIVEN** the same event on its first day +- **WHEN** the third guest submits their invite +- **THEN** they are registered + +### Requirement: Guest list access + +Users with `BO_EVENTS` SHALL see an event's guest list with each guest's status, invite sent count and salesperson. Only users with `BO_EVENT_GUESTS` SHALL add, paste, remove, copy links for or send invites to guests. Guest endpoints SHALL apply the company scope as everywhere: staff only reach their company's events. + +#### Scenario: Read only + +- **GIVEN** a user with `BO_EVENTS` but not `BO_EVENT_GUESTS` +- **WHEN** they open `KL Expo` +- **THEN** they see the guests and their statuses without any guest actions + +#### Scenario: Other company + +- **GIVEN** a CV staff user with both modules +- **WHEN** they call the guest endpoints of an INS event +- **THEN** the answer is not found + +### Requirement: Invite abuse limits + +The public invite endpoints SHALL apply the QR page's limits: 120 page loads per IP per 10 minutes and 60 submissions per IP per event per 10 minutes, answering "Too many attempts. Try again later." beyond them. The IP SHALL be determined as on the QR page. + +#### Scenario: Too many submissions + +- **WHEN** one IP submits a 61st invite registration for `KL Expo` within 10 minutes +- **THEN** it is refused as too many diff --git a/openspec/changes/add-event-invitations/specs/qr-registration/spec.md b/openspec/changes/add-event-invitations/specs/qr-registration/spec.md new file mode 100644 index 0000000..a76ab9e --- /dev/null +++ b/openspec/changes/add-event-invitations/specs/qr-registration/spec.md @@ -0,0 +1,46 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: Sharing personal walk-in codes + +On My QR codes, each code SHALL offer: + +- Share: opens the device's share sheet with the link and a short message, or copies them where the device has no share sheet; +- Show full screen: shows the QR as large as the screen allows, on a plain background. + +After sign-in, a user with a personal code for an event they joined in the last 7 days SHALL see a notice that links to My QR codes. + +#### Scenario: Share from a phone + +- **WHEN** `sales1` presses Share on their `KL Expo` code on a phone +- **THEN** the phone's share sheet opens with the registration link + +#### Scenario: Full screen at the booth + +- **WHEN** `sales1` presses Show full screen +- **THEN** only the QR is shown, filling the screen + +#### Scenario: New code notice + +- **GIVEN** `sales1` was added to the team of `KL Expo` yesterday +- **WHEN** `sales1` signs in +- **THEN** a notice links to My QR codes + +### Requirement: Printing event codes + +On the event page, users with `BO_EVENTS` SHALL have: + +- Print cards: opens a print-ready page with one card per team member (name, event name and dates, QR and link), plus the event code and the check-in code; +- Copy all links: copies one line per code, as `name: link`. + +#### Scenario: Print cards + +- **GIVEN** `KL Expo` has three team members +- **WHEN** an admin presses Print cards +- **THEN** the print page shows three member cards plus the event and check-in codes + +#### Scenario: Copy all links + +- **WHEN** an admin presses Copy all links on `KL Expo` +- **THEN** the clipboard holds one `name: link` line per code diff --git a/openspec/changes/add-event-invitations/tasks.md b/openspec/changes/add-event-invitations/tasks.md new file mode 100644 index 0000000..0e0edbb --- /dev/null +++ b/openspec/changes/add-event-invitations/tasks.md @@ -0,0 +1,194 @@ +# Tasks + +Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-01-event-invitations-attendance-design.md` (product). + +Waves: +- **Wave 0** (serial, controller): 1.1 touches SQL and the seed. +- **Wave 1** (parallel, at most 3): 2.1 (services-counter, part A) and 3.1 (mobile-api admin). Each is in one module, and they build against the fixed contracts in decisions 3 and 4. +- **Wave 2** (parallel, at most 3): + - 2.2 (services-counter, part B, after 2.1); + - 3.2 (mobile-api public, after 3.1); + - 4.1 (gateway). +- **Wave 3** (serial): 5.1, 5.2 and 5.3 (portal). They share the message catalogue, and 5.1 touches the route guard, which is security code. +- **Wave 4** (serial, controller): 6.1. + +## 1. Data + +- [ ] 1.1 SQL `sql/01-event-guests.sql` (table `event_guest`, event `capacity`/`invitation_cap`/`checkin_token`, event_lead `attended_at`), `sql/02-event-guests-module.sql` (module `BO_EVENT_GUESTS`), `sql/99-rollback.sql`; 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-event-invitations/sql/**` + - Verify: `SELECT` shows the table, its unique keys, the new columns and the module row. + +## 2. services-counter + +- [ ] 2.1 Shared rules, attendance, event settings and numbers (decisions 2 and 3). + - Depends on: 1.1 + - Tests first: + - **`EventDays.isDuring`:** the first day, the last day, the day before, the day after, a null start, a null end. + - **Attendance at capture:** + - staff capture during the event days sets `attended_at`, and before them does not; + - QR register sets it the same way; + - `attend: true` sets it on a new or already-captured event lead; + - a repeat registration does not set it. + - **Event lead update:** `attended` true sets the time, and false clears it. + - **Event save:** + - `capacity` and `invitationCap` are null or at least 1; + - a cap below the guest count gives 409 `CAP_BELOW_GUESTS`. + - **`event/attendance`:** returns the spec's numbers on a fixture with guests, linked guests, attended event leads and walk-ins. + - **`registrationLink/mine`:** returns `addedAt`. + - **`EventGuest` entity:** maps to the DDL. + - **`GuestLinker`:** links by mobile, then by email; does nothing when the event lead is already linked; staff capture and QR register both call it. + - Scope: `solvway-services-counter/src/**` + - Verify: `mvn -T 1C -q -pl solvway-services-counter verify` +- [ ] 2.2 Guests, invite registration and check-in endpoints (decision 3). + - Depends on: 2.1 + - Tests first: + - **Guest add:** + - saves in order up to the cap; + - `DUPLICATE` names the existing guest, and the unique-key race is treated as a duplicate; + - `CAP_REACHED`; + - `NOT_ON_TEAM`; + - 404 for another company's event. + - **Guest remove:** 409 `GUEST_REGISTERED` when the guest is linked. + - **`markSent`:** sets `invited_at` once and increments the count. + - **`findByToken`:** returns the guest or 404. + - **`eventGuest/register`:** + - registers with source `INVITE` and the guest's salesperson, and links by token; + - gives `ALREADY_REGISTERED` on repeat; + - gives `EVENT_FULL` before the event days at capacity; + - never gives `EVENT_FULL` on the event days. + - **Check-in:** + - `checkin/ensureToken` creates the token once; + - `checkin/findEvent` returns the event or 404; + - `checkin/lookup` gives CHECKED_IN and a first name for a registered guest or any event lead of the event, and sets `attended_at`; + - `checkin/lookup` gives FORM for an invited-not-registered guest and for an unknown person, and returns no details; + - `checkin/byGuest` requires a registered guest and an event day. + - Scope: `solvway-services-counter/src/**` + - Verify: `mvn -T 1C -q -pl solvway-services-counter verify` + +## 3. mobile-api + +- [ ] 3.1 Admin guest endpoints, invite email, event fields, attendance, check-in token, event-lead attended (decision 4, admin part). + - Depends on: 1.1 (the contracts in decision 3) + - Tests first: + - **Access:** + - reads are gated `BO_EVENTS`, writes `BO_EVENT_GUESTS`; + - the company scope gives 404 for another company's event. + - **Guest add:** validates and normalises like staff capture, with `rejected[].field` naming the field. `?preview=true` saves nothing. + - **Send:** + - builds one bilingual email per guest with escaped values and `/i/`, sets `companyId` to the event's company, and calls `markSent` only for the guests sent; + - `allUnsent` skips guests already sent and guests with no email, and returns `skippedNoEmail`. + - **Event PUT:** ignores `capacity` and `invitationCap` without `BO_EVENT_GUESTS`. + - **Event-lead PUT:** passes `attended`. + - **Audit:** the target is the event uuid on every guest endpoint. + - **Wiring:** a test proves the new services start (constructor selection). + - Scope: `solvway-mobile-api/src/**` + - Verify: `mvn -T 1C -q -pl solvway-mobile-api verify` +- [ ] 3.2 Public invite and check-in endpoints (decision 4, public part). + - Depends on: 3.1 + - Tests first: + - **Token checks:** a bad token shape gives 404 with no backend call; inactive gives `INVITE_INACTIVE` or `CODE_INACTIVE`. + - **Invite GET:** + - returns the guest's own details only for their own token; + - state is OPEN, REGISTERED, CHECKIN or CHECKED_IN by registration, attendance and event day. + - **Invite POST:** + - checks consent and the honeypot as `/registration` does; + - `EVENT_FULL` gives 409; + - registration gives 200 `{eventName}`. + - **Invite check-in:** only for a registered guest on an event day. + - **Check-in GET:** + - NOT_YET and ENDED carry only `startDate`; + - OPEN carries the event, notice and interests. + - **Check-in lookup:** + - detects mobile or email; + - returns `firstName` only for CHECKED_IN; + - the FORM answer carries no details. + - **Check-in register:** calls counter register with `attend: true` and no salesperson. + - **Limits:** `inv:load` 120, `inv:submit` 60 and `chk` 300 give 429 `TOO_MANY`; the check-in page does not count `reg:load`. + - Scope: `solvway-mobile-api/src/**` + - Verify: `mvn -T 1C -q -pl solvway-mobile-api verify` + +## 4. Gateway + +- [ ] 4.1 Add the decision-5 pairs to `JWTAuthFilter.PUBLIC_REGISTRATION`. + - Depends on: none (contracts fixed) + - Tests first: + - each new pair passes without a user token; + - these still get 401: `/counter/eventGuest/list`, `/counter/eventGuest/add`, `/counter/eventGuest/remove`, `/counter/eventGuest/markSent`, `/counter/checkin/ensureToken`, wrong methods, extra segments and bad token shapes. + - Scope: `solvway-api-gateway/src/**` + - Verify: `mvn -T 1C -q -pl solvway-api-gateway verify` + +## 5. Portal + +Every portal verify must report the exit codes of lint, tsc and vitest. Vitest exits 1 on unhandled errors even when every test passes. + +- [ ] 5.1 Public pages: extract the shared registration form from `/r/[token]`; add `/i/[token]` and `/c/[token]` and their proxies; make all three paths public in `routeGuard` with one pattern, including the reset-pending exemption. + - Depends on: 3.2 + - Tests first: + - **Route guard:** `/i/x` and `/c/x` pass signed out and with a reset pending; `/events`, `/i` and `/c/` still redirect. + - **Proxies:** forward GET and POST with the last X-Forwarded-For hop only. + - **Invite page:** + - is filled with the guest's details; + - shows the full state, the inactive state, the check-in button on an event day, and the checked-in state. + - **Check-in page:** + - shows the not-yet, ended and inactive states with no other details; + - a lookup shows the welcome or a blank form; + - a walk-in submit shows checked in; + - too-many is handled. + - **`/r/`:** works unchanged. + - Scope: `solvway-admin-portal/app/**`, `solvway-admin-portal/middleware*.test.ts` + - Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run` +- [ ] 5.2 Event page: the Guests section, the numbers strip, the capacity and cap fields, the check-in code in the QR card, Print cards (`/events/[uuid]/print`), and Copy all links. + - Depends on: 3.1, 5.1 + - Tests first: + - **Guest actions:** shown only with `BO_EVENT_GUESTS`. + - **Add and paste:** + - add shows field errors; + - paste shows a preview with per-line errors and then saves. + - **Send and links:** + - send to one and send to all unsent; + - guests with no email offer copy link only; + - "emails are saved until delivery is set up" is stated. + - **Remove:** only for Invited guests. + - **Numbers strip:** matches the API. + - **Capacity and cap:** disabled without the module, with the `CAP_BELOW_GUESTS` error shown. + - **Print page:** one card per member plus the event and check-in codes. + - **Copy all:** `name: link` lines. + - **`ROUTE_MODULES`:** maps the print route. + - Scope: `solvway-admin-portal/app/**` + - Verify: as 5.1 +- [ ] 5.3 My QR codes (Share, full screen), the new-code notice in the shell, and the event leads Attended column and filter, Source column and Attended checkbox in the edit form. + - Depends on: 5.2 + - Tests first: + - **Share:** uses `navigator.share` when present, otherwise the clipboard. + - **Full screen:** shows only the QR. + - **Notice:** shown for a code with `addedAt` within 7 days, and dismissed per code. + - **Event leads:** + - the Attended column and filter; + - the Source column; + - the edit Attended checkbox sends `attended`. + - Scope: `solvway-admin-portal/app/**` + - Verify: as 5.1 + +## 6. Release + +- [ ] 6.1 Release checks and docs. + - Depends on: 1.1 to 5.3 + - **`docs/deployment.md`:** the SQL order, `ADMIN_PORTAL_BASE_URL`, granting Event guests, the new gateway paths, and email delivery until SMTP. + - **Live check on the local stack:** + - invite → register → check in by link; + - check in by lookup, as a guest and as a walk-in; + - a guest captured by staff is linked; + - the cap is refused; + - full before the event, not refused on the day; + - numbers agree with the lists; + - an invite email is saved under Emails; + - the audit targets. + - **Playwright at 1280 and 360 px:** the invite page, the check-in page (all states), the Guests section, the print page, and My QR codes share and full screen. + - Scope: `docs/deployment.md`, `openspec/changes/add-event-invitations/tasks.md` + - Verify: the four Maven modules and the portal verify. + +## Workflow follow-up + +- Whole-branch Opus review, PR to `main`, merge, then archive on its own branch with its own PR. +- The visual revamp (separate change) restyles these screens with the rest of the portal. -- 2.54.1 From f47e2a855934fabf258d440ef55515ee257e3c3b Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 16:01:38 +0800 Subject: [PATCH 03/24] feat: event guest, capacity, check-in and attendance schema Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 42 +++++++++++++++++++ .../sql/01-event-guests.sql | 36 ++++++++++++++++ .../sql/02-event-guests-module.sql | 6 +++ .../add-event-invitations/sql/99-rollback.sql | 9 ++++ .../changes/add-event-invitations/tasks.md | 2 +- 5 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/add-event-invitations/sql/01-event-guests.sql create mode 100644 openspec/changes/add-event-invitations/sql/02-event-guests-module.sql create mode 100644 openspec/changes/add-event-invitations/sql/99-rollback.sql diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 42b24bc..0ac41d2 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -301,3 +301,45 @@ SELECT c.`id`, 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`); + +-- add-event-invitations/sql/01-event-guests.sql +USE `service-counter`; + +CREATE TABLE IF NOT EXISTS `event_guest` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `event_uuid` bigint NOT NULL, + `name` varchar(100) NOT NULL, + `mobile_e164` varchar(20) NULL, + `email` varchar(254) NULL, + `company_name` varchar(150) NULL, + `salesperson_user_id` bigint NULL, + `token` varchar(32) NOT NULL, + `invited_at` datetime NULL, + `invite_sent_count` int NOT NULL DEFAULT 0, + `registered_at` datetime NULL, + `event_lead_id` bigint NULL, + `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_event_guest_token` (`token`), + UNIQUE KEY `uk_event_guest_mobile` (`event_uuid`, `mobile_e164`), + UNIQUE KEY `uk_event_guest_email` (`event_uuid`, `email`), + KEY `idx_event_guest_lead` (`event_lead_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +ALTER TABLE `event` + ADD COLUMN `capacity` int NULL, + ADD COLUMN `invitation_cap` int NULL, + ADD COLUMN `checkin_token` varchar(32) NULL, + ADD UNIQUE KEY `uk_event_checkin_token` (`checkin_token`); + +ALTER TABLE `event_lead` ADD COLUMN `attended_at` datetime NULL AFTER `consent_notice_id`; + +-- add-event-invitations/sql/02-event-guests-module.sql +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (41150000, 'BO_EVENT_GUESTS', 'Event guests', 'BO', 'M', 40000000, NULL, NULL); diff --git a/openspec/changes/add-event-invitations/sql/01-event-guests.sql b/openspec/changes/add-event-invitations/sql/01-event-guests.sql new file mode 100644 index 0000000..5ed2abb --- /dev/null +++ b/openspec/changes/add-event-invitations/sql/01-event-guests.sql @@ -0,0 +1,36 @@ +-- Co-Lite change add-event-invitations: guest list, event capacity, invitation cap, check-in code, attendance (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 `event_guest` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `event_uuid` bigint NOT NULL, + `name` varchar(100) NOT NULL, + `mobile_e164` varchar(20) NULL, + `email` varchar(254) NULL, + `company_name` varchar(150) NULL, + `salesperson_user_id` bigint NULL, + `token` varchar(32) NOT NULL, + `invited_at` datetime NULL, + `invite_sent_count` int NOT NULL DEFAULT 0, + `registered_at` datetime NULL, + `event_lead_id` bigint NULL, + `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_event_guest_token` (`token`), + UNIQUE KEY `uk_event_guest_mobile` (`event_uuid`, `mobile_e164`), + UNIQUE KEY `uk_event_guest_email` (`event_uuid`, `email`), + KEY `idx_event_guest_lead` (`event_lead_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +ALTER TABLE `event` + ADD COLUMN `capacity` int NULL, + ADD COLUMN `invitation_cap` int NULL, + ADD COLUMN `checkin_token` varchar(32) NULL, + ADD UNIQUE KEY `uk_event_checkin_token` (`checkin_token`); + +ALTER TABLE `event_lead` ADD COLUMN `attended_at` datetime NULL AFTER `consent_notice_id`; diff --git a/openspec/changes/add-event-invitations/sql/02-event-guests-module.sql b/openspec/changes/add-event-invitations/sql/02-event-guests-module.sql new file mode 100644 index 0000000..61f5412 --- /dev/null +++ b/openspec/changes/add-event-invitations/sql/02-event-guests-module.sql @@ -0,0 +1,6 @@ +-- Co-Lite change add-event-invitations: permission-only module for managing guests, capacity and the invitation cap. +-- Target: `service-system`. No role gets it by default; a super admin grants it under Roles. +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (41150000, 'BO_EVENT_GUESTS', 'Event guests', 'BO', 'M', 40000000, NULL, NULL); diff --git a/openspec/changes/add-event-invitations/sql/99-rollback.sql b/openspec/changes/add-event-invitations/sql/99-rollback.sql new file mode 100644 index 0000000..0d457ad --- /dev/null +++ b/openspec/changes/add-event-invitations/sql/99-rollback.sql @@ -0,0 +1,9 @@ +-- Co-Lite change add-event-invitations: rollback. Deletes guests and attendance marks. +USE `service-system`; +DELETE FROM `modules_roles` WHERE `module_id` = 41150000; +DELETE FROM `module` WHERE `id` = 41150000; + +USE `service-counter`; +DROP TABLE IF EXISTS `event_guest`; +ALTER TABLE `event_lead` DROP COLUMN `attended_at`; +ALTER TABLE `event` DROP INDEX `uk_event_checkin_token`, DROP COLUMN `checkin_token`, DROP COLUMN `invitation_cap`, DROP COLUMN `capacity`; diff --git a/openspec/changes/add-event-invitations/tasks.md b/openspec/changes/add-event-invitations/tasks.md index 0e0edbb..b7d2f18 100644 --- a/openspec/changes/add-event-invitations/tasks.md +++ b/openspec/changes/add-event-invitations/tasks.md @@ -14,7 +14,7 @@ Waves: ## 1. Data -- [ ] 1.1 SQL `sql/01-event-guests.sql` (table `event_guest`, event `capacity`/`invitation_cap`/`checkin_token`, event_lead `attended_at`), `sql/02-event-guests-module.sql` (module `BO_EVENT_GUESTS`), `sql/99-rollback.sql`; mirror 01 and 02 in `local/seed/03-colite.sql`; apply 01 and 02 to the local database. +- [x] 1.1 SQL `sql/01-event-guests.sql` (table `event_guest`, event `capacity`/`invitation_cap`/`checkin_token`, event_lead `attended_at`), `sql/02-event-guests-module.sql` (module `BO_EVENT_GUESTS`), `sql/99-rollback.sql`; 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-event-invitations/sql/**` - Verify: `SELECT` shows the table, its unique keys, the new columns and the module row. -- 2.54.1 From d7a11ab71cd5bbd9a6374ec8439cd48544256c73 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 16:03:38 +0800 Subject: [PATCH 04/24] docs(openspec): close attendance path, guard attend flag, order portal after revamp Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-event-invitations/design.md | 8 ++++---- openspec/changes/add-event-invitations/tasks.md | 10 ++++++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/openspec/changes/add-event-invitations/design.md b/openspec/changes/add-event-invitations/design.md index cf9e350..e316dbc 100644 --- a/openspec/changes/add-event-invitations/design.md +++ b/openspec/changes/add-event-invitations/design.md @@ -25,7 +25,7 @@ The services run with `TZ=Asia/Kuala_Lumpur`, so every stored time is Malaysian - Keep the module-based access model: one new module, and no read-only flags. **Non-Goals:** -- A redesign of the existing screens. The new screens use the current components and will be restyled with the rest of the portal by the coming visual revamp. +- A redesign of the existing screens. The visual revamp is a separate change. The portal tasks of this change start after its foundation (PRODUCT.md, DESIGN.md and tokens) lands, so the new screens are built in the new look. - WhatsApp sending, reminders, RSVP declines. - Backfilling attendance for existing event leads. @@ -117,7 +117,7 @@ All bodies are JSON. `companyId` is always a concrete company, set by mobile-api - `POST /api/admin/events/{uuid}/guests/send` with `{guestIds}` or `{allUnsent: true}` returns `{sent, skippedNoEmail}`. - It builds one email per guest: escaped values, English then Bahasa Malaysia, and the link `/i/`. - It sends with `companyId` = the event's company, then calls counter `markSent` for the sent ones. - - `ADMIN_PORTAL_BASE_URL` is a new mobile-api setting. Emails have no browser origin, unlike the QR card. + - `ADMIN_PORTAL_BASE_URL` is a new mobile-api setting. Emails have no browser origin, unlike the QR card. Only the local profile has a default (`http://localhost:3001`); elsewhere it is required. - `GET /api/admin/events/{uuid}/checkin` returns `{token}`, ensured. - `GET /api/admin/events/{uuid}/attendance` returns the numbers. - Event GET and PUT gain `capacity` and `invitationCap`. The PUT only changes them when the caller has `BO_EVENT_GUESTS`; otherwise it ignores them. @@ -136,6 +136,7 @@ All bodies are JSON. `companyId` is always a concrete company, set by mobile-api - `NOT_YET` and `ENDED` carry only `startDate`, not the other details. An unknown token gives 404 `CODE_INACTIVE`. - `POST /api/public/checkin/{token}/lookup` with `{value}` (mobile or email, detected by the presence of `@`) returns `{result, firstName}`. - `POST /api/public/checkin/{token}/register` takes the walk-in form and returns 200 `{eventName}` (counter register with `attend: true`). + - Only the check-in register sets `attend`. The QR `/api/public/registration` and the invite POST never pass it, whatever the client sends. - **Limits** (Redis keys, 10 minutes): - `inv:load:` 120 and `inv:submit::` 60 for invites; - `chk::` 300 for every check-in call. The check-in page does not count `reg:load`. @@ -149,9 +150,8 @@ Add these anchored method and path pairs: - GET `/counter/checkin/findEvent/[A-Za-z0-9_-]{22}` - POST `/counter/checkin/lookup` - POST `/counter/checkin/byGuest` -- POST `/counter/event/attendance` (for the capacity check on the public invite) -`/counter/registration/register` is already open. Everything else stays closed. +`/counter/registration/register` is already open. The public pages load the event, company, notice and interests through the paths the QR change already opened. Everything else stays closed, including `/counter/event/attendance`: the capacity check runs inside `eventGuest/register`. ### 6. Portal diff --git a/openspec/changes/add-event-invitations/tasks.md b/openspec/changes/add-event-invitations/tasks.md index b7d2f18..3e7f8e0 100644 --- a/openspec/changes/add-event-invitations/tasks.md +++ b/openspec/changes/add-event-invitations/tasks.md @@ -9,7 +9,7 @@ Waves: - 2.2 (services-counter, part B, after 2.1); - 3.2 (mobile-api public, after 3.1); - 4.1 (gateway). -- **Wave 3** (serial): 5.1, 5.2 and 5.3 (portal). They share the message catalogue, and 5.1 touches the route guard, which is security code. +- **Wave 3** (serial): 5.1, 5.2 and 5.3 (portal). They start after the visual revamp foundation (PRODUCT.md, DESIGN.md and tokens) is on `main`, and are built in the new look. They share the message catalogue, and 5.1 touches the route guard, which is security code. - **Wave 4** (serial, controller): 6.1. ## 1. Data @@ -82,6 +82,7 @@ Waves: - **Event-lead PUT:** passes `attended`. - **Audit:** the target is the event uuid on every guest endpoint. - **Wiring:** a test proves the new services start (constructor selection). + - **Setting:** `ADMIN_PORTAL_BASE_URL` defaults to `http://localhost:3001` in the local profile only, and is logged at startup. - Scope: `solvway-mobile-api/src/**` - Verify: `mvn -T 1C -q -pl solvway-mobile-api verify` - [ ] 3.2 Public invite and check-in endpoints (decision 4, public part). @@ -104,6 +105,7 @@ Waves: - returns `firstName` only for CHECKED_IN; - the FORM answer carries no details. - **Check-in register:** calls counter register with `attend: true` and no salesperson. + - **No `attend` leak:** `/api/public/registration` and the invite POST never pass `attend`, even when the client sends it. - **Limits:** `inv:load` 120, `inv:submit` 60 and `chk` 300 give 429 `TOO_MANY`; the check-in page does not count `reg:load`. - Scope: `solvway-mobile-api/src/**` - Verify: `mvn -T 1C -q -pl solvway-mobile-api verify` @@ -114,7 +116,7 @@ Waves: - Depends on: none (contracts fixed) - Tests first: - each new pair passes without a user token; - - these still get 401: `/counter/eventGuest/list`, `/counter/eventGuest/add`, `/counter/eventGuest/remove`, `/counter/eventGuest/markSent`, `/counter/checkin/ensureToken`, wrong methods, extra segments and bad token shapes. + - these still get 401: `/counter/event/attendance`, `/counter/eventGuest/list`, `/counter/eventGuest/add`, `/counter/eventGuest/remove`, `/counter/eventGuest/markSent`, `/counter/checkin/ensureToken`, wrong methods, extra segments and bad token shapes. - Scope: `solvway-api-gateway/src/**` - Verify: `mvn -T 1C -q -pl solvway-api-gateway verify` @@ -123,7 +125,7 @@ Waves: Every portal verify must report the exit codes of lint, tsc and vitest. Vitest exits 1 on unhandled errors even when every test passes. - [ ] 5.1 Public pages: extract the shared registration form from `/r/[token]`; add `/i/[token]` and `/c/[token]` and their proxies; make all three paths public in `routeGuard` with one pattern, including the reset-pending exemption. - - Depends on: 3.2 + - Depends on: 3.2, the visual revamp foundation - Tests first: - **Route guard:** `/i/x` and `/c/x` pass signed out and with a reset pending; `/events`, `/i` and `/c/` still redirect. - **Proxies:** forward GET and POST with the last X-Forwarded-For hop only. @@ -191,4 +193,4 @@ Every portal verify must report the exit codes of lint, tsc and vitest. Vitest e ## Workflow follow-up - Whole-branch Opus review, PR to `main`, merge, then archive on its own branch with its own PR. -- The visual revamp (separate change) restyles these screens with the rest of the portal. +- The visual revamp (separate change) lands its foundation before wave 3, then restyles the existing screens. -- 2.54.1 From 84bc0e5e11a95ed281847afa5f94850ecfcdc903 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 16:41:30 +0800 Subject: [PATCH 05/24] feat: event days, guest linking, attendance and event headcount Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../counter/controller/EventController.java | 7 + .../counter/dto/EventLeadUpdateRequest.java | 9 +- .../solvway/services/counter/model/Event.java | 2 + .../services/counter/model/EventGuest.java | 68 +++++ .../services/counter/model/EventLead.java | 3 + .../counter/repo/EventGuestRepository.java | 20 ++ .../counter/repo/EventLeadRepository.java | 7 + .../service/EventHeadcountService.java | 33 +++ .../counter/service/EventLeadService.java | 31 +- .../counter/service/EventService.java | 20 +- .../services/counter/service/GuestLinker.java | 33 +++ .../service/RegistrationLinkService.java | 16 +- .../counter/service/RegistrationService.java | 40 ++- .../services/counter/util/EventDays.java | 18 ++ .../counter/model/EventGuestMappingTest.java | 41 +++ .../service/AttendanceAtCaptureTest.java | 265 ++++++++++++++++++ .../service/EventHeadcountServiceTest.java | 79 ++++++ .../counter/service/EventSettingsTest.java | 99 +++++++ .../counter/service/GuestLinkerTest.java | 103 +++++++ .../counter/service/InvitationWiringTest.java | 43 +++ .../RegistrationLinkMineAddedAtTest.java | 67 +++++ .../services/counter/util/EventDaysTest.java | 51 ++++ 22 files changed, 1036 insertions(+), 19 deletions(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventGuest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventGuestRepository.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventHeadcountService.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/GuestLinker.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/util/EventDays.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/model/EventGuestMappingTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/AttendanceAtCaptureTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventHeadcountServiceTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventSettingsTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/GuestLinkerTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/InvitationWiringTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkMineAddedAtTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/util/EventDaysTest.java diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventController.java index 2905c11..db00a83 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventController.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventController.java @@ -1,6 +1,7 @@ package com.solvway.services.counter.controller; import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.service.EventHeadcountService; import com.solvway.services.counter.service.EventService; import com.solvway.services.counter.util.paging.PageableRest; import lombok.AllArgsConstructor; @@ -22,6 +23,7 @@ import java.util.Optional; public class EventController { private final EventService eventService; private final ModelMapper modelMapper; + private final EventHeadcountService headcountService; @GetMapping("/findAll") public List findAll(){ return eventService.findAll(); @@ -35,6 +37,11 @@ public class EventController { return eventService.findByUuid(uuid); } + @PostMapping("/attendance") + public EventHeadcountService.Headcount attendance(@RequestBody EventHeadcountService.Request req) { + return headcountService.headcount(req); + } + @PostMapping("/save") public Event save(@RequestBody Event event) { return eventService.save(event); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java index 0e46885..ce4fb63 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java @@ -3,7 +3,12 @@ package com.solvway.services.counter.dto; import java.time.LocalDate; import java.util.List; -/** Replaces an event lead's working fields and its interest set. Values arrive validated by mobile-api. */ +/** Replaces an event lead's working fields and its interest set. Values arrive validated by mobile-api. attended: true stamps now if empty, false clears, null leaves it. */ public record EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature, String status, List interestIds, LocalDate nextFollowUpDate, String notes, - String doneBy) {} + String doneBy, Boolean attended) { + public EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature, + String status, List interestIds, LocalDate nextFollowUpDate, String notes, String doneBy) { + this(companyId, eventLeadUuid, salespersonUserId, temperature, status, interestIds, nextFollowUpDate, notes, doneBy, null); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java index 58ab73f..19ff6db 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java @@ -24,6 +24,8 @@ public class Event implements Serializable { private LocalDateTime dateEnd; @Column(name = "company_id", updatable = false) private Long companyId; + private Integer capacity; + private Integer invitationCap; private String uploadFloorPlan; private String uploadStageActivities; private String uploadLuckyDraw; diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventGuest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventGuest.java new file mode 100644 index 0000000..0efc934 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventGuest.java @@ -0,0 +1,68 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** A person invited to an event; linked to an event lead once they register or are captured. */ +@Getter +@Setter +@Entity +@Table(name = "event_guest", uniqueConstraints = { + @UniqueConstraint(columnNames = {"token"}), + @UniqueConstraint(columnNames = {"event_uuid", "mobile_e164"}), + @UniqueConstraint(columnNames = {"event_uuid", "email"}) +}) +public class EventGuest { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "company_id") + private long companyId; + + @Column(name = "event_uuid") + private long eventUuid; + + private String name; + + @Column(name = "mobile_e164") + private String mobileE164; + + private String email; + + @Column(name = "company_name") + private String companyName; + + @Column(name = "salesperson_user_id") + private Long salespersonUserId; + + @Column(length = 32) + private String token; + + @Column(name = "invited_at") + private LocalDateTime invitedAt; + + @Column(name = "invite_sent_count") + private int inviteSentCount = 0; + + @Column(name = "registered_at") + private LocalDateTime registeredAt; + + @Column(name = "event_lead_id") + private Long eventLeadId; + + @Column(name = "created_by", updatable = false) + private String createdBy; + + @Column(name = "created_at", updatable = false) + private LocalDateTime createdAt = LocalDateTime.now(); + + @Column(name = "updated_by") + private String updatedBy; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java index 692f642..1e87232 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java @@ -55,6 +55,9 @@ public class EventLead { private Long consentNoticeId; + @Column(name = "attended_at") + private LocalDateTime attendedAt; + @Column(updatable = false) private LocalDateTime capturedAt = LocalDateTime.now(); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventGuestRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventGuestRepository.java new file mode 100644 index 0000000..5e71d3c --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventGuestRepository.java @@ -0,0 +1,20 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.EventGuest; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface EventGuestRepository extends JpaRepository { + Optional findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(long eventUuid, String mobileE164); + + Optional findFirstByEventUuidAndEventLeadIdIsNullAndEmail(long eventUuid, String email); + + boolean existsByEventLeadId(Long eventLeadId); + + long countByEventUuid(long eventUuid); + + long countByEventUuidAndEventLeadIdIsNotNull(long eventUuid); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java index 8e2276b..15724d4 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java @@ -40,6 +40,13 @@ public interface EventLeadRepository extends JpaRepository { @Param("status") String status, @Param("interestId") Long interestId, @Param("leadType") String leadType, Pageable pageable); + long countByEventUuidAndAttendedAtIsNotNull(long eventUuid); + + /** Event leads of the event that no guest row links to. */ + @Query("SELECT COUNT(e) FROM EventLead e WHERE e.eventUuid = :eventUuid" + + " AND NOT EXISTS (SELECT 1 FROM EventGuest g WHERE g.eventLeadId = e.id)") + long countWalkIns(@Param("eventUuid") long eventUuid); + /** Rows are [EventLead, Event]; Event is null when the event row is gone. Newest capture first. */ @Query("SELECT e, ev FROM EventLead e LEFT JOIN Event ev ON ev.uuid = e.eventUuid" + " WHERE e.companyId = :companyId AND e.leadUuid = :leadUuid ORDER BY e.capturedAt DESC, e.id DESC") diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventHeadcountService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventHeadcountService.java new file mode 100644 index 0000000..6c9f139 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventHeadcountService.java @@ -0,0 +1,33 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventRepository; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +/** Invited / registered / attended numbers of one event. */ +@Service +@AllArgsConstructor +public class EventHeadcountService { + public record Request(Long companyId, long eventUuid) {} + /** total = registered guests + walk-ins (event leads with no guest row). */ + public record Headcount(long invited, Integer cap, long registered, long attended, long walkIns, long total, Integer capacity) {} + + private final EventRepository eventRepository; + private final EventGuestRepository guestRepository; + private final EventLeadRepository eventLeadRepository; + + public Headcount headcount(Request req) { + var event = eventRepository.findByUuid(req.eventUuid()) + .filter(e -> req.companyId() != null && req.companyId().equals(e.getCompanyId())) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND")); + long registered = guestRepository.countByEventUuidAndEventLeadIdIsNotNull(req.eventUuid()); + long walkIns = eventLeadRepository.countWalkIns(req.eventUuid()); + return new Headcount(guestRepository.countByEventUuid(req.eventUuid()), event.getInvitationCap(), registered, + eventLeadRepository.countByEventUuidAndAttendedAtIsNotNull(req.eventUuid()), walkIns, registered + walkIns, + event.getCapacity()); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java index 06c8df0..b6e06e7 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java @@ -14,8 +14,11 @@ import com.solvway.services.counter.model.Lead; import com.solvway.services.counter.repo.EventLeadInterestRepository; import com.solvway.services.counter.repo.EventLeadRepository; import com.solvway.services.counter.repo.EventLeadStatusChangeRepository; +import com.solvway.services.counter.repo.EventRepository; import com.solvway.services.counter.repo.LeadRepository; +import com.solvway.services.counter.util.EventDays; import lombok.AllArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -39,7 +42,7 @@ import java.util.stream.Collectors; * Never log a lead's name, mobile or email. */ @Service -@AllArgsConstructor +@AllArgsConstructor(onConstructor_ = @Autowired) public class EventLeadService { private static final int MAX_MATCHES = 20; private static final int MAX_PAGE_SIZE = 100; @@ -48,6 +51,25 @@ public class EventLeadService { private final EventLeadRepository eventLeadRepository; private final EventLeadInterestRepository eventLeadInterestRepository; private final EventLeadStatusChangeRepository eventLeadStatusChangeRepository; + private final EventRepository eventRepository; + private final GuestLinker guestLinker; + + // ponytail: null event repository and linker keep the pre-invitation wiring working; drop once callers pass both. + public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository, + EventLeadInterestRepository eventLeadInterestRepository, + EventLeadStatusChangeRepository eventLeadStatusChangeRepository) { + this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, null, null); + } + + /** True when today is one of the event's days. */ + public boolean isDuringEvent(long eventUuid) { + return eventRepository != null && eventRepository.findByUuid(eventUuid) + .map(e -> EventDays.isDuring(e, LocalDateTime.now())).orElse(false); + } + + public void linkGuest(long eventUuid, EventLead eventLead, Lead lead) { + if (guestLinker != null) guestLinker.link(eventUuid, eventLead, lead); + } public List findMatches(LeadMatchRequest req) { requireCompany(req.companyId()); @@ -111,6 +133,7 @@ public class EventLeadService { eventLead.setNextFollowUpDate(req.nextFollowUpDate()); eventLead.setNotes(req.notes()); eventLead.setCapturedBy(req.doneBy()); + if (isDuringEvent(req.eventUuid())) eventLead.setAttendedAt(LocalDateTime.now()); try { eventLead = eventLeadRepository.saveAndFlush(eventLead); } catch (DataIntegrityViolationException e) { @@ -119,6 +142,7 @@ public class EventLeadService { } recordStatusChange(eventLead, null, eventLead.getStatus(), eventLead.getCapturedAt(), req.doneBy()); + linkGuest(req.eventUuid(), eventLead, lead); List interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds()); return detail(eventLead, lead, interestIds); } @@ -162,6 +186,11 @@ public class EventLeadService { if (req.status() != null) eventLead.setStatus(req.status()); eventLead.setNextFollowUpDate(req.nextFollowUpDate()); eventLead.setNotes(blankToNull(req.notes())); + if (Boolean.TRUE.equals(req.attended())) { + if (eventLead.getAttendedAt() == null) eventLead.setAttendedAt(LocalDateTime.now()); + } else if (Boolean.FALSE.equals(req.attended())) { + eventLead.setAttendedAt(null); + } eventLead.setUpdatedBy(req.doneBy()); eventLead.setUpdatedAt(LocalDateTime.now()); eventLead = eventLeadRepository.saveAndFlush(eventLead); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java index b873dbf..248302f 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java @@ -2,12 +2,14 @@ package com.solvway.services.counter.service; import com.solvway.core.enums.GeneralEnum; import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.repo.EventGuestRepository; import com.solvway.services.counter.repo.EventRepository; import com.solvway.services.counter.util.paging.PageableRest; import com.solvway.services.counter.util.redis.RedisUtil; import jakarta.annotation.PostConstruct; import jakarta.transaction.Transactional; import lombok.AllArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.scheduling.annotation.EnableScheduling; @@ -24,11 +26,17 @@ import java.util.concurrent.TimeUnit; @Service @Slf4j -@AllArgsConstructor +@AllArgsConstructor(onConstructor_ = @Autowired) @EnableScheduling public class EventService { private final EventRepository eventRepository; private final RedisUtil redisUtil; + private final EventGuestRepository guestRepository; + + // ponytail: null guest repository skips the cap-below-guests check; drop once callers pass one. + public EventService(EventRepository eventRepository, RedisUtil redisUtil) { + this(eventRepository, redisUtil, null); + } private static final String EVENT_CACHE_PREFIX = "service:counter:event:"; private static final String EVENT_CACHE_CURRENT_PREFIX="service:counter:event:current:"; @PostConstruct @@ -38,12 +46,20 @@ public class EventService { } @Transactional public Event save(Event event) { + if (event.getCapacity() != null && event.getCapacity() < 1) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "CAPACITY_INVALID"); + if (event.getInvitationCap() != null && event.getInvitationCap() < 1) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVITATION_CAP_INVALID"); if (event.getId() == null) { if (event.getCompanyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); } else { // company is immutable: always carry the stored one so entity and cache match the DB Optional stored = eventRepository.findById(event.getId()); - if (stored.isPresent()) event.setCompanyId(stored.get().getCompanyId()); + if (stored.isPresent()) { + event.setCompanyId(stored.get().getCompanyId()); + if (event.getInvitationCap() != null && guestRepository != null + && guestRepository.countByEventUuid(stored.get().getUuid()) > event.getInvitationCap()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "CAP_BELOW_GUESTS"); + } + } } event = eventRepository.save(event); updateEventCache(event); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/GuestLinker.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/GuestLinker.java new file mode 100644 index 0000000..b4e4ee6 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/GuestLinker.java @@ -0,0 +1,33 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.EventGuest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventGuestRepository; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.Optional; + +/** Links an unlinked guest of the event to the event lead that matches by mobile, else email. Never logs contact data. */ +@Service +@AllArgsConstructor +public class GuestLinker { + private final EventGuestRepository guests; + + // ponytail: unlocked read-modify-write; two concurrent captures could link the same guest (last write wins). Upgrade: SELECT ... FOR UPDATE on the guest row. + public void link(long eventUuid, EventLead eventLead, Lead lead) { + if (guests.existsByEventLeadId(eventLead.getId())) return; + Optional guest = lead.getMobileE164() == null ? Optional.empty() + : guests.findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(eventUuid, lead.getMobileE164()); + if (guest.isEmpty() && lead.getEmailNormalised() != null) { + guest = guests.findFirstByEventUuidAndEventLeadIdIsNullAndEmail(eventUuid, lead.getEmailNormalised()); + } + guest.ifPresent(g -> { + g.setEventLeadId(eventLead.getId()); + if (g.getRegisteredAt() == null) g.setRegisteredAt(LocalDateTime.now()); + guests.save(g); + }); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java index 3ae5f9f..92606c1 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java @@ -19,7 +19,9 @@ import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Base64; import java.util.Comparator; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; /** QR registration codes per event: one event code and one personal code per salesperson. */ @@ -34,7 +36,7 @@ public class RegistrationLinkService { public record LinkView(long eventUuid, Long salespersonUserId, String token, boolean enabled) {} public record LinkLookup(long companyId, long eventUuid, Long salespersonUserId, String token, boolean enabled) {} public record MineRow(String eventUuid, String eventName, String startDate, String endDate, String location, - String token, boolean enabled) {} + String token, boolean enabled, String addedAt) {} private final RegistrationLinkRepository linkRepository; private final EventRepository eventRepository; @@ -73,16 +75,18 @@ public class RegistrationLinkService { @Transactional public List mine(MineRequest req) { LocalDate today = LocalDate.parse(req.today()); - List uuids = eventSalespersonRepository.findByCompanyIdAndUserId(req.companyId(), req.userId()).stream() - .map(EventSalesperson::getEventUuid).toList(); - if (uuids.isEmpty()) return List.of(); - return eventRepository.findByCompanyIdAndUuidIn(req.companyId(), uuids).stream() + Map addedAt = new HashMap<>(); + eventSalespersonRepository.findByCompanyIdAndUserId(req.companyId(), req.userId()) + .forEach(r -> addedAt.putIfAbsent(r.getEventUuid(), r.getCreateDateTime())); + if (addedAt.isEmpty()) return List.of(); + return eventRepository.findByCompanyIdAndUuidIn(req.companyId(), addedAt.keySet()).stream() .filter(e -> e.getEnabled() == GeneralEnum.FlagYesNo.Y && e.getDateEnd() != null && !e.getDateEnd().toLocalDate().isBefore(today)) .sorted(Comparator.comparing(Event::getDateStart, Comparator.nullsLast(Comparator.naturalOrder()))) .map(e -> { RegistrationLink l = personal(req.companyId(), e.getUuid(), req.userId()); return new MineRow(String.valueOf(e.getUuid()), e.getName(), e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString(), - e.getDateEnd().toLocalDate().toString(), e.getLocation(), l.getToken(), l.isEnabled()); + e.getDateEnd().toLocalDate().toString(), e.getLocation(), l.getToken(), l.isEnabled(), + addedAt.get(e.getUuid()) == null ? null : addedAt.get(e.getUuid()).toString()); }).toList(); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java index b2d4eb0..73ca77f 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java @@ -5,6 +5,7 @@ import com.solvway.services.counter.model.Lead; import com.solvway.services.counter.repo.EventLeadRepository; import com.solvway.services.counter.repo.LeadRepository; import lombok.AllArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.springframework.transaction.support.TransactionTemplate; @@ -19,11 +20,18 @@ import java.util.Optional; * Never log a lead's name, mobile or email. */ @Service -@AllArgsConstructor +@AllArgsConstructor(onConstructor_ = @Autowired) public class RegistrationService { public record RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, String email, String companyName, String jobTitle, List interestIds, - Long consentNoticeId, LocalDateTime consentAt) {} + Long consentNoticeId, LocalDateTime consentAt, boolean attend) { + public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, + String email, String companyName, String jobTitle, List interestIds, + Long consentNoticeId, LocalDateTime consentAt) { + this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds, + consentNoticeId, consentAt, false); + } + } public record RegisterResult(String outcome, String eventLeadUuid) {} private static final String QR = "qr"; @@ -32,6 +40,13 @@ public class RegistrationService { private final LeadRepository leadRepository; private final EventLeadRepository eventLeadRepository; private final EventLeadService eventLeadService; + private final GuestLinker guestLinker; + + // ponytail: null linker keeps the pre-invitation wiring working; drop once callers pass one. + public RegistrationService(TransactionTemplate transactionTemplate, LeadRepository leadRepository, + EventLeadRepository eventLeadRepository, EventLeadService eventLeadService) { + this(transactionTemplate, leadRepository, eventLeadRepository, eventLeadService, null); + } public RegisterResult register(RegisterRequest req) { try { @@ -72,7 +87,7 @@ public class RegistrationService { } else { lead = match.get(); Optional captured = eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid()); - if (captured.isPresent()) return alreadyCaptured(captured.get(), req.salespersonUserId()); + if (captured.isPresent()) return alreadyCaptured(captured.get(), lead, req); notes = differences(lead, req); leadType = "EXISTING"; } @@ -89,21 +104,30 @@ public class RegistrationService { e.setCapturedBy(QR); e.setConsentAt(req.consentAt()); e.setConsentNoticeId(req.consentNoticeId()); + if (req.attend() || eventLeadService.isDuringEvent(req.eventUuid())) e.setAttendedAt(LocalDateTime.now()); e = eventLeadRepository.saveAndFlush(e); eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR); eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds()); + link(req, e, lead); return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid())); } - private RegisterResult alreadyCaptured(EventLead e, Long salespersonUserId) { - if (e.getSalespersonUserId() == null && salespersonUserId != null) { - e.setSalespersonUserId(salespersonUserId); + private RegisterResult alreadyCaptured(EventLead e, Lead lead, RegisterRequest req) { + boolean assign = e.getSalespersonUserId() == null && req.salespersonUserId() != null; + boolean attend = req.attend() && e.getAttendedAt() == null; + if (assign) e.setSalespersonUserId(req.salespersonUserId()); + if (attend) e.setAttendedAt(LocalDateTime.now()); + if (assign || attend) { e.setUpdatedBy(QR); e.setUpdatedAt(LocalDateTime.now()); eventLeadRepository.save(e); - return new RegisterResult("ASSIGNED", String.valueOf(e.getUuid())); } - return new RegisterResult("ALREADY_CAPTURED", String.valueOf(e.getUuid())); + link(req, e, lead); + return new RegisterResult(assign ? "ASSIGNED" : "ALREADY_CAPTURED", String.valueOf(e.getUuid())); + } + + private void link(RegisterRequest req, EventLead e, Lead lead) { + if (guestLinker != null) guestLinker.link(req.eventUuid(), e, lead); } /** Submitted non-blank values that differ from the lead's, as an event-lead note; null when nothing differs. */ diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/util/EventDays.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/util/EventDays.java new file mode 100644 index 0000000..ff49930 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/util/EventDays.java @@ -0,0 +1,18 @@ +package com.solvway.services.counter.util; + +import com.solvway.services.counter.model.Event; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** Event days are calendar days in the server zone: the whole first and last day count. */ +public final class EventDays { + private EventDays() {} + + public static boolean isDuring(Event event, LocalDateTime now) { + if (event.getDateEnd() == null) return false; + LocalDate day = now.toLocalDate(); + boolean started = event.getDateStart() == null || !day.isBefore(event.getDateStart().toLocalDate()); + return started && !day.isAfter(event.getDateEnd().toLocalDate()); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/model/EventGuestMappingTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/model/EventGuestMappingTest.java new file mode 100644 index 0000000..f42b78b --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/model/EventGuestMappingTest.java @@ -0,0 +1,41 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Table; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** EventGuest maps the event_guest table of 01-event-guests.sql. */ +class EventGuestMappingTest { + @Test + void tableAndUniqueKeys() { + Table t = EventGuest.class.getAnnotation(Table.class); + assertThat(t.name()).isEqualTo("event_guest"); + List> uniques = Arrays.stream(t.uniqueConstraints()).map(u -> List.of(u.columnNames())).toList(); + assertThat(uniques).containsExactlyInAnyOrder(List.of("token"), List.of("event_uuid", "mobile_e164"), List.of("event_uuid", "email")); + } + + @Test + void columnNames() throws Exception { + assertThat(columnOf("eventUuid")).isEqualTo("event_uuid"); + assertThat(columnOf("mobileE164")).isEqualTo("mobile_e164"); + assertThat(columnOf("eventLeadId")).isEqualTo("event_lead_id"); + assertThat(columnOf("salespersonUserId")).isEqualTo("salesperson_user_id"); + assertThat(EventGuest.class.getDeclaredField("token").getAnnotation(Column.class).length()).isEqualTo(32); + for (String f : List.of("companyId", "name", "companyName", "token", "invitedAt", "inviteSentCount", "registeredAt", + "createdBy", "createdAt", "updatedBy", "updatedAt")) { + assertThat(EventGuest.class.getDeclaredField(f)).isNotNull(); + } + assertThat(new EventGuest().getInviteSentCount()).isZero(); + } + + private static String columnOf(String field) throws Exception { + Field f = EventGuest.class.getDeclaredField(field); + return f.getAnnotation(Column.class).name(); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/AttendanceAtCaptureTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/AttendanceAtCaptureTest.java new file mode 100644 index 0000000..4eaf059 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/AttendanceAtCaptureTest.java @@ -0,0 +1,265 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import com.solvway.services.counter.dto.EventLeadUpdateRequest; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventLeadStatusChangeRepository; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Attendance stamped at capture (staff and QR), the attend flag, the staff edit toggle, and the guest link call. */ +@ExtendWith(MockitoExtension.class) +class AttendanceAtCaptureTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository interestRepository; + @Mock private EventLeadStatusChangeRepository statusChangeRepository; + @Mock private EventRepository eventRepository; + @Mock private GuestLinker guestLinker; + + private EventLeadService eventLeadService; + private RegistrationService registration; + + @BeforeEach + void setUp() { + eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, interestRepository, statusChangeRepository, + eventRepository, guestLinker); + registration = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)), + leadRepository, eventLeadRepository, eventLeadService, guestLinker); + lenient().when(leadRepository.saveAndFlush(any(Lead.class))).then(returnsFirstArg()); + lenient().when(eventLeadRepository.saveAndFlush(any(EventLead.class))).then(i -> { + EventLead e = i.getArgument(0); + e.setId(1L); + return e; + }); + } + + private void eventDays(int startOffset, int endOffset) { + Event ev = new Event(); + ev.setDateStart(LocalDateTime.now().plusDays(startOffset)); + ev.setDateEnd(LocalDateTime.now().plusDays(endOffset)); + lenient().when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(ev)); + } + + private EventLead staffCapture() { + eventLeadService.capture(new EventLeadCaptureRequest(COMPANY, EVENT, null, "Aisyah", "+60123456789", null, null, null, + 7L, null, null, List.of(), null, null, "sales1")); + ArgumentCaptor c = ArgumentCaptor.forClass(EventLead.class); + verify(eventLeadRepository).saveAndFlush(c.capture()); + return c.getValue(); + } + + private static RegistrationService.RegisterRequest qr(boolean attend) { + return new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "Aisyah", "+60123456789", null, null, null, + List.of(), null, null, attend); + } + + private EventLead qrNewEventLead(boolean attend) { + lenient().when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, "+60123456789")).thenReturn(Optional.empty()); + registration.register(qr(attend)); + ArgumentCaptor c = ArgumentCaptor.forClass(EventLead.class); + verify(eventLeadRepository).saveAndFlush(c.capture()); + return c.getValue(); + } + + private EventLead existingCaptured(LocalDateTime attendedAt) { + Lead lead = new Lead(); + lead.setCompanyId(COMPANY); + EventLead existing = new EventLead(); + existing.setId(9L); + existing.setLeadUuid(lead.getUuid()); + existing.setSalespersonUserId(7L); + existing.setAttendedAt(attendedAt); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, "+60123456789")).thenReturn(Optional.of(lead)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, lead.getUuid())).thenReturn(Optional.of(existing)); + return existing; + } + + // --- staff capture --- + + @Test + void staffCaptureDuringEventDaysSetsAttendedAt() { + eventDays(-1, 1); + assertThat(staffCapture().getAttendedAt()).isNotNull(); + } + + private EventLead staffCaptureOfExistingLead() { + Lead crm = new Lead(); + crm.setName("Aisyah"); + lenient().when(leadRepository.findByUuidAndCompanyId(crm.getUuid(), COMPANY)).thenReturn(Optional.of(crm)); + eventLeadService.capture(new EventLeadCaptureRequest(COMPANY, EVENT, crm.getUuid(), "Aisyah", null, null, null, null, + 7L, null, null, List.of(), null, null, "sales1")); + ArgumentCaptor c = ArgumentCaptor.forClass(EventLead.class); + verify(eventLeadRepository).saveAndFlush(c.capture()); + return c.getValue(); + } + + @Test + void staffCaptureOfExistingLeadDuringEventDaysSetsAttendedAt() { + eventDays(-1, 1); + assertThat(staffCaptureOfExistingLead().getAttendedAt()).isNotNull(); + } + + @Test + void staffCaptureOfExistingLeadBeforeEventDaysLeavesAttendedAtEmpty() { + eventDays(2, 3); + assertThat(staffCaptureOfExistingLead().getAttendedAt()).isNull(); + } + + @Test + void staffCaptureBeforeEventDaysLeavesAttendedAtEmpty() { + eventDays(2, 3); + assertThat(staffCapture().getAttendedAt()).isNull(); + } + + @Test + void staffCaptureLinksGuestAfterTheEventLeadIsSaved() { + eventDays(-1, 1); + EventLead e = staffCapture(); + var order = inOrder(eventLeadRepository, guestLinker); + order.verify(eventLeadRepository).saveAndFlush(e); + order.verify(guestLinker).link(org.mockito.ArgumentMatchers.eq(EVENT), org.mockito.ArgumentMatchers.same(e), any(Lead.class)); + } + + // --- QR register --- + + @Test + void qrNewDuringEventDaysSetsAttendedAt() { + eventDays(-1, 1); + assertThat(qrNewEventLead(false).getAttendedAt()).isNotNull(); + } + + @Test + void qrNewBeforeEventDaysLeavesAttendedAtEmpty() { + eventDays(2, 3); + assertThat(qrNewEventLead(false).getAttendedAt()).isNull(); + } + + @Test + void attendTrueSetsAttendedAtOnNewEvenOutsideEventDays() { + eventDays(2, 3); + assertThat(qrNewEventLead(true).getAttendedAt()).isNotNull(); + } + + @Test + void attendTrueSetsAttendedAtOnAlreadyCapturedAndSaves() { + EventLead existing = existingCaptured(null); + + RegistrationService.RegisterResult r = registration.register(qr(true)); + + assertThat(r.outcome()).isEqualTo("ALREADY_CAPTURED"); + assertThat(existing.getAttendedAt()).isNotNull(); + verify(eventLeadRepository).save(existing); + } + + @Test + void repeatRegistrationDuringEventDaysDoesNotSetAttendedAt() { + eventDays(-1, 1); + EventLead existing = existingCaptured(null); + + registration.register(qr(false)); + + assertThat(existing.getAttendedAt()).isNull(); + } + + @Test + void attendTrueKeepsAnExistingAttendedAt() { + LocalDateTime earlier = LocalDateTime.of(2026, 12, 1, 9, 0); + EventLead existing = existingCaptured(earlier); + + registration.register(qr(true)); + + assertThat(existing.getAttendedAt()).isEqualTo(earlier); + } + + @Test + void qrRegisterLinksGuestForNewAndForAlreadyCaptured() { + eventDays(-1, 1); + EventLead existing = existingCaptured(null); + + registration.register(qr(false)); + + verify(guestLinker).link(org.mockito.ArgumentMatchers.eq(EVENT), org.mockito.ArgumentMatchers.same(existing), any(Lead.class)); + } + + @Test + void qrRegisterNewLinksGuest() { + eventDays(-1, 1); + EventLead e = qrNewEventLead(false); + verify(guestLinker).link(org.mockito.ArgumentMatchers.eq(EVENT), org.mockito.ArgumentMatchers.same(e), any(Lead.class)); + } + + // --- staff edit --- + + private EventLeadUpdateRequest update(Boolean attended) { + return new EventLeadUpdateRequest(COMPANY, 3L, null, null, null, List.of(), null, null, "sales2", attended); + } + + private EventLead editable(LocalDateTime attendedAt) { + EventLead el = new EventLead(); + el.setId(5L); + el.setAttendedAt(attendedAt); + lenient().when(eventLeadRepository.findByUuidAndCompanyId(3L, COMPANY)).thenReturn(Optional.of(el)); + lenient().when(eventLeadRepository.saveAndFlush(el)).thenReturn(el); + lenient().when(leadRepository.findByUuidAndCompanyId(el.getLeadUuid(), COMPANY)).thenReturn(Optional.of(new Lead())); + return el; + } + + @Test + void updateAttendedTrueSetsTimeWhenEmpty() { + EventLead el = editable(null); + eventLeadService.update(update(true)); + assertThat(el.getAttendedAt()).isNotNull(); + } + + @Test + void updateAttendedTrueKeepsExistingTime() { + LocalDateTime earlier = LocalDateTime.of(2026, 12, 1, 9, 0); + EventLead el = editable(earlier); + eventLeadService.update(update(true)); + assertThat(el.getAttendedAt()).isEqualTo(earlier); + } + + @Test + void updateAttendedFalseClears() { + EventLead el = editable(LocalDateTime.of(2026, 12, 1, 9, 0)); + eventLeadService.update(update(false)); + assertThat(el.getAttendedAt()).isNull(); + } + + @Test + void updateAttendedNullLeavesUnchanged() { + LocalDateTime earlier = LocalDateTime.of(2026, 12, 1, 9, 0); + EventLead el = editable(earlier); + eventLeadService.update(update(null)); + assertThat(el.getAttendedAt()).isEqualTo(earlier); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventHeadcountServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventHeadcountServiceTest.java new file mode 100644 index 0000000..ca8f5f4 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventHeadcountServiceTest.java @@ -0,0 +1,79 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EventHeadcountServiceTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + + @Mock private EventRepository eventRepository; + @Mock private EventGuestRepository guestRepository; + @Mock private EventLeadRepository eventLeadRepository; + + private EventHeadcountService service() { + return new EventHeadcountService(eventRepository, guestRepository, eventLeadRepository); + } + + @Test + void reportsTheNumbers() { + Event e = new Event(); + e.setCompanyId(COMPANY); + e.setCapacity(100); + e.setInvitationCap(50); + when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(e)); + when(guestRepository.countByEventUuid(EVENT)).thenReturn(40L); + when(guestRepository.countByEventUuidAndEventLeadIdIsNotNull(EVENT)).thenReturn(30L); + when(eventLeadRepository.countByEventUuidAndAttendedAtIsNotNull(EVENT)).thenReturn(35L); + when(eventLeadRepository.countWalkIns(EVENT)).thenReturn(15L); + + EventHeadcountService.Headcount h = service().headcount(new EventHeadcountService.Request(COMPANY, EVENT)); + + assertThat(h).isEqualTo(new EventHeadcountService.Headcount(40, 50, 30, 35, 15, 45, 100)); + } + + @Test + void nullCapAndCapacityStayNull() { + Event e = new Event(); + e.setCompanyId(COMPANY); + when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(e)); + + EventHeadcountService.Headcount h = service().headcount(new EventHeadcountService.Request(COMPANY, EVENT)); + + assertThat(h.cap()).isNull(); + assertThat(h.capacity()).isNull(); + assertThat(h.total()).isZero(); + } + + @Test + void eventOfAnotherCompanyIs404() { + Event e = new Event(); + e.setCompanyId(99L); + when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(e)); + + assertThatThrownBy(() -> service().headcount(new EventHeadcountService.Request(COMPANY, EVENT))) + .isInstanceOfSatisfying(ResponseStatusException.class, ex -> assertThat(ex.getStatusCode().value()).isEqualTo(404)); + } + + @Test + void unknownEventIs404() { + when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service().headcount(new EventHeadcountService.Request(COMPANY, EVENT))) + .isInstanceOfSatisfying(ResponseStatusException.class, ex -> assertThat(ex.getStatusCode().value()).isEqualTo(404)); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventSettingsTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventSettingsTest.java new file mode 100644 index 0000000..8159207 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventSettingsTest.java @@ -0,0 +1,99 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.util.redis.RedisUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Event capacity and invitation cap on save. */ +@ExtendWith(MockitoExtension.class) +class EventSettingsTest { + @Mock private EventRepository eventRepository; + @Mock private RedisUtil redisUtil; + @Mock private EventGuestRepository guestRepository; + + private EventService service; + + @BeforeEach + void setUp() { + service = new EventService(eventRepository, redisUtil, guestRepository); + lenient().when(eventRepository.save(any(Event.class))).thenAnswer(i -> i.getArgument(0)); + } + + private static Event event(Long id, Integer capacity, Integer cap) { + Event e = new Event(); + e.setId(id); + e.setCompanyId(7L); + e.setCapacity(capacity); + e.setInvitationCap(cap); + return e; + } + + private void assertRejected(Event e, int status, String reason) { + assertThatThrownBy(() -> service.save(e)).isInstanceOfSatisfying(ResponseStatusException.class, ex -> { + assertThat(ex.getStatusCode().value()).isEqualTo(status); + assertThat(ex.getReason()).isEqualTo(reason); + }); + verify(eventRepository, never()).save(any(Event.class)); + } + + @Test + void nullAndPositiveValuesAreAccepted() { + assertThat(service.save(event(null, null, null)).getCapacity()).isNull(); + Event saved = service.save(event(null, 100, 1)); + assertThat(saved.getCapacity()).isEqualTo(100); + assertThat(saved.getInvitationCap()).isEqualTo(1); + } + + @Test + void capacityBelowOneIsRefused() { + assertRejected(event(null, 0, null), 400, "CAPACITY_INVALID"); + } + + @Test + void invitationCapBelowOneIsRefused() { + assertRejected(event(null, null, -3), 400, "INVITATION_CAP_INVALID"); + } + + @Test + void capBelowCurrentGuestCountIsConflict() { + Event stored = event(5L, null, null); + when(eventRepository.findById(5L)).thenReturn(Optional.of(stored)); + when(guestRepository.countByEventUuid(stored.getUuid())).thenReturn(40L); + + assertRejected(event(5L, null, 39), 409, "CAP_BELOW_GUESTS"); + } + + @Test + void capEqualToGuestCountIsAccepted() { + Event stored = event(5L, null, null); + when(eventRepository.findById(5L)).thenReturn(Optional.of(stored)); + when(guestRepository.countByEventUuid(stored.getUuid())).thenReturn(40L); + + assertThat(service.save(event(5L, null, 40)).getInvitationCap()).isEqualTo(40); + } + + @Test + void eventExposesTheTwoFieldsAsJsonProperties() throws Exception { + Event e = event(1L, 100, 50); + var json = new com.fasterxml.jackson.databind.ObjectMapper().findAndRegisterModules().valueToTree(e); + assertThat(json.get("capacity").asInt()).isEqualTo(100); + assertThat(json.get("invitationCap").asInt()).isEqualTo(50); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/GuestLinkerTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/GuestLinkerTest.java new file mode 100644 index 0000000..67aa69d --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/GuestLinkerTest.java @@ -0,0 +1,103 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.EventGuest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventGuestRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDateTime; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class GuestLinkerTest { + private static final long EVENT = 1000L; + private static final String MOBILE = "+60123456789"; + private static final String EMAIL = "aisyah@example.com"; + + @Mock private EventGuestRepository guests; + private GuestLinker linker; + + @BeforeEach + void setUp() { + linker = new GuestLinker(guests); + lenient().when(guests.findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(any(Long.class), any())).thenReturn(Optional.empty()); + lenient().when(guests.findFirstByEventUuidAndEventLeadIdIsNullAndEmail(any(Long.class), any())).thenReturn(Optional.empty()); + } + + private static EventLead eventLead() { + EventLead e = new EventLead(); + e.setId(55L); + return e; + } + + private static Lead lead(String mobile, String email) { + Lead l = new Lead(); + l.setMobileE164(mobile); + l.setEmailNormalised(email); + return l; + } + + @Test + void linksByMobileAndStampsRegisteredAt() { + EventGuest g = new EventGuest(); + when(guests.findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(EVENT, MOBILE)).thenReturn(Optional.of(g)); + + linker.link(EVENT, eventLead(), lead(MOBILE, EMAIL)); + + assertThat(g.getEventLeadId()).isEqualTo(55L); + assertThat(g.getRegisteredAt()).isNotNull(); + verify(guests).save(g); + verify(guests, never()).findFirstByEventUuidAndEventLeadIdIsNullAndEmail(any(Long.class), any()); + } + + @Test + void fallsBackToEmailWhenNoMobileMatch() { + EventGuest g = new EventGuest(); + when(guests.findFirstByEventUuidAndEventLeadIdIsNullAndEmail(EVENT, EMAIL)).thenReturn(Optional.of(g)); + + linker.link(EVENT, eventLead(), lead(MOBILE, EMAIL)); + + assertThat(g.getEventLeadId()).isEqualTo(55L); + verify(guests).save(g); + } + + @Test + void keepsExistingRegisteredAt() { + EventGuest g = new EventGuest(); + LocalDateTime earlier = LocalDateTime.of(2026, 12, 1, 9, 0); + g.setRegisteredAt(earlier); + when(guests.findFirstByEventUuidAndEventLeadIdIsNullAndEmail(EVENT, EMAIL)).thenReturn(Optional.of(g)); + + linker.link(EVENT, eventLead(), lead(null, EMAIL)); + + assertThat(g.getRegisteredAt()).isEqualTo(earlier); + } + + @Test + void noOpWhenEventLeadAlreadyLinked() { + when(guests.existsByEventLeadId(55L)).thenReturn(true); + + linker.link(EVENT, eventLead(), lead(MOBILE, EMAIL)); + + verify(guests, never()).save(any()); + verify(guests, never()).findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(any(Long.class), any()); + } + + @Test + void noGuestNothingSaved() { + linker.link(EVENT, eventLead(), lead(MOBILE, EMAIL)); + verify(guests, never()).save(any()); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InvitationWiringTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InvitationWiringTest.java new file mode 100644 index 0000000..8e815a2 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InvitationWiringTest.java @@ -0,0 +1,43 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventLeadStatusChangeRepository; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.LeadRepository; +import com.solvway.services.counter.util.redis.RedisUtil; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionTemplate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +/** Spring must pick the full constructors, so production always gets the linker and the extra repositories. */ +class InvitationWiringTest { + private static void mockBean(AnnotationConfigApplicationContext ctx, Class c) { + ctx.registerBean(c, () -> mock(c)); + } + + @Test + void servicesAreWiredWithTheirFullDependencies() { + try (var ctx = new AnnotationConfigApplicationContext()) { + for (Class c : new Class[]{LeadRepository.class, EventLeadRepository.class, EventLeadInterestRepository.class, + EventLeadStatusChangeRepository.class, EventRepository.class, EventGuestRepository.class, + RedisUtil.class, TransactionTemplate.class}) { + mockBean(ctx, c); + } + ctx.register(GuestLinker.class, EventLeadService.class, RegistrationService.class, EventService.class, + EventHeadcountService.class); + ctx.refresh(); + + assertThat(ReflectionTestUtils.getField(ctx.getBean(EventLeadService.class), "guestLinker")).isNotNull(); + assertThat(ReflectionTestUtils.getField(ctx.getBean(EventLeadService.class), "eventRepository")).isNotNull(); + assertThat(ReflectionTestUtils.getField(ctx.getBean(RegistrationService.class), "guestLinker")).isNotNull(); + assertThat(ReflectionTestUtils.getField(ctx.getBean(EventService.class), "guestRepository")).isNotNull(); + assertThat(ctx.getBean(EventHeadcountService.class)).isNotNull(); + } + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkMineAddedAtTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkMineAddedAtTest.java new file mode 100644 index 0000000..01f0f2e --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkMineAddedAtTest.java @@ -0,0 +1,67 @@ +package com.solvway.services.counter.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventSalesperson; +import com.solvway.services.counter.model.RegistrationLink; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.EventSalespersonRepository; +import com.solvway.services.counter.repo.RegistrationLinkRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.lang.reflect.Field; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RegistrationLinkMineAddedAtTest { + @Mock private RegistrationLinkRepository linkRepository; + @Mock private EventRepository eventRepository; + @Mock private EventSalespersonRepository eventSalespersonRepository; + + @Test + void mineReturnsTheTeamRowCreateTimeAsAddedAt() throws Exception { + LocalDateTime added = LocalDateTime.of(2026, 11, 20, 14, 30); + assertThat(mineAddedAt(added)).isEqualTo(added.toString()); + } + + @Test + void mineReturnsNullAddedAtWhenCreateTimeIsMissing() throws Exception { + assertThat(mineAddedAt(null)).isNull(); + } + + private String mineAddedAt(LocalDateTime added) throws Exception { + EventSalesperson row = new EventSalesperson(); + row.setEventUuid(1L); + row.setCreateDateTime(added); + when(eventSalespersonRepository.findByCompanyIdAndUserId(42L, 7L)).thenReturn(List.of(row)); + Event ev = new Event(); + Field uuid = Event.class.getDeclaredField("uuid"); + uuid.setAccessible(true); + uuid.set(ev, 1L); + ev.setCompanyId(42L); + ev.setName("Expo"); + ev.setEnabled(GeneralEnum.FlagYesNo.Y); + ev.setDateEnd(LocalDateTime.of(2026, 12, 12, 18, 0)); + when(eventRepository.findByCompanyIdAndUuidIn(eq(42L), anyCollection())).thenReturn(List.of(ev)); + RegistrationLink link = new RegistrationLink(); + link.setToken("T"); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(anyLong(), eq(7L))).thenReturn(Optional.of(link)); + + var out = new RegistrationLinkService(linkRepository, eventRepository, eventSalespersonRepository) + .mine(new RegistrationLinkService.MineRequest(42L, 7L, "2026-12-01")); + + assertThat(out).hasSize(1); + return out.get(0).addedAt(); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/util/EventDaysTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/util/EventDaysTest.java new file mode 100644 index 0000000..5b69f9f --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/util/EventDaysTest.java @@ -0,0 +1,51 @@ +package com.solvway.services.counter.util; + +import com.solvway.services.counter.model.Event; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; + +import static org.assertj.core.api.Assertions.assertThat; + +class EventDaysTest { + private static Event event(LocalDateTime start, LocalDateTime end) { + Event e = new Event(); + e.setDateStart(start); + e.setDateEnd(end); + return e; + } + + private static final Event EVENT = event(LocalDateTime.of(2026, 12, 5, 18, 0), LocalDateTime.of(2026, 12, 7, 9, 0)); + + @Test + void firstDayCountsEvenBeforeTheStartTime() { + assertThat(EventDays.isDuring(EVENT, LocalDateTime.of(2026, 12, 5, 0, 1))).isTrue(); + } + + @Test + void lastDayCountsEvenAfterTheEndTime() { + assertThat(EventDays.isDuring(EVENT, LocalDateTime.of(2026, 12, 7, 23, 59))).isTrue(); + } + + @Test + void dayBeforeDoesNotCount() { + assertThat(EventDays.isDuring(EVENT, LocalDateTime.of(2026, 12, 4, 23, 59))).isFalse(); + } + + @Test + void dayAfterDoesNotCount() { + assertThat(EventDays.isDuring(EVENT, LocalDateTime.of(2026, 12, 8, 0, 0))).isFalse(); + } + + @Test + void nullStartOnlyTheEndCounts() { + Event e = event(null, LocalDateTime.of(2026, 12, 7, 9, 0)); + assertThat(EventDays.isDuring(e, LocalDateTime.of(2020, 1, 1, 0, 0))).isTrue(); + assertThat(EventDays.isDuring(e, LocalDateTime.of(2026, 12, 8, 0, 0))).isFalse(); + } + + @Test + void nullEndIsNeverDuring() { + assertThat(EventDays.isDuring(event(LocalDateTime.of(2026, 12, 5, 18, 0), null), LocalDateTime.of(2026, 12, 5, 19, 0))).isFalse(); + } +} -- 2.54.1 From 4e938bb6a99b26f6603d082dfc17bfd7e2ffa210 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 16:41:37 +0800 Subject: [PATCH 06/24] docs: tick task 2.1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-event-invitations/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/add-event-invitations/tasks.md b/openspec/changes/add-event-invitations/tasks.md index 3e7f8e0..5837d32 100644 --- a/openspec/changes/add-event-invitations/tasks.md +++ b/openspec/changes/add-event-invitations/tasks.md @@ -21,7 +21,7 @@ Waves: ## 2. services-counter -- [ ] 2.1 Shared rules, attendance, event settings and numbers (decisions 2 and 3). +- [x] 2.1 Shared rules, attendance, event settings and numbers (decisions 2 and 3). - Depends on: 1.1 - Tests first: - **`EventDays.isDuring`:** the first day, the last day, the day before, the day after, a null start, a null end. -- 2.54.1 From 87dfc4863214e50b5f88a5ce292b27a3dca01cdd Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 16:45:48 +0800 Subject: [PATCH 07/24] feat: admin guest, invite email, check-in and attendance endpoints Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../api/RestApiCounterServiceConstants.java | 6 + .../admin/AdminEventGuestController.java | 76 +++ .../admin/AdminEventLeadUpdateRequest.java | 9 +- .../api/dto/admin/AdminEventRequest.java | 11 +- .../api/dto/admin/AdminGuestSendRequest.java | 9 + .../api/dto/admin/AdminGuestsRequest.java | 12 + .../mobile/api/dto/admin/CompanyEvent.java | 2 + .../api/service/AdminEventGuestService.java | 272 +++++++++++ .../api/service/AdminEventLeadService.java | 2 + .../mobile/api/service/AdminEventService.java | 34 +- .../api/useraccess/AdminModuleAccess.java | 23 +- .../src/main/resources/application-local.yml | 2 + .../src/main/resources/application.yml | 2 + .../config/AdminPortalBaseUrlSettingTest.java | 41 ++ .../admin/AdminEventGuestControllerTest.java | 116 +++++ .../service/AdminEventGuestServiceTest.java | 444 ++++++++++++++++++ .../AdminEventGuestServiceWiringTest.java | 31 ++ .../service/AdminEventLeadAttendedTest.java | 95 ++++ .../AdminEventServiceCapacityTest.java | 181 +++++++ 19 files changed, 1361 insertions(+), 7 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventGuestController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestSendRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestsRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventGuestService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/config/AdminPortalBaseUrlSettingTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventGuestControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventGuestServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventGuestServiceWiringTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadAttendedTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventServiceCapacityTest.java diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index ea6123d..57617ef 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -35,6 +35,12 @@ public class RestApiCounterServiceConstants { //Event admin public static final String API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE="/counter/event/findByPropertyAndPageable"; public static final String API_REST_COUNTER_EVENT_SAVE="/counter/event/save"; + public static final String API_REST_COUNTER_EVENT_GUEST_LIST = "/counter/eventGuest/list"; + public static final String API_REST_COUNTER_EVENT_GUEST_ADD = "/counter/eventGuest/add"; + public static final String API_REST_COUNTER_EVENT_GUEST_REMOVE = "/counter/eventGuest/remove"; + public static final String API_REST_COUNTER_EVENT_GUEST_MARK_SENT = "/counter/eventGuest/markSent"; + public static final String API_REST_COUNTER_CHECKIN_ENSURE_TOKEN = "/counter/checkin/ensureToken"; + public static final String API_REST_COUNTER_EVENT_ATTENDANCE = "/counter/event/attendance"; public static final String API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}"; public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace"; public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventGuestController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventGuestController.java new file mode 100644 index 0000000..94dab5c --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventGuestController.java @@ -0,0 +1,76 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminGuestSendRequest; +import com.solvway.mobile.api.dto.admin.AdminGuestsRequest; +import com.solvway.mobile.api.service.AdminEventGuestService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** Event invitations: guest list, send, check-in token and attendance. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin/events/{uuid}") +@RequiredArgsConstructor +public class AdminEventGuestController { + private final AdminEventGuestService guests; + + @AppAuth + @AdminModule("BO_EVENTS") + @GetMapping("/guests") + public ResponseEntity>> list(@PathVariable String uuid) { + return ResponseEntity.ok(guests.list(uuid)); + } + + @AppAuth + @AdminModule(value = "BO_EVENT_GUESTS", also = "BO_EVENTS") + @Audited(targetVariable = "uuid") + @PostMapping("/guests") + public ResponseEntity> add(@PathVariable String uuid, @RequestBody AdminGuestsRequest body, + @RequestParam(defaultValue = "false") boolean preview) { + return ResponseEntity.ok(guests.add(uuid, body, preview)); + } + + @AppAuth + @AdminModule(value = "BO_EVENT_GUESTS", also = "BO_EVENTS") + @Audited(targetVariable = "uuid") + @DeleteMapping("/guests/{guestId}") + public ResponseEntity remove(@PathVariable String uuid, @PathVariable String guestId) { + guests.remove(uuid, guestId); + return ResponseEntity.noContent().build(); + } + + @AppAuth + @AdminModule(value = "BO_EVENT_GUESTS", also = "BO_EVENTS") + @Audited(targetVariable = "uuid") + @PostMapping("/guests/send") + public ResponseEntity> send(@PathVariable String uuid, @RequestBody AdminGuestSendRequest body) { + return ResponseEntity.ok(guests.send(uuid, body)); + } + + @AppAuth + @AdminModule("BO_EVENTS") + @GetMapping("/checkin") + public ResponseEntity> checkin(@PathVariable String uuid) { + return ResponseEntity.ok(guests.checkin(uuid)); + } + + @AppAuth + @AdminModule("BO_EVENTS") + @GetMapping("/attendance") + public ResponseEntity> attendance(@PathVariable String uuid) { + return ResponseEntity.ok(guests.attendance(uuid)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java index 42b5a9e..e76833f 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java @@ -2,6 +2,11 @@ package com.solvway.mobile.api.dto.admin; import java.util.List; -/** An event lead's working fields. nextFollowUpDate is YYYY-MM-DD; null clears it. */ +/** An event lead's working fields. nextFollowUpDate is YYYY-MM-DD; null clears it. attended null leaves the flag alone. */ public record AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List interestIds, - String nextFollowUpDate, String notes) {} + String nextFollowUpDate, String notes, Boolean attended) { + public AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List interestIds, + String nextFollowUpDate, String notes) { + this(salespersonId, temperature, status, interestIds, nextFollowUpDate, notes, null); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java index d971af9..a9fe2c9 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java @@ -6,12 +6,17 @@ import java.util.List; /** * Create/update body. Dates are kept as text so a malformed date answers INVALID_DATE, not a bind error. enabled is update-only. - * companyId is read on create only, and only from a super admin; staff get their own company and an edit never moves an event. + * capacity and invitationCap (null = no limit) are read only from a caller holding BO_EVENT_GUESTS. companyId is read on create only, and only from a super admin; staff get their own company and an edit never moves an event. */ @JsonIgnoreProperties(ignoreUnknown = true) public record AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List salespersonIds, - Long companyId) { + Long companyId, Integer capacity, Integer invitationCap) { + public AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List salespersonIds, + Long companyId) { + this(name, location, startDate, endDate, enabled, salespersonIds, companyId, null, null); + } + public AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List salespersonIds) { - this(name, location, startDate, endDate, enabled, salespersonIds, null); + this(name, location, startDate, endDate, enabled, salespersonIds, null, null, null); } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestSendRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestSendRequest.java new file mode 100644 index 0000000..08d4183 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestSendRequest.java @@ -0,0 +1,9 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** Which guests to email: the listed ids, or every guest not yet sent when allUnsent is true. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminGuestSendRequest(List guestIds, Boolean allUnsent) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestsRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestsRequest.java new file mode 100644 index 0000000..2fc6920 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestsRequest.java @@ -0,0 +1,12 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** Guests to invite to an event: one line for a single add, many for a paste. Same shape either way. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminGuestsRequest(List guests) { + @JsonIgnoreProperties(ignoreUnknown = true) + public record Guest(String name, String mobile, String email, String companyName, Long salespersonUserId) {} +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java index d189e20..162afde 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java @@ -9,4 +9,6 @@ import lombok.Setter; @Setter public class CompanyEvent extends Event { private Long companyId; + private Integer capacity; + private Integer invitationCap; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventGuestService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventGuestService.java new file mode 100644 index 0000000..374d3ca --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventGuestService.java @@ -0,0 +1,272 @@ +package com.solvway.mobile.api.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.core.enums.EmailEnum; +import com.solvway.core.model.Email; +import com.solvway.core.model.Recipient; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminGuestSendRequest; +import com.solvway.mobile.api.dto.admin.AdminGuestsRequest; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminModuleAccess; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.util.HtmlUtils; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Invited-guest list of an event for the admin portal. Validates and normalises at this boundary; services-counter stores. + * Every operation resolves the event through AdminEventLeadService.loadEvent, so another company's event is a 404. + * Never log a guest's name, mobile or email. + */ +@Service +@Slf4j +@SuppressWarnings("unchecked") +public class AdminEventGuestService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final RestTemplateCustomUtil rest; + private final AdminEventLeadService leads; + private final EmailService emailService; + private final String portalBase; + + public AdminEventGuestService(RestTemplateCustomUtil rest, AdminEventLeadService leads, EmailService emailService, @Value("${app.admin-portal-base-url}") String portalBase) { + this.rest = rest; + this.leads = leads; + this.emailService = emailService; + this.portalBase = portalBase.replaceAll("/+$", ""); + log.info("Admin portal base URL for invitation links: {}", this.portalBase); + } + + public List> list(String uuid) { + CompanyEvent event = leads.loadEvent(uuid, null); + boolean mayCopyLinks = AdminModuleAccess.holds(rest, leads.caller(), "BO_EVENT_GUESTS"); + Map names = new HashMap<>(); + List> out = new ArrayList<>(); + for (Map g : guests(event)) { + Map row = new LinkedHashMap<>(g); + // Only the guest-list module may copy invitation links, so the token stays with it. + if (!mayCopyLinks) row.remove("token"); + if (g.get("salespersonUserId") instanceof Number n) { + row.put("salespersonName", names.computeIfAbsent(n.longValue(), id -> { + Map user = leads.user(id); + return user == null ? null : user.get("name"); + })); + } + out.add(row); + } + return out; + } + + private List> guests(CompanyEvent event) { + List> guests = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_LIST), MAP_LIST, + eventBody(event)).getBody(); + return guests == null ? List.of() : guests; + } + + /** Valid lines go to the counter (unless previewing); rejections of both kinds come back with the line's original index. */ + public Map add(String uuid, AdminGuestsRequest r, boolean preview) { + CompanyEvent event = leads.loadEvent(uuid, null); + if (r == null || r.guests() == null || r.guests().isEmpty()) throw AdminEventLeadService.required(List.of("guests")); + List> valid = new ArrayList<>(); + List validIndexes = new ArrayList<>(); + List> rejected = new ArrayList<>(); + for (int i = 0; i < r.guests().size(); i++) { + try { + valid.add(normalise(r.guests().get(i))); + validIndexes.add(i); + } catch (CodedResponseStatusException e) { + rejected.add(rejection(i, e.getCode(), field(e), e.getReason())); + } + } + List added = new ArrayList<>(valid); + if (!preview && !valid.isEmpty()) { + Map body = eventBody(event); + body.put("guests", valid); + body.put("doneBy", leads.caller().getUsername()); + Map result; + try { + result = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_ADD), MAP, body).getBody(); + } catch (HttpClientErrorException.NotFound e) { + throw AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Event not found", "EVENT_NOT_FOUND", null); + } + added = result == null || result.get("added") == null ? new ArrayList<>() : new ArrayList<>((List) result.get("added")); + if (result != null && result.get("rejected") instanceof List counterRejected) { + for (Object o : counterRejected) { + Map m = new LinkedHashMap<>((Map) o); + int at = m.get("index") instanceof Number n ? n.intValue() : -1; + if (at < 0 || at >= validIndexes.size()) { + log.warn("Counter rejected a guest line outside the request for event {}", event.getUuid()); + continue; + } + m.put("index", validIndexes.get(at)); + rejected.add(m); + } + } + } + rejected.sort(Comparator.comparingInt(m -> (Integer) m.get("index"))); + Map out = new LinkedHashMap<>(); + out.put("added", added); + out.put("rejected", rejected); + return out; + } + + public void remove(String uuid, String guestId) { + CompanyEvent event = leads.loadEvent(uuid, null); + Map body = eventBody(event); + body.put("guestId", AdminEventLeadService.parseOr(guestId, + () -> AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Guest not found", "GUEST_NOT_FOUND", null))); + body.put("doneBy", leads.caller().getUsername()); + try { + rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_REMOVE), MAP, body); + } catch (HttpClientErrorException.Conflict e) { + throw AdminEventLeadService.error(HttpStatus.CONFLICT, "Guest has registered and cannot be removed", "GUEST_REGISTERED", null); + } catch (HttpClientErrorException.NotFound e) { + throw AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Guest not found", "GUEST_NOT_FOUND", null); + } + } + + /** One email per guest, English then Bahasa Malaysia. Only guests whose email was accepted are marked as sent. */ + public Map send(String uuid, AdminGuestSendRequest r) { + CompanyEvent event = leads.loadEvent(uuid, null); + boolean allUnsent = r != null && Boolean.TRUE.equals(r.allUnsent()); + if (!allUnsent && (r == null || r.guestIds() == null || r.guestIds().isEmpty())) { + throw AdminEventLeadService.required(List.of("guestIds")); + } + Set wanted = allUnsent ? Set.of() : new HashSet<>(r.guestIds()); + List sentIds = new ArrayList<>(); + int skippedNoEmail = 0; + try { + for (Map g : guests(event)) { + long id = ((Number) g.get("id")).longValue(); + boolean selected = allUnsent ? !(g.get("inviteSentCount") instanceof Number n && n.intValue() > 0) : wanted.contains(id); + if (!selected) continue; + String to = AdminEventLeadService.trimmed(AdminEventLeadService.str(g.get("email"))); + if (to == null) { + skippedNoEmail++; + continue; + } + if (deliver(event, g, to)) sentIds.add(id); + } + } finally { + // Whatever was queued is marked, even if a later guest blew up, so a retry does not email them twice. + if (!sentIds.isEmpty()) { + Map body = eventBody(event); + body.put("guestIds", sentIds); + body.put("doneBy", leads.caller().getUsername()); + rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_MARK_SENT), MAP, body); + } + } + Map out = new LinkedHashMap<>(); + out.put("sent", sentIds.size()); + out.put("skippedNoEmail", skippedNoEmail); + return out; + } + + public Map checkin(String uuid) { + return rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CHECKIN_ENSURE_TOKEN), MAP, + eventBody(leads.loadEvent(uuid, null))).getBody(); + } + + public Map attendance(String uuid) { + return rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_ATTENDANCE), MAP, + eventBody(leads.loadEvent(uuid, null))).getBody(); + } + + // --- helpers --- + + private boolean deliver(CompanyEvent event, Map guest, String to) { + try { + Email email = new Email(); + email.setCompanyId(event.getCompanyId()); + email.setSubject("You are invited / Anda dijemput: " + event.getName()); + email.setBody(invitationBody(event, guest)); + email.setStatus(EmailEnum.StatusType.P); + email.setRecipients(List.of(new Recipient(null, to, EmailEnum.RecipientType.R, EmailEnum.RecipientStatusType.Y))); + Optional sent = emailService.send(email); + return sent != null && sent.isPresent(); + } catch (RuntimeException e) { + log.error("Invitation email failed for event {}: {}", event.getUuid(), e.getMessage()); + return false; + } + } + + private String invitationBody(CompanyEvent event, Map guest) { + String name = esc(guest.get("name")); + String link = esc(portalBase + "/i/" + guest.get("token")); + String details = "

" + esc(event.getName()) + "
" + esc(date(event.getDateStart())) + " - " + + esc(date(event.getDateEnd())) + "
" + esc(event.getLocation()) + "

"; + return "

Dear " + name + ",

You are invited to our event.

" + details + + "

Please confirm your attendance: " + link + "

" + + "

Bahasa Malaysia

Tuan/Puan " + name + ",

Anda dijemput ke acara kami.

" + details + + "

Sila sahkan kehadiran anda: " + link + "

"; + } + + private static Object date(java.time.LocalDateTime d) { + return d == null ? null : d.toLocalDate(); + } + + private static String esc(Object value) { + return HtmlUtils.htmlEscape(String.valueOf(value == null ? "" : value)); + } + + /** Trims, normalises mobile to E.164 and email to lower case; throws the coded error of the first problem found. */ + private static Map normalise(AdminGuestsRequest.Guest g) { + String name = AdminEventLeadService.trimmed(g == null ? null : g.name()); + if (name == null) throw AdminEventLeadService.required(List.of("name")); + AdminEventLeadService.maxLength("name", name, 100); + String mobile = AdminEventLeadService.trimmed(g.mobile()); + String email = AdminEventLeadService.trimmed(g.email()); + if (mobile == null && email == null) throw AdminEventLeadService.required(List.of("mobile", "email")); + String companyName = AdminEventLeadService.maxLength("companyName", AdminEventLeadService.trimmed(g.companyName()), 150); + Map m = new LinkedHashMap<>(); + m.put("name", name); + m.put("mobileE164", mobile == null ? null : AdminEventLeadService.mobile(mobile)); + m.put("email", email == null ? null : AdminEventLeadService.maxLength("email", AdminEventLeadService.email(email), 254)); + m.put("companyName", companyName); + m.put("salespersonUserId", g.salespersonUserId()); + return m; + } + + private static Map rejection(int index, String code, String field, String message) { + Map m = new LinkedHashMap<>(); + m.put("index", index); + m.put("code", code); + m.put("field", field); + m.put("message", message); + return m; + } + + private static String field(CodedResponseStatusException e) { + return e.getBody().getProperties() != null && e.getBody().getProperties().get("details") instanceof Map d + ? AdminEventLeadService.str(d.get("field")) : null; + } + + private Map eventBody(CompanyEvent event) { + Map body = new LinkedHashMap<>(); + body.put("companyId", event.getCompanyId()); + body.put("eventUuid", event.getUuid()); + return body; + } + + private String url(String api) { + return rest.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java index 36ffdc7..fcd6a11 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -267,6 +267,7 @@ public class AdminEventLeadService { body.put("interestIds", interestIds); body.put("nextFollowUpDate", followUp == null ? null : followUp.toString()); body.put("notes", trimmed(r.notes())); + body.put("attended", r.attended()); body.put("doneBy", caller.getUsername()); Map saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(); // field names only: follow-up values are personal data @@ -277,6 +278,7 @@ public class AdminEventLeadService { if (!new HashSet<>(interestIds).equals(new HashSet<>(longs(current.get("interestIds"))))) changed.add("interestIds"); if (!Objects.equals(body.get("nextFollowUpDate"), current.get("nextFollowUpDate") == null ? null : current.get("nextFollowUpDate").toString())) changed.add("nextFollowUpDate"); if (!Objects.equals(body.get("notes"), current.get("notes"))) changed.add("notes"); + if (r.attended() != null && !r.attended().equals(current.get("attended"))) changed.add("attended"); if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new)); return view(saved, known, new HashMap<>()); } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java index 93ab79f..2b34443 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java @@ -1,6 +1,7 @@ package com.solvway.mobile.api.service; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.ObjectMapper; import com.solvway.core.enums.GeneralEnum; import com.solvway.core.model.User; import com.solvway.core.utils.HttpReqRespUtils; @@ -10,12 +11,14 @@ import com.solvway.mobile.api.dto.admin.AdminEventRequest; import com.solvway.mobile.api.dto.admin.CompanyEvent; import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.useraccess.AdminModuleAccess; import com.solvway.mobile.api.util.RestTemplateCustomUtil; import lombok.RequiredArgsConstructor; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; import java.time.LocalDate; import java.time.LocalDateTime; @@ -68,6 +71,8 @@ public class AdminEventService { public Map get(String uuid) { CompanyEvent event = load(uuid); Map out = row(event); + out.put("capacity", event.getCapacity()); + out.put("invitationCap", event.getInvitationCap()); List> team = new ArrayList<>(); for (Long id : teamIds(event.getUuid())) { Map user = user(id); @@ -103,6 +108,11 @@ public class AdminEventService { CompanyEvent event = load(uuid); List team = r.salespersonIds() == null ? null : checkedTeam(r.salespersonIds(), teamIds(event.getUuid()), event.getCompanyId()); apply(event, f); + // Capacity and invitation cap belong to the guest-list module; other editors leave them as they are. + if (AdminModuleAccess.holds(restTemplateUtil, caller, "BO_EVENT_GUESTS")) { + event.setCapacity(positiveOrNull(r.capacity(), "capacity")); + event.setInvitationCap(positiveOrNull(r.invitationCap(), "invitationCap")); + } if (r.enabled() != null) event.setEnabled(r.enabled() ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N); event.setDoneBy(caller.getUsername()); CompanyEvent saved = save(event); @@ -110,6 +120,11 @@ public class AdminEventService { return row(saved); } + private static Integer positiveOrNull(Integer value, String field) { + if (value != null && value < 1) throw error(HttpStatus.BAD_REQUEST, field + " must be at least 1", "INVALID_LIMIT", field); + return value; + } + /** Active admins of the chosen company; a super admin who has not chosen one is offered nobody. */ public List> salespersonOptions(Long companyId) { Long company = scope.scope(caller(), companyId); @@ -236,7 +251,15 @@ public class AdminEventService { } private CompanyEvent save(CompanyEvent event) { - CompanyEvent saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SAVE), EVENT, event).getBody(); + CompanyEvent saved; + try { + saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SAVE), EVENT, event).getBody(); + } catch (HttpClientErrorException.Conflict e) { + // The counter refuses a cap below the guests already on the list (CAP_BELOW_GUESTS). + String code = counterField(e, "code", "CONFLICT"); + throw error(HttpStatus.CONFLICT, "CAP_BELOW_GUESTS".equals(code) ? "Limit is below the guests already invited" + : counterField(e, "message", "Event could not be saved"), code, null); + } if (saved == null) throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Event could not be saved", "SAVE_FAILED", null); return saved; } @@ -253,6 +276,15 @@ public class AdminEventService { return m; } + private static String counterField(HttpClientErrorException e, String field, String fallback) { + try { + String v = new ObjectMapper().readTree(e.getResponseBodyAsString()).path(field).asText(); + return v.isEmpty() ? fallback : v; + } catch (Exception ex) { + return fallback; + } + } + private User caller() { User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java index a0729f1..3a18149 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java @@ -1,20 +1,41 @@ package com.solvway.mobile.api.useraccess; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.extern.slf4j.Slf4j; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.ResponseEntity; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.stream.Collectors; +@Slf4j public final class AdminModuleAccess { private static final String MODULES_BY_AREA = "/module/findAllByArea/{area}"; + private static final long INJECTED_ROLE_ADMIN_ID = 2L; // services-auth adds ROLE_ADMIN to every admin; never a module grant + private AdminModuleAccess() { } + /** True for a super admin or a caller whose roles hold the module. A failing lookup fails closed (false, logged). */ + public static boolean holds(RestTemplateCustomUtil restTemplateUtil, User caller, String module) { + if (AdminCompanyScope.isSuper(caller)) return true; + Set roleIds = caller.getRoles() == null ? Set.of() : caller.getRoles().stream() + .map(Role::getId).filter(id -> Objects.nonNull(id) && id != INJECTED_ROLE_ADMIN_ID).collect(Collectors.toSet()); + try { + return grantedAny(restTemplateUtil, roleIds, module); + } catch (RuntimeException e) { + log.error("Admin module lookup for {} failed, treating as not granted: {}", module, e.getClass().getSimpleName()); + return false; + } + } + /** True when one of {@code roleIds} is granted any of the named BO modules. */ public static boolean grantedAny(RestTemplateCustomUtil restTemplateUtil, Set roleIds, String... moduleNames) { if (moduleNames.length == 0) { @@ -24,7 +45,7 @@ public final class AdminModuleAccess { ResponseEntity>> ent = restTemplateUtil.getForEntity( restTemplateUtil.getURLforApiService(MODULES_BY_AREA), new ParameterizedTypeReference>>() {}, "BO"); - List> modules = ent.getBody() != null ? ent.getBody() : List.of(); + List> modules = ent != null && ent.getBody() != null ? ent.getBody() : List.of(); return modules.stream() .filter(m -> m.get("name") instanceof String name && wanted.contains(name)) // services-system writes a role already seen in this response as its bare id diff --git a/solvway-mobile-api/src/main/resources/application-local.yml b/solvway-mobile-api/src/main/resources/application-local.yml index ea3d07a..9a5ffff 100644 --- a/solvway-mobile-api/src/main/resources/application-local.yml +++ b/solvway-mobile-api/src/main/resources/application-local.yml @@ -5,3 +5,5 @@ spring: project-id: co-lite-local pubsub: emulator-host: pubsub:8085 +app: + admin-portal-base-url: ${ADMIN_PORTAL_BASE_URL:http://localhost:3001} diff --git a/solvway-mobile-api/src/main/resources/application.yml b/solvway-mobile-api/src/main/resources/application.yml index ddc6f57..6175bb5 100644 --- a/solvway-mobile-api/src/main/resources/application.yml +++ b/solvway-mobile-api/src/main/resources/application.yml @@ -2,6 +2,8 @@ app: api-key: ${APIKEY:} api-gateway-url: ${APIGATEWAYURL} # TODO: confirm real customer-portal host + # Required outside the local profile (no default): invitation emails link to /i/. + admin-portal-base-url: ${ADMIN_PORTAL_BASE_URL} customer-portal-base-url: ${CUSTOMER_PORTAL_BASE_URL:https://user.tastefullyexpo.com} system: format: diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/config/AdminPortalBaseUrlSettingTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/config/AdminPortalBaseUrlSettingTest.java new file mode 100644 index 0000000..4124d54 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/config/AdminPortalBaseUrlSettingTest.java @@ -0,0 +1,41 @@ +package com.solvway.mobile.api.config; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertySource; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.ClassPathResource; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** ADMIN_PORTAL_BASE_URL has a default in the local profile only. */ +class AdminPortalBaseUrlSettingTest { + + private static StandardEnvironment env(String... files) throws IOException { + StandardEnvironment env = new StandardEnvironment(); + MutablePropertySources sources = env.getPropertySources(); + for (String f : files) { + List> loaded = new YamlPropertySourceLoader().load(f, new ClassPathResource(f)); + // later files override earlier ones, as an active profile does + loaded.forEach(sources::addFirst); + } + return env; + } + + @Test + void localProfileDefaultsToLocalhost3001() throws IOException { + assertThat(env("application.yml", "application-local.yml").resolveRequiredPlaceholders("${app.admin-portal-base-url}")) + .isEqualTo("http://localhost:3001"); + } + + @Test + void otherProfilesHaveNoDefault() throws IOException { + StandardEnvironment env = env("application.yml"); + assertThatThrownBy(() -> env.resolveRequiredPlaceholders("${app.admin-portal-base-url}")).isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventGuestControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventGuestControllerTest.java new file mode 100644 index 0000000..3323968 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventGuestControllerTest.java @@ -0,0 +1,116 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminGuestSendRequest; +import com.solvway.mobile.api.dto.admin.AdminGuestsRequest; +import com.solvway.mobile.api.service.AdminEventGuestService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +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.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminEventGuestControllerTest { + + @Mock private AdminEventGuestService guests; + @InjectMocks private AdminEventGuestController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + private static List handlers() { + return Arrays.stream(AdminEventGuestController.class.getDeclaredMethods()) + .filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList(); + } + + @Test + void readsAreGuardedByBoEventsAndWritesByBoEventGuests() { + assertThat(handlers()).hasSize(6); + for (Method m : handlers()) { + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue(); + String expected = Arrays.asList("list", "checkin", "attendance").contains(m.getName()) ? "BO_EVENTS" : "BO_EVENT_GUESTS"; + AdminModule module = m.getAnnotation(AdminModule.class); + assertThat(Arrays.asList(module.value())).as(m.getName()).containsExactly(expected); + // writes are a sub-module: they need BO_EVENTS too, like the other event sub-modules + assertThat(Arrays.asList(module.also())).as(m.getName() + " also").isEqualTo(expected.equals("BO_EVENTS") ? List.of() : List.of("BO_EVENTS")); + } + } + + @Test + void everyGuestWriteIsAuditedAgainstTheEventUuid() { + for (Method m : handlers()) { + if (Arrays.asList("list", "checkin", "attendance").contains(m.getName())) continue; + Audited a = m.getAnnotation(Audited.class); + assertThat(a).as(m.getName() + " @Audited").isNotNull(); + assertThat(a.targetVariable()).as(m.getName()).isEqualTo("uuid"); + } + } + + @Test + void list_checkin_attendance() throws Exception { + when(guests.list("77")).thenReturn(List.of(Map.of("id", 1))); + when(guests.checkin("77")).thenReturn(Map.of("token", "abc")); + when(guests.attendance("77")).thenReturn(Map.of("invited", 3)); + mvc.perform(get("/api/admin/events/77/guests")).andExpect(status().isOk()).andExpect(content().json("[{\"id\":1}]")); + mvc.perform(get("/api/admin/events/77/checkin")).andExpect(status().isOk()).andExpect(content().json("{\"token\":\"abc\"}")); + mvc.perform(get("/api/admin/events/77/attendance")).andExpect(status().isOk()).andExpect(content().json("{\"invited\":3}")); + } + + @Test + void add_bindsBodyAndPreviewFlag() throws Exception { + when(guests.add(eq("77"), any(), eq(true))).thenReturn(Map.of("added", List.of(), "rejected", List.of())); + String body = "{\"guests\":[{\"name\":\"Amy\",\"mobile\":\"0123456789\",\"email\":\"a@b.co\",\"companyName\":\"Acme\",\"salespersonUserId\":4,\"extra\":1}]}"; + mvc.perform(post("/api/admin/events/77/guests").param("preview", "true").contentType(MediaType.APPLICATION_JSON).content(body)) + .andExpect(status().isOk()); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminGuestsRequest.class); + verify(guests).add(eq("77"), c.capture(), eq(true)); + assertThat(c.getValue().guests()).containsExactly(new AdminGuestsRequest.Guest("Amy", "0123456789", "a@b.co", "Acme", 4L)); + } + + @Test + void add_previewDefaultsToFalse() throws Exception { + when(guests.add(eq("77"), any(), eq(false))).thenReturn(Map.of()); + mvc.perform(post("/api/admin/events/77/guests").contentType(MediaType.APPLICATION_JSON).content("{\"guests\":[]}")).andExpect(status().isOk()); + verify(guests).add(eq("77"), any(), eq(false)); + } + + @Test + void remove_returnsNoContent_andSend_bindsBody() throws Exception { + mvc.perform(delete("/api/admin/events/77/guests/9")).andExpect(status().isNoContent()); + verify(guests).remove("77", "9"); + when(guests.send(eq("77"), any())).thenReturn(Map.of("sent", 2, "skippedNoEmail", 1)); + mvc.perform(post("/api/admin/events/77/guests/send").contentType(MediaType.APPLICATION_JSON).content("{\"allUnsent\":true}")) + .andExpect(status().isOk()).andExpect(content().json("{\"sent\":2,\"skippedNoEmail\":1}")); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminGuestSendRequest.class); + verify(guests).send(eq("77"), c.capture()); + assertThat(c.getValue().allUnsent()).isTrue(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventGuestServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventGuestServiceTest.java new file mode 100644 index 0000000..f29fa6d --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventGuestServiceTest.java @@ -0,0 +1,444 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.Email; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminGuestSendRequest; +import com.solvway.mobile.api.dto.admin.AdminGuestsRequest; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminEventGuestServiceTest { + + private static final String EVENT = "/counter/event/findByUuid/{uuid}"; + private static final String USER = "/user/findById/{id}"; + private static final String LIST = "/counter/eventGuest/list"; + private static final String ADD = "/counter/eventGuest/add"; + private static final String REMOVE = "/counter/eventGuest/remove"; + private static final String MARK_SENT = "/counter/eventGuest/markSent"; + private static final String ENSURE_TOKEN = "/counter/checkin/ensureToken"; + private static final String ATTENDANCE = "/counter/event/attendance"; + private static final long EV = 3312726793093644288L; + private static final long COMPANY = 5L; + + private RestTemplateCustomUtil rest; + private EmailService emails; + private AdminAuthenticationService auth; + private AdminEventGuestService service; + private MockedStatic http; + private User caller; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + emails = mock(EmailService.class); + auth = mock(AdminAuthenticationService.class); + AdminCompanyScope scope = new AdminCompanyScope(); + service = new AdminEventGuestService(rest, new AdminEventLeadService(rest, auth, scope), emails, "https://portal.test/"); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + caller = new User(); + caller.setId(21L); + caller.setUsername("boss"); + caller.setCompanyId(COMPANY); + when(auth.loadUserByToken("tok")).thenReturn(caller); + stubEvent(COMPANY); + stubUser(21L, "Sales One"); + when(emails.send(any())).thenAnswer(i -> Optional.of(i.getArgument(0))); + grantGuestsModule(true); + } + + private static final String MODULES = "/module/findAllByArea/{area}"; + + private void grantGuestsModule(boolean granted) { + Role staff = new Role(); + staff.setId(3L); + caller.setRoles(List.of(staff)); + when(rest.getForEntity(eq(MODULES), any(ParameterizedTypeReference.class), eq("BO"))) + .thenReturn(ResponseEntity.ok(List.of(Map.of("name", "BO_EVENT_GUESTS", "roles", List.of(Map.of("id", granted ? 3L : 99L)))))); + } + + @AfterEach + void close() { http.close(); } + + private void stubEvent(long company) { + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(company); + e.setUuid(EV); + e.setName("Fair &Co"); + e.setLocation("MITEC \"Hall\""); + e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0)); + e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e)); + } + + private void stubUser(long id, String name) { + Map u = new HashMap<>(); + u.put("id", id); + u.put("name", name); + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u)); + } + + private void stubGuests(Map... guests) { + when(rest.postForEntity(eq(LIST), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(guests))); + } + + private static Map guest(long id, String name, String email, int sentCount) { + Map g = new LinkedHashMap<>(); + g.put("id", id); + g.put("name", name); + g.put("email", email); + g.put("token", "tok" + id); + g.put("inviteSentCount", sentCount); + g.put("salespersonUserId", 21L); + return g; + } + + private Map sent(String api) { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture()); + return (Map) c.getValue(); + } + + private void assertNothingSent(String api) { + verify(rest, never()).postForEntity(eq(api), any(ParameterizedTypeReference.class), any()); + } + + private static AdminGuestsRequest.Guest line(String name, String mobile, String email) { + return new AdminGuestsRequest.Guest(name, mobile, email, "Acme", 21L); + } + + private static void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + // --- scope --- + + @Test + void anotherCompanysEventIsNotFoundOnEveryOperation() { + stubEvent(99L); + AdminGuestsRequest one = new AdminGuestsRequest(List.of(line("Amy", "0123456789", null))); + String ev = String.valueOf(EV); + assertCoded(() -> service.list(ev), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.add(ev, one, false), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.remove(ev, "1"), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.send(ev, new AdminGuestSendRequest(null, true)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.checkin(ev), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.attendance(ev), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertNothingSent(LIST); + assertNothingSent(ADD); + assertNothingSent(REMOVE); + assertNothingSent(ENSURE_TOKEN); + assertNothingSent(ATTENDANCE); + } + + // --- list --- + + @Test + void list_resolvesSalespersonName() { + stubGuests(guest(1, "Amy", "amy@x.co", 0)); + List> out = service.list(String.valueOf(EV)); + assertThat(out).hasSize(1); + assertThat(out.get(0)).containsEntry("name", "Amy").containsEntry("salespersonName", "Sales One"); + assertThat(sent(LIST)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV); + } + + // --- add --- + + @Test + void add_normalisesValidLinesAndRejectsInvalidOnesWithFieldAndIndex() { + when(rest.postForEntity(eq(ADD), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("added", List.of(Map.of("id", 1)), "rejected", List.of()))); + AdminGuestsRequest r = new AdminGuestsRequest(List.of( + line(" Amy ", "0123456789", " Amy@X.co "), + line(" ", "0123456789", null), + line("Bob", null, null), + line("Cat", "12345", null), + line("Dan", null, "dan@"), + line("E".repeat(101), "0123456789", null))); + + Map out = service.add(String.valueOf(EV), r, false); + + Map body = sent(ADD); + assertThat(body).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("doneBy", "boss"); + List> guests = (List>) body.get("guests"); + assertThat(guests).hasSize(1); + assertThat(guests.get(0)).containsEntry("name", "Amy").containsEntry("mobileE164", "+60123456789") + .containsEntry("email", "amy@x.co").containsEntry("companyName", "Acme").containsEntry("salespersonUserId", 21L); + List> rejected = (List>) out.get("rejected"); + assertThat(rejected).extracting(m -> m.get("index")).containsExactly(1, 2, 3, 4, 5); + assertThat(rejected).extracting(m -> m.get("field")).containsExactly("name", "mobile", "mobile", "email", "name"); + assertThat(rejected).extracting(m -> m.get("code")).containsExactly("REQUIRED_FIELD", "REQUIRED_FIELD", "INVALID_MOBILE", "INVALID_EMAIL", "TOO_LONG"); + assertThat(rejected).allSatisfy(m -> assertThat(m.get("message")).isNotNull()); + assertThat((List) out.get("added")).hasSize(1); + } + + @Test + void add_mergesCounterRejectionsKeepingOriginalIndexes() { + Map counterReject = Map.of("index", 1, "code", "DUPLICATE", "field", "mobile", "message", "already invited"); + when(rest.postForEntity(eq(ADD), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("added", List.of(Map.of("id", 1)), "rejected", List.of(counterReject)))); + // original indexes: 0 valid, 1 invalid (no name), 2 valid (counter sees it as index 1), 3 invalid + AdminGuestsRequest r = new AdminGuestsRequest(List.of( + line("Amy", "0123456789", null), line("", "0123456789", null), line("Bob", "0129876543", null), line("Cat", "x", null))); + + Map out = service.add(String.valueOf(EV), r, false); + + List> rejected = (List>) out.get("rejected"); + assertThat(rejected).extracting(m -> m.get("index")).containsExactly(1, 2, 3); + assertThat(rejected.get(1)).containsEntry("code", "DUPLICATE").containsEntry("field", "mobile"); + } + + @Test + void add_preview_validatesOnlyAndSavesNothing() { + AdminGuestsRequest r = new AdminGuestsRequest(List.of(line("Amy", "0123456789", null), line("", null, null))); + + Map out = service.add(String.valueOf(EV), r, true); + + assertNothingSent(ADD); + assertThat((List) out.get("added")).hasSize(1); + assertThat((List>) out.get("rejected")).extracting(m -> m.get("index")).containsExactly(1); + } + + @Test + void add_allInvalid_skipsTheCounterCall() { + Map out = service.add(String.valueOf(EV), new AdminGuestsRequest(List.of(line("", null, null))), false); + assertNothingSent(ADD); + assertThat((List) out.get("rejected")).hasSize(1); + } + + @Test + void add_emptyList_isBadRequest() { + assertCoded(() -> service.add(String.valueOf(EV), new AdminGuestsRequest(List.of()), false), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + } + + // --- remove --- + + @Test + void remove_registeredGuestIsConflict() { + when(rest.postForEntity(eq(REMOVE), any(ParameterizedTypeReference.class), any())) + .thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, null, null)); + assertCoded(() -> service.remove(String.valueOf(EV), "9"), HttpStatus.CONFLICT, "GUEST_REGISTERED"); + } + + @Test + void remove_sendsCompanyEventGuestAndUser() { + service.remove(String.valueOf(EV), "9"); + assertThat(sent(REMOVE)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("guestId", 9L).containsEntry("doneBy", "boss"); + } + + // --- send --- + + @Test + void send_buildsOneBilingualEscapedEmailPerGuestAndMarksOnlyThoseSent() { + stubGuests(guest(1, "Amy