Compare commits

...
Author SHA1 Message Date
ngqile 96ab8e6f5b Merge pull request 'feat(tickets): ticket QR codes, attendee naming and consent, door and venue check-in (add-event-tickets)' (#89) from add-event-tickets into main
CI / build-and-publish (push) Failing after 1s
2026-12-04 10:31:31 +00:00
ngqileandClaude Opus 5.5 7866427b2e docs(tickets): release note for ticket QR codes and check-in
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 18:31:05 +08:00
ngqileandClaude Opus 5.5 5831d7e15b feat(tickets): order detail shows each ticket's attendee and check-in; no resend once checked in
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 18:30:35 +08:00
ngqileandClaude Opus 5.5 5c2cb605b9 fix(leads): label ticket leads; event leads list no longer crashes on source TICKET
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 18:30:35 +08:00
ngqileandClaude Opus 5.5 02aa19a686 fix(tickets): staff scans skip the public ticket limit; order lookups for naming are rate-limited
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 17:56:55 +08:00
ngqileandClaude Opus 5.5 051fca9a13 feat(tickets): order page tickets and naming, resend ticket, ticket counts and show-your-ticket check-in
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 17:46:18 +08:00
ngqileandClaude Opus 5.5 2b8b3d92bc feat(tickets): ticket page /t/<code> with public and staff views, proxies and labels
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 17:38:07 +08:00
ngqileandClaude Opus 5.5 031ec8449e feat(tickets): staff ticket view, door check-in, resend ticket and ticketed venue check-in results
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 17:25:40 +08:00
ngqileandClaude Opus 5.5 8f3818414d feat(tickets): public ticket page API, QR PNG, attendee naming and consent
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 17:19:56 +08:00
ngqileandClaude Opus 5.5 6215eb5d8c feat(tickets): door check-in, self check-in on ticketed events, no walk-ins and ticket counts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 17:13:58 +08:00
ngqileandClaude Opus 5.5 cc81dc0fa5 feat(tickets): attendee naming, attendee consent, ticket emails and resend ticket
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 17:05:24 +08:00
ngqileandClaude Opus 5.5 1d6b265fd2 feat(tickets): ticket codes on payment, ticket state and lookup by code
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 17:00:21 +08:00
ngqileandClaude Opus 5.5 d56d0c3450 feat(tickets): attendee columns and codes for paid tickets
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 16:56:47 +08:00
ngqileandClaude Opus 5.5 a64ba1ad63 docs(openspec): propose add-event-tickets
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 16:55:19 +08:00
ngqile da5b76069c Merge pull request 'fix(portal): Co-Lite tab icon instead of babyboo's' (#88) from fix-tab-icon into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 08:47:33 +00:00
ngqileandClaude Opus 5.5 09dab5a40b fix(portal): Co-Lite tab icon instead of babyboo's
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 16:47:24 +08:00
ngqile 7c1b986289 Merge pull request 'docs: add Co-Lite blueprint page' (#87) from docs-co-lite-blueprint into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 08:40:50 +00:00
ngqileandClaude Opus 5.5 17126c92e3 docs: add Co-Lite blueprint page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 16:40:42 +08:00
ngqile 43b01c84bf Merge pull request 'chore(openspec): archive add-event-ticket-orders' (#86) from archive-add-event-ticket-orders into main
CI / build-and-publish (push) Failing after 1s
2026-12-04 08:40:11 +00:00
ngqileandClaude Opus 5.5 58d764a175 chore(openspec): archive add-event-ticket-orders
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 16:40:02 +08:00
ngqile 2d95dc203c Merge pull request 'feat(tickets): event ticket orders (add-event-ticket-orders)' (#85) from add-event-ticket-orders into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 08:39:28 +00:00
ngqile 3597adb94c Merge pull request 'fix(pages): end the page at a closing footer, with no blank strip below' (#84) from fix-footer-flush-bottom into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 06:02:08 +00:00
ngqileandClaude Opus 5.5 1d71b9122c fix(pages): end the page at a closing footer, with no blank strip below
The page's main area kept its bottom padding after a footer block,
leaving a light strip under the dark footer. A page whose last block
is a footer now has no bottom padding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 14:02:00 +08:00
102 changed files with 4977 additions and 56 deletions

No files matched your search

+238
View File
@@ -0,0 +1,238 @@
<title>Co-Lite Blueprint</title>
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&family=Space+Grotesk:wght@500;700&display=swap">
<style>
/* Layout: one reading column on a faint drafting grid; sections read top to bottom as now, next, later. */
:root {
--bg: #f4f7fb; --panel: #ffffff; --fg: #142235; --muted: #5a6b80; --line: #d3dce8;
--grid: rgba(30, 90, 160, .06); --accent: #1d5fa8; --accent-soft: #e3edf9;
--done: #1f7a4d; --done-soft: #e2f3ea; --now: #b26a00; --now-soft: #fbefd9; --owed: #a33b2b; --owed-soft: #f8e4e0;
--f-display: "Space Grotesk", "Segoe UI", system-ui, sans-serif;
--f-body: "IBM Plex Sans", "Segoe UI", system-ui, sans-serif;
--f-mono: "IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, monospace;
}
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) {
--bg: #0d1724; --panel: #13202f; --fg: #e3ebf5; --muted: #93a4b8; --line: #263649;
--grid: rgba(120, 170, 230, .06); --accent: #7fb2ec; --accent-soft: #1a2d44;
--done: #6fcf9b; --done-soft: #15301f; --now: #f0b65a; --now-soft: #33260f; --owed: #f08b7a; --owed-soft: #3a1c17; color-scheme: dark } }
:root[data-theme="dark"] {
--bg: #0d1724; --panel: #13202f; --fg: #e3ebf5; --muted: #93a4b8; --line: #263649;
--grid: rgba(120, 170, 230, .06); --accent: #7fb2ec; --accent-soft: #1a2d44;
--done: #6fcf9b; --done-soft: #15301f; --now: #f0b65a; --now-soft: #33260f; --owed: #f08b7a; --owed-soft: #3a1c17; color-scheme: dark }
* { box-sizing: border-box }
body {
background: var(--bg);
background-image: linear-gradient(var(--grid) 1px, transparent 1px), linear-gradient(90deg, var(--grid) 1px, transparent 1px);
background-size: 24px 24px;
color: var(--fg); font: 15px/1.6 var(--f-body);
padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px));
padding-block: 40px 64px;
}
.wrap { max-width: 980px; margin: 0 auto; display: grid; gap: 48px }
h1, h2, h3 { font-family: var(--f-display); text-wrap: balance; margin: 0; line-height: 1.2 }
h1 { font-size: clamp(2rem, 5vw, 2.8rem); letter-spacing: -.01em }
h2 { font-size: 1.45rem }
h3 { font-size: 1.05rem }
p { margin: 0; max-width: 68ch }
.eyebrow { font: 500 .75rem var(--f-mono); letter-spacing: .12em; text-transform: uppercase; color: var(--accent) }
.muted { color: var(--muted) }
section { display: grid; gap: 18px }
.sheet { font: .78rem var(--f-mono); color: var(--muted); display: flex; flex-wrap: wrap; gap: 6px 20px; border-top: 1px solid var(--line); padding-top: 10px }
/* header */
header { display: grid; gap: 14px }
.lede { font-size: 1.08rem }
.facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin-top: 6px }
.fact { border: 1px solid var(--line); background: var(--panel); border-radius: 6px; padding: 12px 14px; min-width: 0 }
.fact b { display: block; font: 600 1.5rem var(--f-display); font-variant-numeric: tabular-nums }
.fact span { font-size: .85rem; color: var(--muted) }
/* status chips */
.chip { display: inline-block; font: 500 .7rem var(--f-mono); letter-spacing: .06em; text-transform: uppercase; padding: 2px 8px; border-radius: 99px; white-space: nowrap }
.chip.done { background: var(--done-soft); color: var(--done) }
.chip.now { background: var(--now-soft); color: var(--now) }
.chip.owed { background: var(--owed-soft); color: var(--owed) }
.chip.later { background: var(--accent-soft); color: var(--accent) }
/* architecture */
.arch { display: grid; gap: 8px; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 18px }
.tier { display: grid; grid-template-columns: 140px 1fr; gap: 12px; align-items: center }
.tier > .label { font: 500 .75rem var(--f-mono); color: var(--muted); text-transform: uppercase; letter-spacing: .08em }
.boxes { display: flex; flex-wrap: wrap; gap: 8px; min-width: 0 }
.box { border: 1px solid var(--line); border-radius: 5px; padding: 6px 10px; font-size: .85rem; background: var(--bg) }
.box code { font: .78rem var(--f-mono); color: var(--accent) }
.box.new { border-style: dashed; border-color: var(--now); }
.down { text-align: center; color: var(--muted); font: .8rem var(--f-mono) }
@media (max-width: 560px) { .tier { grid-template-columns: 1fr; gap: 6px } }
/* shipped grid */
.groups { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 14px }
.group { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 16px; display: grid; gap: 8px; align-content: start; min-width: 0 }
.group ul { margin: 0; padding-left: 18px; display: grid; gap: 3px; font-size: .92rem }
/* owed list */
.owed-list { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none }
.owed-list li { display: grid; grid-template-columns: auto 1fr; gap: 12px; align-items: start; background: var(--panel); border: 1px solid var(--line); border-left: 3px solid var(--owed); border-radius: 6px; padding: 10px 14px }
/* roadmap */
.road { display: grid; gap: 0; position: relative }
.stage { display: grid; grid-template-columns: 56px 1fr; gap: 16px; padding-bottom: 22px; position: relative }
.stage::before { content: ""; position: absolute; left: 27px; top: 44px; bottom: 0; width: 2px; background: var(--line) }
.stage:last-child::before { display: none }
.num { width: 56px; height: 56px; border-radius: 50%; display: grid; place-items: center; font: 700 1.3rem var(--f-display); background: var(--panel); border: 2px solid var(--line); color: var(--muted); font-variant-numeric: tabular-nums }
.stage.current .num { border-color: var(--now); color: var(--now) }
.stage-body { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 16px; display: grid; gap: 10px; min-width: 0 }
.stage.current .stage-body { border-color: var(--now) }
.stage-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px }
.stage-body ul { margin: 0; padding-left: 18px; display: grid; gap: 3px; font-size: .92rem }
.changes { display: grid; gap: 6px }
.change { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: baseline; font-size: .9rem }
.change code { font: .8rem var(--f-mono); color: var(--accent) }
/* tables */
.tbl { overflow-x: auto; background: var(--panel); border: 1px solid var(--line); border-radius: 8px }
table { border-collapse: collapse; width: 100%; font-size: .9rem; min-width: 560px }
th, td { text-align: left; padding: 10px 14px; border-bottom: 1px solid var(--line); vertical-align: top }
th { font: 500 .72rem var(--f-mono); text-transform: uppercase; letter-spacing: .08em; color: var(--muted) }
tr:last-child td { border-bottom: 0 }
.decisions { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px }
.decision { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; display: grid; gap: 4px; min-width: 0 }
.decision .when { font: .72rem var(--f-mono); color: var(--muted) }
</style>
<div class="wrap">
<header>
<span class="eyebrow">Product blueprint · revision 4 December 2026</span>
<h1>Co-Lite Blueprint</h1>
<p class="lede">Co-Lite starts as an event CRM for INS and CV: it captures leads at events and from landing pages, and sales follows them up. It is growing into an event hosting platform with tickets, merch and membership, and will later open to any company as self-serve SaaS. <strong>Leads stay at the centre at every stage.</strong> Free events feed sales, and paid events feed sales too.</p>
<div class="facts">
<div class="fact"><b>40</b><span>changes shipped and archived</span></div>
<div class="fact"><b>27</b><span>capabilities with live specs</span></div>
<div class="fact"><b>2</b><span>companies at go-live (INS, CV)</span></div>
<div class="fact"><b>15 Jan 2027</b><span>go-live deadline</span></div>
</div>
</header>
<section>
<span class="eyebrow">How it fits together</span>
<h2>Platform architecture</h2>
<p class="muted">Spring Boot services cloned from the Solvway platform, with the MLM modules (bonus, stockist, inventory, tree) dropped. A rebuilt Next.js portal serves both staff screens and public visitor pages. Dashed boxes come with the second ticketing change.</p>
<div class="arch">
<div class="tier"><span class="label">Visitors</span><div class="boxes">
<span class="box">Landing pages <code>/p/</code></span><span class="box">QR sign-up <code>/r/</code></span><span class="box">Invites <code>/i/</code></span><span class="box">Check-in <code>/c/</code></span><span class="box">Orders <code>/o/</code></span><span class="box new">Tickets <code>/t/</code></span>
</div></div>
<div class="tier"><span class="label">Staff</span><div class="boxes">
<span class="box">Admin portal (Next.js): events, leads, dashboard, pages, WhatsApp, users, roles, audit</span>
</div></div>
<div class="down">▼ HTTPS</div>
<div class="tier"><span class="label">Edge</span><div class="boxes"><span class="box">api-gateway: JWT, public path list, request log</span><span class="box">mobile-api: <code>/api/admin/**</code> and <code>/api/public/**</code>, rate limits</span></div></div>
<div class="down">▼ internal</div>
<div class="tier"><span class="label">Services</span><div class="boxes">
<span class="box">counter: events, leads, pages, check-in<span class="new"></span></span><span class="box">system: companies, users, roles, labels</span><span class="box">auth</span><span class="box">email</span><span class="box">whatsapp</span><span class="box">log</span><span class="box">member (kept for later)</span>
</div></div>
<div class="tier"><span class="label">Data</span><div class="boxes"><span class="box">MySQL, one schema per service, every new table carries <code>company_id</code></span><span class="box">Redis: sessions, rate limits</span></div></div>
<div class="tier"><span class="label">Runs on</span><div class="boxes"><span class="box">Docker Compose locally</span><span class="box">Kubernetes manifests (kustomize base + prod overlay)</span></div></div>
</div>
</section>
<section>
<span class="eyebrow">Built</span>
<h2>What is shipped <span class="chip done">done</span></h2>
<div class="groups">
<div class="group"><h3>Foundation and operations</h3><ul>
<li>Repository, local stack, seed data</li><li>Release CI and image packaging</li><li>Kubernetes manifests</li><li>Gateway request logging without bodies</li></ul></div>
<div class="group"><h3>Admin, access and security</h3><ul>
<li>Users, roles, permission modules</li><li>Login security, lockout, temporary passwords</li><li>Company scoping: INS and CV see only their own data</li><li>Audit log, email log</li></ul></div>
<div class="group"><h3>Events and leads</h3><ul>
<li>Events with teams, interests</li><li>Staff lead capture, listings, export</li><li>Lead dashboard, follow-up notifications</li><li>QR self-registration with personal codes</li><li>Invitations, capacity and invite cap</li><li>Venue check-in and attendance numbers</li></ul></div>
<div class="group"><h3>Landing pages</h3><ul>
<li>Visual on-page editor, drafts, templates</li><li>Hero, sections, features, steps, trust, FAQ, CTA</li><li>Sign-up forms with UTM tracking</li><li>Custom HTML, image upload, anchors</li><li>Top bar, footer, thank-you text, contact links</li><li>INS hotel-technology page built natively</li></ul></div>
<div class="group"><h3>Ticket orders</h3><ul>
<li>Tickets switch, payment instructions, hold days per event</li><li>Ticket types with price, quantity, sales end</li><li>Tickets page section; seats locked per order</li><li>Order page and order emails; holds expire</li><li>Staff orders: mark paid, cancel order or ticket, resend</li><li>Buyer becomes an event lead</li></ul></div>
<div class="group"><h3>Messaging and language</h3><ul>
<li>WhatsApp inbox</li><li>Simplified Chinese interface</li><li>Message catalogue filter</li></ul></div>
</div>
</section>
<section>
<span class="eyebrow">Before 15 January 2027</span>
<h2>Still owed for go-live <span class="chip owed">open</span></h2>
<ul class="owed-list">
<li><span class="chip owed">deploy</span><span>Kubernetes dry run on the real cluster, then the first apply.</span></li>
<li><span class="chip owed">verify</span><span>WhatsApp end-to-end check once the business account is linked.</span></li>
<li><span class="chip owed">legal</span><span>PDPA owner to confirm the shortened privacy notice on the landing form.</span></li>
<li><span class="chip owed">content</span><span>Rebuild the INS landing page on the real server; it exists only in the local database today.</span></li>
</ul>
</section>
<section>
<span class="eyebrow">Where it is going</span>
<h2>Roadmap</h2>
<p class="muted">Order agreed with the owner on 4 December 2026. Each stage is brainstormed and approved as its own design before it is built.</p>
<div class="road">
<div class="stage current"><div class="num">1</div><div class="stage-body">
<div class="stage-head"><h3>Event ticketing</h3><span class="chip now">in progress</span></div>
<p>Paid events sell tickets; free events keep today's lead flow. Buyers pay outside Co-Lite for now, by bank transfer or a payment link, and staff mark the order paid.</p>
<div class="changes">
<div class="change"><code>add-event-ticket-orders</code><span class="chip done">done</span><span class="muted">Ticket types, Tickets page block, orders with seat locking, holds that expire, order page and emails, staff order screens, buyer becomes a lead.</span></div>
<div class="change"><code>add-event-tickets</code><span class="chip now">next</span><span class="muted">QR ticket per seat, buyer names attendees later, attendee consent, check-in at the door, invites count as free tickets.</span></div>
</div>
</div></div>
<div class="stage"><div class="num">2</div><div class="stage-body">
<div class="stage-head"><h3>Merch collected at events</h3><span class="chip later">planned</span></div>
<ul><li>Products with variants (size, colour) and a stock count</li><li>Sold alongside tickets in the same order</li><li>Handed over at check-in</li></ul>
</div></div>
<div class="stage"><div class="num">3</div><div class="stage-body">
<div class="stage-head"><h3>Merch shop with manual shipping</h3><span class="chip later">planned</span></div>
<ul><li>Standalone shop, not tied to an event</li><li>Delivery address on the order; staff ship and mark it shipped</li><li>No courier integration at first</li></ul>
</div></div>
<div class="stage"><div class="num">4</div><div class="stage-body">
<div class="stage-head"><h3>Membership</h3><span class="chip later">planned</span></div>
<ul><li>Member accounts: profile, My tickets, events attended. Tickets already held are claimed by mobile or email.</li><li>Member-only events, early access and member prices on tickets and merch</li><li>Points earned at check-in and on paid tickets, spent as discounts; tiers later</li><li>Referrals through invite links, one level only</li><li>Leads from free events invited to join; likely built on the kept customer portal</li></ul>
</div></div>
<div class="stage"><div class="num">5</div><div class="stage-body">
<div class="stage-head"><h3>Self-serve SaaS</h3><span class="chip later">planned</span></div>
<ul><li>Companies sign up themselves on a Free or Premium plan</li><li>No admin needs to create the company by hand</li><li>Built on the company scoping already in place</li></ul>
</div></div>
</div>
</section>
<section>
<span class="eyebrow">At any stage</span>
<h2>Upgrades that wait for a trigger</h2>
<div class="tbl"><table>
<thead><tr><th>Upgrade</th><th>Trigger</th><th>What it changes</th></tr></thead>
<tbody>
<tr><td>Payment gateway (FPX, card)</td><td>A gateway account is chosen</td><td>Adds "pay now" to the same order; holds shrink from days to minutes</td></tr>
<tr><td>Faster seat updates</td><td>An event with thousands rushing at once</td><td>Single conditional update instead of the event lock; CAPTCHA, cached pages, a load test</td></tr>
<tr><td>Launch-day protection</td><td>Concert-size launches</td><td>Virtual waiting room, queued orders, member-only sales, ticketing as its own service</td></tr>
<tr><td>Receipts, invoices, SST</td><td>When payment moves inside Co-Lite</td><td>Issued from the order instead of outside the system</td></tr>
</tbody>
</table></div>
</section>
<section>
<span class="eyebrow">Settled</span>
<h2>Decisions that shape the build</h2>
<div class="decisions">
<div class="decision"><span class="when">foundation</span><h3>Leads are their own table</h3><p class="muted">Not a status on members. Every route in (QR, invite, page, ticket) creates or reuses a lead.</p></div>
<div class="decision"><span class="when">30 Nov 2026</span><h3>Every new table has a company</h3><p class="muted">So INS and CV stay apart now, and SaaS later is a sign-up flow, not a rebuild.</p></div>
<div class="decision"><span class="when">4 Dec 2026</span><h3>One order for every kind of item</h3><p class="muted">Order lines carry a kind: ticket now, merch pickup and shipping later, one checkout like a fan-platform shop.</p></div>
<div class="decision"><span class="when">4 Dec 2026</span><h3>Attendees consent themselves</h3><p class="muted">A buyer's partner can attend without joining; they become a lead only after ticking the consent.</p></div>
<div class="decision"><span class="when">4 Dec 2026</span><h3>No walk-ins on paid events</h3><p class="muted">Venue check-in admits ticket holders and registered invited guests only.</p></div>
<div class="decision"><span class="when">4 Dec 2026</span><h3>No inventory service</h3><p class="muted">Seats and later merch stock are counted in the counter service with one locked, all-or-nothing write.</p></div>
</div>
</section>
<div class="sheet"><span>Source: openspec/specs, openspec/changes/archive, docs/superpowers/specs/2026-12-04-event-ticketing-design.md</span><span>Status as of 4 December 2026</span></div>
</div>
+16
View File
@@ -492,3 +492,19 @@ Staff sell tickets for an event from its **Tickets** card; buyers request them o
**Release add-event-ticket-orders (SQL, in its OpenSpec change folder):** run `sql/01-event-ticket-orders.sql` (adds the ticket columns to `event` and creates `ticket_type`, `shop_order`, `shop_order_line` and `ticket`; DDL) and `sql/02-event-tickets-module.sql` (the `BO_EVENT_TICKETS` module; no role gets it) before the new images go live: the new services-counter reads the new `event` columns on every event query. Then deploy services-counter, mobile-api, api-gateway (opens the public ticket paths) and the portal, then run `sql/03-ticket-labels.sql` (labels only; same rule as `05-page-labels.sql`). Order emails go through the email service like the other emails. Rollback: the previous images, then `sql/99-rollback.sql`, which drops every order and ticket, so export the orders first.
Known limit: a page whose Tickets event has ended, been disabled or had tickets switched off cannot be saved until the Tickets section is removed or points at another event.
## 14. Ticket QR codes and check-in
Every ticket on a Paid order (free orders included) has its own link `/t/<code>` with a QR code. The order-paid email carries each ticket's QR and link, and a link to the order page where the buyer names the attendees.
1. **Naming attendees.** On the order page `/o/<token>` the buyer names each ticket (name, and a mobile number or email) and ticks that they have permission to share the details. Naming or renaming gives the ticket a new link, so the old one stops working, and emails the ticket to the attendee when an email is given. A checked-in or cancelled ticket cannot be renamed.
2. **Attendee consent.** A named attendee can tick "Keep me updated" on their ticket page, or at the door. That makes them an event lead with source Ticket under the company's current privacy notice.
3. **Door check-in.** Door staff sign in to the portal on their phone once, with `BO_EVENTS`. Scanning a ticket's QR then opens the staff view: a large Valid, Already checked in, or Not valid banner and a **Check in** button. An unnamed ticket asks for the attendee's name and a mobile number or email first. Staff of another company, and visitors who are not signed in, see the public ticket page instead. Check-in is only possible on the event's days.
4. **Venue self check-in.** On an event that sells tickets, the venue QR (`/c/...`) checks in a paid ticket whose attendee matches the mobile number or email entered (for an unnamed ticket, the buyer's), or a registered invited guest. Anyone else is asked to show their ticket at the entrance; there is no walk-in form.
5. **Order detail.** Each ticket row shows its attendee and check-in time. **Resend ticket** sends a valid ticket again, to its attendee's email when named, otherwise to the buyer (`BO_EVENT_TICKETS`, audited).
6. **Attendance numbers.** The event's Guests card adds tickets awaiting payment, tickets paid and tickets checked in.
7. **Limits.** The public ticket page allows 120 loads per device. Naming and consent allow 60 submissions per device per event, and naming also counts towards the order page's 120 loads.
**Release add-event-tickets (SQL, in its OpenSpec change folder):** run `sql/01-ticket-attendees.sql` before the new services-counter starts. It adds three `ticket` columns and two keys, and gives every active ticket on an order that is already Paid its code. It is additive, and the old images ignore the new columns. Then deploy services-counter, mobile-api (adds `com.google.zxing:core` for the QR image), api-gateway (opens the public ticket paths) and the portal. Then run `sql/02-ticket-labels.sql` (labels only). Rollback: the previous images, then `sql/99-rollback.sql`.
This release also fixes the event leads list, which failed to load for any event with a ticket buyer lead (source Ticket had no label).
+6 -1
View File
@@ -615,10 +615,15 @@ CREATE TABLE IF NOT EXISTS `ticket` (
`cancelled_by` varchar(255) NULL,
`checked_in_at` datetime NULL,
`checked_in_by` varchar(255) NULL,
`attendee_named_at` datetime NULL,
`attendee_consent_at` datetime NULL,
`attendee_notice_id` bigint NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_ticket_code` (`code`),
KEY `idx_ticket_type_status` (`ticket_type_id`, `status`),
KEY `idx_ticket_order` (`order_id`)
KEY `idx_ticket_order` (`order_id`),
KEY `idx_ticket_event_mobile` (`event_uuid`, `attendee_mobile_e164`),
KEY `idx_ticket_event_email` (`event_uuid`, `attendee_email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- add-event-ticket-orders/sql/02-event-tickets-module.sql
+90
View File
@@ -695,6 +695,8 @@ INSERT INTO message (code, content, area) SELECT 'LeadSourceInvite', JSON_OBJECT
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '邀请') WHERE LOWER(code) = LOWER('LeadSourceInvite') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'LeadSourceWeb', JSON_OBJECT('en_US', 'Web page', 'zh_CN', '网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('LeadSourceWeb') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '网页') WHERE LOWER(code) = LOWER('LeadSourceWeb') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'LeadSourceTicket', JSON_OBJECT('en_US', 'Ticket', 'zh_CN', '门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('LeadSourceTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票') WHERE LOWER(code) = LOWER('LeadSourceTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'LeadWebPage', JSON_OBJECT('en_US', 'Web page: {path}', 'zh_CN', '网页:{path}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('LeadWebPage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '网页:{path}') WHERE LOWER(code) = LOWER('LeadWebPage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'LeadCampaign', JSON_OBJECT('en_US', 'Campaign: {tags}', 'zh_CN', '推广活动:{tags}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('LeadCampaign') AND area = 'A');
@@ -2007,6 +2009,94 @@ INSERT INTO message (code, content, area) SELECT 'TktPublicExpired', JSON_OBJECT
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此订单在收到付款前已过期。') WHERE LOWER(code) = LOWER('TktPublicExpired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderInvalid', JSON_OBJECT('en_US', 'This order link is not valid.', 'zh_CN', '此订单链接无效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderInvalid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此订单链接无效。') WHERE LOWER(code) = LOWER('TktOrderInvalid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketInvalid', JSON_OBJECT('en_US', 'This ticket link is not valid.', 'zh_CN', '此门票链接无效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketInvalid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票链接无效。') WHERE LOWER(code) = LOWER('TktTicketInvalid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketFor', JSON_OBJECT('en_US', 'Ticket for {name}', 'zh_CN', '{name} 的门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketFor') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{name} 的门票') WHERE LOWER(code) = LOWER('TktTicketFor') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktQrAlt', JSON_OBJECT('en_US', 'Ticket QR code', 'zh_CN', '门票二维码'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktQrAlt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票二维码') WHERE LOWER(code) = LOWER('TktQrAlt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktShowQr', JSON_OBJECT('en_US', 'Show this QR code at the entrance.', 'zh_CN', '请在入口出示此二维码。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktShowQr') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请在入口出示此二维码。') WHERE LOWER(code) = LOWER('TktShowQr') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckedInAt', JSON_OBJECT('en_US', 'Checked in at {when}', 'zh_CN', '已于 {when} 签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckedInAt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已于 {when} 签到') WHERE LOWER(code) = LOWER('TktCheckedInAt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotValid', JSON_OBJECT('en_US', 'This ticket is not valid', 'zh_CN', '此门票无效'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotValid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票无效') WHERE LOWER(code) = LOWER('TktNotValid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonAWAITING', JSON_OBJECT('en_US', 'awaiting payment', 'zh_CN', '等待付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonAWAITING') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '等待付款') WHERE LOWER(code) = LOWER('TktReasonAWAITING') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonORDER_CANCELLED', JSON_OBJECT('en_US', 'order cancelled', 'zh_CN', '订单已取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonORDER_CANCELLED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已取消') WHERE LOWER(code) = LOWER('TktReasonORDER_CANCELLED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonORDER_EXPIRED', JSON_OBJECT('en_US', 'order expired', 'zh_CN', '订单已过期'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonORDER_EXPIRED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已过期') WHERE LOWER(code) = LOWER('TktReasonORDER_EXPIRED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonTICKET_CANCELLED', JSON_OBJECT('en_US', 'ticket cancelled', 'zh_CN', '门票已取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonTICKET_CANCELLED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票已取消') WHERE LOWER(code) = LOWER('TktReasonTICKET_CANCELLED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktKeepUpdated', JSON_OBJECT('en_US', 'Keep me updated about {company} events', 'zh_CN', '向我发送 {company} 的活动资讯'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktKeepUpdated') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '向我发送 {company} 的活动资讯') WHERE LOWER(code) = LOWER('TktKeepUpdated') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktConsentSave', JSON_OBJECT('en_US', 'Save', 'zh_CN', '保存'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktConsentSave') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存') WHERE LOWER(code) = LOWER('TktConsentSave') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktConsentDone', JSON_OBJECT('en_US', 'Thank you. We will keep you updated.', 'zh_CN', '谢谢,我们会向您发送最新资讯。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktConsentDone') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '谢谢,我们会向您发送最新资讯。') WHERE LOWER(code) = LOWER('TktConsentDone') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStaffView', JSON_OBJECT('en_US', 'Staff check-in', 'zh_CN', '工作人员签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStaffView') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '工作人员签到') WHERE LOWER(code) = LOWER('TktStaffView') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStaffValid', JSON_OBJECT('en_US', 'Valid', 'zh_CN', '有效'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStaffValid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有效') WHERE LOWER(code) = LOWER('TktStaffValid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAlreadyCheckedIn', JSON_OBJECT('en_US', 'Already checked in at {when}', 'zh_CN', '已于 {when} 签到过'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAlreadyCheckedIn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已于 {when} 签到过') WHERE LOWER(code) = LOWER('TktAlreadyCheckedIn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotValidReason', JSON_OBJECT('en_US', 'Not valid: {reason}', 'zh_CN', '无效:{reason}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotValidReason') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无效:{reason}') WHERE LOWER(code) = LOWER('TktNotValidReason') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotEventDay', JSON_OBJECT('en_US', 'Check-in is only open on the event days.', 'zh_CN', '仅在活动日开放签到。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotEventDay') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '仅在活动日开放签到。') WHERE LOWER(code) = LOWER('TktNotEventDay') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckIn', JSON_OBJECT('en_US', 'Check in', 'zh_CN', '签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckIn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '签到') WHERE LOWER(code) = LOWER('TktCheckIn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckedInNow', JSON_OBJECT('en_US', 'Checked in.', 'zh_CN', '签到成功。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckedInNow') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '签到成功。') WHERE LOWER(code) = LOWER('TktCheckedInNow') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktUnnamed', JSON_OBJECT('en_US', 'No attendee named yet', 'zh_CN', '尚未填写参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktUnnamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚未填写参加者') WHERE LOWER(code) = LOWER('TktUnnamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAttendeeName', JSON_OBJECT('en_US', 'Attendee name', 'zh_CN', '参加者姓名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAttendeeName') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '参加者姓名') WHERE LOWER(code) = LOWER('TktAttendeeName') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktContactRequired', JSON_OBJECT('en_US', 'Enter a mobile number or an email.', 'zh_CN', '请输入手机号码或电子邮件。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktContactRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入手机号码或电子邮件。') WHERE LOWER(code) = LOWER('TktContactRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'ChkShowTicket', JSON_OBJECT('en_US', 'Please show your ticket at the entrance.', 'zh_CN', '请在入口出示您的门票。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('ChkShowTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请在入口出示您的门票。') WHERE LOWER(code) = LOWER('ChkShowTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'GuestTicketsAwaiting', JSON_OBJECT('en_US', 'Tickets awaiting payment', 'zh_CN', '待付款门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('GuestTicketsAwaiting') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待付款门票') WHERE LOWER(code) = LOWER('GuestTicketsAwaiting') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'GuestTicketsPaid', JSON_OBJECT('en_US', 'Tickets paid', 'zh_CN', '已付款门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('GuestTicketsPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已付款门票') WHERE LOWER(code) = LOWER('GuestTicketsPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'GuestTicketsCheckedIn', JSON_OBJECT('en_US', 'Tickets checked in', 'zh_CN', '已签到门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('GuestTicketsCheckedIn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已签到门票') WHERE LOWER(code) = LOWER('GuestTicketsCheckedIn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrTicketNotValid', JSON_OBJECT('en_US', 'This ticket is not valid, so it cannot be sent.', 'zh_CN', '此门票无效,无法发送。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrTicketNotValid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票无效,无法发送。') WHERE LOWER(code) = LOWER('TktErrTicketNotValid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktResendTicket', JSON_OBJECT('en_US', 'Resend ticket', 'zh_CN', '重新发送门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktResendTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '重新发送门票') WHERE LOWER(code) = LOWER('TktResendTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketSent', JSON_OBJECT('en_US', 'Ticket sent.', 'zh_CN', '门票已发送。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketSent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票已发送。') WHERE LOWER(code) = LOWER('TktTicketSent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktYourTickets', JSON_OBJECT('en_US', 'Your tickets', 'zh_CN', '您的门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktYourTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您的门票') WHERE LOWER(code) = LOWER('TktYourTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNameAttendeesHelp', JSON_OBJECT('en_US', 'Name each attendee so their ticket can be emailed to them, or share each ticket''s link.', 'zh_CN', '填写每位参加者,以便通过电子邮件将门票发送给他们,或分享每张门票的链接。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNameAttendeesHelp') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '填写每位参加者,以便通过电子邮件将门票发送给他们,或分享每张门票的链接。') WHERE LOWER(code) = LOWER('TktNameAttendeesHelp') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAttendeeSaved', JSON_OBJECT('en_US', 'Saved. The ticket has a new link; the old one no longer works.', 'zh_CN', '已保存。门票已有新链接,旧链接已失效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAttendeeSaved') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已保存。门票已有新链接,旧链接已失效。') WHERE LOWER(code) = LOWER('TktAttendeeSaved') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotNamed', JSON_OBJECT('en_US', 'Not named yet', 'zh_CN', '尚未填写'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotNamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚未填写') WHERE LOWER(code) = LOWER('TktNotNamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOpenTicket', JSON_OBJECT('en_US', 'Open ticket', 'zh_CN', '打开门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOpenTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '打开门票') WHERE LOWER(code) = LOWER('TktOpenTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCopyLink', JSON_OBJECT('en_US', 'Copy link', 'zh_CN', '复制链接'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCopyLink') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制链接') WHERE LOWER(code) = LOWER('TktCopyLink') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktLinkCopied', JSON_OBJECT('en_US', 'Link copied.', 'zh_CN', '链接已复制。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktLinkCopied') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接已复制。') WHERE LOWER(code) = LOWER('TktLinkCopied') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNameAttendee', JSON_OBJECT('en_US', 'Name attendee', 'zh_CN', '填写参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNameAttendee') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '填写参加者') WHERE LOWER(code) = LOWER('TktNameAttendee') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktChangeAttendee', JSON_OBJECT('en_US', 'Change attendee', 'zh_CN', '更改参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktChangeAttendee') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '更改参加者') WHERE LOWER(code) = LOWER('TktChangeAttendee') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAttendeeRequired', JSON_OBJECT('en_US', 'Enter the attendee''s name and a mobile number or an email.', 'zh_CN', '请输入参加者姓名,以及手机号码或电子邮件。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAttendeeRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入参加者姓名,以及手机号码或电子邮件。') WHERE LOWER(code) = LOWER('TktAttendeeRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPermissionRequired', JSON_OBJECT('en_US', 'Tick the box to confirm you have permission.', 'zh_CN', '请勾选以确认您已获得许可。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPermissionRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请勾选以确认您已获得许可。') WHERE LOWER(code) = LOWER('TktPermissionRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPermission', JSON_OBJECT('en_US', 'I have permission to share these details so their ticket can be sent', 'zh_CN', '我已获得许可分享这些资料,以便发送其门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPermission') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '我已获得许可分享这些资料,以便发送其门票') WHERE LOWER(code) = LOWER('TktPermission') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktRenameWarning', JSON_OBJECT('en_US', 'Saving gives this ticket a new link and QR code. The old ones stop working.', 'zh_CN', '保存后此门票将获得新的链接和二维码,旧的将失效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktRenameWarning') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存后此门票将获得新的链接和二维码,旧的将失效。') WHERE LOWER(code) = LOWER('TktRenameWarning') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSaveAttendee', JSON_OBJECT('en_US', 'Save attendee', 'zh_CN', '保存参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSaveAttendee') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存参加者') WHERE LOWER(code) = LOWER('TktSaveAttendee') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockTickets', JSON_OBJECT('en_US', 'Tickets', 'zh_CN', '门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票') WHERE LOWER(code) = LOWER('PagesBlockTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTicketsEvent', JSON_OBJECT('en_US', 'Event selling tickets', 'zh_CN', '售票活动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTicketsEvent') AND area = 'A');
@@ -0,0 +1,130 @@
# Design
Product design: `docs/superpowers/specs/2026-12-04-event-ticketing-design.md` (approved 2026-12-04). This file holds the technical contracts. Change 1 (`add-event-ticket-orders`) already built the `ticket` table with `code`, the attendee columns, `event_lead_uuid` and the `checked_in_*` columns, so this change mostly fills them in.
## Context
- **Tickets and orders:**
- Orders and tickets live in services-counter: `TicketOrderService` handles the request and `byToken`; `TicketOrderStaffService` handles mark paid, cancel and resend; `TicketOrderMailer` sends the order emails; `TicketOrderExpiryJob` expires holds.
- mobile-api's `PublicPageService` holds the public order endpoints and `AdminTicketService` the staff ones.
- The gateway's `JWTAuthFilter` lists the counter paths that are public.
- **Venue self check-in:**
- `EventCheckInService.lookup` returns `CHECKED_IN` or `FORM`.
- The walk-in form posts to the existing register path with `attend=true`.
- **Capacity:** "a registered invite counts toward capacity" already holds. `EventGuestService.register`, `TicketOrderService.create` and `EventHeadcountService` all add registered guests, walk-ins and held tickets. No work here.
- **Leads:** `RegistrationService.register(RegisterRequest)` does the QR-registration matching and takes `source`, `consentNoticeId`, `consentAt` and `attend`. It returns the event lead uuid.
- **Portal:**
- `clientApi` redirects to `/login` on a 401.
- `/api/auth/session` does not redirect, and tells whether a staff session exists.
- `qrcode.react` draws QRs in the browser only.
## Goals / Non-Goals
**Goals:**
- Ticket codes on payment.
- The `/t/<code>` page with its public and staff views.
- Attendee naming on the order page.
- Attendee consent.
- The paid email with the tickets, the ticket email, and resend ticket.
- Door check-in.
- Self check-in rules on ticketed events.
- The ticket counts.
**Non-Goals:**
- Payment gateway.
- Merch.
- Member accounts.
- WhatsApp ticket delivery: an attendee named with a mobile only gets no message; the buyer forwards the link.
- Transferring a ticket to another order.
- Printing tickets.
## Decisions
1. **Codes are issued when the order becomes Paid.** This happens inside the same transaction as the status change, at three places: `TicketOrderService.create` (free order), `TicketOrderStaffService.markPaid` (Awaiting payment or Expired), and nowhere else. Codes use the existing 22-character `RegistrationLinkService.newToken()`; `uk_ticket_code` guards uniqueness. Cancelling keeps the code, and validity is computed: the order is `PAID` and the ticket is `ACTIVE`.
- *Alternative:* codes at request time. Rejected, because an unpaid order would then carry QRs that look real.
2. **Ticket state, computed in one place.** `TicketState.of(order, ticket)` returns `VALID`, `CHECKED_IN`, `AWAITING`, `ORDER_CANCELLED`, `ORDER_EXPIRED` or `TICKET_CANCELLED`. The public page, the staff view, check-in and self check-in all use it.
3. **Renaming replaces the code.** The attendee save is `POST ticket/attendee` with the order token, ticket id, name, mobile, email and `permission`. In one transaction it:
- checks the order token and that the order is `PAID`;
- checks the ticket is `ACTIVE` and not checked in;
- sets a new code, `attendee_named_at`, the attendee fields, and clears `attendee_consent_at`, `attendee_notice_id` and `event_lead_uuid`;
- after commit, sends the Ticket email when an email is set.
- Normalisation and the `MOBILE_OR_EMAIL_REQUIRED`, name-length and email-format errors reuse the QR registration helpers in mobile-api.
4. **Consent creates the lead through `RegistrationService.register`.** It is called with source `TICKET`, no salesperson, the company's current notice and `attend=false`. At check-in it is called with `attend=true`. The returned event lead uuid is stored on the ticket. An attendee whose details match a lead is linked to it, as QR registration already does.
- **Unnamed tickets:** the consent needs a name and contact, so on the public page it is offered only for a named ticket. At the door, staff enter them first.
5. **Staff view detection.** The `/t/[code]` page first calls the portal's `/api/tickets/{code}`, which answers 401 at once when there is no session and otherwise calls `GET /api/admin/tickets/{code}`. Only when that fails does it load the public view (`GET /api/public/tickets/{code}`), so a door scan never counts toward the public `tkt:load` limit. That call is guarded by `@AdminModule("BO_EVENTS")` and scoped by company in mobile-api with `loadEvent(uuid, null)`, so another company's event is a 404. On 401, 403 or 404 the page stays public. The admin call uses a plain `fetch`, not `clientApi`, so a signed-out visitor is never bounced to login.
6. **Check-in.** `POST /api/admin/tickets/{code}/checkin` takes optional `{name, mobile, email, consent}`, which are required when the ticket is unnamed. Refusals are 409 with the codes `ALREADY_CHECKED_IN|<time>`, `NOT_VALID|<state>` and `NOT_EVENT_DAY`. The update is conditional (`checked_in_at IS NULL`), so two scanners cannot both check a ticket in; the loser gets `ALREADY_CHECKED_IN`. The action is `@Audited`.
7. **Self check-in on a ticketed event.** For `tickets_enabled` events only, `EventCheckInService.lookup` checks, in order:
1. the oldest `ACTIVE` ticket on a `PAID` order of the event, not checked in, whose attendee mobile or email matches, or whose attendee is blank and whose order's buyer mobile or email matches. It is checked in with `checked_in_by = 'self'`, and the lead is marked attended when the ticket has one;
2. a registered guest of the event, as today;
3. otherwise the result is `SHOW_TICKET`.
The walk-in register path refuses a ticketed event with 409 `TICKETS_ONLY`. The welcome uses the attendee's first name, or the buyer's for an unnamed ticket.
8. **QR PNG in mobile-api.** `GET /api/public/tickets/{code}/qr.png`:
- checks the code shape and validity through counter `ticket/byCode`; an invalid or unknown code is 404;
- encodes `<admin-portal-base>/t/<code>` with zxing `QRCodeWriter` at 300 px, written by `ImageIO`;
- responds `Cache-Control: private, max-age=300`;
- counts toward the `tkt:load` limit.
The portal proxies it like the page images. Emails use the absolute portal URL in `<img src>`.
9. **Order page tickets.** Counter `byToken` adds `tickets: [{id, typeName, attendeeName, code, state, checkedInAt}]` only when the order is PAID. mobile-api passes them through without attendee mobile or email: the counter does not return those to the public call at all.
10. **Emails.** `TicketOrderMailer`:
- **PAID:** gains one block per active ticket: the type, the QR `<img>` and the link. It ends with "Name your attendees: <order link>".
- **New kind TICKET:** sends one ticket to its attendee (or to the buyer, when staff resend an unnamed ticket), with the consent invitation link pointing to the ticket page.
- All of them are sent after commit and are best effort, as today.
11. **Counts.** `EventHeadcountService.Headcount` gains `ticketsAwaiting`, `ticketsPaid` and `ticketsCheckedIn`, from one grouped query over active tickets joined to their order status. The portal's GuestsCard shows them when the event sells tickets.
12. **Limits.**
- `tkt:load:<ip>` allows 120 per 10 minutes, for the ticket page and the QR together.
- `tkt:submit:<ip>:<event>` allows 60 per 10 minutes, for naming and consent. Naming first looks up the order by its token, which counts toward the order page's `ord:load:<ip>` limit (120 per 10 minutes).
- Staff check-in has no IP limit: it is an authenticated admin call.
## Data
`sql/01-ticket-attendees.sql` (services-counter, additive):
```sql
ALTER TABLE `ticket`
ADD COLUMN `attendee_named_at` datetime NULL,
ADD COLUMN `attendee_consent_at` datetime NULL,
ADD COLUMN `attendee_notice_id` bigint NULL,
ADD KEY `idx_ticket_event_mobile` (`event_uuid`, `attendee_mobile_e164`),
ADD KEY `idx_ticket_event_email` (`event_uuid`, `attendee_email`);
```
- `sql/02-ticket-labels.sql` holds the labels, cut from `npm run i18n:sql`.
- `sql/99-rollback.sql` drops the three columns and two keys. Codes stay, because change 1 owns the column.
## Endpoints
| Layer | Method and path | Auth |
|---|---|---|
| counter | `GET ticket/byCode/{code}` | public via gateway |
| counter | `POST ticket/attendee` (order token, ticket id, attendee, permission) | public via gateway |
| counter | `POST ticket/consent` (code, notice id) | public via gateway |
| counter | `POST ticket/staff` and `POST ticket/checkin` (company id and code in the body) | JWT (from mobile-api admin) |
| counter | `POST ticketOrder/resendTicket` (company, event, order and ticket ids in the body) | JWT |
| mobile-api | `GET /api/public/tickets/{code}`, `GET .../qr.png`, `POST .../consent` | public |
| mobile-api | `POST /api/public/orders/{token}/tickets/{ticketId}/attendee` | public |
| mobile-api | `GET /api/admin/tickets/{code}`, `POST /api/admin/tickets/{code}/checkin` | `BO_EVENTS` |
| mobile-api | `POST /api/admin/events/{uuid}/orders/{orderId}/tickets/{ticketId}/resend` | `BO_EVENT_TICKETS` |
| gateway | public: `GET /counter/ticket/byCode/[A-Za-z0-9_-]{22}`, `POST /counter/ticket/attendee`, `POST /counter/ticket/consent` | |
| portal | `/t/[code]` page (public in the route guard); proxies for each mobile-api path above | |
## Risks / Trade-offs
- **Mobile-only attendees get no ticket message.** The buyer shares the link. *Mitigation:* the order page shows each ticket's link with a copy button. WhatsApp delivery can follow once the business account is linked.
- **A forwarded ticket link works for whoever holds it.** This is the same as any paper ticket; check-in is one-time. *Mitigation:* renaming replaces the code.
- **Staff view on a phone needs a signed-in session in that phone's browser.** That is the existing portal login; the door staff sign in once.
- **New dependency** `com.google.zxing:core`, MIT-style Apache 2.0, no transitive dependencies, used only for the email PNG.
- **Self check-in matching an unnamed ticket to its buyer** lets the buyer check in once per unnamed ticket. Each lookup takes one ticket, which matches the buyer bringing friends whose names were never given. ponytail: no per-person cap; add one if abuse is seen.
## Migration Plan
1. Run `sql/01-ticket-attendees.sql` before the new services-counter starts. It is additive, and the old images ignore the columns.
2. Deploy services-counter, mobile-api, api-gateway and the portal.
3. Run `sql/02-ticket-labels.sql`.
4. Orders paid before this release have tickets without codes. A one-off statement in `01` gives every active ticket on a PAID order a code, using `REPLACE(TO_BASE64(RANDOM_BYTES(16)), ...)` trimmed to the 22-character URL-safe form.
5. **Rollback:** the previous images, then `99`.
## Open Questions
None for the owner. Builder calls are recorded above (decisions 4, 5 and 7) and in the release note.
@@ -0,0 +1,85 @@
# Proposal
## Why
Change 1 (`add-event-ticket-orders`, merged 2026-12-04) lets visitors request tickets and staff mark orders paid. A paid order still gives the buyer nothing to show at the door, and the venue's self check-in still offers the walk-in form, so anyone can walk into a paid event. This change adds the ticket itself: a QR code per seat, attendees, and check-in at the door.
The product design was approved on 2026-12-04: `docs/superpowers/specs/2026-12-04-event-ticketing-design.md`. This is the second and last change from that design.
## What Changes
- **Ticket codes:**
- When an order becomes Paid, each of its active tickets gets an unguessable code. This includes free orders, which are Paid at once, and expired orders that staff mark paid.
- The ticket's link is `/t/<code>`.
- Unpaid, cancelled and expired tickets have no valid QR.
- **Ticket page** `/t/<code>`:
- **Public view:**
- the event and ticket type;
- the attendee's first name;
- the ticket's state;
- the QR image while the ticket is valid;
- "This ticket is not valid" otherwise.
- **Staff view:** for signed-in staff with `BO_EVENTS` in the event's company, on an event day, a large state banner and **Check in**. An unnamed ticket first asks for the attendee's name and mobile or email.
- **Refusals:** a second check-in shows "Already checked in at <time>"; an unpaid, cancelled or expired ticket shows a red refusal.
- **Naming attendees on the order page:**
- Once an order is Paid, the order page lists its tickets, each with its link.
- Per ticket, the buyer can name or rename the attendee (a name plus mobile or email). The save needs the tick "I have permission to share these details so their ticket can be sent".
- Naming issues a new code, so the old QR stops working, and emails the attendee their ticket.
- Naming is refused once the ticket is checked in.
- **Attendee consent:**
- A named attendee is not a lead.
- The ticket page, and the staff view at check-in, offer an optional "Keep me updated about <company> events" with the company's privacy notice. Ticking it records the consent and makes the attendee an event lead with source `TICKET`, matched as in QR registration. The ticket email links to that page.
- An attendee who never ticks it can still attend.
- **Emails:**
- "Order paid" now carries each ticket's QR image and link, plus a "Name your attendees" link to the order page.
- A new **Ticket** email goes to a named attendee who has an email.
- Staff can **Resend ticket** from the order detail.
- **Door check-in:** checking a ticket in records who did it and when. An attendee who consented, now or earlier, has their event lead marked attended.
- **Venue self check-in on a ticketed event:**
- It checks in the attendee of a Paid ticket that is not yet checked in. If several match, it takes the oldest. An unnamed ticket counts as its buyer's.
- It also checks in a registered invited guest, as today.
- Anything else shows "Please show your ticket at the entrance" instead of the walk-in form.
- Events without tickets keep today's flow unchanged.
- **Event attendance numbers:** on a ticketed event they add tickets awaiting payment, tickets paid and tickets checked in.
- **QR image for emails:** a public PNG at `/api/public/tickets/<code>/qr.png`. It encodes the ticket's `/t/<code>` link.
- **Already done in change 1, so not repeated here:** a registered invite counts toward capacity alongside held tickets ("Capacity before the event").
## Capabilities
### New Capabilities
None. Tickets belong to the existing `event-ticketing` capability.
### Modified Capabilities
- `event-ticketing`:
- **Order Emails:** the paid email carries the tickets.
- **New requirements:** ticket codes, the ticket page and invalid links, tickets on the order page, naming attendees, attendee consent, the ticket email, the staff ticket view, door check-in, resend ticket, and the ticket abuse limits.
- `event-attendance`:
- **Self check-in of a known person** and **Self check-in of a walk-in** now apply to events without tickets.
- **New requirements:** self check-in on a ticketed event, no walk-ins on a ticketed event, and the ticket attendance numbers.
## Impact
- **services-counter:**
- ticket code issuing on Paid;
- ticket lookup, naming, consent and check-in services;
- `EventCheckInService.lookup` on ticketed events;
- headcount;
- `TicketOrderMailer` (the paid email with tickets, and the ticket email).
- **mobile-api:**
- public endpoints for the ticket page, the QR PNG, naming attendees and attendee consent;
- admin endpoints for the staff ticket view, check-in and resend ticket.
- **api-gateway:** public path patterns for the new endpoints.
- **admin-portal:**
- `/t/[code]` page (public view and staff view);
- the order page gains its tickets section;
- a Resend ticket button on the order detail;
- the guests card shows the ticket counts;
- proxies and the route guard;
- labels in English and zh-CN.
- **Database:** `ticket` gains the attendee consent time, privacy notice id, and naming time.
- **New dependency:**
- **What:** `com.google.zxing:core` in mobile-api, to draw the email QR as a PNG. It has no transitive dependencies; the PNG is written with the JDK's `ImageIO`.
- **Why it is needed:** nothing in the repo draws a QR server-side. The portal's `qrcode.react` renders in the browser only. Email clients block SVG and data-URI images, so the email needs a hosted PNG.
- **No change for events without tickets.**
@@ -0,0 +1,61 @@
## ADDED Requirements
### Requirement: Self check-in on a ticketed event
On an event that sells tickets, the check-in page SHALL match the mobile or email only to the attendee of a valid ticket that is not checked in, or to a registered guest. An unnamed ticket SHALL count as its buyer's, and the oldest ticket SHALL be used when several match. A matched ticket SHALL be checked in, and the attendee's event lead marked attended when they have consented. A matched registered guest SHALL be handled as on other events.
#### Scenario: Ticket holder checks in
- **GIVEN** `KL Hotel Tech Day` sells tickets and `Lim Wei` holds a valid ticket named with his mobile
- **WHEN** he enters that mobile on the check-in page on the event day
- **THEN** the page welcomes `Lim` and his ticket is checked in
### Requirement: No walk-ins on a ticketed event
On an event that sells tickets, when the value matches no valid unchecked ticket and no registered guest, the check-in page SHALL show "Please show your ticket at the entrance." It SHALL NOT offer or accept a walk-in submission.
#### Scenario: No walk-ins on a paid event
- **GIVEN** `KL Hotel Tech Day` sells tickets
- **WHEN** a visitor whose mobile matches no valid ticket and no registered guest enters it
- **THEN** the page says "Please show your ticket at the entrance." and shows no form
- **AND** a walk-in submission sent directly is refused
### Requirement: Ticket attendance numbers
When the event sells tickets, the event page SHALL also show tickets awaiting payment, tickets paid and tickets checked in, counting active tickets only. The numbers SHALL agree with the event's orders.
#### Scenario: Ticket counts
- **GIVEN** `KL Hotel Tech Day` has 2 tickets awaiting payment and 5 paid tickets, 3 of them checked in
- **WHEN** an admin opens the event page
- **THEN** the page shows tickets awaiting payment 2, paid 5, checked in 3
## MODIFIED Requirements
### 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. On an event that does not sell tickets, when the value matches a registered guest or an event lead of this event, that event lead SHALL be marked attended. After a check-in the page SHALL show "Welcome, <first name>. You're checked in." Checking in again SHALL show the same welcome and change nothing. The page SHALL show no personal details other than the first name.
#### 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
On an event that does not sell tickets, 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
@@ -0,0 +1,191 @@
## ADDED Requirements
### Requirement: Ticket Codes
When an order becomes Paid, the system SHALL give each of its active tickets an unguessable code of 22 URL-safe characters, unique across all tickets. This SHALL apply when staff mark an order paid (also an Expired one) and when a free order is Paid at once. The ticket's link SHALL be `/t/<code>`. A ticket SHALL be valid only while its order is Paid and the ticket is active.
#### Scenario: Codes on payment
- **GIVEN** order `T-7K3M9Q` holds 2 `General` tickets and is Awaiting payment
- **WHEN** staff mark it paid
- **THEN** each ticket has its own code and link
#### Scenario: Free order
- **WHEN** a visitor requests 1 free `Community pass`
- **THEN** the order is Paid and its ticket has a code at once
### Requirement: Ticket Page
The ticket link `/t/<code>` SHALL be public. It SHALL show the event name, dates and location, the ticket type, the attendee's first name (or "Not named yet") and the ticket's state. It SHALL show the QR image of its own link only while the ticket is valid and not checked in; a checked-in ticket SHALL show "Checked in at <time>". It SHALL never show the buyer's details, the attendee's mobile or email, or other tickets.
#### Scenario: Valid ticket
- **GIVEN** the ticket of `Tan Mei Ling` for `KL Hotel Tech Day` is valid
- **WHEN** she opens its link
- **THEN** the page shows the event, `General`, `Tan` and the QR image
### Requirement: Invalid Ticket Links
A ticket whose order is not Paid, or which is cancelled, SHALL show "This ticket is not valid" with no QR. An unknown code SHALL show "This ticket link is not valid." and nothing else.
#### Scenario: Cancelled ticket
- **GIVEN** a Paid order's ticket was cancelled by staff
- **WHEN** someone opens that ticket's link
- **THEN** the page says the ticket is not valid and shows no QR
#### Scenario: Unknown link
- **WHEN** a visitor opens `/t/` with an unknown code
- **THEN** the page says the ticket link is not valid
### Requirement: Tickets On The Order Page
Once an order is Paid, its order page SHALL list each active ticket with its type, attendee name (or "Not named yet"), state and ticket link. It SHALL NOT show any attendee's mobile or email.
#### Scenario: Paid order page
- **GIVEN** order `T-7K3M9Q` is Paid with 2 tickets, one named `Tan Mei Ling`
- **WHEN** the buyer opens its link
- **THEN** the page lists both tickets with their links, `Tan Mei Ling` and "Not named yet", without Tan's email
### Requirement: Naming Attendees
On a Paid order's page, the buyer SHALL be able to name or rename the attendee of each ticket on its own: a name of up to 100 characters and a mobile or an email, normalised as in QR registration. The save SHALL need the tick "I have permission to share these details so their ticket can be sent"; without it the save SHALL be refused with "Tick the box to confirm you may share these details."
#### Scenario: Permission not ticked
- **WHEN** the buyer saves an attendee without the permission tick
- **THEN** the save is refused and nothing changes
### Requirement: Naming Effects
Saving an attendee SHALL replace the ticket's code, so the old link becomes unknown. It SHALL record the naming time, clear any earlier attendee consent and lead link on that ticket, and email the new attendee their ticket when an email was given.
#### Scenario: Name an attendee
- **GIVEN** `Aisyah`'s order `T-7K3M9Q` is Paid with 2 unnamed tickets
- **WHEN** she names `Tan Mei Ling`, `tan@example.com`, on the first ticket and ticks the permission
- **THEN** that ticket shows `Tan Mei Ling` with a new link
- **AND** Tan receives the ticket email
- **AND** the old link of that ticket says the ticket link is not valid
### Requirement: Naming Refusals
Naming SHALL be refused for a ticket that is checked in ("This ticket is already checked in."), cancelled, or on an order that is not Paid.
#### Scenario: Checked-in ticket
- **GIVEN** a ticket is checked in
- **WHEN** the buyer tries to rename its attendee
- **THEN** the save is refused with "This ticket is already checked in."
### Requirement: Attendee Is Not A Lead Without Consent
A named attendee SHALL NOT be an event lead, and SHALL NOT appear in event leads, lead lists, exports or the dashboard, until they consent themselves. Their details SHALL be used only to deliver and check the ticket. An attendee who never consents SHALL still be able to attend.
#### Scenario: Attendee never opts in
- **GIVEN** `Lim Wei` was named on a Paid ticket and never ticked the consent
- **WHEN** staff open the event leads listing
- **THEN** Lim does not appear
### Requirement: Attendee Consent
A valid ticket's page SHALL offer an optional "Keep me updated about <company> events" with the company's privacy notice in English and Bahasa Malaysia. Ticking it SHALL record the consent time and notice version on the ticket. It SHALL capture the attendee as an event lead with source `TICKET` and no salesperson, matched and normalised as in QR registration, and link the ticket to that event lead.
#### Scenario: Attendee opts in
- **GIVEN** `Tan Mei Ling` was named on a valid ticket
- **WHEN** she ticks "Keep me updated about INS events" on her ticket page
- **THEN** she is an event lead of `KL Hotel Tech Day` with source Ticket
### Requirement: Ticket Email
A named attendee with an email SHALL get a Ticket email in English and Bahasa Malaysia. It SHALL hold the event name, dates and location, the ticket type, the attendee name, the QR image, and the ticket link, which also offers the consent. The QR image SHALL be a PNG of the ticket link served at `/api/public/tickets/<code>/qr.png`. Each email SHALL be recorded in Emails, and a failed send SHALL NOT undo the naming.
#### Scenario: Ticket email
- **WHEN** the buyer names `Tan Mei Ling`, `tan@example.com`
- **THEN** Tan receives an email with the QR image and her ticket link
### Requirement: Staff Ticket View
On the ticket page, a signed-in user with `BO_EVENTS` in the event's company (any company for super admins) SHALL see the staff view: the ticket's state as a large banner and, for a valid ticket that is not checked in, **Check in**. An unnamed ticket SHALL first ask for the attendee's name and a mobile or email. The staff view SHALL offer the same optional consent as the ticket page. Everyone else SHALL see only the public view.
#### Scenario: Another company's staff
- **WHEN** CV staff open a ticket of an INS event
- **THEN** they see only the public view
### Requirement: Door Check-In
Check-in from the staff view SHALL record the time and the staff user on the ticket, and SHALL be written to the admin audit log. When the attendee has consented, now or earlier, their event lead SHALL be marked attended. An unnamed ticket SHALL take the name and contact entered by staff, normalised as in QR registration.
#### Scenario: Staff check in a named ticket
- **GIVEN** `Tan Mei Ling`'s ticket is valid and it is the event day
- **WHEN** event staff scan her QR and tap Check in
- **THEN** the ticket is checked in with their name and the time
#### Scenario: Unnamed ticket at the door
- **GIVEN** a valid ticket was never named
- **WHEN** staff enter `Lim Wei` and his mobile and tap Check in
- **THEN** the ticket is checked in with Lim as its attendee
- **AND** no lead is created unless he ticked the consent
### Requirement: Door Check-In Refusals
Check-in SHALL change nothing and the staff view SHALL show:
- "Already checked in at <time>" for a checked-in ticket;
- a red "Not valid: <reason>" banner for an invalid ticket, the reason being "awaiting payment", "order cancelled", "order expired" or "ticket cancelled";
- "Check-in is only open on the event days." outside the event days.
#### Scenario: Second scan
- **WHEN** staff scan a checked-in ticket again
- **THEN** the page shows "Already checked in at" the first time and nothing changes
#### Scenario: Unpaid ticket at the door
- **GIVEN** an order is Awaiting payment
- **WHEN** staff open one of its ticket links
- **THEN** the page shows "Not valid: awaiting payment" and no Check in button
### Requirement: Resend Ticket
Users with `BO_EVENT_TICKETS` SHALL be able to resend one valid ticket from the order detail. It SHALL go to its attendee's email when named with an email, otherwise to the buyer. The action SHALL be written to the admin audit log.
#### Scenario: Resend a ticket
- **GIVEN** a valid ticket is named `Tan Mei Ling`, `tan@example.com`
- **WHEN** staff resend that ticket
- **THEN** Tan receives the ticket email again
### Requirement: Ticket Abuse Limits
The public ticket page and its QR image SHALL be limited to 120 loads per client IP per 10 minutes. Naming attendees and attendee consent SHALL be limited to 60 submissions per client IP per event per 10 minutes. Above a limit the answer SHALL be "Too many requests from this device. Try again later." The QR image SHALL be served only for a valid code.
#### Scenario: Too many ticket loads
- **WHEN** one IP loads ticket pages 121 times within 10 minutes
- **THEN** the 121st is refused with "Too many requests from this device. Try again later."
## MODIFIED Requirements
### Requirement: Order Emails
The buyer SHALL get an email when their order is created (lines, total, payment instructions, hold expiry and order link), becomes Paid (lines, total, each ticket's QR image and link, and a "Name your attendees" link to the order page), Expires, or is Cancelled by staff. Each email SHALL be recorded in Emails. A failed send SHALL NOT undo the order change, and staff SHALL be able to resend the latest email of an order.
#### Scenario: Order received email
- **WHEN** `Aisyah` requests tickets
- **THEN** she receives an email with the order reference, payment instructions, hold expiry and order link
#### Scenario: Paid email
- **WHEN** staff mark her order of 2 tickets Paid
- **THEN** she receives a confirmation email with 2 QR images, their ticket links and a link to name her attendees
@@ -0,0 +1,15 @@
-- Co-Lite change add-event-tickets: attendee naming and consent on tickets, and the keys self check-in matches on.
-- Target: `service-counter`. Additive only. Run before the new services-counter starts. Needs a user that may alter tables.
USE `service-counter`;
ALTER TABLE `ticket`
ADD COLUMN `attendee_named_at` datetime NULL COMMENT 'when the buyer last named the attendee',
ADD COLUMN `attendee_consent_at` datetime NULL COMMENT 'when the attendee agreed to be kept updated',
ADD COLUMN `attendee_notice_id` bigint NULL COMMENT 'privacy notice version they agreed to',
ADD KEY `idx_ticket_event_mobile` (`event_uuid`, `attendee_mobile_e164`),
ADD KEY `idx_ticket_event_email` (`event_uuid`, `attendee_email`);
-- Tickets of orders paid before this release get their code now (22 URL-safe characters, like the new ones).
UPDATE `ticket` t JOIN `shop_order` o ON o.id = t.order_id
SET t.code = LEFT(REPLACE(REPLACE(REPLACE(TO_BASE64(RANDOM_BYTES(16)), '+', '-'), '/', '_'), '=', ''), 22)
WHERE o.status = 'PAID' AND t.status = 'ACTIVE' AND t.code IS NULL;
@@ -0,0 +1,94 @@
-- The labels added by add-event-tickets, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
SET NAMES utf8mb4;
USE `service-system`;
INSERT INTO message (code, content, area) SELECT 'TktTicketInvalid', JSON_OBJECT('en_US', 'This ticket link is not valid.', 'zh_CN', '此门票链接无效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketInvalid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票链接无效。') WHERE LOWER(code) = LOWER('TktTicketInvalid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketFor', JSON_OBJECT('en_US', 'Ticket for {name}', 'zh_CN', '{name} 的门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketFor') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{name} 的门票') WHERE LOWER(code) = LOWER('TktTicketFor') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktQrAlt', JSON_OBJECT('en_US', 'Ticket QR code', 'zh_CN', '门票二维码'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktQrAlt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票二维码') WHERE LOWER(code) = LOWER('TktQrAlt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktShowQr', JSON_OBJECT('en_US', 'Show this QR code at the entrance.', 'zh_CN', '请在入口出示此二维码。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktShowQr') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请在入口出示此二维码。') WHERE LOWER(code) = LOWER('TktShowQr') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckedInAt', JSON_OBJECT('en_US', 'Checked in at {when}', 'zh_CN', '已于 {when} 签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckedInAt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已于 {when} 签到') WHERE LOWER(code) = LOWER('TktCheckedInAt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotValid', JSON_OBJECT('en_US', 'This ticket is not valid', 'zh_CN', '此门票无效'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotValid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票无效') WHERE LOWER(code) = LOWER('TktNotValid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonAWAITING', JSON_OBJECT('en_US', 'awaiting payment', 'zh_CN', '等待付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonAWAITING') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '等待付款') WHERE LOWER(code) = LOWER('TktReasonAWAITING') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonORDER_CANCELLED', JSON_OBJECT('en_US', 'order cancelled', 'zh_CN', '订单已取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonORDER_CANCELLED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已取消') WHERE LOWER(code) = LOWER('TktReasonORDER_CANCELLED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonORDER_EXPIRED', JSON_OBJECT('en_US', 'order expired', 'zh_CN', '订单已过期'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonORDER_EXPIRED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已过期') WHERE LOWER(code) = LOWER('TktReasonORDER_EXPIRED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonTICKET_CANCELLED', JSON_OBJECT('en_US', 'ticket cancelled', 'zh_CN', '门票已取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonTICKET_CANCELLED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票已取消') WHERE LOWER(code) = LOWER('TktReasonTICKET_CANCELLED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktKeepUpdated', JSON_OBJECT('en_US', 'Keep me updated about {company} events', 'zh_CN', '向我发送 {company} 的活动资讯'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktKeepUpdated') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '向我发送 {company} 的活动资讯') WHERE LOWER(code) = LOWER('TktKeepUpdated') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktConsentSave', JSON_OBJECT('en_US', 'Save', 'zh_CN', '保存'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktConsentSave') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存') WHERE LOWER(code) = LOWER('TktConsentSave') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktConsentDone', JSON_OBJECT('en_US', 'Thank you. We will keep you updated.', 'zh_CN', '谢谢,我们会向您发送最新资讯。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktConsentDone') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '谢谢,我们会向您发送最新资讯。') WHERE LOWER(code) = LOWER('TktConsentDone') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStaffView', JSON_OBJECT('en_US', 'Staff check-in', 'zh_CN', '工作人员签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStaffView') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '工作人员签到') WHERE LOWER(code) = LOWER('TktStaffView') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStaffValid', JSON_OBJECT('en_US', 'Valid', 'zh_CN', '有效'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStaffValid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有效') WHERE LOWER(code) = LOWER('TktStaffValid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAlreadyCheckedIn', JSON_OBJECT('en_US', 'Already checked in at {when}', 'zh_CN', '已于 {when} 签到过'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAlreadyCheckedIn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已于 {when} 签到过') WHERE LOWER(code) = LOWER('TktAlreadyCheckedIn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotValidReason', JSON_OBJECT('en_US', 'Not valid: {reason}', 'zh_CN', '无效:{reason}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotValidReason') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无效:{reason}') WHERE LOWER(code) = LOWER('TktNotValidReason') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotEventDay', JSON_OBJECT('en_US', 'Check-in is only open on the event days.', 'zh_CN', '仅在活动日开放签到。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotEventDay') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '仅在活动日开放签到。') WHERE LOWER(code) = LOWER('TktNotEventDay') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckIn', JSON_OBJECT('en_US', 'Check in', 'zh_CN', '签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckIn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '签到') WHERE LOWER(code) = LOWER('TktCheckIn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckedInNow', JSON_OBJECT('en_US', 'Checked in.', 'zh_CN', '签到成功。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckedInNow') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '签到成功。') WHERE LOWER(code) = LOWER('TktCheckedInNow') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktUnnamed', JSON_OBJECT('en_US', 'No attendee named yet', 'zh_CN', '尚未填写参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktUnnamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚未填写参加者') WHERE LOWER(code) = LOWER('TktUnnamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAttendeeName', JSON_OBJECT('en_US', 'Attendee name', 'zh_CN', '参加者姓名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAttendeeName') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '参加者姓名') WHERE LOWER(code) = LOWER('TktAttendeeName') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktContactRequired', JSON_OBJECT('en_US', 'Enter a mobile number or an email.', 'zh_CN', '请输入手机号码或电子邮件。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktContactRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入手机号码或电子邮件。') WHERE LOWER(code) = LOWER('TktContactRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'ChkShowTicket', JSON_OBJECT('en_US', 'Please show your ticket at the entrance.', 'zh_CN', '请在入口出示您的门票。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('ChkShowTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请在入口出示您的门票。') WHERE LOWER(code) = LOWER('ChkShowTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'GuestTicketsAwaiting', JSON_OBJECT('en_US', 'Tickets awaiting payment', 'zh_CN', '待付款门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('GuestTicketsAwaiting') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待付款门票') WHERE LOWER(code) = LOWER('GuestTicketsAwaiting') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'GuestTicketsPaid', JSON_OBJECT('en_US', 'Tickets paid', 'zh_CN', '已付款门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('GuestTicketsPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已付款门票') WHERE LOWER(code) = LOWER('GuestTicketsPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'GuestTicketsCheckedIn', JSON_OBJECT('en_US', 'Tickets checked in', 'zh_CN', '已签到门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('GuestTicketsCheckedIn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已签到门票') WHERE LOWER(code) = LOWER('GuestTicketsCheckedIn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrTicketNotValid', JSON_OBJECT('en_US', 'This ticket is not valid, so it cannot be sent.', 'zh_CN', '此门票无效,无法发送。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrTicketNotValid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票无效,无法发送。') WHERE LOWER(code) = LOWER('TktErrTicketNotValid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktResendTicket', JSON_OBJECT('en_US', 'Resend ticket', 'zh_CN', '重新发送门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktResendTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '重新发送门票') WHERE LOWER(code) = LOWER('TktResendTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketSent', JSON_OBJECT('en_US', 'Ticket sent.', 'zh_CN', '门票已发送。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketSent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票已发送。') WHERE LOWER(code) = LOWER('TktTicketSent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktYourTickets', JSON_OBJECT('en_US', 'Your tickets', 'zh_CN', '您的门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktYourTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您的门票') WHERE LOWER(code) = LOWER('TktYourTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNameAttendeesHelp', JSON_OBJECT('en_US', 'Name each attendee so their ticket can be emailed to them, or share each ticket''s link.', 'zh_CN', '填写每位参加者,以便通过电子邮件将门票发送给他们,或分享每张门票的链接。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNameAttendeesHelp') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '填写每位参加者,以便通过电子邮件将门票发送给他们,或分享每张门票的链接。') WHERE LOWER(code) = LOWER('TktNameAttendeesHelp') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAttendeeSaved', JSON_OBJECT('en_US', 'Saved. The ticket has a new link; the old one no longer works.', 'zh_CN', '已保存。门票已有新链接,旧链接已失效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAttendeeSaved') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已保存。门票已有新链接,旧链接已失效。') WHERE LOWER(code) = LOWER('TktAttendeeSaved') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotNamed', JSON_OBJECT('en_US', 'Not named yet', 'zh_CN', '尚未填写'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotNamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚未填写') WHERE LOWER(code) = LOWER('TktNotNamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOpenTicket', JSON_OBJECT('en_US', 'Open ticket', 'zh_CN', '打开门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOpenTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '打开门票') WHERE LOWER(code) = LOWER('TktOpenTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCopyLink', JSON_OBJECT('en_US', 'Copy link', 'zh_CN', '复制链接'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCopyLink') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制链接') WHERE LOWER(code) = LOWER('TktCopyLink') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktLinkCopied', JSON_OBJECT('en_US', 'Link copied.', 'zh_CN', '链接已复制。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktLinkCopied') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接已复制。') WHERE LOWER(code) = LOWER('TktLinkCopied') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNameAttendee', JSON_OBJECT('en_US', 'Name attendee', 'zh_CN', '填写参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNameAttendee') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '填写参加者') WHERE LOWER(code) = LOWER('TktNameAttendee') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktChangeAttendee', JSON_OBJECT('en_US', 'Change attendee', 'zh_CN', '更改参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktChangeAttendee') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '更改参加者') WHERE LOWER(code) = LOWER('TktChangeAttendee') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAttendeeRequired', JSON_OBJECT('en_US', 'Enter the attendee''s name and a mobile number or an email.', 'zh_CN', '请输入参加者姓名,以及手机号码或电子邮件。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAttendeeRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入参加者姓名,以及手机号码或电子邮件。') WHERE LOWER(code) = LOWER('TktAttendeeRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPermissionRequired', JSON_OBJECT('en_US', 'Tick the box to confirm you have permission.', 'zh_CN', '请勾选以确认您已获得许可。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPermissionRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请勾选以确认您已获得许可。') WHERE LOWER(code) = LOWER('TktPermissionRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPermission', JSON_OBJECT('en_US', 'I have permission to share these details so their ticket can be sent', 'zh_CN', '我已获得许可分享这些资料,以便发送其门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPermission') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '我已获得许可分享这些资料,以便发送其门票') WHERE LOWER(code) = LOWER('TktPermission') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktRenameWarning', JSON_OBJECT('en_US', 'Saving gives this ticket a new link and QR code. The old ones stop working.', 'zh_CN', '保存后此门票将获得新的链接和二维码,旧的将失效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktRenameWarning') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存后此门票将获得新的链接和二维码,旧的将失效。') WHERE LOWER(code) = LOWER('TktRenameWarning') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSaveAttendee', JSON_OBJECT('en_US', 'Save attendee', 'zh_CN', '保存参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSaveAttendee') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存参加者') WHERE LOWER(code) = LOWER('TktSaveAttendee') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'LeadSourceTicket', JSON_OBJECT('en_US', 'Ticket', 'zh_CN', '门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('LeadSourceTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票') WHERE LOWER(code) = LOWER('LeadSourceTicket') AND area = 'A';
UPDATE catalog_meta SET version = version + 1, updated_at = NOW() WHERE id = 1;
@@ -0,0 +1,8 @@
-- Co-Lite change add-event-tickets: rollback. Drops attendee naming times and consent records. Ticket codes stay (add-event-ticket-orders owns that column).
USE `service-counter`;
ALTER TABLE `ticket`
DROP KEY `idx_ticket_event_mobile`,
DROP KEY `idx_ticket_event_email`,
DROP COLUMN `attendee_named_at`,
DROP COLUMN `attendee_consent_at`,
DROP COLUMN `attendee_notice_id`;
+156
View File
@@ -0,0 +1,156 @@
# Tasks
Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04-event-ticketing-design.md` (product).
**Mode:** all tasks run serially in the main session (the owner asked for no worker subagents). Each task starts with failing tests (TDD).
## 1. Data
- [x] 1.1 Write the SQL:
- `sql/01-ticket-attendees.sql`: the three `ticket` columns, the two keys, and codes for active tickets on Paid orders that have none;
- `sql/99-rollback.sql`.
Mirror 01 in `local/seed/03-colite.sql` and apply it to the local database.
- Depends on: none
- Scope: `local/seed/**`, `openspec/changes/add-event-tickets/sql/**`
- Verify: `SHOW CREATE TABLE ticket` shows the columns and keys; local Paid tickets have 22-character codes.
## 2. services-counter
- [x] 2.1 Ticket codes, ticket state and the ticket lookups.
- Depends on: 1.1
- Tests first:
- **Codes:**
- a free order's tickets get codes at creation;
- mark paid (from Awaiting payment and from Expired) gives each active ticket a distinct 22-character code;
- an Awaiting-payment order has none.
- **`TicketState.of`:** valid, checked in, awaiting, order cancelled, order expired and ticket cancelled.
- **`ticket/byCode`:**
- returns the event, type, attendee first name, state and check-in time;
- never returns mobile, email or buyer details;
- an unknown code is 404 `TICKET_NOT_FOUND`.
- **`byToken`:** lists tickets (id, type, attendee name, code, state) only when Paid, without contacts.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
- [x] 2.2 Naming attendees, consent and ticket emails.
- Depends on: 2.1
- Tests first:
- **Naming:**
- refused without `permission`, when the order is not Paid, when the ticket is cancelled, and when it is checked in (`ALREADY_CHECKED_IN`);
- an unknown token or a ticket of another order is 404;
- a save sets a new code and `attendee_named_at`, and clears consent and the lead link.
- **Consent:**
- refused on an invalid or unnamed ticket;
- calls registration with source `TICKET`, the notice and no salesperson, and stores consent time, notice id and lead uuid.
- **Mailer:**
- PAID lists every active ticket with its QR `<img>` URL, its link and the "Name your attendees" link;
- TICKET goes to the attendee's email;
- naming with only a mobile sends nothing.
- **Resend ticket:** goes to the attendee's email, else the buyer; refused for an invalid ticket.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
- [x] 2.3 Door check-in, self check-in rules and the counts.
- Depends on: 2.2
- Tests first:
- **Staff check-in:**
- records the time and user;
- a second check-in gives `ALREADY_CHECKED_IN|<time>`;
- each invalid state gives `NOT_VALID|<state>`;
- outside the event days gives `NOT_EVENT_DAY`;
- an unnamed ticket needs a name and contact;
- consent creates the lead and marks it attended;
- another company's ticket is 404.
- **Self check-in on a ticketed event:**
- a named attendee's ticket is checked in;
- an unnamed ticket matches its buyer, oldest first;
- a registered guest still works;
- anything else gives `SHOW_TICKET`;
- walk-in register is refused with `TICKETS_ONLY`.
- On an event without tickets, the old results are unchanged.
- **Headcount:** tickets awaiting, paid and checked in, counting active tickets only.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
## 3. mobile-api and gateway
- [x] 3.1 Public ticket endpoints, the QR PNG and gateway paths.
- Depends on: 2.3
- Tests first:
- **`GET /api/public/tickets/{code}`:**
- a bad shape is 404 `TICKET_INVALID`;
- the `tkt:load` limit applies;
- the event fields are added.
- **`qr.png`:**
- the PNG decodes back to `<portal>/t/<code>`;
- an invalid ticket is 404;
- the response is `image/png`, `private`.
- **Attendee save:**
- name, mobile and email normalised as in QR registration;
- a missing permission gives a field error;
- counter refusals map to public messages;
- the `tkt:submit` limit applies.
- **Consent:** the current notice id is sent.
- **Order view:** carries the tickets when Paid.
- **Gateway:** the three counter paths are public, other shapes are not.
- Adds `com.google.zxing:core` to `solvway-mobile-api/pom.xml`. This hotspot runs alone.
- Scope: `solvway-mobile-api/**`, `solvway-api-gateway/src/**`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api,solvway-api-gateway verify`
- [x] 3.2 Admin ticket endpoints.
- Depends on: 3.1
- Tests first:
- **`GET /api/admin/tickets/{code}`:** `BO_EVENTS` and company-scoped (another company's ticket is 404).
- **`checkin`:** passes the body, maps 409 codes, is `@Audited`.
- **Resend ticket:** under `BO_EVENT_TICKETS`, `@Audited`.
- **Headcount:** passes the ticket counts.
- **Check-in lookup:** passes `SHOW_TICKET`, and walk-in `TICKETS_ONLY` maps to its message.
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
## 4. admin-portal
- [x] 4.1 The ticket page `/t/[code]`.
- Depends on: 3.2
- Tests first:
- **Public view:** valid, checked in, not valid and unknown.
- **Consent:** only on a valid named ticket, with the notice.
- **Staff view:**
- shown only when the session and admin call succeed;
- a 401, 403 or 404 keeps the public view and never redirects;
- Check in;
- the unnamed form;
- the refusal banners.
- **Routes:**
- the route guard lets `/t/x` through;
- the proxies send one X-Forwarded-For hop;
- the PNG proxy passes bytes and content type.
- Scope: `solvway-admin-portal/app/**`
- Verify: `npx vitest run` (check the exit code), `npx tsc --noEmit`, `npm run lint`
- [x] 4.2 Order page tickets, staff resend, counts, venue check-in message and labels.
- Depends on: 4.1
- Tests first:
- **Order page:**
- a Paid order lists tickets with links and copy buttons;
- the naming form, with the permission tick, mobile or email, and field errors;
- a refusal for a checked-in ticket.
- **Order detail:** Resend ticket per valid ticket.
- **GuestsCard:** the three ticket counts on a ticketed event.
- **`/c/[token]`:** shows "Please show your ticket at the entrance." for `SHOW_TICKET`, with no form.
- **Labels:** English and zh-CN, plus `sql/02-ticket-labels.sql`; seed regenerated.
- Scope: `solvway-admin-portal/app/**`, `openspec/changes/add-event-tickets/sql/**`, `local/seed/04-zh-cn-messages.sql`
- Verify: `npx vitest run` (check the exit code), `npx tsc --noEmit`, `npm run lint`
## 5. Verify and ship
- [x] 5.1 Rebuild the local stack, then check in Playwright, signing in through the form and clicking through.
- On LC CV Expo, use the owner-approved test buyer "Tiket Test", tickets-test@example.com, and ask before any new order.
- Open T-EKBD2K's order page and name an attendee. See the new link and that the old link is not valid.
- On the ticket page, tick the consent and see the lead.
- In the staff view, check a ticket in, then scan it again.
- Check an unpaid ticket's refusal, and an unnamed ticket at the door.
- Venue self check-in: a ticket holder, and a stranger who gets "show your ticket".
- Check the counts on the event page and resend a ticket.
- Take screenshots.
- Depends on: 4.2
- Done 2026-12-04. Not reachable: an unpaid ticket at the door, because an Awaiting order's tickets have no code yet. The staff banner for that state is covered by the page tests. Fixed during the check: the event leads list crashed on source Ticket, and order detail did not show which ticket is whose.
- [ ] 5.2 Write the release note in `docs/deployment.md`. Open the PR to main and merge it, then archive the change in its own PR and republish the blueprint.
- Depends on: 5.1
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -175,5 +175,5 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04
- Check the blocked paths: over 10 tickets, sold out, missing consent, and an unknown order link.
- Take screenshots.
- Depends on: 4.2
- [ ] 5.2 Write the release note in `docs/deployment.md`. Open the PR to main and merge it, then archive the change in its own PR.
- [x] 5.2 Write the release note in `docs/deployment.md`. Open the PR to main and merge it, then archive the change in its own PR.
- Depends on: 5.1
+7 -9
View File
@@ -118,15 +118,7 @@ A guest's status SHALL be derived from the event lead it is linked to: Registere
### 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.
The event page SHALL show invited guests (against the cap), registered guests, attended event leads, walk-ins (event leads linked to no guest and not created by a ticket order), held tickets (only when the event sells tickets), and a total of registered plus walk-ins plus held tickets (against capacity). The numbers SHALL agree with the guest list and event leads listing, and a total above capacity SHALL be shown.
#### Scenario: Numbers
@@ -134,6 +126,12 @@ The numbers SHALL agree with the guest list and the event leads listing. A total
- **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
#### Scenario: Ticket buyers are not walk-ins
- **GIVEN** `KL Hotel Tech Day` has 2 walk-ins, and a buyer whose order holds 3 tickets
- **WHEN** an admin opens the event page
- **THEN** the page shows walk-ins 2, held tickets 3, total 5
### 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.
+7 -1
View File
@@ -152,7 +152,7 @@ An accepted invite submission SHALL register the guest with the same normalisati
### 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.
When an event has a capacity, invite registrations and ticket requests SHALL be refused before the event days once registered guests plus walk-in event leads plus held tickets would exceed it; an invite shows "This event is full". On the event days (Malaysia, start through end date) nothing SHALL be refused for capacity, though ticket types keep their own seats. Staff capture SHALL never be refused for capacity.
#### Scenario: Full before the event
@@ -166,6 +166,12 @@ When an event has a capacity, invite registrations SHALL be refused before the e
- **WHEN** the third guest submits their invite
- **THEN** they are registered
#### Scenario: Held tickets fill the event
- **GIVEN** `KL Expo` starts next week, has capacity 10, one registered guest and 9 held tickets
- **WHEN** another guest submits their invite
- **THEN** the page says the event is full and nothing is saved
### 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.
+254
View File
@@ -0,0 +1,254 @@
# event-ticketing Specification
## Purpose
Event ticket sales with payment outside Co-Lite: per-event ticket settings and types, buyer ticket requests from a landing page's Tickets section with seat holds, the buyer's order page and emails, hold expiry, and the staff order screens that mark orders paid or cancel orders and tickets.
## Requirements
### Requirement: Ticket Settings On An Event
An event SHALL have a Tickets switch that is off by default, payment instructions of up to 1000 characters, and hold days from 1 to 14 that default to 3. Only users with `BO_EVENT_TICKETS` SHALL change them. While the switch is off, the event SHALL behave as it did before this change, and no ticket order SHALL be accepted for it. Turning the switch on SHALL require payment instructions.
#### Scenario: Turn tickets on
- **WHEN** a user with `BO_EVENT_TICKETS` turns Tickets on for `KL Hotel Tech Day` with payment instructions `Maybank 5140 1234 5678, ref your order number` and hold days 3
- **THEN** the event shows Tickets on with those instructions and 3 hold days
#### Scenario: Instructions required
- **WHEN** a user turns Tickets on with empty payment instructions
- **THEN** the save is refused on the payment instructions field and nothing changes
#### Scenario: Hold days out of range
- **WHEN** a user saves hold days 15
- **THEN** the save is refused on the hold days field
#### Scenario: Without the permission
- **GIVEN** a user has `BO_EVENTS` but not `BO_EVENT_TICKETS`
- **WHEN** they open the event
- **THEN** they do not see the Tickets section
### Requirement: Ticket Types
A ticketed event SHALL have zero or more ticket types. Each type SHALL have a name of 1 to 80 characters unique within the event, a price in MYR from 0.00 to 99999.99 in whole sen, a quantity of at least 1, an optional sales end date (empty means the event's end date), a sort order and an enabled flag.
#### Scenario: Add types
- **WHEN** staff add `Early bird` at RM 150.00 quantity 20 and `General` at RM 250.00 quantity 100
- **THEN** both types are listed in sort order with their prices and 20 and 100 seats left
### Requirement: Ticket Type Changes
A type with any order SHALL NOT be deleted, only disabled. A type's quantity SHALL NOT be set below the seats it holds. A price change SHALL apply only to orders made after it.
#### Scenario: Type with orders cannot be deleted
- **GIVEN** `Early bird` has an order
- **WHEN** staff delete it
- **THEN** the delete is refused with "This ticket type has orders. Disable it instead."
#### Scenario: Quantity below held seats
- **GIVEN** `Early bird` holds 12 seats
- **WHEN** staff set its quantity to 10
- **THEN** the save is refused on the quantity field
#### Scenario: Price change keeps old orders
- **GIVEN** an order holds 2 `General` tickets at RM 250.00
- **WHEN** staff change `General` to RM 280.00
- **THEN** that order still totals RM 500.00
### Requirement: Seats Held
A ticket SHALL hold a seat while its order is Awaiting payment or Paid and the ticket is not cancelled. A type's seats left SHALL be its quantity minus the seats it holds. Requests SHALL never cause a type to hold more seats than its quantity, including when requests arrive at the same moment. When the event has a capacity, a request made before the event days SHALL be refused if held tickets plus registered guests plus walk-in event leads would exceed it.
#### Scenario: Last seat taken once
- **GIVEN** `VIP` has 1 seat left
- **WHEN** two visitors request 1 `VIP` ticket at the same moment
- **THEN** one order is created and the other request is told `VIP` has only 0 left
#### Scenario: Expired order frees seats
- **GIVEN** an Awaiting-payment order holds 3 `General` tickets
- **WHEN** it expires
- **THEN** `General` shows 3 more seats left
#### Scenario: Event capacity
- **GIVEN** `KL Hotel Tech Day` starts next week with capacity 50, 45 held tickets and 3 registered guests
- **WHEN** a visitor requests 3 tickets
- **THEN** the request is refused with "Only 2 places are left for this event"
### Requirement: Ticket Request
A ticket request SHALL carry a quantity per ticket type from 0 to 10 with a total from 1 to 10, the buyer's name and email (both required), an optional mobile and company, and the privacy notice consent (required). Inputs SHALL be normalised and limited as in staff capture. An accepted request SHALL create one order with a line per type keeping its name and price at the time, one ticket per seat, an order reference unique within the company, and an unguessable link token.
#### Scenario: Request two types
- **WHEN** a visitor requests 2 `General` and 1 `VIP` as `Aisyah`, `aisyah@example.test`, and ticks the consent
- **THEN** an order with 3 tickets totalling RM 1000.00 is Awaiting payment
- **AND** the thank-you shows its reference, lines, total, payment instructions, hold expiry and a "View your order" link
#### Scenario: Missing email or consent
- **WHEN** a visitor submits without an email, or without ticking the consent
- **THEN** nothing is saved and the error shows under that field
### Requirement: Ticket Request Refusals
A request SHALL be refused, saving nothing, when a requested type is disabled, past its sales end date or short of seats, naming the type and its seats left. A request SHALL be accepted only while the event has Tickets on, is enabled, has not passed its end date in Malaysia time, and its company has a privacy notice.
#### Scenario: Over ten
- **WHEN** a visitor requests 11 tickets
- **THEN** the request is refused and nothing is saved
#### Scenario: Sales ended for a type
- **GIVEN** `Early bird` sales ended yesterday
- **WHEN** a visitor requests 1 `Early bird`
- **THEN** the request is refused naming `Early bird`
#### Scenario: Tickets turned off
- **GIVEN** staff turned Tickets off for `KL Hotel Tech Day`
- **WHEN** a visitor submits a request
- **THEN** the request is refused and nothing is saved
### Requirement: Free Orders
An order whose total is RM 0.00 SHALL be Paid when it is created, without staff action. Its thank-you page and email SHALL say the order is confirmed and SHALL NOT show payment instructions.
#### Scenario: Free ticket type
- **GIVEN** `Community pass` is priced RM 0.00
- **WHEN** a visitor requests 2 `Community pass`
- **THEN** the order is Paid at once and the thank-you says it is confirmed
### Requirement: Awaiting-Payment Limit Per Buyer
An email SHALL have at most 3 orders Awaiting payment per event. A further request SHALL be refused with "You already have orders awaiting payment for this event." and nothing SHALL be saved.
#### Scenario: Fourth unpaid order
- **GIVEN** `aisyah@example.test` has 3 orders Awaiting payment for `KL Hotel Tech Day`
- **WHEN** she requests another ticket
- **THEN** the request is refused with that message
### Requirement: Order States
An order SHALL be in one of four states:
- **Awaiting payment.**
- **Paid.**
- **Cancelled.**
- **Expired.**
An order Awaiting payment SHALL hold its seats until its hold expiry, which is the creation time plus the event's hold days at the time of the request. After the hold expiry it SHALL become Expired within 15 minutes. Paid, Cancelled and Expired orders SHALL never expire.
#### Scenario: Hold runs out
- **GIVEN** an order made on 1 December at 10:00 with 3 hold days is still Awaiting payment
- **WHEN** it is 4 December 10:15
- **THEN** the order is Expired and its seats are free
### Requirement: Buyer Becomes An Event Lead
An accepted request SHALL match the buyer to a lead with the QR registration rules, including the existing-lead notes, and create the buyer's event lead with source TICKET, no salesperson, the consent time and notice version, and the page address and UTM values as for a FORM block. A buyer already captured at the event SHALL change nothing on that event lead except a note naming the order reference. These event leads SHALL appear in every lead listing, export and the dashboard.
#### Scenario: New buyer
- **WHEN** `Aisyah`, unknown to INS, requests tickets
- **THEN** staff see `Aisyah` in the event's leads with source Ticket, NEW and OPEN
#### Scenario: Buyer already captured
- **GIVEN** `Aisyah` registered at `KL Hotel Tech Day` through the QR code
- **WHEN** she requests tickets
- **THEN** her event lead keeps source QR, and its notes name the order reference
### Requirement: Order Page
The order link `/o/<token>` SHALL show:
- the event's name, dates and location;
- the order reference, lines, total, state and creation time;
- while Awaiting payment, the payment instructions and hold expiry.
It SHALL show the buyer's name but no other personal details. An unknown token SHALL show "This order link is not valid." The page SHALL be limited to 120 loads per IP per 10 minutes.
#### Scenario: Unpaid order page
- **GIVEN** order `T-7K3M9Q` is Awaiting payment
- **WHEN** the buyer opens its link
- **THEN** the page shows the lines, total, payment instructions and hold expiry
#### Scenario: Unknown link
- **WHEN** a visitor opens `/o/` with an unknown token
- **THEN** the page says the order link is not valid and shows nothing else
### Requirement: Order Emails
The buyer SHALL get an email when their order is created (lines, total, payment instructions, hold expiry and order link), becomes Paid (a confirmation with lines, total and order link), Expires, or is Cancelled by staff. Each email SHALL be recorded in Emails. A failed send SHALL NOT undo the order change, and staff SHALL be able to resend the latest email of an order.
#### Scenario: Order received email
- **WHEN** `Aisyah` requests tickets
- **THEN** she receives an email with the order reference, payment instructions, hold expiry and order link
#### Scenario: Paid email
- **WHEN** staff mark her order Paid
- **THEN** she receives a confirmation email
### Requirement: Staff Order Screens
The event's Tickets section SHALL list the event's orders with reference, buyer name, email, ticket count, total, state and creation time, newest first in pages of 50, filterable by state and searchable by reference, name, email or mobile. The order detail SHALL show the lines, tickets, buyer details, payment reference, and who changed the state and when. A user without `BO_EVENT_TICKETS` SHALL NOT see or reach these screens.
#### Scenario: Company separation
- **WHEN** INS staff open an order of a CV event by its address
- **THEN** they get not found
### Requirement: Staff Order Actions
Users with `BO_EVENT_TICKETS` SHALL be able to mark an order paid with an optional payment reference of up to 100 characters (when Awaiting payment, or Expired with all its seats still available), cancel an order that is Awaiting payment or Paid (freeing its seats), cancel one ticket of such an order that has another uncancelled ticket (freeing the seat and lowering the total), and resend the latest order email. Each action SHALL be written to the admin audit log.
#### Scenario: Mark paid with reference
- **GIVEN** order `T-7K3M9Q` is Awaiting payment
- **WHEN** staff mark it paid with reference `MBB 0412 883`
- **THEN** the order is Paid with that reference, their name and the time
- **AND** the audit log records the action
#### Scenario: Expired order after its seats were taken
- **GIVEN** order `T-7K3M9Q` expired, and its `VIP` seat was then taken by another order
- **WHEN** staff mark it paid
- **THEN** the action is refused with "Not enough seats left to confirm this order" and the order stays Expired
#### Scenario: Cancel one ticket
- **GIVEN** a Paid order holds 3 `General` tickets at RM 250.00
- **WHEN** staff cancel one ticket
- **THEN** the order holds 2 tickets, totals RM 500.00, and `General` has one more seat left
### Requirement: Ticket Request Abuse Limits
Ticket requests SHALL follow the QR registration limits: at most 60 requests per client IP per event in 10 minutes, answered above the limit with "Too many registrations from this device. Try again later." A request that fills the hidden honeypot field SHALL get the normal thank-you page and save nothing.
#### Scenario: Too many requests
- **WHEN** one IP submits 61 ticket requests for an event within 10 minutes
- **THEN** the 61st is refused with "Too many registrations from this device. Try again later."
#### Scenario: Honeypot filled
- **WHEN** a request fills the hidden honeypot field
- **THEN** the thank-you page shows and no order is saved
+30
View File
@@ -846,3 +846,33 @@ A page with a top bar, a full-width hero with its sign-up form, and a trust stri
- **WHEN** a visitor opens a landing page with a sign-up form
- **THEN** each text field, the service dropdown and the Register button are at least 44 px tall
### Requirement: Tickets Block
A page MAY hold TICKETS blocks. The page SHALL show each enabled ticket type of the block's event in sort order with its name, its price as `RM 150.00` or `Free`, and its seats left or "Sold out" or "Sales ended", a quantity picker per type with an order total of at most 10, the running total, the buyer's fields and the privacy consent. When the event no longer accepts requests, the block SHALL say ticket sales are closed and the rest of the page SHALL still show.
#### Scenario: Visitor sees ticket types
- **GIVEN** a published page with a TICKETS block for `KL Hotel Tech Day`, whose types are `Early bird` RM 150.00 with 12 left, `General` RM 250.00 with 80 left, and `VIP` RM 500.00 sold out
- **WHEN** a visitor opens the page
- **THEN** the block lists the three types with their prices, shows "Sold out" for `VIP`, and offers no quantity for `VIP`
#### Scenario: Sales closed
- **GIVEN** the event of a TICKETS block ended yesterday
- **WHEN** a visitor opens the page
- **THEN** the block says ticket sales are closed and the other blocks still show
### Requirement: Tickets Block Fields
A TICKETS block SHALL name one event of the page's company that is enabled, not ended and has Tickets on when saved. It MAY have a heading (120 characters), text (1000 characters), a section label, a look and a link name. The server SHALL refuse any other field. Both editors SHALL offer the block and pick its event from the company's events that qualify.
#### Scenario: Event without tickets
- **WHEN** staff save a TICKETS block for an event whose Tickets switch is off
- **THEN** the save is refused on that block's event field
#### Scenario: Add a tickets block in the editor
- **WHEN** staff add a Tickets section in the on-page editor and pick `KL Hotel Tech Day`
- **THEN** the canvas shows that event's ticket types
@@ -8,7 +8,7 @@ import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRou
type Ctx = { params: Promise<{ uuid: string; path: string[] }> };
const ALLOWED =
/^(guests(\/(send|\d+))?|checkin|attendance|tickets\/settings|ticket-types(\/\d+)?|orders(\/\d+(\/(paid|cancel|resend|tickets\/\d+\/cancel))?)?)$/;
/^(guests(\/(send|\d+))?|checkin|attendance|tickets\/settings|ticket-types(\/\d+)?|orders(\/\d+(\/(paid|cancel|resend|tickets\/\d+\/(cancel|resend)))?)?)$/;
// Event uuids are strings, not numbers; word characters and hyphens cover them and nothing that can alter the upstream path.
const EVENT_ID = /^[\w-]+$/;
@@ -0,0 +1,11 @@
import { NextResponse, type NextRequest } from "next/server";
import { forwardPublic } from "@/app/lib/server/publicProxy";
type Ctx = { params: Promise<{ token: string; ticketId: string }> };
// add-event-tickets: the buyer names a ticket's attendee from the order page.
export async function POST(req: NextRequest, { params }: Ctx) {
const { token, ticketId } = await params;
if (!/^\d{1,19}$/.test(ticketId)) return NextResponse.json({ error: "Not found" }, { status: 404 });
return forwardPublic(req, `/api/public/orders/${encodeURIComponent(token)}/tickets/${encodeURIComponent(ticketId)}/attendee`, "POST");
}
@@ -0,0 +1,59 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), callMobileApiBinary: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi, callMobileApiBinary: mocks.callMobileApiBinary }));
import { GET as ticketGet } from "./tickets/[token]/route";
import { POST as consentPost } from "./tickets/[token]/consent/route";
import { GET as qrGet } from "./tickets/[token]/qr.png/route";
import { POST as attendeePost } from "./orders/[token]/tickets/[ticketId]/attendee/route";
type Handler = (req: never, ctx: { params: Promise<Record<string, string>> }) => Promise<Response>;
const xff = { "x-forwarded-for": "6.6.6.6, 203.0.113.7" };
const call = (h: unknown, params: Record<string, string>, init: RequestInit = {}) =>
(h as Handler)(new Request("http://localhost/x", init) as never, { params: Promise.resolve(params) });
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { state: "VALID" } });
mocks.callMobileApiBinary.mockReset().mockResolvedValue({ ok: true, data: { body: new Uint8Array([137, 80, 78, 71]).buffer, contentType: "image/png" } });
});
// add-event-tickets: the ticket page, its consent, its QR PNG and naming an attendee, signed out, with only the last X-Forwarded-For hop.
describe("public ticket code proxies", () => {
it("GET a ticket by its code", async () => {
const res = await call(ticketGet, { token: "c/1" }, { headers: xff });
expect(await res.json()).toEqual({ state: "VALID" });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/tickets/c%2F1", { headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("POST a consent", async () => {
await call(consentPost, { token: "c1" }, { method: "POST", body: '{"consent":true}', headers: xff });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/tickets/c1/consent",
{ method: "POST", body: { consent: true }, headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("POST an attendee to an order's ticket", async () => {
await call(attendeePost, { token: "t/1", ticketId: "7" }, { method: "POST", body: '{"name":"Tan"}', headers: xff });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/orders/t%2F1/tickets/7/attendee",
{ method: "POST", body: { name: "Tan" }, headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("refuses a ticket id that is not a number without calling upstream", async () => {
const res = await call(attendeePost, { token: "t1", ticketId: "7/x" }, { method: "POST", body: "{}" });
expect(res.status).toBe(404);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes the QR PNG bytes and type, private, with the client hop", async () => {
const res = await call(qrGet, { token: "c1" }, { headers: xff });
expect(res.headers.get("Content-Type")).toBe("image/png");
expect(res.headers.get("Cache-Control")).toBe("private, max-age=300");
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([137, 80, 78, 71]));
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/public/tickets/c1/qr.png", { headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("answers 404 for a QR that is not there", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: false, status: 404, error: "x" });
expect((await call(qrGet, { token: "c1" })).status).toBe(404);
});
});
@@ -0,0 +1,4 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
// add-event-tickets: the attendee's "keep me updated" on their ticket page.
export const POST = publicRoute("tickets", "/consent", "POST");
@@ -0,0 +1,19 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApiBinary } from "@/app/lib/server/mobileApi";
import { clientIp } from "@/app/lib/server/clientContext";
import type { TokenCtx } from "@/app/lib/server/publicProxy";
// add-event-tickets: a valid ticket's QR as a PNG, for the page and the emails. Rate-limited per client, so the client hop goes along.
export async function GET(req: NextRequest, { params }: TokenCtx) {
const xff = clientIp(req);
const result = await callMobileApiBinary(`/api/public/tickets/${encodeURIComponent((await params).token)}/qr.png`,
{ headers: xff ? { "X-Forwarded-For": xff } : {} });
if (!result.ok) return new NextResponse(null, { status: result.status === 404 ? 404 : 502 });
return new NextResponse(result.data.body, {
headers: {
"Content-Type": result.data.contentType ?? "image/png",
"Cache-Control": "private, max-age=300",
"X-Content-Type-Options": "nosniff",
},
});
}
@@ -0,0 +1,4 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
// add-event-tickets: the public ticket page reads its ticket by the code.
export const GET = publicRoute("tickets", "", "GET");
@@ -0,0 +1,16 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
type Ctx = { params: Promise<{ code: string }> };
// add-event-tickets: door check-in from the staff view.
export async function POST(req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<unknown>(`/api/admin/tickets/${encodeURIComponent((await params).code)}/checkin`,
{ method: "POST", body: await req.json().catch(() => ({})), token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data ?? {});
}
@@ -0,0 +1,15 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
type Ctx = { params: Promise<{ code: string }> };
// add-event-tickets: the staff view of a scanned ticket. mobile-api checks BO_EVENTS and the event's company.
export async function GET(_req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<unknown>(`/api/admin/tickets/${encodeURIComponent((await params).code)}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data ?? {});
}
@@ -0,0 +1,53 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./tickets/[code]/route";
import { POST } from "./tickets/[code]/checkin/route";
const req = (init?: RequestInit) => new Request("http://localhost/x", init) as never;
const p = (code: string) => ({ params: Promise.resolve({ code }) });
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { state: "VALID" } });
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
// add-event-tickets: the staff ticket view and door check-in go to mobile-api with the session token.
describe("staff ticket proxies", () => {
it("forward the view and the check-in with the token", async () => {
await GET(req(), p("c/1"));
await POST(req({ method: "POST", body: '{"name":"Lim Wei"}' }), p("c1"));
expect(mocks.callMobileApi.mock.calls).toEqual([
["/api/admin/tickets/c%2F1", { token: "jwt" }],
["/api/admin/tickets/c1/checkin", { method: "POST", body: { name: "Lim Wei" }, token: "jwt" }],
]);
});
it("answer 401 without a session and never call upstream", async () => {
mocks.getToken.mockResolvedValue(undefined);
expect((await GET(req(), p("c1"))).status).toBe(401);
expect((await POST(req({ method: "POST", body: "{}" }), p("c1"))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("pass a refusal with its status and code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "NOT_EVENT_DAY", code: "NOT_EVENT_DAY" });
const res = await POST(req({ method: "POST", body: "{}" }), p("c1"));
expect(res.status).toBe(409);
expect(((await res.json()) as Record<string, unknown>).code).toBe("NOT_EVENT_DAY");
});
});
import { POST as eventPost } from "./events/[uuid]/[...path]/route";
describe("event proxy: resend one ticket", () => {
it("forwards a ticket resend and refuses other ticket actions", async () => {
await eventPost(req({ method: "POST" }), { params: Promise.resolve({ uuid: "e1", path: ["orders", "300", "tickets", "7", "resend"] }) });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/e1/orders/300/tickets/7/resend", { method: "POST", body: {}, token: "jwt" });
const bad = await eventPost(req({ method: "POST" }), { params: Promise.resolve({ uuid: "e1", path: ["orders", "300", "tickets", "7", "checkin"] }) });
expect(bad.status).toBe(400);
});
});
@@ -0,0 +1,30 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({ getCheckin: vi.fn(), lookupCheckin: vi.fn(), registerWalkIn: vi.fn() }));
vi.mock("@/app/lib/services/publicInvite", () => mocks);
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "chk1" }) }));
import CheckinPage from "./page";
beforeEach(() => {
mocks.getCheckin.mockReset().mockResolvedValue({
state: "OPEN", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", companyName: "INS",
notice: { id: 7, textEn: "We keep your data safe.", textMs: "Data anda selamat." }, interests: [],
});
mocks.lookupCheckin.mockReset().mockResolvedValue({ result: "SHOW_TICKET" });
});
// add-event-tickets: on a ticketed event an unmatched visitor is sent to the entrance, with no walk-in form.
describe("/c/[token] on a ticketed event", () => {
it("asks a visitor with no ticket to show it at the entrance", async () => {
const user = userEvent.setup();
render(<CheckinPage />);
await user.type(await screen.findByLabelText("Mobile number or email"), "0125550101");
await user.click(screen.getByRole("button", { name: "Check in" }));
expect(await screen.findByText("Please show your ticket at the entrance.")).toBeInTheDocument();
expect(screen.queryByLabelText("Your name")).not.toBeInTheDocument();
expect(mocks.registerWalkIn).not.toHaveBeenCalled();
});
});
+4 -3
View File
@@ -2,7 +2,7 @@
import { useEffect, useState, type FormEvent } from "react";
import { useParams } from "next/navigation";
import { AlertCircle, CheckCircle2, Clock, Loader2 } from "lucide-react";
import { AlertCircle, CheckCircle2, Clock, Loader2, Ticket } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
@@ -11,7 +11,7 @@ import { RegistrationForm, apiData, failMessage } from "@/app/components/registr
import { getCheckin, lookupCheckin, registerWalkIn, type CheckinState } from "@/app/lib/services/publicInvite";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type Phase = "loading" | "inactive" | "error" | "lookup" | "form" | "welcome" | "done";
type Phase = "loading" | "inactive" | "error" | "lookup" | "form" | "welcome" | "done" | "showTicket";
// Public event check-in page (QR at the venue): a known person is looked up by mobile or email, anyone else registers as a walk-in.
export default function CheckinPage() {
@@ -52,7 +52,7 @@ export default function CheckinPage() {
if (r.result === "CHECKED_IN") {
setFirstName(r.firstName);
setPhase("welcome");
} else setPhase("form");
} else setPhase(r.result === "SHOW_TICKET" ? "showTicket" : "form"); // a ticketed event takes no walk-ins
} catch (err) {
if (apiData(err).code === "CODE_INACTIVE") setPhase("inactive");
else setError(failMessage(t, err, "InviteTooMany"));
@@ -72,6 +72,7 @@ export default function CheckinPage() {
let body;
if (phase === "welcome") body = <VisitorState icon={CheckCircle2} heading={firstName ? t("InviteWelcome", { name: firstName }) : t("InviteWelcomeAnon")} role="status" />;
else if (phase === "showTicket") body = <VisitorState icon={Ticket} heading={t("ChkShowTicket")} role="status" />;
else if (phase === "done") body = <VisitorState icon={CheckCircle2} heading={t("ChkDone", { event: open.eventName })} role="status" />;
else if (phase === "form") {
body = <RegistrationForm tooManyKey="InviteTooMany" info={open} initial={value.includes("@") ? { email: value.trim() } : { mobile: value.trim() }} submit={(b) => registerWalkIn(token, b)} onDone={() => setPhase("done")} onInactive={() => setPhase("inactive")} />;
@@ -0,0 +1,39 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, within } from "@testing-library/react";
const mocks = vi.hoisted(() => ({
listGuests: vi.fn(), addGuests: vi.fn(), removeGuest: vi.fn(), sendInvites: vi.fn(), getAttendance: vi.fn(), useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminGuests", () => mocks);
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import { GuestsCard } from "./GuestsCard";
const ATT = { invited: 0, cap: null, registered: 0, attended: 3, walkIns: 0, heldTickets: 7, total: 7, capacity: 100,
ticketsAwaiting: 2, ticketsPaid: 5, ticketsCheckedIn: 3 };
beforeEach(() => {
mocks.listGuests.mockReset().mockResolvedValue([]);
mocks.getAttendance.mockReset().mockResolvedValue(ATT);
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" });
});
const number = async (label: string) => {
const list = await screen.findByRole("list", { name: "Attendance numbers" });
return within(list).queryByText(label)?.parentElement?.textContent;
};
// add-event-tickets: a ticketed event's numbers add tickets awaiting payment, paid and checked in.
describe("GuestsCard ticket numbers", () => {
it("shows the three ticket counts when the event sells tickets", async () => {
render(<GuestsCard eventUuid="e1" ticketsEnabled />);
expect(await number("Tickets awaiting payment")).toBe("Tickets awaiting payment2");
expect(await number("Tickets paid")).toBe("Tickets paid5");
expect(await number("Tickets checked in")).toBe("Tickets checked in3");
});
it("hides them on an event without tickets", async () => {
render(<GuestsCard eventUuid="e1" />);
expect(await number("Tickets paid")).toBeUndefined();
});
});
@@ -44,7 +44,7 @@ const parseLines = (text: string): GuestInput[] =>
return { name, mobile, email, companyName };
});
export function GuestsCard({ eventUuid, team = [] }: { eventUuid: string; team?: AdminEventMember[] }) {
export function GuestsCard({ eventUuid, team = [], ticketsEnabled = false }: { eventUuid: string; team?: AdminEventMember[]; ticketsEnabled?: boolean }) {
const t = useT();
const { hasModule } = useAdminAuth();
const canManage = hasModule("BO_EVENT_GUESTS");
@@ -168,6 +168,11 @@ export function GuestsCard({ eventUuid, team = [] }: { eventUuid: string; team?:
[t("GuestAttended"), att?.attended],
[t("GuestWalkIns"), att?.walkIns],
[t("GuestHeldTickets"), att?.heldTickets],
...(ticketsEnabled ? [
[t("GuestTicketsAwaiting"), att?.ticketsAwaiting],
[t("GuestTicketsPaid"), att?.ticketsPaid],
[t("GuestTicketsCheckedIn"), att?.ticketsCheckedIn],
] as [string, number | undefined][] : []),
[t("GuestTotal"), att?.total],
[t("EvtCapacity"), att?.capacity],
];
@@ -222,6 +222,15 @@ describe("LandingPage thank-you text and footer", () => {
expect(within(foot).getByText(/^© 2026/)).toHaveClass("border-t");
});
it("ends the page at the footer: no blank strip below a closing footer", () => {
const { unmount } = render(<LandingPage company={company} page={page([{ type: "FAQ", items: [{ question: "Q", answer: "A" }] }, footer])} />);
expect(screen.getByRole("main")).not.toHaveClass("pb-8");
expect(screen.getByRole("main")).not.toHaveClass("py-8");
unmount();
render(<LandingPage company={company} page={page([footer, { type: "FAQ", items: [{ question: "Q", answer: "A" }] }])} />);
expect(screen.getByRole("main").className).toMatch(/p[by]-8/);
});
it("keeps markup in footer text as text", () => {
render(<LandingPage company={company} page={page([{ type: "FOOTER", cards: [{ title: "Call", text: "<b>Call</b> +60 12-833 2775" }] }])} />);
const foot = screen.getByRole("contentinfo");
@@ -347,7 +347,8 @@ export function LandingPage({ company, page, banner, preview, frameBase, edit }:
)}
</div>
</header>}
<main className={page.hideHeader ? "pb-8" : "py-8"}>
{/* A closing footer is the page's end: no padding below it. */}
<main className={`${page.hideHeader ? "" : "pt-8"} ${page.blocks.at(-1)?.type === "FOOTER" ? "" : "pb-8"}`}>
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
<div>
{page.blocks.map((block, i) => (
@@ -24,6 +24,8 @@ const ALLOW: Record<string, string[]> = {
"app/pos/_components/SplitTenderPanel.tsx": ["bg-white"],
// The full-screen QR sits on a white quiet zone so it scans in dark mode.
"app/components/registration/QrCodeItem.tsx": ["bg-white"],
// add-event-tickets: the ticket QR sits on a white quiet zone so it scans in dark mode.
"app/t/[code]/page.tsx": ["bg-white"],
// A sent email's HTML is authored for a white mail-client canvas; a theme surface would put the
// email's dark text on dark in dark mode.
"app/email-templates/logs/[id]/page.tsx": ["bg-white"],
@@ -153,6 +153,21 @@ describe("EventLeadsDetailPage (listing)", { timeout: 20000 }, () => {
expect(card.getByText("Source: QR")).toBeInTheDocument();
});
it("labels ticket leads (buyers and consenting attendees) as Ticket", async () => {
mocks.listEventLeads.mockResolvedValue({
items: [{
eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "lead-1", name: "John Doe", mobile: null, email: null,
companyName: null, jobTitle: null, leadType: "NEW", salesperson: null, temperature: null, status: "OPEN",
interests: [], nextFollowUpDate: null, notes: null, capturedAt: "2025-06-01", attended: null, source: "TICKET",
}],
total: 1,
});
render(<EventLeadsDetailPage />);
const row = (await screen.findByRole("link", { name: "John Doe" })).closest("tr")!;
expect(within(row).getAllByRole("cell").at(-1)!.textContent).toBe("Ticket");
expect(within(screen.getByTestId("lead-card")).getByText("Source: Ticket")).toBeInTheDocument();
});
it("filters by attendance for the list and the export", async () => {
const user = userEvent.setup();
render(<EventLeadsDetailPage />);
@@ -28,7 +28,7 @@ const TEMPERATURE_OPTIONS = [{ value: "HOT", label: "LeadHot" }, { value: "WARM"
const STATUS_OPTIONS = [{ value: "OPEN", label: "LeadOpen" }, { value: "CONTACTED", label: "LeadContacted" }, { value: "QUALIFIED", label: "LeadQualified" }, { value: "WON", label: "LeadWon" }, { value: "LOST", label: "LeadLost" }];
const LEAD_TYPE_OPTIONS = [{ value: "NEW", label: "LeadNew" }, { value: "EXISTING", label: "LeadExisting" }];
const ATTENDED_OPTIONS = [{ value: "true", label: "GuestAttended" }, { value: "false", label: "LeadNotAttended" }];
const SOURCE_LABEL = { STAFF: "LeadSourceStaff", QR: "LeadSourceQr", INVITE: "LeadSourceInvite", WEB: "LeadSourceWeb" } as const;
const SOURCE_LABEL = { STAFF: "LeadSourceStaff", QR: "LeadSourceQr", INVITE: "LeadSourceInvite", WEB: "LeadSourceWeb", TICKET: "LeadSourceTicket" } as const;
const TEMPERATURE_BADGE = { HOT: "negative", WARM: "warning", COLD: "neutral" } as const;
const STATUS_BADGE = { OPEN: "neutral", CONTACTED: "neutral", QUALIFIED: "contrast", WON: "positive", LOST: "negative" } as const;
@@ -0,0 +1,72 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({ getOrder: vi.fn(), resendTicket: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/services/adminTickets", async (orig) => ({ ...(await orig<object>()), getOrder: mocks.getOrder, resendTicket: mocks.resendTicket }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", () => ({ useParams: () => ({ uuid: "evt-9", orderId: "300" }) }));
import OrderPage from "./page";
const detail = (status: string) => ({
order: {
id: 300, reference: "T-7K3M9Q", status, buyerName: "Aisyah", buyerEmail: "a@example.test", buyerMobileE164: null,
buyerCompany: null, totalSen: 50000, holdUntil: null, paidAt: "2026-12-04T11:00:00", paidBy: "finance1", paymentRef: null,
cancelledAt: null, cancelledBy: null, expiredAt: null, createdAt: "2026-12-04T10:00:00",
},
lines: [{ id: 400, name: "General", unitPriceSen: 25000, quantity: 2 }],
tickets: [
{ id: 1, typeName: "General", status: "ACTIVE", cancelledAt: null, cancelledBy: null },
{ id: 2, typeName: "General", status: "CANCELLED", cancelledAt: "2026-12-04T12:00:00", cancelledBy: "finance1" },
],
});
beforeEach(() => {
mocks.getOrder.mockReset().mockResolvedValue(detail("PAID"));
mocks.resendTicket.mockReset().mockResolvedValue({});
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" || m === "BO_EVENT_TICKETS" });
});
// add-event-tickets: staff resend one valid ticket from the order detail.
describe("OrderPage resend ticket", () => {
it("resends an active ticket of a paid order, not a cancelled one", async () => {
const user = userEvent.setup();
render(<OrderPage />);
await screen.findByRole("heading", { name: /T-7K3M9Q/ });
const rows = screen.getAllByRole("row").filter((r) => r.textContent?.includes("General"));
expect(within(rows[1]).queryByRole("button", { name: "Resend ticket" })).not.toBeInTheDocument();
await user.click(within(rows[0]).getByRole("button", { name: "Resend ticket" }));
await waitFor(() => expect(mocks.resendTicket).toHaveBeenCalledWith("evt-9", "300", 1));
expect(await screen.findByText("Ticket sent.")).toBeInTheDocument();
});
it("shows each ticket's attendee and check-in, and offers no resend once checked in", async () => {
mocks.getOrder.mockResolvedValue({ ...detail("PAID"), tickets: [
{ id: 1, typeName: "General", status: "ACTIVE", cancelledAt: null, cancelledBy: null, attendeeName: "Tan Mei Ling", checkedInAt: null },
{ id: 3, typeName: "General", status: "ACTIVE", cancelledAt: null, cancelledBy: null, attendeeName: null, checkedInAt: "2026-12-04T18:14:00" },
] });
render(<OrderPage />);
const tan = (await screen.findByText("Tan Mei Ling")).closest("tr")!;
expect(within(tan).getByRole("button", { name: "Resend ticket" })).toBeInTheDocument();
const used = screen.getByText("Not named yet").closest("tr")!;
expect(used).toHaveTextContent(/Checked in at/);
expect(within(used).queryByRole("button", { name: "Resend ticket" })).not.toBeInTheDocument();
});
it("offers no resend before payment", async () => {
mocks.getOrder.mockResolvedValue(detail("AWAITING"));
render(<OrderPage />);
await screen.findByRole("heading", { name: /T-7K3M9Q/ });
expect(screen.queryByRole("button", { name: "Resend ticket" })).not.toBeInTheDocument();
});
it("explains a refusal for a ticket that is no longer valid", async () => {
mocks.resendTicket.mockRejectedValue(new ApiError("x", 409, { code: "TICKET_NOT_VALID" }));
const user = userEvent.setup();
render(<OrderPage />);
await user.click(await screen.findByRole("button", { name: "Resend ticket" }));
expect(await screen.findByRole("alert")).toHaveTextContent("This ticket is not valid, so it cannot be sent.");
});
});
@@ -23,6 +23,7 @@ import {
markOrderPaid,
money,
resendOrderEmail,
resendTicket,
type OrderDetail,
} from "@/app/lib/services/adminTickets";
@@ -154,6 +155,7 @@ function OrderContent() {
<TableHeader>
<TableRow>
<TableHead>{t("TktTicketType")}</TableHead>
<TableHead>{t("TktAttendeeName")}</TableHead>
<TableHead>{t("Status")}</TableHead>
<TableHead />
</TableRow>
@@ -162,8 +164,17 @@ function OrderContent() {
{d.tickets.map((x) => (
<TableRow key={x.id}>
<TableCell>{x.typeName ?? "-"}</TableCell>
<TableCell>{x.status === "ACTIVE" ? t("TktTicketActive") : t("TktTicketCancelledBy", { by: x.cancelledBy ?? "-", at: when(x.cancelledAt) })}</TableCell>
<TableCell>{x.attendeeName ?? t("TktNotNamed")}</TableCell>
<TableCell>
{x.status !== "ACTIVE" ? t("TktTicketCancelledBy", { by: x.cancelledBy ?? "-", at: when(x.cancelledAt) })
: x.checkedInAt ? t("TktCheckedInAt", { when: when(x.checkedInAt) }) : t("TktTicketActive")}
</TableCell>
<TableCell className="text-right">
{o.status === "PAID" && x.status === "ACTIVE" && !x.checkedInAt && (
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => run(() => resendTicket(uuid, orderId, x.id).then(() => {}), "TktTicketSent")}>
{t("TktResendTicket")}
</Button>
)}
{open && x.status === "ACTIVE" && (
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => setConfirm({ ticketId: x.id })}>
{t("TktCancelTicket")}
@@ -123,7 +123,7 @@ function EditEventPageContent() {
{/* ponytail: no read-only role for events yet; the events module is the write gate for the code switches. */}
<RegistrationQrCard eventUuid={event.uuid} eventName={event.name} canWrite={hasModule("BO_EVENTS")} />
<GuestsCard eventUuid={event.uuid} team={event.team} />
<GuestsCard eventUuid={event.uuid} team={event.team} ticketsEnabled={!!event.ticketsEnabled} />
<TicketsCard eventUuid={event.uuid} />
</div>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#2563EB"/><path d="M20.5 11.2a7 7 0 1 0 0 9.6" fill="none" stroke="#fff" stroke-width="3.2" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 225 B

@@ -356,6 +356,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
LeadSourceQr: "QR",
LeadSourceInvite: "Invite",
LeadSourceWeb: "Web page",
LeadSourceTicket: "Ticket",
LeadWebPage: "Web page: {path}",
LeadCampaign: "Campaign: {tags}",
LeadHot: "Hot",
@@ -1017,6 +1018,50 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
TktPublicCancelled: "This order was cancelled.",
TktPublicExpired: "This order expired before payment arrived.",
TktOrderInvalid: "This order link is not valid.",
TktTicketInvalid: "This ticket link is not valid.",
TktTicketFor: "Ticket for {name}",
TktQrAlt: "Ticket QR code",
TktShowQr: "Show this QR code at the entrance.",
TktCheckedInAt: "Checked in at {when}",
TktNotValid: "This ticket is not valid",
TktReasonAWAITING: "awaiting payment",
TktReasonORDER_CANCELLED: "order cancelled",
TktReasonORDER_EXPIRED: "order expired",
TktReasonTICKET_CANCELLED: "ticket cancelled",
TktKeepUpdated: "Keep me updated about {company} events",
TktConsentSave: "Save",
TktConsentDone: "Thank you. We will keep you updated.",
TktStaffView: "Staff check-in",
TktStaffValid: "Valid",
TktAlreadyCheckedIn: "Already checked in at {when}",
TktNotValidReason: "Not valid: {reason}",
TktNotEventDay: "Check-in is only open on the event days.",
TktCheckIn: "Check in",
TktCheckedInNow: "Checked in.",
TktUnnamed: "No attendee named yet",
TktAttendeeName: "Attendee name",
TktContactRequired: "Enter a mobile number or an email.",
ChkShowTicket: "Please show your ticket at the entrance.",
GuestTicketsAwaiting: "Tickets awaiting payment",
GuestTicketsPaid: "Tickets paid",
GuestTicketsCheckedIn: "Tickets checked in",
TktErrTicketNotValid: "This ticket is not valid, so it cannot be sent.",
TktResendTicket: "Resend ticket",
TktTicketSent: "Ticket sent.",
TktYourTickets: "Your tickets",
TktNameAttendeesHelp: "Name each attendee so their ticket can be emailed to them, or share each ticket's link.",
TktAttendeeSaved: "Saved. The ticket has a new link; the old one no longer works.",
TktNotNamed: "Not named yet",
TktOpenTicket: "Open ticket",
TktCopyLink: "Copy link",
TktLinkCopied: "Link copied.",
TktNameAttendee: "Name attendee",
TktChangeAttendee: "Change attendee",
TktAttendeeRequired: "Enter the attendee's name and a mobile number or an email.",
TktPermissionRequired: "Tick the box to confirm you have permission.",
TktPermission: "I have permission to share these details so their ticket can be sent",
TktRenameWarning: "Saving gives this ticket a new link and QR code. The old ones stop working.",
TktSaveAttendee: "Save attendee",
PagesBlockTickets: "Tickets",
PagesTicketsEvent: "Event selling tickets",
PagesChooseTicketsEvent: "Choose an event with tickets on",
@@ -710,6 +710,7 @@
"MsgsConfirmImport": "确认导入",
"MsgsImportSummary": "已创建 {created} 条,已更新 {updated} 条,失败 {errors} 条。",
"LeadSourceWeb": "网页",
"LeadSourceTicket": "门票",
"LeadWebPage": "网页:{path}",
"LeadCampaign": "推广活动:{tags}",
"BO_PAGES": "网页",
@@ -1000,6 +1001,50 @@
"TktPublicCancelled": "此订单已取消。",
"TktPublicExpired": "此订单在收到付款前已过期。",
"TktOrderInvalid": "此订单链接无效。",
"TktTicketInvalid": "此门票链接无效。",
"TktTicketFor": "{name} 的门票",
"TktQrAlt": "门票二维码",
"TktShowQr": "请在入口出示此二维码。",
"TktCheckedInAt": "已于 {when} 签到",
"TktNotValid": "此门票无效",
"TktReasonAWAITING": "等待付款",
"TktReasonORDER_CANCELLED": "订单已取消",
"TktReasonORDER_EXPIRED": "订单已过期",
"TktReasonTICKET_CANCELLED": "门票已取消",
"TktKeepUpdated": "向我发送 {company} 的活动资讯",
"TktConsentSave": "保存",
"TktConsentDone": "谢谢,我们会向您发送最新资讯。",
"TktStaffView": "工作人员签到",
"TktStaffValid": "有效",
"TktAlreadyCheckedIn": "已于 {when} 签到过",
"TktNotValidReason": "无效:{reason}",
"TktNotEventDay": "仅在活动日开放签到。",
"TktCheckIn": "签到",
"TktCheckedInNow": "签到成功。",
"TktUnnamed": "尚未填写参加者",
"TktAttendeeName": "参加者姓名",
"TktContactRequired": "请输入手机号码或电子邮件。",
"ChkShowTicket": "请在入口出示您的门票。",
"GuestTicketsAwaiting": "待付款门票",
"GuestTicketsPaid": "已付款门票",
"GuestTicketsCheckedIn": "已签到门票",
"TktErrTicketNotValid": "此门票无效,无法发送。",
"TktResendTicket": "重新发送门票",
"TktTicketSent": "门票已发送。",
"TktYourTickets": "您的门票",
"TktNameAttendeesHelp": "填写每位参加者,以便通过电子邮件将门票发送给他们,或分享每张门票的链接。",
"TktAttendeeSaved": "已保存。门票已有新链接,旧链接已失效。",
"TktNotNamed": "尚未填写",
"TktOpenTicket": "打开门票",
"TktCopyLink": "复制链接",
"TktLinkCopied": "链接已复制。",
"TktNameAttendee": "填写参加者",
"TktChangeAttendee": "更改参加者",
"TktAttendeeRequired": "请输入参加者姓名,以及手机号码或电子邮件。",
"TktPermissionRequired": "请勾选以确认您已获得许可。",
"TktPermission": "我已获得许可分享这些资料,以便发送其门票",
"TktRenameWarning": "保存后此门票将获得新的链接和二维码,旧的将失效。",
"TktSaveAttendee": "保存参加者",
"PagesBlockTickets": "门票",
"PagesTicketsEvent": "售票活动",
"PagesChooseTicketsEvent": "选择已开启售票的活动",
@@ -51,11 +51,11 @@ describe("guardDecision", () => {
describe("visitor pages /r, /i, /c, /o", () => {
it("pass signed out and with a reset pending; the bare prefixes and admin paths do not", () => {
const pending = { present: true, resetRequired: true };
for (const p of ["/r/x", "/i/x", "/c/x", "/o/x"]) {
for (const p of ["/r/x", "/i/x", "/c/x", "/o/x", "/t/x"]) {
expect(guardDecision(p, null), p).toBeNull();
expect(guardDecision(p, pending), p).toBeNull();
}
for (const p of ["/events", "/i", "/c/", "/i/", "/c/x/y", "/o/", "/o/x/y"]) {
for (const p of ["/events", "/i", "/c/", "/i/", "/c/x/y", "/o/", "/o/x/y", "/t/", "/t/x/y"]) {
expect(guardDecision(p, null), p).toBe("/login");
expect(guardDecision(p, pending), p).toBe("/reset-password");
}
+2 -2
View File
@@ -9,9 +9,9 @@
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forgot-password"]);
// Visitor pages, not signed in: /r/<token> QR self-registration, /i/<token> personal invite, /c/<token> event check-in,
// /o/<token> a ticket order (add-event-ticket-orders).
// /o/<token> a ticket order (add-event-ticket-orders), /t/<code> a ticket (add-event-tickets; staff also open it signed in).
// (A pattern, so PUBLIC_PATHS stays exact.)
const VISITOR_PATH = /^\/[rico]\/[^/]+$/;
const VISITOR_PATH = /^\/[ricot]\/[^/]+$/;
// Published landing pages: /p/<company-code>/<slug>.
const LANDING_PATH = /^\/p\/[^/]+\/[^/]+$/;
// add-custom-html-block: a published page's Custom HTML frame, /p/<company-code>/<slug>/frame/<block>.
@@ -191,7 +191,7 @@ export interface BinaryPayload {
/** GET a binary upstream response (e.g. an xlsx export); failures use the same shape as callMobileApi. */
export async function callMobileApiBinary(
path: string,
opts: Pick<MobileCallOptions, "token" | "timeoutMs"> = {},
opts: Pick<MobileCallOptions, "token" | "timeoutMs" | "headers"> = {},
): Promise<ApiResult<BinaryPayload>> {
const up = await upstreamFetch(path, opts);
if ("fail" in up) return up.fail;
@@ -41,6 +41,10 @@ export interface Attendance {
walkIns: number;
/** add-event-ticket-orders: seats of awaiting and paid ticket orders; part of the total. */
heldTickets: number;
/** add-event-tickets: active tickets of awaiting and paid orders, and paid tickets checked in. */
ticketsAwaiting?: number;
ticketsPaid?: number;
ticketsCheckedIn?: number;
total: number;
capacity: number | null;
}
@@ -58,7 +58,8 @@ export interface OrderDetail {
createdAt: string;
};
lines: { id: number; name: string; unitPriceSen: number; quantity: number }[];
tickets: { id: number; typeName: string | null; status: "ACTIVE" | "CANCELLED"; cancelledAt: string | null; cancelledBy: string | null }[];
tickets: { id: number; typeName: string | null; status: "ACTIVE" | "CANCELLED"; cancelledAt: string | null; cancelledBy: string | null;
attendeeName?: string | null; checkedInAt?: string | null }[];
}
const base = (uuid: string) => `/api/events/${encodeURIComponent(uuid)}`;
@@ -82,6 +83,8 @@ export const markOrderPaid = (uuid: string, id: string, paymentRef: string) =>
export const cancelOrder = (uuid: string, id: string) => apiPost<unknown>(`${base(uuid)}/orders/${encodeURIComponent(id)}/cancel`);
export const cancelTicket = (uuid: string, id: string, ticketId: number) =>
apiPost<unknown>(`${base(uuid)}/orders/${encodeURIComponent(id)}/tickets/${ticketId}/cancel`);
export const resendTicket = (uuid: string, id: string, ticketId: number) =>
apiPost<unknown>(`${base(uuid)}/orders/${encodeURIComponent(id)}/tickets/${ticketId}/resend`);
export const resendOrderEmail = (uuid: string, id: string) => apiPost<unknown>(`${base(uuid)}/orders/${encodeURIComponent(id)}/resend`);
/** RM 1,000.00 from whole sen; RM 0 reads "Free" where a caller wants it. */
@@ -98,6 +101,7 @@ export const TICKET_ERRORS: Record<string, string> = {
PRICE_INVALID: "TktErrPrice",
QUANTITY_INVALID: "TktErrQuantity",
QUANTITY_BELOW_HELD: "TktErrQuantityBelowHeld",
TICKET_NOT_VALID: "TktErrTicketNotValid",
DATE_INVALID: "TktErrDate",
TYPE_HAS_ORDERS: "TktErrTypeHasOrders",
NOT_PAYABLE: "TktErrNotPayable",
@@ -15,5 +15,5 @@ export const submitInvite = (token: string, body: RegistrationBody) => publicCal
export const inviteCheckin = (token: string) => publicCall<{ firstName: string }>(`${invite(token)}/checkin`, post());
export const getCheckin = (token: string) => publicCall<CheckinState>(checkin(token));
export const lookupCheckin = (token: string, value: string) =>
publicCall<{ result: "CHECKED_IN"; firstName: string } | { result: "FORM" }>(`${checkin(token)}/lookup`, post({ value }));
publicCall<{ result: "CHECKED_IN"; firstName: string } | { result: "FORM" } | { result: "SHOW_TICKET" }>(`${checkin(token)}/lookup`, post({ value }));
export const registerWalkIn = (token: string, body: RegistrationBody) => publicCall<{ eventName: string }>(`${checkin(token)}/register`, post(body));
@@ -51,6 +51,25 @@ export interface PublicOrder {
location: string | null;
holdUntil?: string | null;
paymentInstructions?: string | null;
/** add-event-tickets: only on a Paid order. */
tickets?: OrderTicket[];
}
/** One ticket on the buyer's order page: no attendee contact. */
export interface OrderTicket {
id: number;
typeName: string | null;
attendeeName: string | null;
code: string;
state: "VALID" | "CHECKED_IN" | "TICKET_CANCELLED";
checkedInAt: string | null;
}
export interface AttendeeBody {
name: string;
mobile: string;
email: string;
permission: boolean;
}
/** A Malaysia wall-clock time from the server ("2027-01-13T12:00:00") as "13 Jan 2027, 12:00". */
@@ -61,3 +80,68 @@ export function when(s: string | null | undefined): string {
}
export const getPublicOrder = (token: string) => publicCall<PublicOrder>(`/api/public/orders/${encodeURIComponent(token)}`);
// add-event-tickets: the ticket page, its staff view and naming attendees.
export type TicketState = "VALID" | "CHECKED_IN" | "AWAITING" | "ORDER_CANCELLED" | "ORDER_EXPIRED" | "TICKET_CANCELLED";
export interface TicketNotice {
id: number;
textEn: string;
textMs: string;
}
interface TicketEvent {
eventName: string;
startDate: string | null;
endDate: string | null;
location: string | null;
}
/** The public view: no contact details; the notice only when the attendee can still opt in. */
export interface PublicTicket extends TicketEvent {
companyName: string;
typeName: string | null;
attendeeFirstName: string | null;
named: boolean;
state: TicketState;
checkedInAt: string | null;
consented: boolean;
notice?: TicketNotice;
}
export interface StaffTicket extends TicketEvent {
companyName: string | null;
typeName: string | null;
attendeeName: string | null;
named: boolean;
consented: boolean;
state: TicketState;
checkedInAt: string | null;
checkedInBy: string | null;
notice?: TicketNotice;
}
export interface CheckInBody {
name?: string;
mobile?: string;
email?: string;
consent: boolean;
}
const code = (c: string) => `/api/public/tickets/${encodeURIComponent(c)}`;
export const getPublicTicket = (c: string) => publicCall<PublicTicket>(code(c));
export const ticketQrUrl = (c: string) => `${code(c)}/qr.png`;
export const consentTicket = (c: string) =>
publicCall<{ consented: boolean }>(`${code(c)}/consent`, { method: "POST", body: JSON.stringify({ consent: true }) });
// Staff calls use plain fetch, not clientApi: a signed-out visitor or another company's staff gets an error and keeps
// the public view, never a redirect to the login page.
export const getStaffTicket = (c: string) => publicCall<StaffTicket>(`/api/tickets/${encodeURIComponent(c)}`);
export const checkInTicket = (c: string, body: CheckInBody) =>
publicCall<StaffTicket>(`/api/tickets/${encodeURIComponent(c)}/checkin`, { method: "POST", body: JSON.stringify(body) });
/** The buyer names or renames an attendee: the ticket comes back with a new code. */
export const nameAttendee = (token: string, ticketId: number, body: AttendeeBody) =>
publicCall<OrderTicket>(`/api/public/orders/${encodeURIComponent(token)}/tickets/${ticketId}/attendee`, { method: "POST", body: JSON.stringify(body) });
+1 -1
View File
@@ -251,7 +251,7 @@ export interface EventLeadRow {
capturedAt: string;
companyId?: number;
attended?: boolean;
source?: "STAFF" | "QR" | "INVITE" | "WEB";
source?: "STAFF" | "QR" | "INVITE" | "WEB" | "TICKET";
/** A web page sign-up's page address and UTM tags. */
pagePath?: string | null;
utmSource?: string | null;
+111 -3
View File
@@ -1,12 +1,16 @@
"use client";
import { useEffect, useState } from "react";
import { useEffect, useState, type FormEvent } from "react";
import { useParams } from "next/navigation";
import { AlertCircle, CalendarDays, Loader2, MapPin } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { VisitorCard, VisitorState } from "@/app/components/registration/VisitorCard";
import { OrderSummary, PaymentBox } from "@/app/components/pages/TicketsBlock";
import { apiData } from "@/app/components/registration/RegistrationForm";
import { getPublicOrder, type PublicOrder } from "@/app/lib/services/publicTickets";
import { apiData, failMessage } from "@/app/components/registration/RegistrationForm";
import { getPublicOrder, nameAttendee, when, type OrderTicket, type PublicOrder } from "@/app/lib/services/publicTickets";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const STATUS: Record<PublicOrder["status"], string> = {
@@ -57,6 +61,110 @@ export default function OrderPage() {
</div>
<OrderSummary lines={order.lines} totalSen={order.totalSen} />
{order.status === "AWAITING" && order.paymentInstructions && <PaymentBox instructions={order.paymentInstructions} holdUntil={order.holdUntil} />}
{order.status === "PAID" && order.tickets && order.tickets.length > 0 && <OrderTickets token={token} initial={order.tickets} />}
</VisitorCard>
);
}
/** add-event-tickets: a Paid order's tickets, each with its link; the buyer names or renames an attendee until check-in. */
function OrderTickets({ token, initial }: { token: string; initial: OrderTicket[] }) {
const t = useT();
const [tickets, setTickets] = useState(initial);
const [editing, setEditing] = useState<number | null>(null);
const [saved, setSaved] = useState<string | null>(null);
const replace = (next: OrderTicket) => {
setTickets((all) => all.map((x) => (x.id === next.id ? next : x)));
setEditing(null);
setSaved(t("TktAttendeeSaved"));
};
return (
<section className="space-y-3 border-t pt-4">
<h2 className="font-semibold">{t("TktYourTickets")}</h2>
<p className="text-sm text-muted-foreground">{t("TktNameAttendeesHelp")}</p>
{saved && <p role="status" className="text-sm">{saved}</p>}
<ul className="space-y-3">
{tickets.map((x) => (
<li key={x.id} className="space-y-2 rounded-md border p-3">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<span className="font-medium">{x.typeName ?? "-"}</span>
<span className="text-sm">{x.attendeeName ?? t("TktNotNamed")}</span>
</div>
{x.state === "CHECKED_IN" && <p className="text-sm text-muted-foreground">{t("TktCheckedInAt", { when: when(x.checkedInAt) })}</p>}
<TicketLink code={x.code} />
{x.state === "VALID" && editing !== x.id && (
<Button type="button" variant="outline" size="sm" onClick={() => { setSaved(null); setEditing(x.id); }}>
{t(x.attendeeName ? "TktChangeAttendee" : "TktNameAttendee")}
</Button>
)}
{editing === x.id && <AttendeeForm token={token} ticket={x} onSaved={replace} onCancel={() => setEditing(null)} />}
</li>
))}
</ul>
</section>
);
}
function TicketLink({ code }: { code: string }) {
const t = useT();
const [copied, setCopied] = useState<string | null>(null);
const path = `/t/${code}`;
const copy = () => {
navigator.clipboard?.writeText(`${window.location.origin}${path}`)
.then(() => setCopied(t("TktLinkCopied")), () => setCopied(t("CopyFailed")));
};
return (
<div className="flex flex-wrap items-center gap-2 text-sm">
<a href={path} className="font-medium text-primary underline">{t("TktOpenTicket")}</a>
<Button type="button" variant="ghost" size="sm" onClick={copy}>{t("TktCopyLink")}</Button>
{copied && <span role="status" className="text-muted-foreground">{copied}</span>}
</div>
);
}
function AttendeeForm({ token, ticket, onSaved, onCancel }: { token: string; ticket: OrderTicket; onSaved: (t: OrderTicket) => void; onCancel: () => void }) {
const t = useT();
const [form, setForm] = useState({ name: "", mobile: "", email: "", permission: false });
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const id = (f: string) => `att-${ticket.id}-${f}`;
const submit = (e: FormEvent) => {
e.preventDefault();
if (!form.name.trim() || (!form.mobile.trim() && !form.email.trim())) return setError(t("TktAttendeeRequired"));
if (!form.permission) return setError(t("TktPermissionRequired"));
setSaving(true);
setError(null);
nameAttendee(token, ticket.id, form)
.then(onSaved)
.catch((err) => setError(failMessage(t, err)))
.finally(() => setSaving(false));
};
return (
<form onSubmit={submit} className="space-y-3" noValidate>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<div className="space-y-1">
<Label htmlFor={id("name")}>{t("TktAttendeeName")}</Label>
<Input id={id("name")} maxLength={100} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
</div>
<div className="space-y-1">
<Label htmlFor={id("mobile")}>{t("RegMobile")}</Label>
<Input id={id("mobile")} type="tel" value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} />
<p className="text-xs text-muted-foreground">{t("RegContactHint")}</p>
</div>
<div className="space-y-1">
<Label htmlFor={id("email")}>{t("RegEmail")}</Label>
<Input id={id("email")} type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
</div>
<Label htmlFor={id("permission")} className="flex items-start gap-3 font-normal">
<Checkbox id={id("permission")} className="mt-0.5 size-5" checked={form.permission} onCheckedChange={(on) => setForm({ ...form, permission: on === true })} />
<span>{t("TktPermission")}</span>
</Label>
<p className="text-xs text-muted-foreground">{t("TktRenameWarning")}</p>
<div className="flex gap-2">
<Button type="submit" disabled={saving}>{t("TktSaveAttendee")}</Button>
<Button type="button" variant="ghost" onClick={onCancel}>{t("Cancel")}</Button>
</div>
</form>
);
}
@@ -0,0 +1,91 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({ getPublicOrder: vi.fn(), nameAttendee: vi.fn() }));
vi.mock("@/app/lib/services/publicTickets", async (orig) => ({ ...(await orig<object>()), getPublicOrder: mocks.getPublicOrder, nameAttendee: mocks.nameAttendee }));
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "abcdefghijklmnopqrstuv" }) }));
import { ApiError } from "@/app/lib/clientApi";
import OrderPage from "./page";
const TOKEN = "abcdefghijklmnopqrstuv";
const PAID = {
reference: "T-7K3M9Q", status: "PAID", buyerName: "Aini", totalSen: 30000, createdAt: "2027-01-10T09:00:00",
lines: [{ name: "General", unitPriceSen: 15000, quantity: 2 }],
eventName: "KL Hotel Tech Day", startDate: "2027-01-15", endDate: "2027-01-16", location: "KLCC",
tickets: [
{ id: 1, typeName: "General", attendeeName: null, code: "aaaaaaaaaaaaaaaaaaaaaa", state: "VALID", checkedInAt: null },
{ id: 2, typeName: "General", attendeeName: "Tan Mei Ling", code: "bbbbbbbbbbbbbbbbbbbbbb", state: "CHECKED_IN", checkedInAt: "2027-01-15T09:30:00" },
],
};
const ticket = (n: number) => screen.getAllByRole("listitem").filter((li) => li.textContent?.includes("Open ticket"))[n];
beforeEach(() => {
mocks.getPublicOrder.mockReset().mockResolvedValue(PAID);
mocks.nameAttendee.mockReset().mockResolvedValue({ id: 1, typeName: "General", attendeeName: "Lim Wei", code: "cccccccccccccccccccccc", state: "VALID", checkedInAt: null });
});
// add-event-tickets: a Paid order's page lists its tickets; the buyer names attendees.
describe("/o/[token] tickets", () => {
it("lists each ticket with its link and a copy button", async () => {
render(<OrderPage />);
await screen.findByText("Your tickets");
const first = ticket(0);
expect(within(first).getByText("Not named yet")).toBeInTheDocument();
expect(within(first).getByRole("link", { name: "Open ticket" })).toHaveAttribute("href", "/t/aaaaaaaaaaaaaaaaaaaaaa");
expect(within(first).getByRole("button", { name: "Copy link" })).toBeInTheDocument();
expect(within(ticket(1)).getByText("Tan Mei Ling")).toBeInTheDocument();
expect(within(ticket(1)).getByText("Checked in at 15 Jan 2027, 09:30")).toBeInTheDocument();
expect(within(ticket(1)).queryByRole("button", { name: "Name attendee" })).not.toBeInTheDocument();
});
it("shows no tickets for an order that is not paid", async () => {
mocks.getPublicOrder.mockResolvedValue({ ...PAID, status: "AWAITING", tickets: undefined, paymentInstructions: "Maybank" });
render(<OrderPage />);
await screen.findByText("Awaiting payment");
expect(screen.queryByText("Your tickets")).not.toBeInTheDocument();
});
it("names an attendee with the permission tick and shows the new link", async () => {
const user = userEvent.setup();
render(<OrderPage />);
await screen.findByText("Your tickets");
await user.click(within(ticket(0)).getByRole("button", { name: "Name attendee" }));
await user.type(screen.getByLabelText("Attendee name"), "Lim Wei");
await user.type(screen.getByLabelText("Email"), "lim@example.test");
await user.click(screen.getByRole("button", { name: "Save attendee" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Tick the box to confirm you have permission.");
expect(mocks.nameAttendee).not.toHaveBeenCalled();
await user.click(screen.getByRole("checkbox", { name: "I have permission to share these details so their ticket can be sent" }));
await user.click(screen.getByRole("button", { name: "Save attendee" }));
expect(await screen.findByText("Saved. The ticket has a new link; the old one no longer works.")).toBeInTheDocument();
expect(mocks.nameAttendee).toHaveBeenCalledWith(TOKEN, 1, { name: "Lim Wei", mobile: "", email: "lim@example.test", permission: true });
expect(within(ticket(0)).getByText("Lim Wei")).toBeInTheDocument();
expect(within(ticket(0)).getByRole("link", { name: "Open ticket" })).toHaveAttribute("href", "/t/cccccccccccccccccccccc");
});
it("asks for a name and a mobile or email before sending", async () => {
const user = userEvent.setup();
render(<OrderPage />);
await screen.findByText("Your tickets");
await user.click(within(ticket(0)).getByRole("button", { name: "Name attendee" }));
await user.click(screen.getByRole("checkbox", { name: "I have permission to share these details so their ticket can be sent" }));
await user.click(screen.getByRole("button", { name: "Save attendee" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Enter the attendee's name and a mobile number or an email.");
expect(mocks.nameAttendee).not.toHaveBeenCalled();
});
it("shows a refusal from the server", async () => {
mocks.nameAttendee.mockRejectedValue(new ApiError("x", 409, { code: "ALREADY_CHECKED_IN", error: "This ticket is already checked in and can no longer be changed." }));
const user = userEvent.setup();
render(<OrderPage />);
await screen.findByText("Your tickets");
await user.click(within(ticket(0)).getByRole("button", { name: "Name attendee" }));
await user.type(screen.getByLabelText("Attendee name"), "Lim Wei");
await user.type(screen.getByLabelText("Mobile number"), "0125550101");
await user.click(screen.getByRole("checkbox", { name: "I have permission to share these details so their ticket can be sent" }));
await user.click(screen.getByRole("button", { name: "Save attendee" }));
expect(await screen.findByRole("alert")).toHaveTextContent("This ticket is already checked in and can no longer be changed.");
});
});
@@ -0,0 +1,157 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
const mocks = vi.hoisted(() => ({ getPublicTicket: vi.fn(), getStaffTicket: vi.fn(), consentTicket: vi.fn(), checkInTicket: vi.fn() }));
vi.mock("@/app/lib/services/publicTickets", async (orig) => ({
...(await orig<object>()),
getPublicTicket: mocks.getPublicTicket,
getStaffTicket: mocks.getStaffTicket,
consentTicket: mocks.consentTicket,
checkInTicket: mocks.checkInTicket,
}));
vi.mock("next/navigation", () => ({ useParams: () => ({ code: "abcdefghijklmnopqrstu_" }) }));
import { ApiError } from "@/app/lib/clientApi";
import TicketPage from "./page";
const CODE = "abcdefghijklmnopqrstu_";
const EVENT = { eventName: "KL Hotel Tech Day", startDate: "2027-01-15", endDate: "2027-01-16", location: "KLCC" };
const NOTICE = { id: 9, textEn: "English notice", textMs: "Notis" };
const VALID = {
...EVENT, companyName: "INS", typeName: "General", attendeeFirstName: "Tan", named: true, state: "VALID",
checkedInAt: null, consented: false, notice: NOTICE,
};
const STAFF = {
...EVENT, companyName: "INS", typeName: "General", attendeeName: "Tan Mei Ling", named: true, consented: false, state: "VALID",
checkedInAt: null, checkedInBy: null, notice: NOTICE,
};
beforeEach(() => {
mocks.getPublicTicket.mockReset().mockResolvedValue(VALID);
mocks.getStaffTicket.mockReset().mockRejectedValue(new ApiError("x", 401, { error: "Not authenticated" }));
mocks.consentTicket.mockReset().mockResolvedValue({ consented: true });
mocks.checkInTicket.mockReset().mockResolvedValue({ ...STAFF, state: "CHECKED_IN", checkedInAt: "2027-01-15T09:30:00", checkedInBy: "door1" });
});
// add-event-tickets: the ticket page /t/<code>, public view and staff view.
describe("/t/[code] public view", () => {
it("shows the event, the ticket, its QR and the consent offer", async () => {
render(<TicketPage />);
expect(await screen.findByRole("heading", { level: 1, name: "KL Hotel Tech Day" })).toBeInTheDocument();
expect(mocks.getPublicTicket).toHaveBeenCalledWith(CODE);
expect(screen.getByText("General")).toBeInTheDocument();
expect(screen.getByText("Ticket for Tan")).toBeInTheDocument();
expect(screen.getByRole("img", { name: "Ticket QR code" })).toHaveAttribute("src", `/api/public/tickets/${CODE}/qr.png`);
expect(screen.getByText("Keep me updated about INS events")).toBeInTheDocument();
expect(screen.getByText("English notice")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("shows a checked-in ticket's time without a QR", async () => {
mocks.getPublicTicket.mockResolvedValue({ ...VALID, state: "CHECKED_IN", checkedInAt: "2027-01-15T09:30:00" });
render(<TicketPage />);
expect(await screen.findByText("Checked in at 15 Jan 2027, 09:30")).toBeInTheDocument();
expect(screen.queryByRole("img", { name: "Ticket QR code" })).not.toBeInTheDocument();
});
it.each(["AWAITING", "ORDER_CANCELLED", "ORDER_EXPIRED", "TICKET_CANCELLED"])("says a %s ticket is not valid, with no QR and no consent", async (state) => {
mocks.getPublicTicket.mockResolvedValue({ ...VALID, state, notice: undefined });
render(<TicketPage />);
expect(await screen.findByRole("alert")).toHaveTextContent("This ticket is not valid");
expect(screen.queryByRole("img", { name: "Ticket QR code" })).not.toBeInTheDocument();
expect(screen.queryByText("Keep me updated about INS events")).not.toBeInTheDocument();
});
it("says an unknown link is not valid", async () => {
mocks.getPublicTicket.mockRejectedValue(new ApiError("x", 404, { code: "TICKET_INVALID" }));
render(<TicketPage />);
expect(await screen.findByRole("alert")).toHaveTextContent("This ticket link is not valid.");
});
it("records the consent once ticked", async () => {
render(<TicketPage />);
const save = await screen.findByRole("button", { name: "Save" });
expect(save).toBeDisabled();
fireEvent.click(screen.getByRole("checkbox", { name: "Keep me updated about INS events" }));
fireEvent.click(save);
expect(await screen.findByText("Thank you. We will keep you updated.")).toBeInTheDocument();
expect(mocks.consentTicket).toHaveBeenCalledWith(CODE);
});
it("offers no consent without a notice", async () => {
mocks.getPublicTicket.mockResolvedValue({ ...VALID, named: false, attendeeFirstName: null, notice: undefined });
render(<TicketPage />);
await screen.findByRole("img", { name: "Ticket QR code" });
expect(screen.queryByText("Keep me updated about INS events")).not.toBeInTheDocument();
expect(screen.queryByText(/Ticket for/)).not.toBeInTheDocument();
});
});
describe("/t/[code] staff view", () => {
it.each([403, 404])("keeps the public view on a %s", async (status) => {
mocks.getStaffTicket.mockRejectedValue(new ApiError("x", status, {}));
render(<TicketPage />);
await screen.findByRole("img", { name: "Ticket QR code" });
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("needs only the staff call, so the public limit never blocks door staff", async () => {
mocks.getStaffTicket.mockResolvedValue(STAFF);
mocks.getPublicTicket.mockRejectedValue(new ApiError("x", 429, { code: "TOO_MANY" }));
render(<TicketPage />);
expect(await screen.findByRole("button", { name: "Check in" })).toBeInTheDocument();
expect(screen.getByRole("heading", { level: 1, name: "KL Hotel Tech Day" })).toBeInTheDocument();
expect(mocks.getPublicTicket).not.toHaveBeenCalled();
expect(screen.queryByRole("img", { name: "Ticket QR code" })).not.toBeInTheDocument();
});
it("shows the state banner and checks a named ticket in", async () => {
mocks.getStaffTicket.mockResolvedValue(STAFF);
render(<TicketPage />);
expect(await screen.findByText("Valid")).toBeInTheDocument();
expect(screen.getByText("Tan Mei Ling")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Check in" }));
expect(await screen.findByText("Checked in.")).toBeInTheDocument();
expect(mocks.checkInTicket).toHaveBeenCalledWith(CODE, { consent: false });
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("asks for the attendee of an unnamed ticket and sends the consent", async () => {
mocks.getStaffTicket.mockResolvedValue({ ...STAFF, named: false, attendeeName: null });
render(<TicketPage />);
expect(await screen.findByText("No attendee named yet")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Attendee name"), { target: { value: "Lim Wei" } });
fireEvent.change(screen.getByLabelText("Mobile number"), { target: { value: "012-555 0101" } });
fireEvent.click(screen.getByRole("checkbox", { name: "Keep me updated about INS events" }));
fireEvent.click(screen.getByRole("button", { name: "Check in" }));
await screen.findByText("Checked in.");
expect(mocks.checkInTicket).toHaveBeenCalledWith(CODE, { name: "Lim Wei", mobile: "012-555 0101", email: "", consent: true });
});
it("shows a second scan as already checked in", async () => {
mocks.getStaffTicket.mockResolvedValue({ ...STAFF, state: "CHECKED_IN", checkedInAt: "2027-01-15T09:30:00", checkedInBy: "door1" });
render(<TicketPage />);
expect(await screen.findByText("Already checked in at 15 Jan 2027, 09:30")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("shows an unpaid ticket as not valid with no Check in", async () => {
mocks.getStaffTicket.mockResolvedValue({ ...STAFF, state: "AWAITING" });
render(<TicketPage />);
expect(await screen.findByText("Not valid: awaiting payment")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it.each([
[{ code: "ALREADY_CHECKED_IN", details: { value: "2027-01-15T09:30" } }, "Already checked in at 15 Jan 2027, 09:30"],
[{ code: "NOT_VALID", details: { value: "ORDER_CANCELLED" } }, "Not valid: order cancelled"],
[{ code: "NOT_EVENT_DAY" }, "Check-in is only open on the event days."],
[{ code: "MOBILE_OR_EMAIL_REQUIRED", error: "MOBILE_OR_EMAIL_REQUIRED", details: { field: "mobile" } }, "Enter a mobile number or an email."],
])("shows the refusal %o", async (data, text) => {
mocks.getStaffTicket.mockResolvedValue(STAFF);
mocks.checkInTicket.mockRejectedValue(new ApiError("x", 409, data));
render(<TicketPage />);
fireEvent.click(await screen.findByRole("button", { name: "Check in" }));
expect(await screen.findByRole("alert")).toHaveTextContent(text);
});
});
+224
View File
@@ -0,0 +1,224 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { useParams } from "next/navigation";
import { AlertCircle, CheckCircle2, Loader2, XCircle } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { VisitorCard, VisitorState } from "@/app/components/registration/VisitorCard";
import { apiData, failMessage } from "@/app/components/registration/RegistrationForm";
import { ApiError } from "@/app/lib/clientApi";
import {
checkInTicket, consentTicket, getPublicTicket, getStaffTicket, ticketQrUrl, when,
type PublicTicket, type StaffTicket, type TicketNotice, type TicketState,
} from "@/app/lib/services/publicTickets";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type T = ReturnType<typeof useT>;
const REASON: Partial<Record<TicketState, string>> = {
AWAITING: "TktReasonAWAITING",
ORDER_CANCELLED: "TktReasonORDER_CANCELLED",
ORDER_EXPIRED: "TktReasonORDER_EXPIRED",
TICKET_CANCELLED: "TktReasonTICKET_CANCELLED",
};
const NOTICE = "space-y-2 rounded-md bg-muted p-3 text-xs text-muted-foreground";
/** add-event-tickets: one ticket, /t/<code>. Everyone sees the public view; staff of the event's company also get the staff view. */
export default function TicketPage() {
const t = useT();
const { code } = useParams<{ code: string }>();
const [ticket, setTicket] = useState<PublicTicket | null>(null);
const [staff, setStaff] = useState<StaffTicket | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Staff first: a door scan then never touches the rate-limited public view. Signed out, another company's staff
// or no BO_EVENTS: the staff call fails and the page loads the public view.
getStaffTicket(code)
.then(setStaff)
.catch(() => getPublicTicket(code)
.then(setTicket)
.catch((err) => {
const c = apiData(err).code;
setError(t(c === "TICKET_INVALID" ? "TktTicketInvalid" : c === "TOO_MANY" ? "RegTooMany" : "RegLoadFailed"));
}));
}, [code, t]);
const shown = staff ?? ticket;
if (error) return <VisitorCard><VisitorState h1 icon={AlertCircle} heading={error} role="alert" tone="error" /></VisitorCard>;
if (!shown) return <VisitorCard><VisitorState h1 icon={Loader2} iconClassName="motion-safe:animate-spin" heading={t("UiLoading")} role="status" /></VisitorCard>;
const event = { ...shown, companyName: shown.companyName ?? "", startDate: shown.startDate ?? shown.endDate ?? "",
endDate: shown.endDate ?? "", location: shown.location ?? "" };
return (
<VisitorCard event={event}>
{staff ? <StaffView code={code} staff={staff} companyName={event.companyName} onChange={setStaff} />
: ticket && <PublicView code={code} ticket={ticket} />}
</VisitorCard>
);
}
function PublicView({ code, ticket }: { code: string; ticket: PublicTicket }) {
const t = useT();
return (
<div className="space-y-4">
<div className="space-y-1 text-center">
{ticket.typeName && <p className="font-semibold">{ticket.typeName}</p>}
{ticket.attendeeFirstName && <p className="text-sm text-muted-foreground">{t("TktTicketFor", { name: ticket.attendeeFirstName })}</p>}
</div>
{ticket.state === "VALID" && (
<div className="flex flex-col items-center gap-2">
{/* eslint-disable-next-line @next/next/no-img-element -- a private, short-lived PNG from our own proxy */}
<img src={ticketQrUrl(code)} alt={t("TktQrAlt")} width={240} height={240} className="rounded-md border bg-white p-2" />
<p className="text-sm text-muted-foreground">{t("TktShowQr")}</p>
</div>
)}
{ticket.state === "CHECKED_IN" && (
<VisitorState icon={CheckCircle2} role="status" heading={t("TktCheckedInAt", { when: when(ticket.checkedInAt) })} />
)}
{ticket.state !== "VALID" && ticket.state !== "CHECKED_IN" && (
<VisitorState icon={XCircle} role="alert" tone="error" heading={t("TktNotValid")} />
)}
{ticket.notice && <PublicConsent code={code} notice={ticket.notice} companyName={ticket.companyName} />}
</div>
);
}
function NoticeText({ notice }: { notice: TicketNotice }) {
const t = useT();
return (
<details className={NOTICE}>
<summary className="cursor-pointer font-medium text-foreground">{t("RegNoticeSummary")}</summary>
<div className="mt-2 space-y-2">
<h2 className="font-semibold text-foreground">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{notice.textEn}</p>
<h2 className="font-semibold text-foreground">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{notice.textMs}</p>
</div>
</details>
);
}
function ConsentBox({ id, checked, onChange, companyName }: { id: string; checked: boolean; onChange: (on: boolean) => void; companyName: string }) {
const t = useT();
return (
<Label htmlFor={id} className="flex items-start gap-3 font-normal">
<Checkbox id={id} className="mt-0.5 size-5" checked={checked} onCheckedChange={(on) => onChange(on === true)} />
<span>{t("TktKeepUpdated", { company: companyName })}</span>
</Label>
);
}
function PublicConsent({ code, notice, companyName }: { code: string; notice: TicketNotice; companyName: string }) {
const t = useT();
const [on, setOn] = useState(false);
const [saving, setSaving] = useState(false);
const [done, setDone] = useState(false);
const [error, setError] = useState<string | null>(null);
if (done) return <p role="status" className="text-sm">{t("TktConsentDone")}</p>;
const save = () => {
setSaving(true);
setError(null);
consentTicket(code)
.then(() => setDone(true))
.catch((err) => setError(failMessage(t, err)))
.finally(() => setSaving(false));
};
return (
<div className="space-y-3 border-t pt-4">
<ConsentBox id="tkt-consent" checked={on} onChange={setOn} companyName={companyName} />
<NoticeText notice={notice} />
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<Button type="button" className="h-11 w-full" disabled={!on || saving} onClick={save}>{t("TktConsentSave")}</Button>
</div>
);
}
/** A refused check-in as the sentence staff read. */
function refusal(t: T, err: unknown): string {
const d = (err instanceof ApiError ? err.data : undefined) as { code?: string; details?: { value?: string } } | undefined;
const value = d?.details?.value;
switch (d?.code) {
case "ALREADY_CHECKED_IN": return t("TktAlreadyCheckedIn", { when: when(value) });
case "NOT_VALID": return t("TktNotValidReason", { reason: t(REASON[value as TicketState] ?? "TktNotValid") });
case "NOT_EVENT_DAY": return t("TktNotEventDay");
case "NAME_REQUIRED": return t("RegNameRequired");
case "MOBILE_OR_EMAIL_REQUIRED": return t("TktContactRequired");
default: return failMessage(t, err);
}
}
function StaffView({ code, staff, companyName, onChange }: {
code: string; staff: StaffTicket; companyName: string; onChange: (s: StaffTicket) => void;
}) {
const t = useT();
const [form, setForm] = useState({ name: "", mobile: "", email: "", consent: false });
const [saving, setSaving] = useState(false);
const [justCheckedIn, setJustCheckedIn] = useState(false);
const [error, setError] = useState<string | null>(null);
const submit = (e: FormEvent) => {
e.preventDefault();
setSaving(true);
setError(null);
checkInTicket(code, staff.named ? { consent: form.consent } : form)
.then((s) => {
setJustCheckedIn(true);
onChange(s);
})
.catch((err) => setError(refusal(t, err)))
.finally(() => setSaving(false));
};
const banner = justCheckedIn ? { tone: "ok", text: t("TktCheckedInNow") }
: staff.state === "VALID" ? { tone: "ok", text: t("TktStaffValid") }
: staff.state === "CHECKED_IN" ? { tone: "warn", text: t("TktAlreadyCheckedIn", { when: when(staff.checkedInAt) }) }
: { tone: "bad", text: t("TktNotValidReason", { reason: t(REASON[staff.state] ?? "TktNotValid") }) };
const tone = banner.tone === "ok" ? "border-2 border-positive bg-positive/10 text-positive"
: banner.tone === "warn" ? "border-2 border-warning bg-warning/10 text-warning" : "bg-destructive text-destructive-foreground";
return (
<div className="space-y-4">
<p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{t("TktStaffView")}</p>
<p role={banner.tone === "bad" ? "alert" : "status"} className={`rounded-md p-4 text-center text-xl font-semibold ${tone}`}>{banner.text}</p>
<div className="space-y-1 text-center">
{staff.typeName && <p className="font-semibold">{staff.typeName}</p>}
<p className="text-sm">{staff.attendeeName ?? t("TktUnnamed")}</p>
</div>
{staff.state === "VALID" && !justCheckedIn && (
<form onSubmit={submit} className="space-y-3" noValidate>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{!staff.named && (
<>
<div className="space-y-1">
<Label htmlFor="tkt-name">{t("TktAttendeeName")}</Label>
<Input id="tkt-name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
</div>
<div className="space-y-1">
<Label htmlFor="tkt-mobile">{t("RegMobile")}</Label>
<Input id="tkt-mobile" type="tel" value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} />
<p className="text-xs text-muted-foreground">{t("RegContactHint")}</p>
</div>
<div className="space-y-1">
<Label htmlFor="tkt-email">{t("RegEmail")}</Label>
<Input id="tkt-email" type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
</div>
</>
)}
{staff.notice && !staff.consented && (
<>
<ConsentBox id="tkt-staff-consent" checked={form.consent} onChange={(on) => setForm({ ...form, consent: on })} companyName={companyName} />
<NoticeText notice={staff.notice} />
</>
)}
<Button type="submit" className="h-12 w-full text-base" disabled={saving}>{t("TktCheckIn")}</Button>
</form>
)}
</div>
);
}
-1
View File
@@ -1 +0,0 @@
<?xml version="1.0"?><svg id="a" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4000 4000"><path d="M2186.36,1601.76c-24.12,17.98-58.25,13.01-76.24-11.11-282.34-378.65-297.94-846.34-34.79-1042.55,24.12-17.98,58.25-13.01,76.24,11.11s13.01,58.25-11.11,76.24c-214.99,160.3-189.41,559.59,57.01,890.08,17.98,24.12,13.01,58.25-11.11,76.24Z" fill="#8e3b19"></path><path d="M2635.68,951.73c-75.77-7.45-150.69,3.21-222.99,29.66-337,123.31-699.95,146.55-1057.37,114.64-67.05-5.99-133.3.63-197.22,21.17-401.04,128.82-558.27,755.87-351.19,1400.57,207.08,644.7,700.06,1062.9,1101.1,934.09,21.26-6.83,41.82-15.07,61.67-24.64,118.07-56.93,251.94-66.89,380.59-41.76,14.91,2.91,30.01,5.13,45.29,6.63,419.19,41.25,812.78-471.61,879.08-1145.49,66.31-673.89-219.76-1253.62-638.96-1294.86Z" fill="#de0d06"></path><ellipse cx="1440.04" cy="1951.4" rx="363.18" ry="541" transform="translate(-77.15 59.36) rotate(-2.3)" fill="#f23f3a"></ellipse><path d="M1827.99,2875.26c62.28,135.79,38.86,279.77-52.3,321.58-91.16,41.81-215.55-34.38-277.82-170.18-62.28-135.79-38.86-279.76,52.3-321.57,91.16-41.81,215.55,34.38,277.82,170.17Z" fill="#f23f3a"></path></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

@@ -64,6 +64,10 @@ public class JWTAuthFilter implements GlobalFilter, Ordered {
publicPath(HttpMethod.POST, "/counter/ticketOrder/request"),
publicPath(HttpMethod.GET, "/counter/ticketOrder/byToken/[A-Za-z0-9_-]{22}"),
publicPath(HttpMethod.GET, "/counter/ticketType/onSale/\\d{1,19}"),
// Tickets (add-event-tickets): a ticket by its code, naming an attendee by the order token, attendee consent. Check-in needs a token.
publicPath(HttpMethod.GET, "/counter/ticket/byCode/[A-Za-z0-9_-]{22}"),
publicPath(HttpMethod.POST, "/counter/ticket/attendee"),
publicPath(HttpMethod.POST, "/counter/ticket/consent"),
// Password hint on public password screens: switched-on rule names and numbers only, no user data
publicPath(HttpMethod.GET, "/passwordRule/adminActive"),
// WhatsApp webhook forward from mobile-api: no user token; the service re-verifies Meta's signature itself
@@ -0,0 +1,81 @@
package com.solvway.gateway.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.gateway.model.AuthAppKey;
import com.solvway.gateway.model.AuthAppKeyMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.util.ReflectionTestUtils;
import reactor.core.publisher.Mono;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
/** add-event-tickets: a ticket by its code, naming an attendee and attendee consent are open; staff check-in stays closed. */
class JWTAuthFilterTicketCodesPathTest {
private static final String KEY = "gateway-test-key";
private JWTAuthFilter filter;
@BeforeEach
void setUp() throws Exception {
AuthAppKey key = new ObjectMapper().readValue(
"{\"key\":\"" + KEY + "\",\"type\":\"BO\",\"ipList\":[\"0.0.0.0/0\"],\"allowList\":[\"/\"]}",
AuthAppKey.class);
AuthAppKeyMap map = new AuthAppKeyMap();
map.add(KEY, key);
filter = new JWTAuthFilter();
ReflectionTestUtils.setField(filter, "authAppKeyMap", map);
}
private MockServerWebExchange call(HttpMethod method, String path) {
return MockServerWebExchange.from(MockServerHttpRequest.method(method, path)
.header("api-key", KEY)
.remoteAddress(new InetSocketAddress("127.0.0.1", 40000)));
}
private boolean passes(MockServerWebExchange exchange) {
AtomicBoolean called = new AtomicBoolean(false);
GatewayFilterChain chain = ex -> {
called.set(true);
return Mono.empty();
};
filter.filter(exchange, chain).block();
return called.get();
}
@Test
void publicTicketCodeCallsNeedNoUserToken() {
for (String[] c : new String[][] {
{"GET", "/counter/ticket/byCode/abcdefghijklmnopqrstu_"},
{"POST", "/counter/ticket/attendee"},
{"POST", "/counter/ticket/consent"} }) {
assertThat(passes(call(HttpMethod.valueOf(c[0]), c[1]))).as(c[0] + " " + c[1]).isTrue();
}
}
@Test
void otherTicketShapesAndStaffCallsNeedAUserToken() {
for (String[] c : new String[][] {
{"GET", "/counter/ticket/byCode/short"},
{"GET", "/counter/ticket/byCode/abcdefghijklmnopqrstuvw"},
{"GET", "/counter/ticket/byCode/abcdefghijklmnopqrstu_/x"},
{"POST", "/counter/ticket/byCode/abcdefghijklmnopqrstu_"},
{"GET", "/counter/ticket/attendee"},
{"GET", "/counter/ticket/consent"},
{"POST", "/counter/ticket/staff"},
{"POST", "/counter/ticket/checkin"} }) {
MockServerWebExchange exchange = call(HttpMethod.valueOf(c[0]), c[1]);
assertThat(passes(exchange)).as(c[0] + " " + c[1]).isFalse();
assertThat(exchange.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED);
}
}
}
+6
View File
@@ -67,6 +67,12 @@
<artifactId>libphonenumber</artifactId>
<version>8.13.55</version>
</dependency>
<!-- Ticket QR as a PNG for emails (add-event-tickets): core only, no transitive dependencies; written with ImageIO. -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -60,6 +60,12 @@ public class RestApiCounterServiceConstants {
public static final String API_REST_COUNTER_TICKET_TYPE_ON_SALE = "/counter/ticketType/onSale/{eventUuid}";
public static final String API_REST_COUNTER_TICKET_ORDER_REQUEST = "/counter/ticketOrder/request";
public static final String API_REST_COUNTER_TICKET_ORDER_BY_TOKEN = "/counter/ticketOrder/byToken/{token}";
public static final String API_REST_COUNTER_TICKET_BY_CODE = "/counter/ticket/byCode/{code}";
public static final String API_REST_COUNTER_TICKET_ATTENDEE = "/counter/ticket/attendee";
public static final String API_REST_COUNTER_TICKET_CONSENT = "/counter/ticket/consent";
public static final String API_REST_COUNTER_TICKET_STAFF = "/counter/ticket/staff";
public static final String API_REST_COUNTER_TICKET_CHECKIN = "/counter/ticket/checkin";
public static final String API_REST_COUNTER_TICKET_ORDER_RESEND_TICKET = "/counter/ticketOrder/resendTicket";
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}";
@@ -0,0 +1,41 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminTicketService;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/** add-event-tickets: the staff view of a scanned ticket and door check-in. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin/tickets/{code}")
@RequiredArgsConstructor
public class AdminTicketCodeController {
private final AdminTicketService tickets;
@AppAuth
@AdminModule("BO_EVENTS")
@GetMapping
public ResponseEntity<Map<String, Object>> ticket(@PathVariable String code) {
return ResponseEntity.ok(tickets.ticket(code));
}
/** The ticket code is a bearer link, so it is not recorded as the audit target; the ticket keeps who checked it in. */
@AppAuth
@AdminModule("BO_EVENTS")
@Audited(target = false)
@PostMapping("/checkin")
public ResponseEntity<Map<String, Object>> checkIn(@PathVariable String code,
@RequestBody(required = false) AdminTicketService.CheckInBody body) {
return ResponseEntity.ok(tickets.checkIn(code, body));
}
}
@@ -127,4 +127,13 @@ public class AdminTicketController {
tickets.resend(uuid, orderId);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited(targetVariable = "ticketId")
@PostMapping("/orders/{orderId}/tickets/{ticketId}/resend")
public ResponseEntity<Void> resendTicket(@PathVariable String uuid, @PathVariable String orderId, @PathVariable String ticketId) {
tickets.resendTicket(uuid, orderId, ticketId);
return ResponseEntity.noContent().build();
}
}
@@ -4,6 +4,7 @@ import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.PublicPageFormRequest;
import com.solvway.mobile.api.dto.PublicTicketRequest;
import com.solvway.mobile.api.service.PublicPageService;
import com.solvway.mobile.api.service.PublicTicketService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@@ -19,6 +20,7 @@ import java.util.Map;
@RequiredArgsConstructor
public class PublicPageController {
private final PublicPageService pages;
private final PublicTicketService tickets;
@AppAuth(skipValidate = true)
@GetMapping("/api/public/pages/{company}/{slug}")
@@ -51,4 +53,29 @@ public class PublicPageController {
public ResponseEntity<byte[]> image(@PathVariable long id) {
return pages.image(id);
}
@AppAuth(skipValidate = true)
@GetMapping("/api/public/tickets/{code}")
public ResponseEntity<Map<String, Object>> ticket(@PathVariable String code) {
return ResponseEntity.ok(tickets.ticket(code));
}
@AppAuth(skipValidate = true)
@GetMapping("/api/public/tickets/{code}/qr.png")
public ResponseEntity<byte[]> ticketQr(@PathVariable String code) {
return tickets.qr(code);
}
@AppAuth(skipValidate = true)
@PostMapping("/api/public/tickets/{code}/consent")
public ResponseEntity<Map<String, Object>> ticketConsent(@PathVariable String code, @RequestBody PublicTicketService.ConsentRequest request) {
return ResponseEntity.ok(tickets.consent(code, request));
}
@AppAuth(skipValidate = true)
@PostMapping("/api/public/orders/{token}/tickets/{ticketId}/attendee")
public ResponseEntity<Map<String, Object>> attendee(@PathVariable String token, @PathVariable long ticketId,
@RequestBody PublicTicketService.AttendeeRequest request) {
return ResponseEntity.ok(tickets.attendee(token, ticketId, request));
}
}
@@ -2,6 +2,7 @@ package com.solvway.mobile.api.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
@@ -31,10 +32,12 @@ public class AdminTicketService {
private static final ObjectMapper JSON = new ObjectMapper();
private static final int PAGE_SIZE = 50;
/** The form field a counter refusal belongs to, so the portal can show it beside that field. */
private static final Map<String, String> FIELDS = Map.of(
"PAYMENT_INSTRUCTIONS_REQUIRED", "paymentInstructions", "PAYMENT_INSTRUCTIONS_TOO_LONG", "paymentInstructions",
"HOLD_DAYS_INVALID", "holdDays", "NAME_INVALID", "name", "NAME_TAKEN", "name", "PRICE_INVALID", "priceSen",
"QUANTITY_INVALID", "quantity", "QUANTITY_BELOW_HELD", "quantity", "PAYMENT_REF_TOO_LONG", "paymentRef");
private static final Map<String, String> FIELDS = Map.ofEntries(
Map.entry("PAYMENT_INSTRUCTIONS_REQUIRED", "paymentInstructions"), Map.entry("PAYMENT_INSTRUCTIONS_TOO_LONG", "paymentInstructions"),
Map.entry("HOLD_DAYS_INVALID", "holdDays"), Map.entry("NAME_INVALID", "name"), Map.entry("NAME_TAKEN", "name"),
Map.entry("PRICE_INVALID", "priceSen"), Map.entry("QUANTITY_INVALID", "quantity"), Map.entry("QUANTITY_BELOW_HELD", "quantity"),
Map.entry("PAYMENT_REF_TOO_LONG", "paymentRef"), Map.entry("NAME_REQUIRED", "name"), Map.entry("NAME_TOO_LONG", "name"),
Map.entry("MOBILE_OR_EMAIL_REQUIRED", "mobile"));
private final RestTemplateCustomUtil rest;
private final AdminEventLeadService leads;
@@ -45,6 +48,11 @@ public class AdminTicketService {
public record PayBody(String paymentRef) {}
/** Door check-in: name, mobile and email only for an unnamed ticket; consent ticked by the attendee at the door. */
public record CheckInBody(String name, String mobile, String email, Boolean consent) {}
private record Staff(CompanyEvent event, Map<String, Object> body) {}
public Map<String, Object> settings(String uuid) {
CompanyEvent e = leads.loadEvent(uuid, null);
Map<String, Object> out = new LinkedHashMap<>();
@@ -127,6 +135,78 @@ public class AdminTicketService {
post(API_REST_COUNTER_TICKET_ORDER_RESEND, MAP, orderBody(read(uuid), orderId));
}
public void resendTicket(String uuid, String orderId, String ticketId) {
Map<String, Object> body = orderBody(write(uuid), orderId);
body.put("ticketId", AdminEventLeadService.parseOr(ticketId, AdminTicketService::ticketNotFound));
post(API_REST_COUNTER_TICKET_ORDER_RESEND_TICKET, MAP, body);
}
/** add-event-tickets: the staff view of a scanned ticket; only for the event's company (super admins: any), else not found. */
public Map<String, Object> ticket(String code) {
Staff s = staff(code);
return view(post(API_REST_COUNTER_TICKET_STAFF, MAP, s.body()), s.event());
}
/** Door check-in; the counter refuses a second check-in, an invalid ticket and a day outside the event. */
public Map<String, Object> checkIn(String code, CheckInBody b) {
Staff s = staff(code);
Map<String, Object> body = s.body();
if (b != null) {
body.put("name", AdminEventLeadService.trimmed(b.name()));
body.put("mobileE164", AdminEventLeadService.mobile(b.mobile()));
body.put("email", AdminEventLeadService.email(b.email()));
if (Boolean.TRUE.equals(b.consent())) body.put("noticeId", notice(s.event()).get("id"));
}
body.put("doneBy", leads.caller().getUsername());
return view(post(API_REST_COUNTER_TICKET_CHECKIN, MAP, body), s.event());
}
private Staff staff(String code) {
if (code == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(code).matches()) throw ticketNotFound();
Map<String, Object> t = PublicRegistrationService.found(() -> rest.getForEntity(rest.getURLforApiService(API_REST_COUNTER_TICKET_BY_CODE),
MAP, code).getBody());
if (t == null || !(t.get("eventUuid") instanceof Number uuid)) throw ticketNotFound();
CompanyEvent e;
try {
e = leads.loadEvent(String.valueOf(uuid.longValue()), null);
} catch (com.solvway.mobile.api.errorhandler.CodedResponseStatusException x) {
if (x.getStatusCode().value() == 404) throw ticketNotFound(); // another company's ticket looks unknown
throw x;
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", e.getCompanyId());
body.put("code", code);
return new Staff(e, body);
}
private Map<String, Object> view(Map<String, Object> staffView, CompanyEvent e) {
Map<String, Object> out = new LinkedHashMap<>(staffView == null ? Map.of() : staffView);
out.put("eventName", e.getName());
out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
out.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
out.put("location", e.getLocation());
Map<String, Object> company = PublicRegistrationService.found(() -> rest.getForEntity(
rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_BY_ID), MAP, e.getCompanyId()).getBody());
out.put("companyName", company == null ? null : company.get("name"));
if (!Boolean.TRUE.equals(out.get("consented"))) {
Map<String, Object> n = notice(e);
if (n.get("id") != null) {
out.put("notice", Map.of("id", n.get("id"), "textEn", String.valueOf(n.get("textEn")), "textMs", String.valueOf(n.get("textMs"))));
}
}
return out;
}
private Map<String, Object> notice(CompanyEvent e) {
Map<String, Object> n = PublicRegistrationService.found(() -> rest.getForEntity(
rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE), MAP, e.getCompanyId()).getBody());
return n == null ? Map.of() : n;
}
private static com.solvway.mobile.api.errorhandler.CodedResponseStatusException ticketNotFound() {
return AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Ticket not found", "TICKET_NOT_FOUND", null);
}
private Map<String, Object> read(String uuid) {
CompanyEvent e = leads.loadEvent(uuid, null);
Map<String, Object> body = new LinkedHashMap<>();
@@ -163,7 +243,11 @@ public class AdminTicketService {
} catch (Exception ignored) {
// not a ProblemDetail: keep the generic code
}
throw AdminEventLeadService.error(HttpStatus.valueOf(e.getStatusCode().value()), code, code, FIELDS.get(code));
// "CODE|value" (add-event-tickets: ALREADY_CHECKED_IN|<time>, NOT_VALID|<state>): the value goes in details
String[] p = code.split("\\|", 2);
var x = AdminEventLeadService.error(HttpStatus.valueOf(e.getStatusCode().value()), p[0], p[0], FIELDS.get(p[0]));
if (p.length > 1) x.getBody().setProperty("details", Map.of("value", p[1]));
throw x;
}
}
}
@@ -123,6 +123,7 @@ public class PublicInviteService {
body.put(email ? "email" : "mobileE164", normalised);
Map<String, Object> out = post(RestApiCounterServiceConstants.API_REST_COUNTER_CHECKIN_LOOKUP, body);
if (out != null && "CHECKED_IN".equals(out.get("result"))) return Map.of("result", "CHECKED_IN", "firstName", firstName(out));
if (out != null && "SHOW_TICKET".equals(out.get("result"))) return Map.of("result", "SHOW_TICKET"); // a ticketed event
return Map.of("result", "FORM");
}
@@ -167,7 +168,7 @@ public class PublicInviteService {
}
}
/** A counter 409 (EVENT_FULL, NOT_REGISTERED, NOT_EVENT_DAY) goes to the visitor with its own code. */
/** A counter 409 (EVENT_FULL, NOT_REGISTERED, NOT_EVENT_DAY, TICKETS_ONLY) goes to the visitor with its own code. */
private Map<String, Object> post(String api, Object body) {
try {
return rest.postForEntity(url(api), MAP, body).getBody();
@@ -177,12 +178,13 @@ public class PublicInviteService {
case "EVENT_FULL" -> "This event is full";
case "NOT_REGISTERED" -> "Register before checking in";
case "NOT_EVENT_DAY" -> "Check-in opens on the event day";
case "TICKETS_ONLY" -> "Please show your ticket at the entrance.";
default -> "This could not be completed";
}, code, null);
}
}
private static String counterCode(HttpClientErrorException e) {
static String counterCode(HttpClientErrorException e) {
try {
// The counter's core error handler sends a ProblemDetail whose "detail" is the reason code.
com.fasterxml.jackson.databind.JsonNode body = new ObjectMapper().readTree(e.getResponseBodyAsString());
@@ -257,6 +257,7 @@ public class PublicPageService {
out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
out.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
out.put("location", e.getLocation());
if ("PAID".equals(o.get("status"))) out.put("tickets", o.get("tickets") instanceof List<?> l ? l : List.of());
if ("AWAITING".equals(o.get("status"))) {
out.put("holdUntil", o.get("holdUntil"));
out.put("paymentInstructions", e.getPaymentInstructions());
@@ -0,0 +1,212 @@
package com.solvway.mobile.api.service;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* add-event-tickets, public side: the ticket page by its code, the ticket's QR as a PNG for emails, attendee consent, and the buyer
* naming a ticket's attendee by the order's link token. Inputs are normalised as in QR registration; no attendee contact goes out.
*/
@Service
@SuppressWarnings("unchecked")
public class PublicTicketService {
private static final int LOAD_LIMIT = 120;
private static final int SUBMIT_LIMIT = 60;
private static final int ORDER_LOAD_LIMIT = 120;
private static final int QR_PX = 300;
private static final String TOO_MANY = "Too many requests from this device. Try again later.";
private static final Set<String> CONSENT_STATES = Set.of("VALID", "CHECKED_IN");
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
public record AttendeeRequest(String name, String mobile, String email, Boolean permission) {}
public record ConsentRequest(Boolean consent) {}
private record Loaded(Map<String, Object> ticket, PublicRegistrationService.Open open) {}
private final RestTemplateCustomUtil rest;
private final PublicRegistrationService registration;
private final String portalBase;
public PublicTicketService(RestTemplateCustomUtil rest, PublicRegistrationService registration,
@Value("${app.admin-portal-base-url}") String portalBase) {
this.rest = rest;
this.registration = registration;
this.portalBase = portalBase.replaceAll("/+$", "");
}
/** The public ticket page: event, ticket type, attendee first name and state; the consent offer only for a named valid ticket. */
public Map<String, Object> ticket(String code) {
Loaded l = load(code);
Map<String, Object> out = new LinkedHashMap<>();
for (String k : List.of("typeName", "attendeeFirstName", "named", "state", "checkedInAt", "consented")) out.put(k, l.ticket().get(k));
CompanyEvent e = l.open().event();
out.put("eventName", e.getName());
out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
out.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
out.put("location", e.getLocation());
out.put("companyName", l.open().companyName());
if (offersConsent(l.ticket())) {
Map<String, Object> n = l.open().notice();
out.put("notice", Map.of("id", n.get("id"), "textEn", String.valueOf(n.get("textEn")), "textMs", String.valueOf(n.get("textMs"))));
}
return out;
}
/** The ticket's QR for emails: encodes the ticket page link; only while the ticket is valid. */
public ResponseEntity<byte[]> qr(String code) {
Loaded l = load(code);
if (!"VALID".equals(l.ticket().get("state"))) throw invalid();
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePrivate())
.body(png(portalBase + "/t/" + code));
}
/** The attendee opts in on their ticket page, under the company's current notice. */
public Map<String, Object> consent(String code, ConsentRequest r) {
Loaded l = load(code);
registration.limit("tkt:submit:" + PublicRegistrationService.ip() + ":" + l.open().event().getUuid(), SUBMIT_LIMIT, TOO_MANY);
if (r == null || !Boolean.TRUE.equals(r.consent())) {
throw AdminEventLeadService.error(HttpStatus.BAD_REQUEST, "Please tick the box to be kept updated.", "CONSENT_REQUIRED", "consent");
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("code", code);
body.put("noticeId", l.open().notice().get("id"));
try {
rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_CONSENT), Void.class, body);
} catch (HttpClientErrorException e) {
throw refusal(e);
}
return Map.of("consented", true);
}
/** The buyer names or renames a ticket of their Paid order; the counter issues a new code and emails the attendee. */
public Map<String, Object> attendee(String token, long ticketId, AttendeeRequest r) {
if (token == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(token).matches()) throw orderInvalid();
// Probing order tokens counts as order loads, as on the order page, before the per-event submit limit.
registration.limit("ord:load:" + PublicRegistrationService.ip(), ORDER_LOAD_LIMIT, TOO_MANY);
Map<String, Object> order = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ORDER_BY_TOKEN), MAP, token).getBody());
if (order == null || !(order.get("eventUuid") instanceof Number uuid)) throw orderInvalid();
registration.limit("tkt:submit:" + PublicRegistrationService.ip() + ":" + uuid.longValue(), SUBMIT_LIMIT, TOO_MANY);
if (r == null) throw AdminEventLeadService.required(List.of("name"));
String name = AdminEventLeadService.trimmed(r.name());
String mobile = AdminEventLeadService.mobile(r.mobile());
String email = AdminEventLeadService.email(r.email());
List<String> missing = new ArrayList<>();
if (name == null) missing.add("name");
if (mobile == null && email == null) {
missing.add("mobile");
missing.add("email");
}
if (!missing.isEmpty()) throw AdminEventLeadService.required(missing);
AdminEventLeadService.maxLength("name", name, 100);
AdminEventLeadService.maxLength("email", email, 254);
if (!Boolean.TRUE.equals(r.permission())) {
throw AdminEventLeadService.error(HttpStatus.BAD_REQUEST, "Please confirm you have permission to share these details.",
"PERMISSION_REQUIRED", "permission");
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("orderToken", token);
body.put("ticketId", ticketId);
body.put("name", name);
body.put("mobileE164", mobile);
body.put("email", email);
body.put("permission", true);
try {
Map<String, Object> out = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ATTENDEE), MAP, body).getBody();
return out == null ? Map.of() : out;
} catch (HttpClientErrorException e) {
throw refusal(e);
}
}
/** Shape check, load limit, the ticket and its event with company and notice; anything missing is one "not valid". */
private Loaded load(String code) {
if (code == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(code).matches()) throw invalid();
registration.limit("tkt:load:" + PublicRegistrationService.ip(), LOAD_LIMIT, TOO_MANY);
Map<String, Object> t = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_BY_CODE), MAP, code).getBody());
if (t == null || !(t.get("eventUuid") instanceof Number uuid) || !(t.get("companyId") instanceof Number company)) throw invalid();
Map<String, Object> link = new LinkedHashMap<>();
link.put("eventUuid", uuid.longValue());
link.put("companyId", company.longValue());
PublicRegistrationService.Open o = registration.load(link, false);
if (o == null) throw invalid();
return new Loaded(t, o);
}
private static boolean offersConsent(Map<String, Object> t) {
return Boolean.TRUE.equals(t.get("named")) && !Boolean.TRUE.equals(t.get("consented")) && CONSENT_STATES.contains(t.get("state"));
}
/** The counter's refusal as the message a visitor reads. */
private static CodedResponseStatusException refusal(HttpClientErrorException e) {
String code = PublicInviteService.counterCode(e);
return switch (code) {
case "NOT_PAID" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "Tickets can be named once the order is paid.", code);
case "TICKET_CANCELLED" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "This ticket was cancelled.", code);
case "ALREADY_CHECKED_IN" -> new CodedResponseStatusException(HttpStatus.CONFLICT,
"This ticket is already checked in and can no longer be changed.", code);
case "ATTENDEE_REQUIRED" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "This ticket has no attendee yet.", code);
case "ORDER_NOT_FOUND" -> orderInvalid();
case "TICKET_NOT_FOUND", "TICKET_NOT_VALID" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "This ticket is not valid.",
"TICKET_INVALID");
default -> new CodedResponseStatusException(HttpStatus.valueOf(e.getStatusCode().value()), "This could not be completed.", code);
};
}
static byte[] png(String text) {
try {
BitMatrix m = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, QR_PX, QR_PX);
BufferedImage img = new BufferedImage(m.getWidth(), m.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
for (int y = 0; y < m.getHeight(); y++) {
for (int x = 0; x < m.getWidth(); x++) img.setRGB(x, y, m.get(x, y) ? 0x000000 : 0xFFFFFF);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(img, "png", out);
return out.toByteArray();
} catch (WriterException e) {
throw new IllegalStateException(e);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static CodedResponseStatusException invalid() {
return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "This ticket link is not valid.", "TICKET_INVALID");
}
private static CodedResponseStatusException orderInvalid() {
return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "This order link is not valid.", "ORDER_INVALID");
}
private String url(String api) {
return rest.getURLforApiService(api);
}
}
@@ -0,0 +1,74 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminTicketService;
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.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 org.springframework.web.bind.annotation.GetMapping;
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.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/** add-event-tickets: the staff ticket view and door check-in need BO_EVENTS; check-in is audited without the code as target. */
@ExtendWith(MockitoExtension.class)
class AdminTicketCodeControllerTest {
private static final String CODE = "abcdefghijklmnopqrstu_";
@Mock private AdminTicketService tickets;
@InjectMocks private AdminTicketCodeController controller;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
private static List<Method> handlers() {
return Arrays.stream(AdminTicketCodeController.class.getDeclaredMethods())
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
}
@Test
void bothEndpointsNeedTheEventsModuleAndOnlyCheckInIsAudited() {
assertThat(handlers()).hasSize(2);
for (Method m : handlers()) {
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName()).isTrue();
assertThat(m.getAnnotation(AdminModule.class).value()).as(m.getName()).containsExactly("BO_EVENTS");
boolean read = m.isAnnotationPresent(GetMapping.class);
assertThat(m.isAnnotationPresent(Audited.class)).as(m.getName() + " @Audited").isEqualTo(!read);
if (!read) assertThat(m.getAnnotation(Audited.class).target()).isFalse();
}
}
@Test
void routesBindToTheService() throws Exception {
when(tickets.ticket(CODE)).thenReturn(Map.of());
mvc.perform(get("/api/admin/tickets/" + CODE)).andExpect(status().isOk());
when(tickets.checkIn(eq(CODE), any())).thenReturn(Map.of());
mvc.perform(post("/api/admin/tickets/" + CODE + "/checkin").contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Lim Wei\",\"mobile\":\"0125550101\",\"consent\":true}")).andExpect(status().isOk());
verify(tickets).checkIn(CODE, new AdminTicketService.CheckInBody("Lim Wei", "0125550101", null, true));
mvc.perform(post("/api/admin/tickets/" + CODE + "/checkin")).andExpect(status().isOk());
}
}
@@ -52,7 +52,7 @@ class AdminTicketControllerTest {
@Test
void everyEndpointNeedsTheTicketsModule() {
assertThat(handlers()).hasSize(12);
assertThat(handlers()).hasSize(13);
for (Method m : handlers()) {
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue();
AdminModule module = m.getAnnotation(AdminModule.class);
@@ -0,0 +1,185 @@
package com.solvway.mobile.api.service;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.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.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-event-tickets: staff ticket view, door check-in, resend ticket and the ticket counts (spec: Staff Ticket View, Door Check-In, Resend Ticket). */
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminTicketCheckInTest {
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
private static final String SETTINGS = "/counter/ticketType/settings";
private static final String TYPES = "/counter/ticketType/list";
private static final String TYPE_SAVE = "/counter/ticketType/save";
private static final String TYPE_DELETE = "/counter/ticketType/delete";
private static final String ORDERS = "/counter/ticketOrder/list";
private static final String ORDER = "/counter/ticketOrder/get";
private static final String PAID = "/counter/ticketOrder/markPaid";
private static final String CANCEL = "/counter/ticketOrder/cancel";
private static final String CANCEL_TICKET = "/counter/ticketOrder/cancelTicket";
private static final String RESEND = "/counter/ticketOrder/resend";
private static final String BY_CODE = "/counter/ticket/byCode/{code}";
private static final String STAFF = "/counter/ticket/staff";
private static final String CHECKIN = "/counter/ticket/checkin";
private static final String RESEND_TICKET = "/counter/ticketOrder/resendTicket";
private static final String NOTICE = "/company/{id}/privacyNotice";
private static final String CODE = "abcdefghijklmnopqrstu_";
private static final long EV = 3312726793093644288L;
private static final long COMPANY = 5L;
private RestTemplateCustomUtil rest;
private AdminTicketService service;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
service = new AdminTicketService(rest, new AdminEventLeadService(rest, auth, new AdminCompanyScope()));
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setId(21L);
caller.setUsername("finance1");
caller.setCompanyId(COMPANY);
when(auth.loadUserByToken("tok")).thenReturn(caller);
stubEvent(COMPANY);
stubTicket(COMPANY);
when(rest.getForEntity(eq("/company/findById/{id}"), any(ParameterizedTypeReference.class), eq(COMPANY)))
.thenReturn(ResponseEntity.ok(Map.of("id", COMPANY, "name", "INS", "status", "A")));
when(rest.getForEntity(eq(NOTICE), any(ParameterizedTypeReference.class), eq(COMPANY)))
.thenReturn(ResponseEntity.ok(Map.of("id", 9L, "textEn", "English notice", "textMs", "Notis")));
when(rest.postForEntity(anyString(), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of()));
}
@AfterEach
void close() { http.close(); }
private void stubEvent(long company) {
CompanyEvent e = new CompanyEvent();
e.setCompanyId(company);
e.setUuid(EV);
e.setName("KL Hotel Tech Day");
e.setDateStart(LocalDateTime.of(2027, 1, 15, 9, 0));
e.setDateEnd(LocalDateTime.of(2027, 1, 16, 18, 0));
e.setTicketsEnabled(true);
e.setPaymentInstructions("Maybank 5140");
e.setHoldDays(3);
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
}
private void stubTicket(long company) {
when(rest.getForEntity(eq(BY_CODE), any(ParameterizedTypeReference.class), eq(CODE)))
.thenReturn(ResponseEntity.ok(Map.of("companyId", company, "eventUuid", EV, "state", "VALID")));
}
private Map<String, Object> sent(String api) {
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture());
return (Map<String, Object>) c.getValue();
}
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);
});
}
private static HttpClientErrorException counter(HttpStatus status, String code) {
String body = "{\"type\":\"about:blank\",\"status\":" + status.value() + ",\"detail\":\"" + code + "\"}";
return HttpClientErrorException.create(status, status.getReasonPhrase(), null, body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
private final String ev = String.valueOf(EV);
@Test
void theStaffViewIsScopedToTheCallersCompanyAndAddsTheEvent() {
when(rest.postForEntity(eq(STAFF), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(
Map.of("typeName", "General", "attendeeName", "Tan Mei Ling", "named", true, "consented", false, "state", "VALID")));
Map<String, Object> out = service.ticket(CODE);
assertThat(sent(STAFF)).containsEntry("companyId", COMPANY).containsEntry("code", CODE);
assertThat(out).containsEntry("attendeeName", "Tan Mei Ling").containsEntry("eventName", "KL Hotel Tech Day")
.containsEntry("companyName", "INS");
assertThat((Map<String, Object>) out.get("notice")).containsEntry("id", 9L);
}
@Test
void anotherCompanysTicketOrABadCodeIsNotFound() {
stubEvent(99L);
assertCoded(() -> service.ticket(CODE), HttpStatus.NOT_FOUND, "TICKET_NOT_FOUND");
assertCoded(() -> service.checkIn(CODE, null), HttpStatus.NOT_FOUND, "TICKET_NOT_FOUND");
assertCoded(() -> service.ticket("short"), HttpStatus.NOT_FOUND, "TICKET_NOT_FOUND");
verify(rest, never()).postForEntity(eq(STAFF), any(ParameterizedTypeReference.class), any());
verify(rest, never()).postForEntity(eq(CHECKIN), any(ParameterizedTypeReference.class), any());
}
@Test
void checkInSendsTheNormalisedAttendeeTheConsentNoticeAndTheStaffUser() {
service.checkIn(CODE, new AdminTicketService.CheckInBody(" Lim Wei ", "012-555 0101", null, true));
assertThat(sent(CHECKIN)).containsEntry("companyId", COMPANY).containsEntry("code", CODE).containsEntry("name", "Lim Wei")
.containsEntry("mobileE164", "+60125550101").containsEntry("noticeId", 9L).containsEntry("doneBy", "finance1");
}
@Test
void checkInWithoutConsentSendsNoNotice() {
service.checkIn(CODE, new AdminTicketService.CheckInBody(null, null, null, false));
assertThat(sent(CHECKIN)).doesNotContainKey("noticeId").containsEntry("doneBy", "finance1");
}
@Test
void checkInRefusalsKeepTheirCodeAndValue() {
when(rest.postForEntity(eq(CHECKIN), any(ParameterizedTypeReference.class), any()))
.thenThrow(counter(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN|2027-01-15T09:30"))
.thenThrow(counter(HttpStatus.CONFLICT, "NOT_VALID|AWAITING"))
.thenThrow(counter(HttpStatus.CONFLICT, "NOT_EVENT_DAY"))
.thenThrow(counter(HttpStatus.BAD_REQUEST, "NAME_REQUIRED"));
assertThatThrownBy(() -> service.checkIn(CODE, null)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getCode()).isEqualTo("ALREADY_CHECKED_IN");
assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("value", "2027-01-15T09:30"));
});
assertThatThrownBy(() -> service.checkIn(CODE, null)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getCode()).isEqualTo("NOT_VALID");
assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("value", "AWAITING"));
});
assertCoded(() -> service.checkIn(CODE, null), HttpStatus.CONFLICT, "NOT_EVENT_DAY");
assertThatThrownBy(() -> service.checkIn(CODE, null)).isInstanceOfSatisfying(CodedResponseStatusException.class,
e -> assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("field", "name")));
}
@Test
void resendTicketSendsTheTicketAndTheStaffUser() {
service.resendTicket(ev, "300", "1");
assertThat(sent(RESEND_TICKET)).containsEntry("companyId", COMPANY).containsEntry("orderId", 300L).containsEntry("ticketId", 1L)
.containsEntry("doneBy", "finance1");
}
}
@@ -488,4 +488,22 @@ class PublicInviteServiceTest {
verify(rest, never()).getForEntity(eq(COMPANY_URL), any(ParameterizedTypeReference.class), any());
verify(rest, never()).getForEntity(eq(NOTICE), any(ParameterizedTypeReference.class), any());
}
// --- ticketed events (add-event-tickets) ---
@Test
void lookup_showTicketPassesThrough() {
post(LOOKUP, Map.of("result", "SHOW_TICKET"));
assertThat(service.lookup(CK, new PublicCheckinLookupRequest("a@x.com"))).isEqualTo(Map.of("result", "SHOW_TICKET"));
}
@Test
void walkIn_onATicketedEventIsRefused() {
postConflict(REGISTER, "TICKETS_ONLY");
assertThatThrownBy(() -> service.walkIn(CK, ok())).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getCode()).isEqualTo("TICKETS_ONLY");
assertThat(e.getReason()).isEqualTo("Please show your ticket at the entrance.");
});
}
}
@@ -0,0 +1,294 @@
package com.solvway.mobile.api.service;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-event-tickets: the public ticket page, its QR PNG, attendee consent, naming attendees and the order page's tickets. */
@SuppressWarnings({"unchecked", "rawtypes"})
class PublicTicketPageTest {
private static final String BY_CODE = "/counter/ticket/byCode/{code}";
private static final String ATTENDEE = "/counter/ticket/attendee";
private static final String CONSENT = "/counter/ticket/consent";
private static final String BY_TOKEN = "/counter/ticketOrder/byToken/{token}";
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
private static final String COMPANY_URL = "/company/findById/{id}";
private static final String NOTICE = "/company/{id}/privacyNotice";
private static final long EV = 3312726793093644288L;
private static final long COMPANY = 1L;
private static final String CODE = "abcdefghijklmnopqrstu_";
private static final String TOKEN = "tokentokentokentokento";
private RestTemplateCustomUtil rest;
private ValueOperations<String, Object> ops;
private MockedStatic<HttpReqRespUtils> http;
private PublicTicketService service;
private PublicPageService pages;
private Map<String, Object> ticket;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
RedisTemplate<String, Object> redis = mock(RedisTemplate.class);
ops = mock(ValueOperations.class);
when(redis.opsForValue()).thenReturn(ops);
when(ops.increment(any())).thenReturn(1L);
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic();
AdminEventLeadService leads = new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope());
PublicRegistrationService registration = new PublicRegistrationService(rest, leads, redis,
Clock.fixed(Instant.parse("2027-01-10T04:00:00Z"), ZoneOffset.UTC));
service = new PublicTicketService(rest, registration, "https://portal.example.test/");
pages = new PublicPageService(rest, registration);
CompanyEvent e = new CompanyEvent();
e.setCompanyId(COMPANY);
e.setUuid(EV);
e.setName("KL Hotel Tech Day");
e.setLocation("KLCC");
e.setDateStart(LocalDateTime.of(2027, 1, 15, 9, 0));
e.setDateEnd(LocalDateTime.of(2027, 1, 16, 18, 0));
e.setEnabled(GeneralEnum.FlagYesNo.Y);
e.setTicketsEnabled(true);
stub(EVENT, EV, e);
stub(COMPANY_URL, COMPANY, Map.of("id", COMPANY, "name", "INS", "status", "A"));
stub(NOTICE, COMPANY, Map.of("id", 9L, "textEn", "English notice", "textMs", "Notis"));
ticket = new HashMap<>(Map.of("companyId", COMPANY, "eventUuid", EV, "typeName", "General", "attendeeFirstName", "Tan",
"named", true, "state", "VALID", "consented", false));
stub(BY_CODE, CODE, ticket);
}
private MockedStatic<HttpReqRespUtils> mockStatic() {
MockedStatic<HttpReqRespUtils> m = org.mockito.Mockito.mockStatic(HttpReqRespUtils.class);
m.when(HttpReqRespUtils::getClientIpAddressIfServletRequestExist).thenReturn("1.2.3.4");
return m;
}
@AfterEach
void close() {
http.close();
}
private void stub(String url, Object var, Object body) {
when(rest.getForEntity(eq(url), any(ParameterizedTypeReference.class), eq(var))).thenReturn(ResponseEntity.ok(body));
}
private static HttpClientErrorException counter(HttpStatus status, String code) {
return HttpClientErrorException.create(status, status.getReasonPhrase(), HttpHeaders.EMPTY,
("{\"detail\":\"" + code + "\"}").getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
private static void assertCoded(Runnable r, HttpStatus status, String code) {
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, ex -> {
assertThat(ex.getStatusCode()).isEqualTo(status);
assertThat(ex.getCode()).isEqualTo(code);
});
}
// ---- ticket page
@Test
void theTicketPageShowsTheEventTicketAndTheConsentOfferWithoutPersonalDetails() {
Map<String, Object> out = service.ticket(CODE);
assertThat(out).containsEntry("eventName", "KL Hotel Tech Day").containsEntry("typeName", "General")
.containsEntry("attendeeFirstName", "Tan").containsEntry("state", "VALID").containsEntry("companyName", "INS")
.containsEntry("startDate", "2027-01-15").containsEntry("location", "KLCC");
assertThat((Map<String, Object>) out.get("notice")).containsEntry("id", 9L);
assertThat(out).doesNotContainKeys("companyId", "eventUuid");
verify(ops).increment("tkt:load:1.2.3.4");
}
@Test
void noConsentOfferOnAnUnnamedAConsentedOrAnInvalidTicket() {
ticket.put("named", false);
assertThat(service.ticket(CODE)).doesNotContainKey("notice");
ticket.put("named", true);
ticket.put("consented", true);
assertThat(service.ticket(CODE)).doesNotContainKey("notice");
ticket.put("consented", false);
ticket.put("state", "ORDER_CANCELLED");
assertThat(service.ticket(CODE)).doesNotContainKey("notice").containsEntry("state", "ORDER_CANCELLED");
}
@Test
void aBadShapeOrUnknownCodeIsNotValid() {
assertCoded(() -> service.ticket("short"), HttpStatus.NOT_FOUND, "TICKET_INVALID");
assertCoded(() -> service.ticket("abcdefghijklmnopqrstu/"), HttpStatus.NOT_FOUND, "TICKET_INVALID");
verify(rest, never()).getForEntity(eq(BY_CODE), any(ParameterizedTypeReference.class), anyString());
when(rest.getForEntity(eq(BY_CODE), any(ParameterizedTypeReference.class), eq("zzzzzzzzzzzzzzzzzzzzzz")))
.thenThrow(counter(HttpStatus.NOT_FOUND, "TICKET_NOT_FOUND"));
assertCoded(() -> service.ticket("zzzzzzzzzzzzzzzzzzzzzz"), HttpStatus.NOT_FOUND, "TICKET_INVALID");
}
@Test
void theLoadLimitApplies() {
when(ops.increment("tkt:load:1.2.3.4")).thenReturn(121L);
assertCoded(() -> service.ticket(CODE), HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
verify(rest, never()).getForEntity(eq(BY_CODE), any(ParameterizedTypeReference.class), anyString());
}
// ---- QR PNG
@Test
void theQrPngDecodesToTheTicketLinkAndIsPrivate() throws Exception {
ResponseEntity<byte[]> r = service.qr(CODE);
assertThat(r.getHeaders().getContentType()).isEqualTo(MediaType.IMAGE_PNG);
assertThat(r.getHeaders().getCacheControl()).contains("private").contains("max-age=300");
BufferedImage img = ImageIO.read(new ByteArrayInputStream(r.getBody()));
int[] px = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
String text = new QRCodeReader().decode(new BinaryBitmap(new HybridBinarizer(
new RGBLuminanceSource(img.getWidth(), img.getHeight(), px)))).getText();
assertThat(text).isEqualTo("https://portal.example.test/t/" + CODE);
verify(ops).increment("tkt:load:1.2.3.4");
}
@Test
void anInvalidTicketHasNoQr() {
ticket.put("state", "AWAITING");
assertCoded(() -> service.qr(CODE), HttpStatus.NOT_FOUND, "TICKET_INVALID");
}
// ---- consent
@Test
void consentSendsTheCompanysCurrentNotice() {
assertThat(service.consent(CODE, new PublicTicketService.ConsentRequest(true))).containsEntry("consented", true);
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(CONSENT), any(Class.class), body.capture());
assertThat((Map<String, Object>) body.getValue()).containsEntry("code", CODE).containsEntry("noticeId", 9L);
verify(ops).increment("tkt:submit:1.2.3.4:" + EV);
}
@Test
void consentNeedsTheTickAndMapsCounterRefusals() {
assertCoded(() -> service.consent(CODE, new PublicTicketService.ConsentRequest(false)), HttpStatus.BAD_REQUEST, "CONSENT_REQUIRED");
when(rest.postForEntity(eq(CONSENT), any(Class.class), any())).thenThrow(counter(HttpStatus.CONFLICT, "TICKET_NOT_VALID"));
assertCoded(() -> service.consent(CODE, new PublicTicketService.ConsentRequest(true)), HttpStatus.CONFLICT, "TICKET_INVALID");
}
// ---- naming attendees
private void stubOrder() {
stub(BY_TOKEN, TOKEN, new HashMap<>(Map.of("eventUuid", EV, "status", "PAID", "reference", "T-7K3M9Q")));
}
@Test
void namingNormalisesTheAttendeeAndSendsThePermission() {
stubOrder();
when(rest.postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(
new HashMap<>(Map.of("id", 1, "attendeeName", "Tan Mei Ling", "code", "newcodenewcodenewcode_", "state", "VALID"))));
Map<String, Object> out = service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest(" Tan Mei Ling ", "012-555 0101",
" Tan@Example.COM ", true));
assertThat(out).containsEntry("code", "newcodenewcodenewcode_");
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), body.capture());
assertThat((Map<String, Object>) body.getValue()).containsEntry("orderToken", TOKEN).containsEntry("ticketId", 1L)
.containsEntry("name", "Tan Mei Ling").containsEntry("mobileE164", "+60125550101")
.containsEntry("email", "tan@example.com").containsEntry("permission", true);
verify(ops).increment("tkt:submit:1.2.3.4:" + EV);
}
@Test
void namingNeedsThePermissionANameAndAContact() {
stubOrder();
assertCoded(() -> service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", false)),
HttpStatus.BAD_REQUEST, "PERMISSION_REQUIRED");
assertCoded(() -> service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest("Tan", " ", null, true)),
HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
assertCoded(() -> service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest(" ", null, "t@x.test", true)),
HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
verify(rest, never()).postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), any());
}
@Test
void namingRefusalsBecomePublicMessages() {
stubOrder();
PublicTicketService.AttendeeRequest r = new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true);
when(rest.postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), any()))
.thenThrow(counter(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN"))
.thenThrow(counter(HttpStatus.CONFLICT, "NOT_PAID"))
.thenThrow(counter(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND"));
assertCoded(() -> service.attendee(TOKEN, 1L, r), HttpStatus.CONFLICT, "ALREADY_CHECKED_IN");
assertCoded(() -> service.attendee(TOKEN, 1L, r), HttpStatus.CONFLICT, "NOT_PAID");
assertCoded(() -> service.attendee(TOKEN, 1L, r), HttpStatus.NOT_FOUND, "ORDER_INVALID");
}
@Test
void theSubmitLimitAppliesToNaming() {
stubOrder();
when(ops.increment("tkt:submit:1.2.3.4:" + EV)).thenReturn(61L);
assertCoded(() -> service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true)),
HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
}
@Test
void orderLookupsForNamingCountTowardTheOrderLoadLimitFirst() {
when(ops.increment("ord:load:1.2.3.4")).thenReturn(121L);
assertCoded(() -> service.attendee("zzzzzzzzzzzzzzzzzzzzzz", 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true)),
HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
verify(rest, never()).getForEntity(eq(BY_TOKEN), any(ParameterizedTypeReference.class), anyString());
}
@Test
void aBadOrderTokenIsNotValid() {
assertCoded(() -> service.attendee("bad", 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true)),
HttpStatus.NOT_FOUND, "ORDER_INVALID");
}
// ---- order page
@Test
void aPaidOrderPageCarriesItsTickets() {
List<Map<String, Object>> tickets = List.of(Map.of("id", 1, "typeName", "General", "code", CODE, "state", "VALID"));
stub(BY_TOKEN, TOKEN, new HashMap<>(Map.of("eventUuid", EV, "status", "PAID", "reference", "T-7K3M9Q", "tickets", tickets)));
assertThat(pages.order(TOKEN)).containsEntry("tickets", tickets);
}
@Test
void anUnpaidOrderPageHasNoTickets() {
stub(BY_TOKEN, TOKEN, new HashMap<>(Map.of("eventUuid", EV, "status", "AWAITING", "reference", "T-7K3M9Q", "tickets", List.of())));
assertThat(pages.order(TOKEN)).doesNotContainKey("tickets");
}
}
@@ -0,0 +1,48 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.service.TicketOrderService;
import com.solvway.services.counter.service.TicketService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** Tickets (add-event-tickets). byCode, attendee and consent are public paths; mobile-api checks and normalises input first. */
@RestController
@RequestMapping("/counter/ticket")
@AllArgsConstructor
public class TicketController {
private final TicketService service;
@GetMapping("/byCode/{code}")
public TicketService.TicketView byCode(@PathVariable String code) {
return service.byCode(code);
}
/** Public: the buyer names a ticket of their Paid order, by the order's link token. */
@PostMapping("/attendee")
public TicketOrderService.OrderTicket attendee(@RequestBody TicketService.AttendeeRequest req) {
return service.nameAttendee(req);
}
/** Staff (JWT): mobile-api has checked BO_EVENTS and the event's company. */
@PostMapping("/staff")
public TicketService.StaffView staff(@RequestBody TicketService.StaffRequest req) {
return service.staffView(req);
}
/** Staff (JWT): door check-in. */
@PostMapping("/checkin")
public TicketService.StaffView checkIn(@RequestBody TicketService.CheckInRequest req) {
return service.checkIn(req);
}
/** Public: the attendee opts in on their ticket page. */
@PostMapping("/consent")
public void consent(@RequestBody TicketService.ConsentRequest req) {
service.consent(req);
}
}
@@ -57,4 +57,10 @@ public class TicketOrderController {
public void resend(@RequestBody TicketOrderStaffService.OrderRef req) {
staff.resend(req);
}
/** add-event-tickets: staff resend one ticket. */
@PostMapping("/resendTicket")
public void resendTicket(@RequestBody TicketOrderStaffService.ActionRequest req) {
staff.resendTicket(req);
}
}
@@ -63,4 +63,13 @@ public class Ticket {
@Column(name = "checked_in_by")
private String checkedInBy;
@Column(name = "attendee_named_at")
private LocalDateTime attendeeNamedAt;
@Column(name = "attendee_consent_at")
private LocalDateTime attendeeConsentAt;
@Column(name = "attendee_notice_id")
private Long attendeeNoticeId;
}
@@ -22,6 +22,27 @@ public interface TicketRepository extends JpaRepository<Ticket, Long> {
List<Ticket> findByOrderIdOrderByIdAsc(long orderId);
java.util.Optional<Ticket> findByCode(String code);
/** Checks a ticket in only if nobody has yet: two scanners cannot both win. Returns 1 for the winner, 0 otherwise. */
@org.springframework.transaction.annotation.Transactional
@org.springframework.data.jpa.repository.Modifying
@Query("update Ticket t set t.checkedInAt = :at, t.checkedInBy = :by where t.id = :id and t.checkedInAt is null")
int checkIn(@Param("id") long id, @Param("at") java.time.LocalDateTime at, @Param("by") String by);
/** Valid unchecked tickets of an event matching a mobile or email, oldest first, with the buyer's name. A named ticket matches its
* attendee, an unnamed one its buyer. Rows are [Ticket, buyerName]. */
@Query("select t, o.buyerName from Ticket t, ShopOrder o where o.id = t.orderId and t.eventUuid = :eventUuid"
+ " and t.status = 'ACTIVE' and o.status = 'PAID' and t.checkedInAt is null and ("
+ " (t.attendeeName is not null and (t.attendeeMobileE164 = :mobile or t.attendeeEmail = :email))"
+ " or (t.attendeeName is null and (o.buyerMobileE164 = :mobile or o.buyerEmail = :email))) order by t.id")
List<Object[]> selfCheckIn(@Param("eventUuid") long eventUuid, @Param("mobile") String mobile, @Param("email") String email);
/** Active tickets of an event per order status (AWAITING, PAID) with how many are checked in: rows are [status, count, checkedIn]. */
@Query("select o.status, count(t), count(t.checkedInAt) from Ticket t, ShopOrder o where o.id = t.orderId"
+ " and t.eventUuid = :eventUuid and t.status = 'ACTIVE' and o.status in ('AWAITING', 'PAID') group by o.status")
List<Object[]> countsByOrderStatus(@Param("eventUuid") long eventUuid);
/** Active tickets per order for one page of the staff list: one query, no N+1. */
@Query("select new com.solvway.services.counter.repo.TicketCount(t.orderId, count(t)) from Ticket t"
+ " where t.orderId in :orderIds and t.status = 'ACTIVE' group by t.orderId")
@@ -9,7 +9,9 @@ import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.LeadRepository;
import lombok.AllArgsConstructor;
import com.solvway.services.counter.model.Ticket;
import com.solvway.services.counter.repo.TicketRepository;
import org.springframework.beans.factory.annotation.Autowired;
import com.solvway.services.counter.util.EventDays;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
@@ -20,7 +22,6 @@ import java.util.List;
/** Event-day check-in. Reveals a first name only, nothing else about a person. Never log contact data. */
@Service
@AllArgsConstructor
public class EventCheckInService {
public record EventRef(long companyId, long eventUuid) {}
public record EnsureRequest(Long companyId, long eventUuid) {}
@@ -34,6 +35,23 @@ public class EventCheckInService {
private final EventGuestRepository guestRepository;
private final EventLeadRepository eventLeadRepository;
private final LeadRepository leadRepository;
private final TicketRepository ticketRepository;
@Autowired
public EventCheckInService(EventRepository eventRepository, EventGuestRepository guestRepository,
EventLeadRepository eventLeadRepository, LeadRepository leadRepository, TicketRepository ticketRepository) {
this.eventRepository = eventRepository;
this.guestRepository = guestRepository;
this.eventLeadRepository = eventLeadRepository;
this.leadRepository = leadRepository;
this.ticketRepository = ticketRepository;
}
// ponytail: null ticket repository keeps the pre-ticketing wiring of older tests; ticketed events then never match a ticket.
public EventCheckInService(EventRepository eventRepository, EventGuestRepository guestRepository,
EventLeadRepository eventLeadRepository, LeadRepository leadRepository) {
this(eventRepository, guestRepository, eventLeadRepository, leadRepository, null);
}
private static ResponseStatusException notFound(String code) {
return new ResponseStatusException(HttpStatus.NOT_FOUND, code);
@@ -80,8 +98,10 @@ public class EventCheckInService {
boolean hasMobile = req.mobileE164() != null && !req.mobileE164().isBlank();
boolean hasEmail = req.email() != null && !req.email().isBlank();
if (hasMobile == hasEmail) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "MOBILE_OR_EMAIL_REQUIRED");
List<Object[]> rows = hasMobile ? eventLeadRepository.findByEventAndMobile(req.eventUuid(), req.mobileE164())
: eventLeadRepository.findByEventAndEmail(req.eventUuid(), req.email());
String mobile = hasMobile ? req.mobileE164() : null, email = hasMobile ? null : req.email();
if (event.isTicketsEnabled() && ticketRepository != null) return ticketed(req.eventUuid(), mobile, email);
List<Object[]> rows = hasMobile ? eventLeadRepository.findByEventAndMobile(req.eventUuid(), mobile)
: eventLeadRepository.findByEventAndEmail(req.eventUuid(), email);
if (rows.isEmpty()) return new LookupResult("FORM", null);
EventLead el = (EventLead) rows.get(0)[0];
Lead lead = (Lead) rows.get(0)[1];
@@ -89,6 +109,26 @@ public class EventCheckInService {
return new LookupResult("CHECKED_IN", firstName(lead.getName()));
}
/** A ticketed event: the oldest valid unchecked ticket of this person, else a registered guest, else show the ticket. */
private LookupResult ticketed(long eventUuid, String mobile, String email) {
LocalDateTime now = LocalDateTime.now();
for (Object[] row : ticketRepository.selfCheckIn(eventUuid, mobile, email)) {
Ticket t = (Ticket) row[0];
if (ticketRepository.checkIn(t.getId(), now, "self") == 0) continue; // checked in elsewhere meanwhile
if (t.getEventLeadUuid() != null) eventLeadRepository.findByUuid(t.getEventLeadUuid()).ifPresent(this::markAttended);
return new LookupResult("CHECKED_IN", firstName(t.getAttendeeName() != null ? t.getAttendeeName() : (String) row[1]));
}
List<Object[]> rows = mobile != null ? eventLeadRepository.findByEventAndMobile(eventUuid, mobile)
: eventLeadRepository.findByEventAndEmail(eventUuid, email);
for (Object[] row : rows) {
EventLead el = (EventLead) row[0];
if (!guestRepository.existsByEventLeadId(el.getId())) continue;
markAttended(el);
return new LookupResult("CHECKED_IN", firstName(((Lead) row[1]).getName()));
}
return new LookupResult("SHOW_TICKET", null);
}
public NameView byGuest(ByGuestRequest req) {
long company = requireCompany(req.companyId());
EventGuest g = guestRepository.findByToken(req.guestToken())
@@ -8,15 +8,17 @@ import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
/** Invited / registered / attended numbers of one event. */
@Service
public class EventHeadcountService {
public record Request(Long companyId, long eventUuid) {}
/** total = registered guests + walk-ins (event leads with no guest row and no ticket order) + held tickets. */
public record Headcount(long invited, Integer cap, long registered, long attended, long walkIns, long total, Integer capacity,
long heldTickets) {
long heldTickets, long ticketsAwaiting, long ticketsPaid, long ticketsCheckedIn) {
public Headcount(long invited, Integer cap, long registered, long attended, long walkIns, long total, Integer capacity) {
this(invited, cap, registered, attended, walkIns, total, capacity, 0);
this(invited, cap, registered, attended, walkIns, total, capacity, 0, 0, 0, 0);
}
}
@@ -46,8 +48,16 @@ public class EventHeadcountService {
long registered = guestRepository.countByEventUuidAndEventLeadIdIsNotNull(req.eventUuid());
long walkIns = eventLeadRepository.countWalkIns(req.eventUuid());
long held = ticketRepository == null ? 0 : ticketRepository.countHeld(req.eventUuid());
long awaiting = 0, paid = 0, checkedIn = 0;
for (Object[] row : ticketRepository == null ? List.<Object[]>of() : ticketRepository.countsByOrderStatus(req.eventUuid())) {
if ("AWAITING".equals(row[0])) awaiting = ((Number) row[1]).longValue();
if ("PAID".equals(row[0])) {
paid = ((Number) row[1]).longValue();
checkedIn = ((Number) row[2]).longValue();
}
}
return new Headcount(guestRepository.countByEventUuid(req.eventUuid()), event.getInvitationCap(), registered,
eventLeadRepository.countByEventUuidAndAttendedAtIsNotNull(req.eventUuid()), walkIns, registered + walkIns + held,
event.getCapacity(), held);
event.getCapacity(), held, awaiting, paid, checkedIn);
}
}
@@ -102,6 +102,11 @@ public class EventLeadService {
.map(e -> EventDays.isDuring(e, LocalDateTime.now())).orElse(false);
}
/** add-event-tickets: a ticketed event takes no walk-ins. */
public boolean sellsTickets(long eventUuid) {
return eventRepository != null && eventRepository.findByUuid(eventUuid).map(e -> e.isTicketsEnabled()).orElse(false);
}
public void linkGuest(long eventUuid, EventLead eventLead, Lead lead) {
if (guestLinker != null) guestLinker.link(eventUuid, eventLead, lead);
}
@@ -8,7 +8,9 @@ import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.ArrayList;
@@ -67,6 +69,10 @@ public class RegistrationService {
}
public RegisterResult register(RegisterRequest req) {
// A walk-in (attending, no source) on a ticketed event must show a ticket instead (add-event-tickets).
if (req.attend() && req.source() == null && eventLeadService.sellsTickets(req.eventUuid())) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "TICKETS_ONLY");
}
try {
return transactionTemplate.execute(s -> registerOnce(req));
} catch (DataIntegrityViolationException e) {
@@ -8,6 +8,8 @@ import com.solvway.services.counter.model.ShopOrder;
import com.solvway.services.counter.model.ShopOrderLine;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.ShopOrderLineRepository;
import com.solvway.services.counter.repo.TicketRepository;
import com.solvway.services.counter.model.Ticket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@@ -36,16 +38,66 @@ public class TicketOrderMailer {
private final EmailService emailService;
private final EventRepository events;
private final ShopOrderLineRepository lines;
private final TicketRepository tickets;
private final String portalBase;
public TicketOrderMailer(EmailService emailService, EventRepository events, ShopOrderLineRepository lines,
public TicketOrderMailer(EmailService emailService, EventRepository events, ShopOrderLineRepository lines, TicketRepository tickets,
@Value("${app.admin-portal-base-url}") String portalBase) {
this.emailService = emailService;
this.events = events;
this.lines = lines;
this.tickets = tickets;
this.portalBase = portalBase;
}
/** add-event-tickets: one ticket to one address, after the surrounding transaction commits; best effort as above. */
public void sendTicket(Ticket ticket, String to) {
Runnable deliver = () -> deliverTicket(ticket, to);
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
deliver.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCommit() { deliver.run(); }
});
}
private void deliverTicket(Ticket t, String to) {
try {
Event event = events.findByUuid(t.getEventUuid()).orElse(null);
String eventName = event == null ? "" : event.getName();
String type = lines.findById(t.getOrderLineId()).map(ShopOrderLine::getName).orElse("");
String who = t.getAttendeeName() == null ? "" : "<p>" + esc(t.getAttendeeName()) + "</p>";
String card = eventLine(event) + "<p>" + esc(type) + "</p>" + who + ticketBlock(t.getCode());
Email email = new Email();
email.setCompanyId(t.getCompanyId());
email.setSubject("Your ticket: " + eventName + " / Tiket anda: " + eventName);
email.setBody("<p>Here is your ticket. Show this QR code at the entrance. Open the link to keep the ticket at hand; there you can"
+ " also choose to hear about future events.</p>" + card
+ "<hr><p><i>Bahasa Malaysia</i></p><p>Ini tiket anda. Tunjukkan kod QR ini di pintu masuk. Buka pautan untuk menyimpan tiket;"
+ " di situ anda juga boleh memilih untuk menerima berita acara akan datang.</p>" + card);
email.setStatus(EmailEnum.StatusType.P);
email.setRecipients(List.of(new Recipient(null, to, EmailEnum.RecipientType.R, EmailEnum.RecipientStatusType.Y)));
emailService.send(email);
} catch (RuntimeException e) {
log.warn("Ticket {} email failed: {}", t.getId(), e.getClass().getSimpleName());
}
}
/** The ticket's QR image (a PNG mobile-api draws) and its link. */
private String ticketBlock(String code) {
String link = esc(portalBase + "/t/" + code);
return "<p><img src=\"" + esc(portalBase + "/api/public/tickets/" + code + "/qr.png") + "\" width=\"200\" height=\"200\" alt=\"Ticket QR\"><br>"
+ "<a href=\"" + link + "\">" + link + "</a></p>";
}
private static String eventLine(Event event) {
if (event == null) return "";
String dates = event.getDateStart() == null ? "" : "<br>" + esc(event.getDateStart().toLocalDate())
+ (event.getDateEnd() == null ? "" : " - " + esc(event.getDateEnd().toLocalDate()));
return "<p><strong>" + esc(event.getName()) + "</strong>" + dates + (event.getLocation() == null ? "" : "<br>" + esc(event.getLocation())) + "</p>";
}
public void send(ShopOrder order, String kind) {
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
deliver(order, kind);
@@ -99,8 +151,15 @@ public class TicketOrderMailer {
String en, ms;
switch (kind) {
case PAID -> {
en = "<p>Your order " + esc(o.getReference()) + " is confirmed.</p>";
ms = "<p>Pesanan anda " + esc(o.getReference()) + " telah disahkan.</p>";
// add-event-tickets: the tickets, each with its QR and link, and where to name the attendees.
StringBuilder qrs = new StringBuilder();
for (Ticket t : tickets.findByOrderIdOrderByIdAsc(o.getId())) {
if (Ticket.ACTIVE.equals(t.getStatus()) && t.getCode() != null) qrs.append(ticketBlock(t.getCode()));
}
en = "<p>Your order " + esc(o.getReference()) + " is confirmed. Your tickets are below; show a QR code at the entrance.</p>" + qrs
+ "<p>Name your attendees, so each gets their own ticket: " + orderLink + "</p>";
ms = "<p>Pesanan anda " + esc(o.getReference()) + " telah disahkan. Tiket anda di bawah; tunjukkan kod QR di pintu masuk.</p>" + qrs
+ "<p>Namakan peserta anda supaya setiap seorang menerima tiket sendiri: " + orderLink + "</p>";
}
case EXPIRED -> {
en = "<p>Your order " + esc(o.getReference()) + " was not paid in time, so its tickets were released.</p>";
@@ -76,14 +76,26 @@ public class TicketOrderService {
/** The public order page: the buyer's name but no other personal details. */
public record OrderView(long companyId, Long eventUuid, String reference, String status, String buyerName, int totalSen,
LocalDateTime holdUntil, LocalDateTime createdAt, List<LineView> lines) {}
LocalDateTime holdUntil, LocalDateTime createdAt, List<LineView> lines, List<OrderTicket> tickets) {}
/** add-event-tickets: a Paid order's ticket on its order page; never the attendee's contact. */
public record OrderTicket(long id, String typeName, String attendeeName, String code, String state, LocalDateTime checkedInAt) {}
public OrderView byToken(String token) {
ShopOrder o = orders.findByToken(token).orElseThrow(() -> status(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND"));
List<LineView> views = lines.findByOrderIdOrderByIdAsc(o.getId()).stream()
.map(l -> new LineView(l.getName(), l.getUnitPriceSen(), l.getQuantity())).toList();
List<OrderTicket> paid = List.of();
if (ShopOrder.PAID.equals(o.getStatus())) {
Map<Long, String> names = lines.findByOrderIdOrderByIdAsc(o.getId()).stream()
.collect(Collectors.toMap(ShopOrderLine::getId, ShopOrderLine::getName));
paid = tickets.findByOrderIdOrderByIdAsc(o.getId()).stream().filter(t -> Ticket.ACTIVE.equals(t.getStatus()))
.map(t -> new OrderTicket(t.getId(), names.get(t.getOrderLineId()), t.getAttendeeName(), t.getCode(),
TicketState.of(o, t), t.getCheckedInAt()))
.toList();
}
return new OrderView(o.getCompanyId(), o.getEventUuid(), o.getReference(), o.getStatus(), o.getBuyerName(), o.getTotalSen(),
o.getHoldUntil(), o.getCreatedAt(), views);
o.getHoldUntil(), o.getCreatedAt(), views, paid);
}
public Result request(Request r) {
@@ -175,6 +187,7 @@ public class TicketOrderService {
ticket.setOrderId(o.getId());
ticket.setOrderLineId(line.getId());
ticket.setTicketTypeId(t.getId());
if (total == 0) ticket.setCode(TicketState.newCode()); // add-event-tickets: a free order is Paid at once
tickets.save(ticket);
}
views.add(new LineView(t.getName(), t.getPriceSen(), l.quantity()));
@@ -55,7 +55,8 @@ public class TicketOrderStaffService {
/** ticketId is used by cancelTicket only. */
public record ActionRequest(Long companyId, long eventUuid, long orderId, Long ticketId, String doneBy) {}
public record TicketView(Long id, String typeName, String status, LocalDateTime cancelledAt, String cancelledBy) {}
public record TicketView(Long id, String typeName, String status, LocalDateTime cancelledAt, String cancelledBy, String attendeeName,
LocalDateTime checkedInAt) {}
public record Detail(ShopOrder order, List<ShopOrderLine> lines, List<TicketView> tickets) {}
@@ -80,7 +81,7 @@ public class TicketOrderStaffService {
Map<Long, String> typeNames = types.findByEventUuidOrderBySortAscIdAsc(r.eventUuid()).stream()
.collect(Collectors.toMap(TicketType::getId, TicketType::getName));
List<TicketView> views = tickets.findByOrderIdOrderByIdAsc(o.getId()).stream().map(t -> new TicketView(t.getId(),
typeNames.get(t.getTicketTypeId()), t.getStatus(), t.getCancelledAt(), t.getCancelledBy())).toList();
typeNames.get(t.getTicketTypeId()), t.getStatus(), t.getCancelledAt(), t.getCancelledBy(), t.getAttendeeName(), t.getCheckedInAt())).toList();
return new Detail(o, lines.findByOrderIdOrderByIdAsc(o.getId()), views);
}
@@ -110,6 +111,12 @@ public class TicketOrderStaffService {
o.setPaymentRef(ref);
o.setLastEmail(TicketOrderMailer.PAID);
orders.save(o);
for (Ticket t : tickets.findByOrderIdOrderByIdAsc(o.getId())) { // add-event-tickets: the codes come with payment
if (Ticket.ACTIVE.equals(t.getStatus()) && t.getCode() == null) {
t.setCode(TicketState.newCode());
tickets.save(t);
}
}
mailer.send(o, TicketOrderMailer.PAID);
}
@@ -145,6 +152,15 @@ public class TicketOrderStaffService {
orders.save(o);
}
/** add-event-tickets: one valid ticket again, to its attendee's email, else the buyer (spec: Resend Ticket). */
public void resendTicket(ActionRequest r) {
ShopOrder o = order(r.companyId(), r.eventUuid(), r.orderId());
Ticket t = tickets.findByOrderIdOrderByIdAsc(o.getId()).stream().filter(x -> x.getId().equals(r.ticketId())).findFirst()
.orElseThrow(() -> status(HttpStatus.NOT_FOUND, "TICKET_NOT_FOUND"));
if (!TicketState.VALID.equals(TicketState.of(o, t))) throw status(HttpStatus.CONFLICT, "TICKET_NOT_VALID");
mailer.sendTicket(t, t.getAttendeeEmail() != null ? t.getAttendeeEmail() : o.getBuyerEmail());
}
public void resend(OrderRef r) {
ShopOrder o = order(r.companyId(), r.eventUuid(), r.orderId());
mailer.send(o, o.getLastEmail() == null ? TicketOrderMailer.RECEIVED : o.getLastEmail());
@@ -0,0 +1,198 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.ShopOrderLineRepository;
import com.solvway.services.counter.util.EventDays;
import com.solvway.services.counter.repo.ShopOrderRepository;
import com.solvway.services.counter.repo.TicketRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import com.solvway.services.counter.model.ShopOrder;
import com.solvway.services.counter.model.ShopOrderLine;
import com.solvway.services.counter.model.Ticket;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
/** add-event-tickets: tickets by their code. */
@Service
@AllArgsConstructor
public class TicketService {
private final TicketRepository tickets;
private final ShopOrderRepository orders;
private final ShopOrderLineRepository lines;
private final RegistrationService registration;
private final TicketOrderMailer mailer;
private final EventRepository events;
private final EventLeadRepository eventLeads;
public record AttendeeRequest(String orderToken, long ticketId, String name, String mobileE164, String email, boolean permission) {}
public record ConsentRequest(String code, Long noticeId) {}
/** The buyer names a Paid order's ticket: a new code, consent and lead link cleared, the ticket emailed (spec: Naming Effects). */
@Transactional
public TicketOrderService.OrderTicket nameAttendee(AttendeeRequest r) {
if (!r.permission()) throw status(HttpStatus.BAD_REQUEST, "PERMISSION_REQUIRED");
Attendee a = attendee(r.name(), r.mobileE164(), r.email());
ShopOrder o = r.orderToken() == null ? null : orders.findByToken(r.orderToken()).orElse(null);
Ticket t = o == null ? null : tickets.findById(r.ticketId()).filter(x -> x.getOrderId() == o.getId()).orElse(null);
if (t == null) throw status(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND");
if (!ShopOrder.PAID.equals(o.getStatus())) throw status(HttpStatus.CONFLICT, "NOT_PAID");
if (Ticket.CANCELLED.equals(t.getStatus())) throw status(HttpStatus.CONFLICT, "TICKET_CANCELLED");
if (t.getCheckedInAt() != null) throw status(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN");
t.setCode(TicketState.newCode());
a.applyTo(t);
t.setAttendeeConsentAt(null);
t.setAttendeeNoticeId(null);
t.setEventLeadUuid(null);
tickets.save(t);
if (a.email() != null) mailer.sendTicket(t, a.email()); // delivered after commit
String typeName = lines.findById(t.getOrderLineId()).map(ShopOrderLine::getName).orElse(null);
return new TicketOrderService.OrderTicket(t.getId(), typeName, a.name(), t.getCode(), TicketState.of(o, t), null);
}
/** The attendee opts in on their ticket page: they become a TICKET event lead (spec: Attendee Consent). */
@Transactional
public void consent(ConsentRequest r) {
if (r.noticeId() == null) throw status(HttpStatus.BAD_REQUEST, "CONSENT_REQUIRED");
Ticket t = ticket(r.code());
ShopOrder o = orders.findById(t.getOrderId()).orElseThrow(TicketService::notFound);
String state = TicketState.of(o, t);
if (!TicketState.VALID.equals(state) && !TicketState.CHECKED_IN.equals(state)) throw status(HttpStatus.CONFLICT, "TICKET_NOT_VALID");
if (t.getAttendeeName() == null) throw status(HttpStatus.CONFLICT, "ATTENDEE_REQUIRED");
if (t.getAttendeeConsentAt() != null) return;
capture(t, r.noticeId(), t.getCheckedInAt() != null);
}
/** Records the attendee's consent and links their event lead, matched as in QR registration; attend marks it attended. */
void capture(Ticket t, long noticeId, boolean attend) {
LocalDateTime now = LocalDateTime.now();
RegistrationService.RegisterResult res = registration.register(new RegistrationService.RegisterRequest(t.getCompanyId(),
t.getEventUuid(), null, t.getAttendeeName(), t.getAttendeeMobileE164(), t.getAttendeeEmail(), null, null, List.of(),
noticeId, now, attend, "TICKET", null));
t.setAttendeeConsentAt(now);
t.setAttendeeNoticeId(noticeId);
if (res != null && res.eventLeadUuid() != null) t.setEventLeadUuid(Long.valueOf(res.eventLeadUuid()));
tickets.save(t);
}
/** A checked attendee: a name of up to 100 characters and a mobile or an email (mobile-api has normalised them). */
private record Attendee(String name, String mobile, String email) {
void applyTo(Ticket t) {
t.setAttendeeName(name);
t.setAttendeeMobileE164(mobile);
t.setAttendeeEmail(email);
t.setAttendeeNamedAt(LocalDateTime.now());
}
}
private static Attendee attendee(String rawName, String rawMobile, String rawEmail) {
String name = rawName == null ? "" : rawName.strip();
if (name.isEmpty()) throw status(HttpStatus.BAD_REQUEST, "NAME_REQUIRED");
if (name.length() > 100) throw status(HttpStatus.BAD_REQUEST, "NAME_TOO_LONG");
String mobile = blankToNull(rawMobile), email = blankToNull(rawEmail);
if (mobile == null && email == null) throw status(HttpStatus.BAD_REQUEST, "MOBILE_OR_EMAIL_REQUIRED");
return new Attendee(name, mobile, email);
}
/** Staff calls carry the event's company; another company's ticket is not found. */
public record StaffRequest(Long companyId, String code) {}
/** name, mobile and email are needed only for an unnamed ticket; noticeId is the attendee's consent, ticked at the door. */
public record CheckInRequest(Long companyId, String code, String name, String mobileE164, String email, Long noticeId, String doneBy) {}
public record StaffView(long companyId, long eventUuid, String typeName, String attendeeName, boolean named, boolean consented,
String state, LocalDateTime checkedInAt, String checkedInBy) {}
public StaffView staffView(StaffRequest r) {
Ticket t = staffTicket(r.companyId(), r.code());
return staffView(t, orders.findById(t.getOrderId()).orElseThrow(TicketService::notFound));
}
/** Door check-in (spec: Door Check-In, Door Check-In Refusals). The conditional update lets only one scanner win. */
@Transactional
public StaffView checkIn(CheckInRequest r) {
Ticket t = staffTicket(r.companyId(), r.code());
ShopOrder o = orders.findById(t.getOrderId()).orElseThrow(TicketService::notFound);
String state = TicketState.of(o, t);
if (TicketState.CHECKED_IN.equals(state)) throw status(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN|" + t.getCheckedInAt());
if (!TicketState.VALID.equals(state)) throw status(HttpStatus.CONFLICT, "NOT_VALID|" + state);
LocalDateTime now = LocalDateTime.now();
Event e = events.findByUuid(t.getEventUuid()).orElseThrow(TicketService::notFound);
if (!EventDays.isDuring(e, now)) throw status(HttpStatus.CONFLICT, "NOT_EVENT_DAY");
Attendee a = t.getAttendeeName() == null ? attendee(r.name(), r.mobileE164(), r.email()) : null;
// ponytail: the loser of a race is told the time it tried, not the winner's; seconds apart at the same door.
if (tickets.checkIn(t.getId(), now, r.doneBy()) == 0) throw status(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN|" + now);
// keep the entity in step with the update, or a later save would write checked_in_at back to null
t.setCheckedInAt(now);
t.setCheckedInBy(r.doneBy());
if (a != null) a.applyTo(t);
if (r.noticeId() != null && t.getAttendeeConsentAt() == null) {
capture(t, r.noticeId(), true);
} else {
if (t.getEventLeadUuid() != null) eventLeads.findByUuid(t.getEventLeadUuid()).filter(el -> el.getAttendedAt() == null)
.ifPresent(el -> {
el.setAttendedAt(now);
eventLeads.save(el);
});
tickets.save(t);
}
return staffView(t, o);
}
private Ticket staffTicket(Long companyId, String code) {
Ticket t = ticket(code);
if (companyId == null || companyId != t.getCompanyId()) throw notFound();
return t;
}
private StaffView staffView(Ticket t, ShopOrder o) {
String typeName = lines.findById(t.getOrderLineId()).map(ShopOrderLine::getName).orElse(null);
return new StaffView(t.getCompanyId(), t.getEventUuid(), typeName, t.getAttendeeName(), t.getAttendeeName() != null,
t.getAttendeeConsentAt() != null, TicketState.of(o, t), t.getCheckedInAt(), t.getCheckedInBy());
}
private static String blankToNull(String s) {
return s == null || s.isBlank() ? null : s.strip();
}
static ResponseStatusException status(HttpStatus status, String reason) {
return new ResponseStatusException(status, reason);
}
/** The public ticket page: no buyer details and no attendee contact. */
public record TicketView(long companyId, long eventUuid, String typeName, String attendeeFirstName, boolean named, String state,
LocalDateTime checkedInAt, boolean consented) {}
public TicketView byCode(String code) {
Ticket t = ticket(code);
ShopOrder o = orders.findById(t.getOrderId()).orElseThrow(TicketService::notFound);
String typeName = lines.findById(t.getOrderLineId()).map(ShopOrderLine::getName).orElse(null);
return new TicketView(t.getCompanyId(), t.getEventUuid(), typeName, firstName(t.getAttendeeName()), t.getAttendeeName() != null,
TicketState.of(o, t), t.getCheckedInAt(), t.getAttendeeConsentAt() != null);
}
Ticket ticket(String code) {
if (code == null) throw notFound();
return tickets.findByCode(code).orElseThrow(TicketService::notFound);
}
static ResponseStatusException notFound() {
return new ResponseStatusException(HttpStatus.NOT_FOUND, "TICKET_NOT_FOUND");
}
static String firstName(String name) {
if (name == null || name.isBlank()) return null;
String t = name.strip();
int sp = t.indexOf(' ');
return sp < 0 ? t : t.substring(0, sp);
}
}
@@ -0,0 +1,31 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.ShopOrder;
import com.solvway.services.counter.model.Ticket;
/** add-event-tickets: one ticket's state, the single rule the ticket page, the door and self check-in all use. */
public final class TicketState {
public static final String VALID = "VALID";
public static final String CHECKED_IN = "CHECKED_IN";
public static final String AWAITING = "AWAITING";
public static final String ORDER_CANCELLED = "ORDER_CANCELLED";
public static final String ORDER_EXPIRED = "ORDER_EXPIRED";
public static final String TICKET_CANCELLED = "TICKET_CANCELLED";
private TicketState() {}
public static String of(ShopOrder order, Ticket ticket) {
if (Ticket.CANCELLED.equals(ticket.getStatus())) return TICKET_CANCELLED;
return switch (order.getStatus()) {
case ShopOrder.PAID -> ticket.getCheckedInAt() != null ? CHECKED_IN : VALID;
case ShopOrder.CANCELLED -> ORDER_CANCELLED;
case ShopOrder.EXPIRED -> ORDER_EXPIRED;
default -> AWAITING;
};
}
/** A new ticket code: 22 URL-safe characters, as the other link tokens. */
public static String newCode() {
return RegistrationLinkService.newToken();
}
}
@@ -0,0 +1,205 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.ShopOrder;
import com.solvway.services.counter.model.ShopOrderLine;
import com.solvway.services.counter.model.Ticket;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.ShopOrderLineRepository;
import com.solvway.services.counter.repo.ShopOrderRepository;
import com.solvway.services.counter.repo.TicketRepository;
import com.solvway.services.counter.repo.TicketTypeRepository;
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.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-event-tickets: naming attendees, attendee consent and resend ticket (spec: Naming Attendees, Naming Effects, Naming Refusals,
* Attendee Is Not A Lead Without Consent, Attendee Consent, Resend Ticket). */
@ExtendWith(MockitoExtension.class)
class TicketAttendeeTest {
private static final long COMPANY = 7L;
private static final long EVENT = 900L;
private static final String TOKEN = "tokentokentokentokento";
private static final String CODE = "aaaaaaaaaaaaaaaaaaaaaa";
@Mock private TicketRepository tickets;
@Mock private ShopOrderRepository orders;
@Mock private ShopOrderLineRepository lines;
@Mock private EventRepository events;
@Mock private TicketTypeRepository types;
@Mock private RegistrationService registration;
@Mock private TicketOrderMailer mailer;
private TicketService service;
private TicketOrderStaffService staff;
private ShopOrder order;
private Ticket ticket;
@BeforeEach
void setUp() {
service = new TicketService(tickets, orders, lines, registration, mailer, events, null);
staff = new TicketOrderStaffService(events, new TicketTypeService(events, types, tickets, lines), types, tickets, orders, lines, mailer);
order = new ShopOrder();
order.setId(300L);
order.setCompanyId(COMPANY);
order.setEventUuid(EVENT);
order.setToken(TOKEN);
order.setStatus(ShopOrder.PAID);
order.setBuyerName("Aisyah Rahman");
order.setBuyerEmail("a@example.test");
lenient().when(orders.findByToken(TOKEN)).thenReturn(Optional.of(order));
lenient().when(orders.findById(300L)).thenReturn(Optional.of(order));
ticket = new Ticket();
ticket.setId(1L);
ticket.setCompanyId(COMPANY);
ticket.setEventUuid(EVENT);
ticket.setOrderId(300L);
ticket.setOrderLineId(400L);
ticket.setCode(CODE);
lenient().when(tickets.findById(1L)).thenReturn(Optional.of(ticket));
lenient().when(tickets.findByCode(CODE)).thenReturn(Optional.of(ticket));
lenient().when(tickets.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(ticket));
lenient().when(tickets.save(any(Ticket.class))).thenAnswer(i -> i.getArgument(0));
ShopOrderLine line = new ShopOrderLine();
line.setId(400L);
line.setName("General");
lenient().when(lines.findById(400L)).thenReturn(Optional.of(line));
Event e = new Event();
e.setUuid(EVENT);
e.setCompanyId(COMPANY);
lenient().when(events.findByUuid(EVENT)).thenReturn(Optional.of(e));
lenient().when(registration.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "5000"));
}
private static TicketService.AttendeeRequest name(String name, String mobile, String email, boolean permission) {
return new TicketService.AttendeeRequest(TOKEN, 1L, name, mobile, email, permission);
}
private static void assertStatus(Runnable r, int status, String reason) {
assertThatThrownBy(r::run).isInstanceOfSatisfying(ResponseStatusException.class, ex -> {
assertThat(ex.getStatusCode().value()).isEqualTo(status);
assertThat(ex.getReason()).isEqualTo(reason);
});
}
@Test
void namingNeedsThePermissionTick() {
assertStatus(() -> service.nameAttendee(name("Tan Mei Ling", null, "tan@example.test", false)), 400, "PERMISSION_REQUIRED");
assertThat(ticket.getCode()).isEqualTo(CODE);
verify(tickets, never()).save(any());
}
@Test
void namingNeedsANameAndOneContact() {
assertStatus(() -> service.nameAttendee(name(" ", null, "tan@example.test", true)), 400, "NAME_REQUIRED");
assertStatus(() -> service.nameAttendee(name("Tan", null, null, true)), 400, "MOBILE_OR_EMAIL_REQUIRED");
}
@Test
void namingIsRefusedForAnUnpaidOrderACancelledOrACheckedInTicket() {
order.setStatus(ShopOrder.AWAITING);
assertStatus(() -> service.nameAttendee(name("Tan", null, "tan@example.test", true)), 409, "NOT_PAID");
order.setStatus(ShopOrder.PAID);
ticket.setStatus(Ticket.CANCELLED);
assertStatus(() -> service.nameAttendee(name("Tan", null, "tan@example.test", true)), 409, "TICKET_CANCELLED");
ticket.setStatus(Ticket.ACTIVE);
ticket.setCheckedInAt(LocalDateTime.now());
assertStatus(() -> service.nameAttendee(name("Tan", null, "tan@example.test", true)), 409, "ALREADY_CHECKED_IN");
}
@Test
void anUnknownTokenOrAnotherOrdersTicketIsNotFound() {
when(orders.findByToken("zzzzzzzzzzzzzzzzzzzzzz")).thenReturn(Optional.empty());
assertStatus(() -> service.nameAttendee(new TicketService.AttendeeRequest("zzzzzzzzzzzzzzzzzzzzzz", 1L, "Tan", null, "t@x.test", true)),
404, "ORDER_NOT_FOUND");
ticket.setOrderId(301L);
assertStatus(() -> service.nameAttendee(name("Tan", null, "tan@example.test", true)), 404, "ORDER_NOT_FOUND");
}
@Test
void namingReplacesTheCodeClearsConsentAndEmailsTheAttendee() {
ticket.setAttendeeConsentAt(LocalDateTime.now());
ticket.setAttendeeNoticeId(77L);
ticket.setEventLeadUuid(5000L);
TicketOrderService.OrderTicket t = service.nameAttendee(name(" Tan Mei Ling ", null, "tan@example.test", true));
assertThat(ticket.getCode()).matches("[A-Za-z0-9_-]{22}").isNotEqualTo(CODE);
assertThat(t.code()).isEqualTo(ticket.getCode());
assertThat(ticket.getAttendeeName()).isEqualTo("Tan Mei Ling");
assertThat(ticket.getAttendeeEmail()).isEqualTo("tan@example.test");
assertThat(ticket.getAttendeeNamedAt()).isNotNull();
assertThat(ticket.getAttendeeConsentAt()).isNull();
assertThat(ticket.getAttendeeNoticeId()).isNull();
assertThat(ticket.getEventLeadUuid()).isNull();
verify(mailer).sendTicket(ticket, "tan@example.test");
verify(registration, never()).register(any());
}
@Test
void namingWithOnlyAMobileSendsNoEmail() {
service.nameAttendee(name("Lim Wei", "+60125550101", null, true));
assertThat(ticket.getAttendeeMobileE164()).isEqualTo("+60125550101");
verify(mailer, never()).sendTicket(any(), anyString());
}
@Test
void consentCapturesTheAttendeeAsATicketLead() {
order.setStatus(ShopOrder.PAID);
ticket.setAttendeeName("Tan Mei Ling");
ticket.setAttendeeEmail("tan@example.test");
service.consent(new TicketService.ConsentRequest(CODE, 77L));
ArgumentCaptor<RegistrationService.RegisterRequest> r = ArgumentCaptor.forClass(RegistrationService.RegisterRequest.class);
verify(registration).register(r.capture());
assertThat(r.getValue().source()).isEqualTo("TICKET");
assertThat(r.getValue().salespersonUserId()).isNull();
assertThat(r.getValue().consentNoticeId()).isEqualTo(77L);
assertThat(r.getValue().email()).isEqualTo("tan@example.test");
assertThat(r.getValue().attend()).isFalse();
assertThat(ticket.getAttendeeConsentAt()).isNotNull();
assertThat(ticket.getAttendeeNoticeId()).isEqualTo(77L);
assertThat(ticket.getEventLeadUuid()).isEqualTo(5000L);
}
@Test
void consentIsRefusedOnAnInvalidOrUnnamedTicket() {
assertStatus(() -> service.consent(new TicketService.ConsentRequest(CODE, 77L)), 409, "ATTENDEE_REQUIRED");
ticket.setAttendeeName("Tan");
ticket.setAttendeeEmail("tan@example.test");
order.setStatus(ShopOrder.CANCELLED);
assertStatus(() -> service.consent(new TicketService.ConsentRequest(CODE, 77L)), 409, "TICKET_NOT_VALID");
verify(registration, never()).register(any());
}
@Test
void resendTicketGoesToTheAttendeeElseTheBuyer() {
staff.resendTicket(new TicketOrderStaffService.ActionRequest(COMPANY, EVENT, 300L, 1L, "staff1"));
verify(mailer).sendTicket(ticket, "a@example.test");
ticket.setAttendeeName("Tan");
ticket.setAttendeeEmail("tan@example.test");
staff.resendTicket(new TicketOrderStaffService.ActionRequest(COMPANY, EVENT, 300L, 1L, "staff1"));
verify(mailer).sendTicket(ticket, "tan@example.test");
}
@Test
void resendTicketRefusesAnInvalidTicket() {
order.setStatus(ShopOrder.AWAITING);
assertStatus(() -> staff.resendTicket(new TicketOrderStaffService.ActionRequest(COMPANY, EVENT, 300L, 1L, "staff1")),
409, "TICKET_NOT_VALID");
}
}
@@ -0,0 +1,332 @@
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.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.model.ShopOrder;
import com.solvway.services.counter.model.ShopOrderLine;
import com.solvway.services.counter.model.Ticket;
import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.LeadRepository;
import com.solvway.services.counter.repo.ShopOrderLineRepository;
import com.solvway.services.counter.repo.ShopOrderRepository;
import com.solvway.services.counter.repo.TicketRepository;
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 org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-event-tickets: door check-in, self check-in on a ticketed event, no walk-ins, ticket counts
* (spec: Door Check-In, Door Check-In Refusals, Self check-in on a ticketed event, No walk-ins on a ticketed event, Ticket attendance numbers). */
@ExtendWith(MockitoExtension.class)
class TicketCheckInTest {
private static final long COMPANY = 7L;
private static final long EVENT = 900L;
private static final String CODE = "aaaaaaaaaaaaaaaaaaaaaa";
@Mock private TicketRepository tickets;
@Mock private ShopOrderRepository orders;
@Mock private ShopOrderLineRepository lines;
@Mock private EventRepository events;
@Mock private EventLeadRepository eventLeads;
@Mock private EventGuestRepository guests;
@Mock private LeadRepository leads;
@Mock private RegistrationService registration;
@Mock private TicketOrderMailer mailer;
private TicketService service;
private EventCheckInService venue;
private Event event;
private ShopOrder order;
private Ticket ticket;
@BeforeEach
void setUp() {
service = new TicketService(tickets, orders, lines, registration, mailer, events, eventLeads);
venue = new EventCheckInService(events, guests, eventLeads, leads, tickets);
event = new Event();
event.setUuid(EVENT);
event.setCompanyId(COMPANY);
event.setEnabled(GeneralEnum.FlagYesNo.Y);
event.setTicketsEnabled(true);
event.setDateStart(LocalDateTime.now().minusHours(2));
event.setDateEnd(LocalDateTime.now().plusHours(6));
lenient().when(events.findByUuid(EVENT)).thenReturn(Optional.of(event));
order = new ShopOrder();
order.setId(300L);
order.setCompanyId(COMPANY);
order.setEventUuid(EVENT);
order.setStatus(ShopOrder.PAID);
order.setBuyerName("Aisyah Rahman");
lenient().when(orders.findById(300L)).thenReturn(Optional.of(order));
ticket = new Ticket();
ticket.setId(1L);
ticket.setCompanyId(COMPANY);
ticket.setEventUuid(EVENT);
ticket.setOrderId(300L);
ticket.setOrderLineId(400L);
ticket.setCode(CODE);
lenient().when(tickets.findByCode(CODE)).thenReturn(Optional.of(ticket));
lenient().when(tickets.save(any(Ticket.class))).thenAnswer(i -> i.getArgument(0));
lenient().when(tickets.checkIn(eq(1L), any(), any())).thenReturn(1);
ShopOrderLine line = new ShopOrderLine();
line.setName("General");
lenient().when(lines.findById(400L)).thenReturn(Optional.of(line));
lenient().when(registration.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "5000"));
}
private static void assertStatus(Runnable r, int status, String reason) {
assertThatThrownBy(r::run).isInstanceOfSatisfying(ResponseStatusException.class, ex -> {
assertThat(ex.getStatusCode().value()).isEqualTo(status);
assertThat(ex.getReason()).isEqualTo(reason);
});
}
private TicketService.CheckInRequest door(String name, String mobile, String email, Long noticeId) {
return new TicketService.CheckInRequest(COMPANY, CODE, name, mobile, email, noticeId, "staff1");
}
private void named() {
ticket.setAttendeeName("Tan Mei Ling");
ticket.setAttendeeEmail("tan@example.test");
}
// ---- staff view and door check-in
@Test
void theStaffViewShowsTheAttendeeAndStateButAnotherCompanysTicketIsNotFound() {
named();
TicketService.StaffView v = service.staffView(new TicketService.StaffRequest(COMPANY, CODE));
assertThat(v.attendeeName()).isEqualTo("Tan Mei Ling");
assertThat(v.state()).isEqualTo(TicketState.VALID);
assertThat(v.typeName()).isEqualTo("General");
assertStatus(() -> service.staffView(new TicketService.StaffRequest(8L, CODE)), 404, "TICKET_NOT_FOUND");
assertStatus(() -> service.checkIn(new TicketService.CheckInRequest(8L, CODE, null, null, null, null, "x")), 404, "TICKET_NOT_FOUND");
assertStatus(() -> service.staffView(new TicketService.StaffRequest(null, CODE)), 404, "TICKET_NOT_FOUND");
}
@Test
void thePublicViewTellsWhetherTheAttendeeHasConsented() {
named();
assertThat(service.byCode(CODE).consented()).isFalse();
ticket.setAttendeeConsentAt(LocalDateTime.now());
assertThat(service.byCode(CODE).consented()).isTrue();
}
@Test
void checkInRecordsTheTimeAndTheStaffUserWithAConditionalUpdate() {
named();
TicketService.StaffView v = service.checkIn(door(null, null, null, null));
verify(tickets).checkIn(eq(1L), any(LocalDateTime.class), eq("staff1"));
assertThat(v.state()).isEqualTo(TicketState.CHECKED_IN);
assertThat(v.checkedInBy()).isEqualTo("staff1");
assertThat(ticket.getCheckedInAt()).isNotNull();
verify(registration, never()).register(any());
}
@Test
void aSecondCheckInIsRefusedWithTheFirstTime() {
named();
LocalDateTime first = LocalDateTime.of(2026, 12, 4, 9, 30);
ticket.setCheckedInAt(first);
assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "ALREADY_CHECKED_IN|" + first);
verify(tickets, never()).checkIn(anyLong(), any(), any());
}
@Test
void aScannerThatLosesTheRaceIsRefused() {
named();
when(tickets.checkIn(eq(1L), any(), any())).thenReturn(0);
assertThatThrownBy(() -> service.checkIn(door(null, null, null, null)))
.isInstanceOfSatisfying(ResponseStatusException.class, ex -> assertThat(ex.getReason()).startsWith("ALREADY_CHECKED_IN|"));
}
@Test
void anInvalidTicketIsRefusedWithItsState() {
named();
order.setStatus(ShopOrder.AWAITING);
assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_VALID|AWAITING");
order.setStatus(ShopOrder.CANCELLED);
assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_VALID|ORDER_CANCELLED");
order.setStatus(ShopOrder.EXPIRED);
assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_VALID|ORDER_EXPIRED");
order.setStatus(ShopOrder.PAID);
ticket.setStatus(Ticket.CANCELLED);
assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_VALID|TICKET_CANCELLED");
verify(tickets, never()).checkIn(anyLong(), any(), any());
}
@Test
void checkInIsRefusedOutsideTheEventDays() {
named();
event.setDateStart(LocalDateTime.now().plusDays(3));
event.setDateEnd(LocalDateTime.now().plusDays(4));
assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_EVENT_DAY");
verify(tickets, never()).checkIn(anyLong(), any(), any());
}
@Test
void anUnnamedTicketNeedsANameAndContactAndCreatesNoLeadWithoutConsent() {
assertStatus(() -> service.checkIn(door(null, "+60125550101", null, null)), 400, "NAME_REQUIRED");
assertStatus(() -> service.checkIn(door("Lim Wei", null, " ", null)), 400, "MOBILE_OR_EMAIL_REQUIRED");
verify(tickets, never()).checkIn(anyLong(), any(), any());
service.checkIn(door(" Lim Wei ", "+60125550101", null, null));
assertThat(ticket.getAttendeeName()).isEqualTo("Lim Wei");
assertThat(ticket.getAttendeeMobileE164()).isEqualTo("+60125550101");
assertThat(ticket.getAttendeeNamedAt()).isNotNull();
assertThat(ticket.getCode()).isEqualTo(CODE);
verify(registration, never()).register(any());
}
@Test
void consentAtTheDoorCreatesTheLeadMarkedAttended() {
service.checkIn(door("Lim Wei", "+60125550101", null, 77L));
ArgumentCaptor<RegistrationService.RegisterRequest> r = ArgumentCaptor.forClass(RegistrationService.RegisterRequest.class);
verify(registration).register(r.capture());
assertThat(r.getValue().source()).isEqualTo("TICKET");
assertThat(r.getValue().attend()).isTrue();
assertThat(r.getValue().mobileE164()).isEqualTo("+60125550101");
assertThat(ticket.getEventLeadUuid()).isEqualTo(5000L);
assertThat(ticket.getAttendeeConsentAt()).isNotNull();
}
@Test
void anEarlierConsentMarksTheExistingLeadAttended() {
named();
ticket.setAttendeeConsentAt(LocalDateTime.now().minusDays(1));
ticket.setEventLeadUuid(5000L);
EventLead el = new EventLead();
when(eventLeads.findByUuid(5000L)).thenReturn(Optional.of(el));
service.checkIn(door(null, null, null, null));
assertThat(el.getAttendedAt()).isNotNull();
verify(eventLeads).save(el);
verify(registration, never()).register(any());
}
// ---- venue self check-in on a ticketed event
private EventCheckInService.LookupResult selfCheckIn(String mobile, String email) {
return venue.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, mobile, email));
}
@Test
void aNamedAttendeeChecksThemselvesIn() {
ticket.setAttendeeName("Lim Wei");
ticket.setAttendeeMobileE164("+60125550101");
when(tickets.selfCheckIn(EVENT, "+60125550101", null)).thenReturn(List.<Object[]>of(new Object[]{ticket, "Aisyah Rahman"}));
EventCheckInService.LookupResult r = selfCheckIn("+60125550101", null);
assertThat(r.result()).isEqualTo("CHECKED_IN");
assertThat(r.firstName()).isEqualTo("Lim");
verify(tickets).checkIn(eq(1L), any(LocalDateTime.class), eq("self"));
}
@Test
void anUnnamedTicketWelcomesItsBuyerAndMarksAConsentedLeadAttended() {
ticket.setEventLeadUuid(5000L);
EventLead el = new EventLead();
when(eventLeads.findByUuid(5000L)).thenReturn(Optional.of(el));
when(tickets.selfCheckIn(EVENT, null, "a@example.test")).thenReturn(List.<Object[]>of(new Object[]{ticket, "Aisyah Rahman"}));
EventCheckInService.LookupResult r = selfCheckIn(null, "a@example.test");
assertThat(r.firstName()).isEqualTo("Aisyah");
assertThat(el.getAttendedAt()).isNotNull();
}
@Test
void theNextTicketIsTakenWhenTheOldestWasJustCheckedInElsewhere() {
Ticket second = new Ticket();
second.setId(2L);
when(tickets.selfCheckIn(EVENT, "+60125550101", null))
.thenReturn(List.of(new Object[]{ticket, "Aisyah Rahman"}, new Object[]{second, "Aisyah Rahman"}));
when(tickets.checkIn(eq(1L), any(), any())).thenReturn(0);
when(tickets.checkIn(eq(2L), any(), any())).thenReturn(1);
assertThat(selfCheckIn("+60125550101", null).result()).isEqualTo("CHECKED_IN");
verify(tickets).checkIn(eq(2L), any(), eq("self"));
}
@Test
void aRegisteredGuestStillChecksIn() {
EventLead el = new EventLead();
el.setId(55L);
Lead lead = new Lead();
lead.setName("Tan Mei Ling");
when(tickets.selfCheckIn(EVENT, "+60125550102", null)).thenReturn(List.of());
when(eventLeads.findByEventAndMobile(EVENT, "+60125550102")).thenReturn(List.<Object[]>of(new Object[]{el, lead}));
when(guests.existsByEventLeadId(55L)).thenReturn(true);
EventCheckInService.LookupResult r = selfCheckIn("+60125550102", null);
assertThat(r.result()).isEqualTo("CHECKED_IN");
assertThat(r.firstName()).isEqualTo("Tan");
assertThat(el.getAttendedAt()).isNotNull();
}
@Test
void anyoneElseIsAskedToShowTheirTicket() {
EventLead el = new EventLead();
el.setId(56L);
Lead lead = new Lead();
lead.setName("Buyer Of A Cancelled Order");
when(tickets.selfCheckIn(EVENT, "+60125550103", null)).thenReturn(List.of());
when(eventLeads.findByEventAndMobile(EVENT, "+60125550103")).thenReturn(List.<Object[]>of(new Object[]{el, lead}));
when(guests.existsByEventLeadId(56L)).thenReturn(false);
EventCheckInService.LookupResult r = selfCheckIn("+60125550103", null);
assertThat(r.result()).isEqualTo("SHOW_TICKET");
assertThat(r.firstName()).isNull();
assertThat(el.getAttendedAt()).isNull();
verify(eventLeads, never()).save(any());
}
@Test
void anEventWithoutTicketsKeepsTheOldResults() {
event.setTicketsEnabled(false);
when(eventLeads.findByEventAndMobile(EVENT, "+60125550104")).thenReturn(List.of());
assertThat(selfCheckIn("+60125550104", null).result()).isEqualTo("FORM");
verify(tickets, never()).selfCheckIn(anyLong(), any(), any());
}
@Test
void aWalkInRegistrationIsRefusedOnATicketedEvent() {
EventLeadService leadService = mock(EventLeadService.class);
when(leadService.sellsTickets(EVENT)).thenReturn(true);
RegistrationService reg = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)),
leads, eventLeads, leadService);
RegistrationService.RegisterRequest walkIn = new RegistrationService.RegisterRequest(COMPANY, EVENT, null, "Walk In",
"+60125550105", null, null, null, List.of(), 77L, LocalDateTime.now(), true, null, null);
assertStatus(() -> reg.register(walkIn), 409, "TICKETS_ONLY");
verify(eventLeads, never()).saveAndFlush(any());
}
// ---- counts
@Test
void theHeadcountGivesTicketsAwaitingPaidAndCheckedIn() {
when(tickets.countsByOrderStatus(EVENT)).thenReturn(List.of(new Object[]{ShopOrder.AWAITING, 2L, 0L},
new Object[]{ShopOrder.PAID, 5L, 3L}));
EventHeadcountService.Headcount h = new EventHeadcountService(events, guests, eventLeads, tickets)
.headcount(new EventHeadcountService.Request(COMPANY, EVENT));
assertThat(h.ticketsAwaiting()).isEqualTo(2);
assertThat(h.ticketsPaid()).isEqualTo(5);
assertThat(h.ticketsCheckedIn()).isEqualTo(3);
}
}
@@ -0,0 +1,252 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.ShopOrder;
import com.solvway.services.counter.model.ShopOrderLine;
import com.solvway.services.counter.model.Ticket;
import com.solvway.services.counter.model.TicketType;
import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.ShopOrderLineRepository;
import com.solvway.services.counter.repo.ShopOrderRepository;
import com.solvway.services.counter.repo.TicketRepository;
import com.solvway.services.counter.repo.TicketTypeRepository;
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.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** add-event-tickets: codes on payment, ticket state, the code lookup and the order page's tickets (spec: Ticket Codes, Ticket Page,
* Invalid Ticket Links, Tickets On The Order Page). */
@ExtendWith(MockitoExtension.class)
class TicketCodesTest {
private static final long COMPANY = 7L;
private static final long EVENT = 900L;
private static final LocalDate TODAY = LocalDate.now(ZoneId.of("Asia/Kuala_Lumpur"));
private static final String CODE_SHAPE = "[A-Za-z0-9_-]{22}";
@Mock private EventRepository events;
@Mock private TicketTypeRepository types;
@Mock private TicketRepository tickets;
@Mock private ShopOrderRepository orders;
@Mock private ShopOrderLineRepository lines;
@Mock private EventGuestRepository guests;
@Mock private EventLeadRepository eventLeads;
@Mock private RegistrationService registration;
@Mock private TicketOrderMailer mailer;
private TicketOrderService orderService;
private TicketOrderStaffService staff;
private TicketService ticketService;
private final List<Ticket> saved = new ArrayList<>();
private ShopOrder order;
private ShopOrderLine line;
@BeforeEach
void setUp() {
TicketTypeService typeService = new TicketTypeService(events, types, tickets, lines);
orderService = new TicketOrderService(new TransactionTemplate(mock(PlatformTransactionManager.class)), events, typeService, types,
orders, lines, tickets, guests, eventLeads, registration, mailer);
staff = new TicketOrderStaffService(events, typeService, types, tickets, orders, lines, mailer);
ticketService = new TicketService(tickets, orders, lines, registration, mailer, events, eventLeads);
Event event = new Event();
event.setUuid(EVENT);
event.setCompanyId(COMPANY);
event.setDateStart(TODAY.plusDays(7).atTime(9, 0));
event.setDateEnd(TODAY.plusDays(8).atTime(18, 0));
event.setTicketsEnabled(true);
event.setHoldDays(3);
lenient().when(events.lockByUuid(EVENT)).thenReturn(Optional.of(event));
TicketType free = new TicketType();
free.setId(5L);
free.setCompanyId(COMPANY);
free.setEventUuid(EVENT);
free.setName("Community pass");
free.setQuantity(50);
free.setEnabled(true);
TicketType general = new TicketType();
general.setId(2L);
general.setCompanyId(COMPANY);
general.setEventUuid(EVENT);
general.setName("General");
general.setPriceSen(25000);
general.setQuantity(50);
general.setEnabled(true);
lenient().when(types.findByEventUuidOrderBySortAscIdAsc(EVENT)).thenReturn(List.of(general, free));
lenient().when(orders.saveAndFlush(any(ShopOrder.class))).thenAnswer(i -> {
ShopOrder o = i.getArgument(0);
o.setId(300L);
return o;
});
lenient().when(orders.save(any(ShopOrder.class))).thenAnswer(i -> i.getArgument(0));
lenient().when(lines.save(any(ShopOrderLine.class))).thenAnswer(i -> {
ShopOrderLine l = i.getArgument(0);
l.setId(400L);
return l;
});
lenient().when(tickets.save(any(Ticket.class))).thenAnswer(i -> {
saved.add(i.getArgument(0));
return i.getArgument(0);
});
lenient().when(registration.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", null));
order = new ShopOrder();
order.setId(300L);
order.setCompanyId(COMPANY);
order.setEventUuid(EVENT);
order.setReference("T-7K3M9Q");
order.setStatus(ShopOrder.AWAITING);
order.setBuyerName("Aisyah Rahman");
order.setBuyerEmail("a@example.test");
lenient().when(orders.findById(300L)).thenReturn(Optional.of(order));
line = new ShopOrderLine();
line.setId(400L);
line.setOrderId(300L);
line.setItemId(2L);
line.setName("General");
line.setUnitPriceSen(25000);
line.setQuantity(2);
lenient().when(lines.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(line));
lenient().when(lines.findById(400L)).thenReturn(Optional.of(line));
}
private static TicketOrderService.Request request(long typeId, int qty) {
return new TicketOrderService.Request(COMPANY, EVENT, List.of(new TicketOrderService.LineRequest(typeId, qty)), "Aisyah",
"a@example.test", null, null, 77L, LocalDateTime.now(), null, null, null, null);
}
private static Ticket ticket(long id, String status) {
Ticket t = new Ticket();
t.setId(id);
t.setCompanyId(COMPANY);
t.setEventUuid(EVENT);
t.setOrderId(300L);
t.setOrderLineId(400L);
t.setTicketTypeId(2L);
t.setStatus(status);
return t;
}
@Test
void aFreeOrdersTicketsGetDistinctCodesAtOnce() {
orderService.request(request(5L, 3));
assertThat(saved).hasSize(3).allSatisfy(t -> assertThat(t.getCode()).matches(CODE_SHAPE));
assertThat(new HashSet<>(saved.stream().map(Ticket::getCode).toList())).hasSize(3);
}
@Test
void anAwaitingOrdersTicketsHaveNoCode() {
orderService.request(request(2L, 2));
assertThat(saved).hasSize(2).allSatisfy(t -> assertThat(t.getCode()).isNull());
}
@Test
void markPaidGivesEachActiveTicketACode() {
Ticket a = ticket(1L, Ticket.ACTIVE), b = ticket(2L, Ticket.ACTIVE), c = ticket(3L, Ticket.CANCELLED);
when(tickets.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(a, b, c));
staff.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, null, "staff1"));
assertThat(a.getCode()).matches(CODE_SHAPE);
assertThat(b.getCode()).matches(CODE_SHAPE).isNotEqualTo(a.getCode());
assertThat(c.getCode()).isNull();
}
@Test
void anExpiredOrderMarkedPaidGetsCodes() {
order.setStatus(ShopOrder.EXPIRED);
Ticket a = ticket(1L, Ticket.ACTIVE);
when(tickets.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(a));
staff.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, null, "staff1"));
assertThat(a.getCode()).matches(CODE_SHAPE);
}
@Test
void ticketStateCoversEveryCase() {
Ticket t = ticket(1L, Ticket.ACTIVE);
order.setStatus(ShopOrder.PAID);
assertThat(TicketState.of(order, t)).isEqualTo(TicketState.VALID);
t.setCheckedInAt(LocalDateTime.now());
assertThat(TicketState.of(order, t)).isEqualTo(TicketState.CHECKED_IN);
t.setCheckedInAt(null);
t.setStatus(Ticket.CANCELLED);
assertThat(TicketState.of(order, t)).isEqualTo(TicketState.TICKET_CANCELLED);
t.setStatus(Ticket.ACTIVE);
order.setStatus(ShopOrder.AWAITING);
assertThat(TicketState.of(order, t)).isEqualTo(TicketState.AWAITING);
order.setStatus(ShopOrder.CANCELLED);
assertThat(TicketState.of(order, t)).isEqualTo(TicketState.ORDER_CANCELLED);
order.setStatus(ShopOrder.EXPIRED);
assertThat(TicketState.of(order, t)).isEqualTo(TicketState.ORDER_EXPIRED);
}
@Test
void byCodeShowsTheTicketWithoutContactDetails() {
order.setStatus(ShopOrder.PAID);
Ticket t = ticket(1L, Ticket.ACTIVE);
t.setCode("abcdefghijklmnopqrstuv");
t.setAttendeeName("Tan Mei Ling");
t.setAttendeeEmail("tan@example.test");
t.setAttendeeMobileE164("+60125550101");
when(tickets.findByCode("abcdefghijklmnopqrstuv")).thenReturn(Optional.of(t));
TicketService.TicketView v = ticketService.byCode("abcdefghijklmnopqrstuv");
assertThat(v.companyId()).isEqualTo(COMPANY);
assertThat(v.eventUuid()).isEqualTo(EVENT);
assertThat(v.typeName()).isEqualTo("General");
assertThat(v.attendeeFirstName()).isEqualTo("Tan");
assertThat(v.named()).isTrue();
assertThat(v.state()).isEqualTo(TicketState.VALID);
assertThat(v.toString()).doesNotContain("tan@example.test", "+60125550101", "Aisyah");
}
@Test
void anUnknownCodeIsNotFound() {
when(tickets.findByCode("zzzzzzzzzzzzzzzzzzzzzz")).thenReturn(Optional.empty());
assertThatThrownBy(() -> ticketService.byCode("zzzzzzzzzzzzzzzzzzzzzz")).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode().value()).isEqualTo(404);
assertThat(e.getReason()).isEqualTo("TICKET_NOT_FOUND");
});
}
@Test
void thePaidOrderPageListsTicketsWithoutContacts() {
order.setStatus(ShopOrder.PAID);
Ticket a = ticket(1L, Ticket.ACTIVE), b = ticket(2L, Ticket.ACTIVE), c = ticket(3L, Ticket.CANCELLED);
a.setCode("aaaaaaaaaaaaaaaaaaaaaa");
a.setAttendeeName("Tan Mei Ling");
a.setAttendeeEmail("tan@example.test");
b.setCode("bbbbbbbbbbbbbbbbbbbbbb");
when(orders.findByToken("tokentokentokentokento")).thenReturn(Optional.of(order));
when(tickets.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(a, b, c));
TicketOrderService.OrderView v = orderService.byToken("tokentokentokentokento");
assertThat(v.tickets()).extracting(TicketOrderService.OrderTicket::id).containsExactly(1L, 2L);
assertThat(v.tickets().get(0)).isEqualTo(new TicketOrderService.OrderTicket(1L, "General", "Tan Mei Ling", "aaaaaaaaaaaaaaaaaaaaaa",
TicketState.VALID, null));
assertThat(v.tickets().get(1).attendeeName()).isNull();
assertThat(v.toString()).doesNotContain("tan@example.test");
}
@Test
void anUnpaidOrderPageHasNoTickets() {
when(orders.findByToken("tokentokentokentokento")).thenReturn(Optional.of(order));
assertThat(orderService.byToken("tokentokentokentokento").tickets()).isEmpty();
}
}
@@ -0,0 +1,109 @@
package com.solvway.services.counter.service;
import com.solvway.core.model.Email;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.ShopOrder;
import com.solvway.services.counter.model.ShopOrderLine;
import com.solvway.services.counter.model.Ticket;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.ShopOrderLineRepository;
import com.solvway.services.counter.repo.TicketRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
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.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-event-tickets: the paid email carries the tickets, and the ticket email (spec: Order Emails, Ticket Email). */
class TicketMailTest {
private static final String BASE = "https://co-lite.example";
private final ShopOrderLineRepository lines = mock(ShopOrderLineRepository.class);
private final EventRepository events = mock(EventRepository.class);
private final TicketRepository tickets = mock(TicketRepository.class);
private final EmailService emailService = mock(EmailService.class);
private final TicketOrderMailer mailer = new TicketOrderMailer(emailService, events, lines, tickets, BASE);
private ShopOrder order;
@BeforeEach
void setUp() {
order = new ShopOrder();
order.setId(300L);
order.setCompanyId(7L);
order.setEventUuid(900L);
order.setReference("T-7K3M9Q");
order.setToken("tokentokentokentokento");
order.setBuyerName("Aisyah");
order.setBuyerEmail("a@example.test");
order.setStatus(ShopOrder.PAID);
order.setTotalSen(50000);
Event e = new Event();
e.setName("KL Hotel Tech Day");
e.setLocation("KLCC");
e.setDateStart(LocalDateTime.of(2027, 1, 15, 9, 0));
e.setDateEnd(LocalDateTime.of(2027, 1, 16, 18, 0));
when(events.findByUuid(900L)).thenReturn(Optional.of(e));
ShopOrderLine l = new ShopOrderLine();
l.setId(400L);
l.setName("General");
l.setUnitPriceSen(25000);
l.setQuantity(2);
when(lines.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(l));
when(lines.findById(400L)).thenReturn(Optional.of(l));
when(emailService.send(any())).thenReturn(Optional.of(new Email()));
}
private static Ticket ticket(long id, String code, String status) {
Ticket t = new Ticket();
t.setId(id);
t.setCompanyId(7L);
t.setEventUuid(900L);
t.setOrderId(300L);
t.setOrderLineId(400L);
t.setCode(code);
t.setStatus(status);
return t;
}
private Email sent() {
ArgumentCaptor<Email> e = ArgumentCaptor.forClass(Email.class);
verify(emailService).send(e.capture());
return e.getValue();
}
@Test
void thePaidEmailCarriesEachActiveTicketsQrAndLinkAndTheNamingLink() {
when(tickets.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(
ticket(1L, "aaaaaaaaaaaaaaaaaaaaaa", Ticket.ACTIVE), ticket(2L, "bbbbbbbbbbbbbbbbbbbbbb", Ticket.ACTIVE),
ticket(3L, "cccccccccccccccccccccc", Ticket.CANCELLED)));
mailer.send(order, "PAID");
String body = sent().getBody();
assertThat(body).contains("<img src=\"" + BASE + "/api/public/tickets/aaaaaaaaaaaaaaaaaaaaaa/qr.png\"")
.contains(BASE + "/t/aaaaaaaaaaaaaaaaaaaaaa")
.contains(BASE + "/api/public/tickets/bbbbbbbbbbbbbbbbbbbbbb/qr.png")
.doesNotContain("cccccccccccccccccccccc")
.contains("Name your attendees").contains(BASE + "/o/tokentokentokentokento");
}
@Test
void theTicketEmailGoesToTheGivenAddressWithItsQrAndLink() {
Ticket t = ticket(1L, "aaaaaaaaaaaaaaaaaaaaaa", Ticket.ACTIVE);
t.setAttendeeName("Tan <Mei> Ling");
mailer.sendTicket(t, "tan@example.test");
Email e = sent();
assertThat(e.getCompanyId()).isEqualTo(7L);
assertThat(e.getRecipients()).extracting(r -> r.getRecipient()).containsExactly("tan@example.test");
assertThat(e.getSubject()).contains("KL Hotel Tech Day");
assertThat(e.getBody()).contains(BASE + "/api/public/tickets/aaaaaaaaaaaaaaaaaaaaaa/qr.png")
.contains(BASE + "/t/aaaaaaaaaaaaaaaaaaaaaa").contains("General").contains("KLCC")
.contains("Tan &lt;Mei&gt; Ling").contains("Bahasa Malaysia")
.doesNotContain("Aisyah");
}
}
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more