Compare commits

...
Author SHA1 Message Date
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
ngqileandClaude Opus 5.5 86f5fd73cb docs(tickets): release note for 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:39:11 +08:00
ngqileandClaude Opus 5.5 e850b09cb6 feat(tickets): TICKETS page block, editor picker and public order page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 16:26:11 +08:00
ngqileandClaude Opus 5.5 5a51be1c11 feat(tickets): event Tickets section, orders list and order detail
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 16:08:08 +08:00
ngqileandClaude Opus 5.5 d25641e139 feat(tickets): public ticket request, order page and gateway paths
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 15:53:54 +08:00
ngqileandClaude Opus 5.5 a18ca0db71 feat(tickets): admin ticket settings, types and order endpoints
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 15:48:29 +08:00
ngqileandClaude Opus 5.5 763a295234 feat(tickets): TICKETS page block validation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 15:42:08 +08:00
ngqileandClaude Opus 5.5 687f054acf feat(tickets): staff order actions, order emails and hold expiry job
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 15:39:28 +08:00
ngqileandClaude Opus 5.5 6dca31510e feat(tickets): ticket order request with seat locking, capacity and buyer lead
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 15:31:05 +08:00
ngqileandClaude Opus 5.5 b8a1873266 feat(tickets): ticket settings, ticket types and order tables
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 15:23:16 +08:00
ngqileandClaude Opus 5.5 896ee3bcc5 docs: propose 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 14:58:59 +08:00
ngqileandClaude Opus 5.5 58dc27dbc4 docs: ticketing design answers attendee consent, walk-ins and invites
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 14:49:24 +08:00
ngqileandClaude Opus 5.5 cf0f9d0b6e docs: event ticketing design (draft)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 14:43:50 +08: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
ngqile de8ff61fe0 Merge pull request 'docs: archive add-hero-fits-screen' (#83) from archive-hero-fits-screen into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 04:45:20 +00:00
ngqileandClaude Opus 5.5 12296ac203 docs: archive add-hero-fits-screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 12:45:13 +08:00
ngqile 6164263208 Merge pull request 'fix(pages): fit the top bar, hero and trust strip on one desktop screen' (#82) from add-hero-fits-screen into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 04:45:06 +00:00
ngqileandClaude Opus 5.5 405dab55dd fix(pages): fit the top bar, hero and trust strip on one desktop screen
A trust strip band uses less padding, the full-width hero less padding, and the
landing-page form tighter gaps with the consent in small text. Controls keep
their 44 px height. On the INS page at 1920x1080 the trust strip now ends at
937 px instead of 1077 px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 12:44:55 +08:00
ngqile b6f5fb441e Merge pull request 'docs: archive add-landing-page-polish' (#81) from archive-landing-page-polish into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 04:28:36 +00:00
ngqileandClaude Opus 5.5 cc2d1c794e docs: archive add-landing-page-polish
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 12:28:28 +08:00
ngqile c21a31e10f Merge pull request 'feat(pages): a top bar section, section labels and serif headings' (#80) from add-landing-page-polish into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 04:28:21 +00:00
ngqileandClaude Opus 5.5 e4ad18a8a3 feat(pages): a top bar section, section labels and serif headings
Landing pages gain a Top bar section (the company logo and an optional button,
kept at the top of the window, first section only), a short label above the
headings of five section types, and serif section headings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 12:28:09 +08:00
ngqile 2a69826e66 Merge pull request 'docs: archive add-landing-thanks-and-footer' (#79) from archive-landing-thanks-and-footer into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 03:45:57 +00:00
ngqileandClaude Opus 5.5 92412cb300 docs: archive add-landing-thanks-and-footer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 11:45:49 +08:00
ngqile 35e9b796f7 Merge pull request 'feat(pages): a footer section with contact links, and a thank-you text on landing forms' (#78) from add-landing-thanks-and-footer into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 03:45:38 +00:00
ngqileandClaude Opus 5.5 3446f261be feat(pages): a footer section with contact links, and a thank-you text on landing forms
Landing pages gain a Footer section (1 to 4 columns of title and text, a legal
line under a divider) whose phone numbers, emails and web addresses show as
links. The Form block and a hero with a form may carry a thank-you text shown
after sign-up, with the same links. Full-width heroes get a lighter shade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 11:45:25 +08:00
ngqile 5a1aa447d5 Merge pull request 'docs: archive add-compact-landing-form' (#77) from archive-compact-landing-form into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 02:47:28 +00:00
ngqileandClaude Opus 5.5 2697a591aa docs: archive add-compact-landing-form
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 10:47:20 +08:00
ngqile 23840e8fbf Merge pull request 'feat(pages): a short sign-up form on landing pages, and coloured sections join' (#76) from add-compact-landing-form into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 02:47:12 +00:00
ngqileandClaude Opus 5.5 ba6ab7554d feat(pages): a short sign-up form on landing pages, and coloured sections join
Landing-page forms drop job title, ask for one service in a dropdown and fold the
privacy notice behind one line above the consent box. QR, invitation and customer
forms keep the full form. Sections with a colour look join with no gap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 10:47:02 +08:00
ngqile a7129b417e Merge pull request 'docs: archive add-html-image-upload' (#75) from archive-html-image-upload into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 02:10:43 +00:00
145 changed files with 9613 additions and 132 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>
+21
View File
@@ -470,4 +470,25 @@ A form stops taking sign-ups when its event is disabled, its end date has passed
**Release add-html-image-upload (SQL, in its OpenSpec change folder):** deploy the portal, then run `sql/01-html-image-labels.sql` (labels only). A Custom HTML block's panel can now upload an image and show its link to copy. Rollback: the previous portal image. **Release add-html-image-upload (SQL, in its OpenSpec change folder):** deploy the portal, then run `sql/01-html-image-labels.sql` (labels only). A Custom HTML block's panel can now upload an image and show its link to copy. Rollback: the previous portal image.
**Release add-compact-landing-form (SQL, in its OpenSpec change folder):** deploy the portal, then run `sql/01-compact-form-labels.sql` (labels only). Landing-page sign-up forms drop job title, ask for one service in a dropdown, and fold the privacy notice behind one line. Coloured sections now join with no gap. QR, invitation and customer forms are unchanged. Before go-live, the PDPA owner should confirm the folded notice. Rollback: the previous portal image.
**Release add-landing-thanks-and-footer (SQL, in its OpenSpec change folder):** deploy services-counter and the portal together, then run `sql/01-thanks-footer-labels.sql` (labels only). Landing pages gain a Footer section (1 to 4 columns, a legal line, contact links) and a thank-you text on the Form block and on a hero with a form. Full-width heroes get a lighter shade. Deploy the counter first: an older counter refuses pages that use the new fields. Rollback: the previous images; pages saved with a Footer or thank-you text then fail to save until the release is back.
**Release add-landing-page-polish (SQL, in its OpenSpec change folder):** deploy services-counter first, then the portal, then run `sql/01-polish-labels.sql` (labels only). Landing pages gain a Top bar section (the company logo and an optional button, kept at the top of the window, first section only) and an optional small label above the headings of Feature cards, Steps, Image with text, FAQ and Call to action. Section headings on every landing page, CV included, now use the serif typeface. Rollback: the previous images; pages saved with a top bar or labels then fail to save until the release is back.
**New portal dependencies:** `@tiptap/react`, `@tiptap/pm`, `@tiptap/starter-kit` and `@tiptap/extension-text-align` (the editor, loaded only on the editor screens), and `sanitize-html` (cleans page text on the server before it reaches a visitor). The image build installs them from `package-lock.json`; nothing to do by hand. **New portal dependencies:** `@tiptap/react`, `@tiptap/pm`, `@tiptap/starter-kit` and `@tiptap/extension-text-align` (the editor, loaded only on the editor screens), and `sanitize-html` (cleans page text on the server before it reaches a visitor). The image build installs them from `package-lock.json`; nothing to do by hand.
## 13. Event tickets
Staff sell tickets for an event from its **Tickets** card; buyers request them on a landing page's **Tickets** section and pay outside Co-Lite (for example by bank transfer). Staff mark an order paid when the money arrives.
1. **Module.** Grant `BO_EVENT_TICKETS` (with `BO_EVENTS`) to the roles that manage ticket settings and orders.
2. **Set up an event.** On the event, switch **Sell tickets** on, write the payment instructions (the bank account and what reference to use) and the hold days (how long an unpaid order keeps its seats), then add ticket types with price, quantity and an optional sales end date. A price of RM 0 makes a free ticket: its order is confirmed at once.
3. **Sell on a page.** Add a **Tickets** section to a landing page and pick the event; only events with tickets switched on are offered. A buyer chooses up to 10 tickets, gives name, email and consent, and gets an order reference, the payment instructions and a link to the order page `/o/<token>`. The buyer also becomes an event lead (source Ticket).
4. **Orders.** **View orders** on the Tickets card lists an event's orders by status. An order's page marks it paid (with an optional payment reference), cancels it or one ticket (freeing the seat), and resends the latest email. An expired order can still be marked paid while seats remain.
5. **Holds.** services-counter expires unpaid orders past their hold every 10 minutes (`tickets.expiry.cron`, Malaysia time) and emails the buyer. The update is conditional, so several services-counter replicas may run the job.
6. **Limits.** At most 10 tickets per order and 3 unpaid orders per email per event; requests share the landing-page rate limits, and the order page allows 120 loads per device.
**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.
@@ -0,0 +1,237 @@
# Event Ticketing: Design
Date: 2026-12-04. Status: owner questions answered 2026-12-04; awaiting approval.
## Intent
Co-Lite is growing from an event lead-capture tool into an event hosting platform. The owner's roadmap (2026-12-04) is:
1. Ticketing (this design).
2. Merch collected at events.
3. Merch sold as a standalone shop, with manual shipping.
4. Membership, with member prices, points and a member portal.
5. Self-serve SaaS sign-up with Free and Premium plans.
Some events are free and some are paid. Free events keep today's lead flow unchanged. Paid events sell tickets. **Leads stay the core.** Every ticket buyer, and every attendee they name, becomes a lead on the event, so sales can follow up after a paid event as well as a free one.
There is no payment gateway yet. Buyers pay outside Co-Lite, by bank transfer or the company's own payment link. Staff mark an order paid when the money arrives.
## Goals
- An organiser turns tickets on for an event. The organiser defines ticket types, each with a name, price, quantity and sales end date, and writes the payment instructions.
- A visitor requests tickets on a landing page through a new **Tickets** block. A request can hold up to 10 tickets across one or more types. The visitor gets an order with a private link.
- The order holds the seats for a set number of days (default 3, set per event) while it awaits payment, then expires on its own.
- Staff see each event's orders. They can mark an order paid, cancel an order, or cancel a single ticket.
- When an order is paid, each ticket gets its own QR code.
- The buyer can name an attendee for each ticket through the order link, and swap attendees until a ticket is checked in.
- Each named attendee gets their ticket by email.
- Tickets that are not named go to the buyer.
- At the door, staff open the ticket QR and check it in. An unpaid or cancelled ticket is clearly refused. For a ticket with no name, staff enter the attendee's name and contact details at check-in.
- The buyer becomes an event lead. Each named attendee also becomes an event lead.
## Non-goals (this build)
- **Payment gateway, online payment and refunds in Co-Lite.** Money moves outside. Only the order's status changes.
- **Receipts, invoices and SST.** The company issues these outside Co-Lite.
- **Merch products, stock and shipping.** The order model is shaped for them (see Data), but none is built.
- **Member accounts.** A buyer needs no login. Tickets belong to the person's mobile or email, so a future member account can claim them.
- **Seat maps, discount codes, waiting lists and ticket transfer between buyers.**
- **Currencies other than MYR.**
## Anti-goals (a failure even if it works)
- **Free events behave differently.** Events without tickets must keep every current registration, invite and check-in path unchanged.
- **Overselling.** More seats are held than a ticket type's quantity allows.
- **The order link leaks.** It shows the buyer's or attendees' details to anyone except the holder of that link.
- **Someone walks into a paid event without a paid ticket** through the self check-in walk-in form.
## Constraints
- **Stack and layering:**
- Events, leads, check-in and pages live in `solvway-services-counter`.
- Admin and public JSON endpoints go through `solvway-mobile-api`.
- Screens and public pages are in `solvway-admin-portal`.
- Emails go through `solvway-services-email`.
- **Company scoping:** every new table carries `company_id`, and all reads and writes are scoped as in `company-scoping`.
- **Rules shared with QR registration:** lead matching, normalisation, consent and the privacy notice follow the `qr-registration` rules.
- **Abuse limits:** public endpoints reuse the QR page's abuse limits.
- **Translations:** labels are in English and zh-CN, as in `ui-translations`.
- **Database changes:** DDL goes in the OpenSpec change folder.
## Approaches
1. **Built into Co-Lite (chosen).** Ticket tables sit on the event, a new Tickets block sits in the page builder, and the event gets a Tickets tab. Leads, check-in, capacity, emails and company scoping are all reused. A gateway later adds "pay now" to the same order.
2. **A separate ticketing service.** It would be cleaner to split out for SaaS, but it duplicates events, leads and check-in, and wiring it in costs much more before it brings any benefit.
3. **An outside platform** such as Eventbrite or Ticket2u. It's fastest, and payment is included. But the buyer data lives elsewhere, which works against becoming an event platform.
The owner chose approach 1.
## Decisions (owner)
- Payment happens outside Co-Lite for now, and staff mark orders paid.
- Visitors request tickets on the event page. Staff do not issue them.
- One request can hold several tickets. The buyer names the attendees later.
- The order can hold any kind of item, ready for merch. Merch will be both collected at events and shipped (shipping is manual, with no courier integration), in later builds.
- Ticket buyers become leads.
## Design
### Turning tickets on
- An event gets a **Tickets** switch, which is off by default. While it is off, the event behaves exactly as today.
- While it is on, the event has:
- **Ticket types.** Each has a name (up to 80 characters), a price in MYR (0 or more, stored in sen), a quantity (at least 1), an optional sales end date (default: the event's end date), a sort order and an enabled flag.
- **Payment instructions.** Free text up to 1,000 characters, shown on the thank-you page, the order page and the order email. Phone numbers, emails and links in it work, as in landing-page contact links.
- **Hold days.** 1 to 14, default 3.
- **Changing ticket types:**
- A ticket type with any orders cannot be deleted, only disabled.
- Its quantity cannot drop below the seats already held.
- A price change applies only to new orders, because each order line keeps its own price.
### Seats
- Seats are held by tickets in orders that are **Awaiting payment** or **Paid**, unless that ticket was cancelled.
- A type's seats left = its quantity minus its held seats.
- A request is refused if any type would go below 0. The check and the insert run in one transaction, with the event's ticket types locked, so two requests cannot take the last seat.
- **Event capacity:** when set, held tickets count toward it together with today's registered guests and walk-ins. Before the event days, a request that would go over capacity is refused, matching "Capacity before the event". Ticket types still cap sales at all times.
### Tickets block (page builder)
- **New block type TICKETS:**
- Its fields are the event, an optional heading and text, plus the standard Look, anchor and eyebrow.
- Only enabled, not-ended events of the page's company with Tickets on can be picked, matching the FORM block's event rules.
- **What the block shows:**
- Each enabled type, with its name, price as `RM 150.00` or `Free`, and either seats left or "Sold out" / "Sales ended".
- Next to each type, a quantity picker from 0 to 10. The total across types is at most 10.
- The buyer's fields:
- name (required);
- email (required, because the order link and tickets go there);
- mobile (optional);
- company (optional);
- the privacy notice consent (required).
- **Closed state:** the block shows that ticket sales are closed when:
- the event is disabled or has ended;
- Tickets is off;
- the company has no privacy notice.
- **Submit:**
1. Create the order.
2. Show the thank-you page: the order reference, the lines and total, the payment instructions, the hold expiry date and time, and a "View your order" link.
3. Email the same content to the buyer.
**Free orders:** if every line is free (order total RM 0), the order is **Paid** at once and tickets are issued straight away. This gives organisers free events with tickets, for example to control entry.
### Orders and order page
- **Order states:**
- Awaiting payment;
- Paid;
- Cancelled (by staff);
- Expired (hold ran out).
- **Order reference:** a short one, such as `T-7K3M9Q`, for bank transfer references. It is separate from the unguessable link token.
- **Order page** `/o/<token>`:
- It is public, open to anyone with the link.
- It shows the event, lines, total, status, the payment instructions while awaiting payment, and the hold expiry.
- **Once paid:** it lists the tickets with each attendee's name, a ticket link per ticket, and a form to name or rename each attendee (name, plus mobile or email). Each ticket and each attendee save stands alone.
- **Naming or renaming an attendee:**
- It issues a **new ticket code**, so the old QR stops working.
- It emails the new attendee their ticket.
- It is refused once that ticket is checked in.
- **What it never shows:** any details beyond what the buyer entered, and nothing about other orders.
- **Expiry:** a scheduled job in services-counter expires Awaiting-payment orders past their hold time and emails the buyer. Staff may mark an expired order paid only if its seats are still available, in which case it becomes Paid.
### Tickets and the door
- Each ticket has an unguessable code with the link `/t/<code>`. The ticket email holds the QR image of that link.
- **Ticket page, public view:**
- It shows the event name, dates, location, ticket type, the attendee's first name and the QR image.
- It shows the ticket's state, but for an unpaid, cancelled or expired ticket it shows "This ticket is not valid" instead of the QR.
- **Ticket page, staff view:**
- Who gets it: someone signed in to the admin portal on the same site, with `BO_EVENTS` for that event's company.
- For a valid ticket on an event day, it adds a large state banner and a **Check in** button.
- For an unnamed ticket, it shows name and mobile-or-email fields first.
- **Checking in:**
- It marks the ticket checked in.
- When the attendee has consented, it captures or links them as an event lead, using the QR registration matching, and marks that event lead attended.
- **Refusals:** a second check-in shows "Already checked in at <time>". Unpaid, cancelled or expired tickets show a red refusal banner.
- **Venue self check-in** (`/c/<token>`) on a ticketed event (owner decision 2026-12-04):
- A mobile or email that matches either of these checks them in:
- the attendee of a Paid ticket that is not yet checked in (if several match, the oldest);
- a registered invited guest.
- Anything else shows "Please show your ticket at the entrance" instead of the walk-in form.
- **Invited guests on ticketed events (owner decision 2026-12-04):** a registered invite counts as a free ticket. It holds a seat toward the event's capacity but not toward any ticket type. The guest checks in as today, through their invite link or the venue check-in. Invite links stay available while Tickets is on.
### Leads
- **Buyer:**
- When an order is created, the buyer is matched as in QR registration and becomes an event lead with the new source **TICKET**, no salesperson and the consent recorded.
- A buyer already captured at the event changes nothing, as in QR registration.
- Their notes record the order reference.
- **Named attendee (owner decision 2026-12-04):** an attendee does **not** become a lead until they consent themselves. No member account is needed.
- When naming attendees, the buyer ticks "I have permission to share these details so their ticket can be sent". Without it, the save is refused.
- Until consent is given, the attendee's details are used only to deliver and check the ticket. They appear on the ticket and the order, never in event leads, lead lists, exports or the dashboard.
- The attendee's ticket page and ticket email offer an optional "Keep me updated about <company> events", with the company's privacy notice. Ticking it records the consent time and notice version, and makes them an event lead with source TICKET, matched as in QR registration.
- At check-in, the staff view shows the same optional tick, so the attendee can consent on the spot.
- An attendee who never ticks it can still attend. Their ticket is checked in, but no lead is created.
- **Unnamed ticket:** at check-in, staff enter the person's name and contact details. That person becomes an event lead only if they tick the consent there.
### Staff screens
- **New permission `BO_EVENT_TICKETS`.** It gives access to the event's **Tickets** tab:
- the Tickets switch, ticket types, payment instructions and hold days;
- an **Orders** list for the event: reference, buyer, lines, total, status and created time, with a status filter and a search by reference, name, email or mobile;
- an **Order detail** page with these actions:
- **Mark paid**, with an optional payment reference of up to 100 characters. It records who marked it and when, then issues and emails the tickets.
- **Cancel order.**
- **Cancel ticket.**
- **Resend order email** and **Resend ticket.**
- Every action is written to the admin audit log.
- **Event attendance numbers:** they gain tickets awaiting payment, paid and checked in.
- **Super admins:** they see all companies, as today.
### Emails
All emails are sent through `solvway-services-email` and are in the company's language:
- **Order received:** lines, total, payment instructions, hold expiry and the order link.
- **Order paid:** the tickets. Each unnamed ticket comes as its own QR image and link, and a "Name your attendees" link points to the order page.
- **Ticket:** sent to a named attendee, with the QR image and link.
- **Order expired** and **Order cancelled.**
### Data (shaped for merch)
- `ticket_type` (company_id, event_id, name, price_sen, quantity, sales_end_date, sort, enabled).
- Event gains `tickets_enabled`, `payment_instructions` and `hold_days`.
- `shop_order`:
- company_id, event_id (nullable, for a future standalone shop), reference, token;
- buyer name, email, mobile and company;
- lead_id;
- status, total_sen, hold_until, paid_at, paid_by, payment_ref, cancelled_at, cancelled_by;
- consent time, privacy notice version, page address and UTM values.
- `shop_order_line`:
- order_id, kind, item_id, name snapshot, unit_price_sen, quantity.
- `kind` is `TICKET` now. `PICKUP` and `SHIP` are reserved for merch and are not built.
- `ticket`:
- company_id, event_id, order_line_id, code;
- attendee name, mobile and email;
- event_lead_id;
- status (ACTIVE or CANCELLED), checked_in_at, checked_in_by.
### Abuse limits
- Order requests and order-page views use the QR page's per-IP limits.
- At most **3 Awaiting-payment orders per email per event**, so nobody can hold every seat. A 4th request gets "You already have orders awaiting payment for this event."
## What's left to the builder
- Endpoint paths, DTO shapes and screen layouts, following the existing event and page-builder patterns.
- Email wording, and the zh-CN labels.
- The order reference alphabet and length. It must be unambiguous and unique per company.
- How the staff view of `/t/<code>` detects the staff session, without exposing anything when it is absent.
- Splitting the build into OpenSpec changes. Suggested:
1. ticket types and orders, with the staff side;
2. the Tickets block and order page;
3. tickets, emails and check-in at the door.
## Open questions (owner)
None. All three were answered on 2026-12-04: attendees consent themselves, there are no walk-ins on paid events, and a registered invite counts as a free ticket.
+103
View File
@@ -523,3 +523,106 @@ ALTER TABLE `notification`
-- add-page-drafts-and-templates: a published page's unpublished draft -- add-page-drafts-and-templates: a published page's unpublished draft
USE `service-counter`; USE `service-counter`;
ALTER TABLE `cms_page` ADD COLUMN `draft` json NULL COMMENT 'Unpublished changes of a published page: slug, title, metaDescription, hideHeader, blocks' AFTER `blocks`; ALTER TABLE `cms_page` ADD COLUMN `draft` json NULL COMMENT 'Unpublished changes of a published page: slug, title, metaDescription, hideHeader, blocks' AFTER `blocks`;
-- add-event-ticket-orders/sql/01-event-ticket-orders.sql
USE `service-counter`;
ALTER TABLE `event`
ADD COLUMN `tickets_enabled` tinyint(1) NOT NULL DEFAULT 0,
ADD COLUMN `payment_instructions` varchar(1000) NULL,
ADD COLUMN `hold_days` int NOT NULL DEFAULT 3;
CREATE TABLE IF NOT EXISTS `ticket_type` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_uuid` bigint NOT NULL,
`name` varchar(80) NOT NULL,
`price_sen` int NOT NULL,
`quantity` int NOT NULL,
`sales_end_date` date NULL,
`sort` int NOT NULL DEFAULT 0,
`enabled` tinyint(1) NOT NULL DEFAULT 1,
`created_by` varchar(255) NULL,
`created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP,
`updated_by` varchar(255) NULL,
`updated_at` datetime NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_ticket_type_name` (`event_uuid`, `name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `shop_order` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_uuid` bigint NULL COMMENT 'Null is reserved for a later standalone shop',
`reference` varchar(12) NOT NULL,
`token` varchar(32) NOT NULL,
`buyer_name` varchar(100) NOT NULL,
`buyer_email` varchar(254) NOT NULL,
`buyer_mobile_e164` varchar(20) NULL,
`buyer_company` varchar(150) NULL,
`lead_uuid` bigint NULL,
`event_lead_uuid` bigint NULL,
`status` varchar(20) NOT NULL COMMENT 'AWAITING, PAID, CANCELLED, EXPIRED',
`total_sen` int NOT NULL,
`hold_until` datetime NULL,
`paid_at` datetime NULL,
`paid_by` varchar(255) NULL,
`payment_ref` varchar(100) NULL,
`cancelled_at` datetime NULL,
`cancelled_by` varchar(255) NULL,
`expired_at` datetime NULL,
`consent_at` datetime NULL,
`consent_notice_id` bigint NULL,
`page_path` varchar(200) NULL,
`utm_source` varchar(100) NULL,
`utm_medium` varchar(100) NULL,
`utm_campaign` varchar(100) NULL,
`last_email` varchar(20) NULL COMMENT 'RECEIVED, PAID, EXPIRED, CANCELLED',
`created_at` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_shop_order_reference` (`company_id`, `reference`),
UNIQUE KEY `uk_shop_order_token` (`token`),
KEY `idx_shop_order_event_status` (`event_uuid`, `status`),
KEY `idx_shop_order_hold` (`status`, `hold_until`),
KEY `idx_shop_order_buyer` (`event_uuid`, `buyer_email`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `shop_order_line` (
`id` bigint NOT NULL AUTO_INCREMENT,
`order_id` bigint NOT NULL,
`kind` varchar(10) NOT NULL COMMENT 'TICKET; PICKUP and SHIP reserved for merch',
`item_id` bigint NOT NULL COMMENT 'ticket_type.id for TICKET',
`name` varchar(80) NOT NULL,
`unit_price_sen` int NOT NULL,
`quantity` int NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_shop_order_line_order` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `ticket` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_uuid` bigint NOT NULL,
`order_id` bigint NOT NULL,
`order_line_id` bigint NOT NULL,
`ticket_type_id` bigint NOT NULL,
`code` varchar(32) NULL COMMENT 'QR code, issued by add-event-tickets',
`attendee_name` varchar(100) NULL,
`attendee_mobile_e164` varchar(20) NULL,
`attendee_email` varchar(254) NULL,
`event_lead_uuid` bigint NULL,
`status` varchar(10) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE, CANCELLED',
`cancelled_at` datetime NULL,
`cancelled_by` varchar(255) NULL,
`checked_in_at` datetime NULL,
`checked_in_by` varchar(255) 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`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- add-event-ticket-orders/sql/02-event-tickets-module.sql
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(41160000, 'BO_EVENT_TICKETS', 'Event tickets', 'BO', 'M', 40000000, NULL, NULL);
+240
View File
@@ -1117,6 +1117,12 @@ INSERT INTO message (code, content, area) SELECT 'RegCompany', JSON_OBJECT('en_U
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '公司') WHERE LOWER(code) = LOWER('RegCompany') AND area = 'A'; UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '公司') WHERE LOWER(code) = LOWER('RegCompany') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegJobTitle', JSON_OBJECT('en_US', 'Job title', 'zh_CN', '职位'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegJobTitle') AND area = 'A'); INSERT INTO message (code, content, area) SELECT 'RegJobTitle', JSON_OBJECT('en_US', 'Job title', 'zh_CN', '职位'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegJobTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '职位') WHERE LOWER(code) = LOWER('RegJobTitle') AND area = 'A'; UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '职位') WHERE LOWER(code) = LOWER('RegJobTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegServiceInterest', JSON_OBJECT('en_US', 'Service interested in (optional)', 'zh_CN', '感兴趣的服务(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegServiceInterest') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '感兴趣的服务(可选)') WHERE LOWER(code) = LOWER('RegServiceInterest') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegChooseService', JSON_OBJECT('en_US', 'Choose a service', 'zh_CN', '选择服务'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegChooseService') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '选择服务') WHERE LOWER(code) = LOWER('RegChooseService') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegNoticeSummary', JSON_OBJECT('en_US', 'How we use your details (English / Bahasa Malaysia)', 'zh_CN', '我们如何使用您的资料(English / Bahasa Malaysia)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegNoticeSummary') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '我们如何使用您的资料(English / Bahasa Malaysia)') WHERE LOWER(code) = LOWER('RegNoticeSummary') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegInterests', JSON_OBJECT('en_US', 'Interests (optional)', 'zh_CN', '兴趣(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegInterests') AND area = 'A'); INSERT INTO message (code, content, area) SELECT 'RegInterests', JSON_OBJECT('en_US', 'Interests (optional)', 'zh_CN', '兴趣(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegInterests') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '兴趣(可选)') WHERE LOWER(code) = LOWER('RegInterests') AND area = 'A'; UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '兴趣(可选)') WHERE LOWER(code) = LOWER('RegInterests') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegNoticeEn', JSON_OBJECT('en_US', 'English', 'zh_CN', '英文'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegNoticeEn') AND area = 'A'); INSERT INTO message (code, content, area) SELECT 'RegNoticeEn', JSON_OBJECT('en_US', 'English', 'zh_CN', '英文'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegNoticeEn') AND area = 'A');
@@ -1727,6 +1733,22 @@ INSERT INTO message (code, content, area) SELECT 'PagesFormHeading', JSON_OBJECT
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单标题') WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A'; UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单标题') WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormText', JSON_OBJECT('en_US', 'Form text', 'zh_CN', '表单说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A'); INSERT INTO message (code, content, area) SELECT 'PagesFormText', JSON_OBJECT('en_US', 'Form text', 'zh_CN', '表单说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单说明') WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A'; UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单说明') WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesThanksText', JSON_OBJECT('en_US', 'Thank-you text', 'zh_CN', '感谢语'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesThanksText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '感谢语') WHERE LOWER(code) = LOWER('PagesThanksText') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockFooter', JSON_OBJECT('en_US', 'Footer', 'zh_CN', '页脚'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockFooter') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页脚') WHERE LOWER(code) = LOWER('PagesBlockFooter') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesColumnN', JSON_OBJECT('en_US', 'Column {number}', 'zh_CN', '第 {number} 栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesColumnN') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '第 {number} 栏') WHERE LOWER(code) = LOWER('PagesColumnN') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddColumn', JSON_OBJECT('en_US', 'Add column', 'zh_CN', '添加栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddColumn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加栏') WHERE LOWER(code) = LOWER('PagesAddColumn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFooterLegal', JSON_OBJECT('en_US', 'Legal line', 'zh_CN', '版权声明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFooterLegal') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '版权声明') WHERE LOWER(code) = LOWER('PagesFooterLegal') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockTopBar', JSON_OBJECT('en_US', 'Top bar', 'zh_CN', '顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockTopBar') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '顶栏') WHERE LOWER(code) = LOWER('PagesBlockTopBar') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesEyebrow', JSON_OBJECT('en_US', 'Label', 'zh_CN', '小标签'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesEyebrow') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '小标签') WHERE LOWER(code) = LOWER('PagesEyebrow') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTopBarFirst', JSON_OBJECT('en_US', 'The top bar must be the first section.', 'zh_CN', '顶栏必须是第一个区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTopBarFirst') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '顶栏必须是第一个区块。') WHERE LOWER(code) = LOWER('PagesTopBarFirst') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUploadImage', JSON_OBJECT('en_US', 'Upload image', 'zh_CN', '上传图片'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUploadImage') AND area = 'A'); INSERT INTO message (code, content, area) SELECT 'PagesUploadImage', JSON_OBJECT('en_US', 'Upload image', 'zh_CN', '上传图片'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUploadImage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上传图片') WHERE LOWER(code) = LOWER('PagesUploadImage') AND area = 'A'; UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上传图片') WHERE LOWER(code) = LOWER('PagesUploadImage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUploadImageHint', JSON_OBJECT('en_US', 'PNG, JPEG or WebP up to 2 MB. Paste the link into your HTML, for example in an img tag''s src.', 'zh_CN', 'PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUploadImageHint') AND area = 'A'); INSERT INTO message (code, content, area) SELECT 'PagesUploadImageHint', JSON_OBJECT('en_US', 'PNG, JPEG or WebP up to 2 MB. Paste the link into your HTML, for example in an img tag''s src.', 'zh_CN', 'PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUploadImageHint') AND area = 'A');
@@ -1825,4 +1847,222 @@ INSERT INTO message (code, content, area) SELECT 'CompAccentHint', JSON_OBJECT('
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '用于本公司网页的按钮。留空则使用默认蓝色。') WHERE LOWER(code) = LOWER('CompAccentHint') AND area = 'A'; UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '用于本公司网页的按钮。留空则使用默认蓝色。') WHERE LOWER(code) = LOWER('CompAccentHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'CompBrandingSaveFailed', JSON_OBJECT('en_US', 'Could not save the branding.', 'zh_CN', '无法保存品牌设置。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('CompBrandingSaveFailed') AND area = 'A'); INSERT INTO message (code, content, area) SELECT 'CompBrandingSaveFailed', JSON_OBJECT('en_US', 'Could not save the branding.', 'zh_CN', '无法保存品牌设置。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('CompBrandingSaveFailed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法保存品牌设置。') WHERE LOWER(code) = LOWER('CompBrandingSaveFailed') AND area = 'A'; UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法保存品牌设置。') WHERE LOWER(code) = LOWER('CompBrandingSaveFailed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'GuestHeldTickets', JSON_OBJECT('en_US', 'Held tickets', 'zh_CN', '已占门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('GuestHeldTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已占门票') WHERE LOWER(code) = LOWER('GuestHeldTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTicketsClosed', JSON_OBJECT('en_US', 'Choose an event that is selling tickets.', 'zh_CN', '请选择正在售票的活动。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTicketsClosed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请选择正在售票的活动。') WHERE LOWER(code) = LOWER('PagesTicketsClosed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTitle', JSON_OBJECT('en_US', 'Tickets', 'zh_CN', '门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票') WHERE LOWER(code) = LOWER('TktTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktViewOrders', JSON_OBJECT('en_US', 'View orders', 'zh_CN', '查看订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktViewOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看订单') WHERE LOWER(code) = LOWER('TktViewOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktLoadFailed', JSON_OBJECT('en_US', 'Could not load the tickets.', 'zh_CN', '无法加载门票。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktLoadFailed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法加载门票。') WHERE LOWER(code) = LOWER('TktLoadFailed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSaveFailed', JSON_OBJECT('en_US', 'Could not save. Try again.', 'zh_CN', '无法保存,请重试。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSaveFailed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法保存,请重试。') WHERE LOWER(code) = LOWER('TktSaveFailed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSettingsSaved', JSON_OBJECT('en_US', 'Ticket settings saved.', 'zh_CN', '门票设置已保存。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSettingsSaved') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票设置已保存。') WHERE LOWER(code) = LOWER('TktSettingsSaved') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSellTickets', JSON_OBJECT('en_US', 'Sell tickets', 'zh_CN', '售卖门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSellTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '售卖门票') WHERE LOWER(code) = LOWER('TktSellTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPaymentInstructions', JSON_OBJECT('en_US', 'Payment instructions', 'zh_CN', '付款说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPaymentInstructions') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款说明') WHERE LOWER(code) = LOWER('TktPaymentInstructions') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPaymentInstructionsHelp', JSON_OBJECT('en_US', 'Shown to buyers after they request tickets, e.g. the bank account and what reference to use.', 'zh_CN', '买家申请门票后显示,例如银行账户及付款备注。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPaymentInstructionsHelp') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '买家申请门票后显示,例如银行账户及付款备注。') WHERE LOWER(code) = LOWER('TktPaymentInstructionsHelp') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktHoldDays', JSON_OBJECT('en_US', 'Hold days', 'zh_CN', '保留天数'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktHoldDays') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保留天数') WHERE LOWER(code) = LOWER('TktHoldDays') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSaveSettings', JSON_OBJECT('en_US', 'Save ticket settings', 'zh_CN', '保存门票设置'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSaveSettings') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存门票设置') WHERE LOWER(code) = LOWER('TktSaveSettings') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPrice', JSON_OBJECT('en_US', 'Price', 'zh_CN', '价格'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPrice') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '价格') WHERE LOWER(code) = LOWER('TktPrice') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPriceRm', JSON_OBJECT('en_US', 'Price (RM)', 'zh_CN', '价格(RM)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPriceRm') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '价格(RM)') WHERE LOWER(code) = LOWER('TktPriceRm') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktQuantity', JSON_OBJECT('en_US', 'Quantity', 'zh_CN', '数量'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktQuantity') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '数量') WHERE LOWER(code) = LOWER('TktQuantity') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktLeft', JSON_OBJECT('en_US', 'Left', 'zh_CN', '剩余'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktLeft') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '剩余') WHERE LOWER(code) = LOWER('TktLeft') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSalesEnd', JSON_OBJECT('en_US', 'Sales end', 'zh_CN', '停售日期'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSalesEnd') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '停售日期') WHERE LOWER(code) = LOWER('TktSalesEnd') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSalesEndHelp', JSON_OBJECT('en_US', 'An empty sales end date means sales end with the event.', 'zh_CN', '停售日期留空表示随活动结束而停售。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSalesEndHelp') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '停售日期留空表示随活动结束而停售。') WHERE LOWER(code) = LOWER('TktSalesEndHelp') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNoTypes', JSON_OBJECT('en_US', 'No ticket types yet.', 'zh_CN', '尚无门票类型。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNoTypes') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚无门票类型。') WHERE LOWER(code) = LOWER('TktNoTypes') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktFree', JSON_OBJECT('en_US', 'Free', 'zh_CN', '免费'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktFree') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '免费') WHERE LOWER(code) = LOWER('TktFree') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktDisable', JSON_OBJECT('en_US', 'Disable', 'zh_CN', '停用'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktDisable') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '停用') WHERE LOWER(code) = LOWER('TktDisable') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktEnable', JSON_OBJECT('en_US', 'Enable', 'zh_CN', '启用'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktEnable') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '启用') WHERE LOWER(code) = LOWER('TktEnable') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktDelete', JSON_OBJECT('en_US', 'Delete', 'zh_CN', '删除'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktDelete') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '删除') WHERE LOWER(code) = LOWER('TktDelete') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTypeName', JSON_OBJECT('en_US', 'Ticket name', 'zh_CN', '门票名称'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTypeName') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票名称') WHERE LOWER(code) = LOWER('TktTypeName') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAddType', JSON_OBJECT('en_US', 'Add ticket type', 'zh_CN', '添加门票类型'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAddType') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加门票类型') WHERE LOWER(code) = LOWER('TktAddType') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSaveType', JSON_OBJECT('en_US', 'Save ticket type', 'zh_CN', '保存门票类型'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSaveType') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存门票类型') WHERE LOWER(code) = LOWER('TktSaveType') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktDeleteTitle', JSON_OBJECT('en_US', 'Delete ticket type', 'zh_CN', '删除门票类型'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktDeleteTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '删除门票类型') WHERE LOWER(code) = LOWER('TktDeleteTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktDeleteMessage', JSON_OBJECT('en_US', 'Delete {name}? This cannot be undone.', 'zh_CN', '删除 {name}?此操作无法撤销。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktDeleteMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '删除 {name}?此操作无法撤销。') WHERE LOWER(code) = LOWER('TktDeleteMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrInstructionsRequired', JSON_OBJECT('en_US', 'Enter the payment instructions before turning tickets on.', 'zh_CN', '开启售票前请填写付款说明。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrInstructionsRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '开启售票前请填写付款说明。') WHERE LOWER(code) = LOWER('TktErrInstructionsRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrInstructionsTooLong', JSON_OBJECT('en_US', 'Payment instructions can be at most 1000 characters.', 'zh_CN', '付款说明最多 1000 个字符。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrInstructionsTooLong') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款说明最多 1000 个字符。') WHERE LOWER(code) = LOWER('TktErrInstructionsTooLong') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrHoldDays', JSON_OBJECT('en_US', 'Hold days must be from 1 to 14.', 'zh_CN', '保留天数须为 1 至 14。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrHoldDays') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保留天数须为 1 至 14。') WHERE LOWER(code) = LOWER('TktErrHoldDays') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrName', JSON_OBJECT('en_US', 'Enter a name of 1 to 80 characters.', 'zh_CN', '请输入 1 至 80 个字符的名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrName') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入 1 至 80 个字符的名称。') WHERE LOWER(code) = LOWER('TktErrName') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrNameTaken', JSON_OBJECT('en_US', 'This event already has a ticket type with this name.', 'zh_CN', '本活动已有同名门票类型。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrNameTaken') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '本活动已有同名门票类型。') WHERE LOWER(code) = LOWER('TktErrNameTaken') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrPrice', JSON_OBJECT('en_US', 'Enter a price from 0.00 to 99999.99.', 'zh_CN', '请输入 0.00 至 99999.99 的价格。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrPrice') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入 0.00 至 99999.99 的价格。') WHERE LOWER(code) = LOWER('TktErrPrice') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrQuantity', JSON_OBJECT('en_US', 'Enter a quantity of at least 1.', 'zh_CN', '数量至少为 1。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrQuantity') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '数量至少为 1。') WHERE LOWER(code) = LOWER('TktErrQuantity') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrQuantityBelowHeld', JSON_OBJECT('en_US', 'The quantity cannot be below the seats already held.', 'zh_CN', '数量不能低于已占座位。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrQuantityBelowHeld') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '数量不能低于已占座位。') WHERE LOWER(code) = LOWER('TktErrQuantityBelowHeld') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrDate', JSON_OBJECT('en_US', 'Enter a valid date.', 'zh_CN', '请输入有效日期。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrDate') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入有效日期。') WHERE LOWER(code) = LOWER('TktErrDate') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrTypeHasOrders', JSON_OBJECT('en_US', 'This ticket type has orders. Disable it instead.', 'zh_CN', '此门票类型已有订单,请改为停用。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrTypeHasOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票类型已有订单,请改为停用。') WHERE LOWER(code) = LOWER('TktErrTypeHasOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrNotPayable', JSON_OBJECT('en_US', 'Only an order awaiting payment or expired can be marked paid.', 'zh_CN', '只有待付款或已过期的订单可标记为已付款。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrNotPayable') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '只有待付款或已过期的订单可标记为已付款。') WHERE LOWER(code) = LOWER('TktErrNotPayable') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrSeatsGone', JSON_OBJECT('en_US', 'The seats of this expired order were taken. It cannot be marked paid.', 'zh_CN', '此过期订单的座位已被占用,无法标记为已付款。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrSeatsGone') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此过期订单的座位已被占用,无法标记为已付款。') WHERE LOWER(code) = LOWER('TktErrSeatsGone') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrPaymentRef', JSON_OBJECT('en_US', 'The payment reference can be at most 100 characters.', 'zh_CN', '付款参考最多 100 个字符。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrPaymentRef') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款参考最多 100 个字符。') WHERE LOWER(code) = LOWER('TktErrPaymentRef') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrNotCancellable', JSON_OBJECT('en_US', 'Only an order awaiting payment or paid can be cancelled.', 'zh_CN', '只有待付款或已付款的订单可取消。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrNotCancellable') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '只有待付款或已付款的订单可取消。') WHERE LOWER(code) = LOWER('TktErrNotCancellable') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrLastTicket', JSON_OBJECT('en_US', 'This is the order''s last ticket. Cancel the order instead.', 'zh_CN', '这是订单的最后一张门票,请改为取消订单。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrLastTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '这是订单的最后一张门票,请改为取消订单。') WHERE LOWER(code) = LOWER('TktErrLastTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStatusAWAITING', JSON_OBJECT('en_US', 'Awaiting payment', 'zh_CN', '待付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStatusAWAITING') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待付款') WHERE LOWER(code) = LOWER('TktStatusAWAITING') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStatusPAID', JSON_OBJECT('en_US', 'Paid', 'zh_CN', '已付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStatusPAID') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已付款') WHERE LOWER(code) = LOWER('TktStatusPAID') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStatusCANCELLED', JSON_OBJECT('en_US', 'Cancelled', 'zh_CN', '已取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStatusCANCELLED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已取消') WHERE LOWER(code) = LOWER('TktStatusCANCELLED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStatusEXPIRED', JSON_OBJECT('en_US', 'Expired', 'zh_CN', '已过期'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStatusEXPIRED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已过期') WHERE LOWER(code) = LOWER('TktStatusEXPIRED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrdersTitle', JSON_OBJECT('en_US', 'Ticket orders', 'zh_CN', '门票订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrdersTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票订单') WHERE LOWER(code) = LOWER('TktOrdersTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktBackToEvent', JSON_OBJECT('en_US', 'Back to event', 'zh_CN', '返回活动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktBackToEvent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '返回活动') WHERE LOWER(code) = LOWER('TktBackToEvent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderState', JSON_OBJECT('en_US', 'Order state', 'zh_CN', '订单状态'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderState') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单状态') WHERE LOWER(code) = LOWER('TktOrderState') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSearchOrders', JSON_OBJECT('en_US', 'Search orders', 'zh_CN', '搜索订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSearchOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '搜索订单') WHERE LOWER(code) = LOWER('TktSearchOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSearchOrdersHint', JSON_OBJECT('en_US', 'Reference, name, email or mobile', 'zh_CN', '编号、姓名、电邮或手机'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSearchOrdersHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '编号、姓名、电邮或手机') WHERE LOWER(code) = LOWER('TktSearchOrdersHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReference', JSON_OBJECT('en_US', 'Reference', 'zh_CN', '编号'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReference') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '编号') WHERE LOWER(code) = LOWER('TktReference') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktBuyer', JSON_OBJECT('en_US', 'Buyer', 'zh_CN', '买家'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktBuyer') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '买家') WHERE LOWER(code) = LOWER('TktBuyer') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTickets', JSON_OBJECT('en_US', 'Tickets', 'zh_CN', '门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票') WHERE LOWER(code) = LOWER('TktTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTotal', JSON_OBJECT('en_US', 'Total', 'zh_CN', '总额'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTotal') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '总额') WHERE LOWER(code) = LOWER('TktTotal') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSalesEnded', JSON_OBJECT('en_US', 'Sales ended', 'zh_CN', '已停售'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSalesEnded') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已停售') WHERE LOWER(code) = LOWER('TktSalesEnded') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSeatsLeft', JSON_OBJECT('en_US', '{count} left', 'zh_CN', '剩余 {count} 张'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSeatsLeft') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '剩余 {count} 张') WHERE LOWER(code) = LOWER('TktSeatsLeft') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSoldOut', JSON_OBJECT('en_US', 'Sold out', 'zh_CN', '已售罄'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSoldOut') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已售罄') WHERE LOWER(code) = LOWER('TktSoldOut') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktRemoveOne', JSON_OBJECT('en_US', 'Remove one {name}', 'zh_CN', '减少一张 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktRemoveOne') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '减少一张 {name}') WHERE LOWER(code) = LOWER('TktRemoveOne') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAddOne', JSON_OBJECT('en_US', 'Add one {name}', 'zh_CN', '增加一张 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAddOne') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '增加一张 {name}') WHERE LOWER(code) = LOWER('TktAddOne') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPreviewNote', JSON_OBJECT('en_US', 'Visitors choose tickets and fill in their details here.', 'zh_CN', '访客在此选择门票并填写资料。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPreviewNote') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '访客在此选择门票并填写资料。') WHERE LOWER(code) = LOWER('TktPreviewNote') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSalesClosed', JSON_OBJECT('en_US', 'Ticket sales are closed.', 'zh_CN', '门票销售已结束。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSalesClosed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票销售已结束。') WHERE LOWER(code) = LOWER('TktSalesClosed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktChooseTickets', JSON_OBJECT('en_US', 'Choose at least one ticket.', 'zh_CN', '请至少选择一张门票。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktChooseTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请至少选择一张门票。') WHERE LOWER(code) = LOWER('TktChooseTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktEmailRequired', JSON_OBJECT('en_US', 'Enter your email.', 'zh_CN', '请输入电子邮件。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktEmailRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入电子邮件。') WHERE LOWER(code) = LOWER('TktEmailRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktConsentRequired', JSON_OBJECT('en_US', 'Tick the box to agree to the privacy notice.', 'zh_CN', '请勾选以同意隐私声明。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktConsentRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请勾选以同意隐私声明。') WHERE LOWER(code) = LOWER('TktConsentRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktMax', JSON_OBJECT('en_US', 'Up to 10 tickets per order.', 'zh_CN', '每笔订单最多 10 张门票。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktMax') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '每笔订单最多 10 张门票。') WHERE LOWER(code) = LOWER('TktMax') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktRequest', JSON_OBJECT('en_US', 'Request tickets', 'zh_CN', '申请门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktRequest') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '申请门票') WHERE LOWER(code) = LOWER('TktRequest') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktThanksPlain', JSON_OBJECT('en_US', 'Thank you. Your request for {event} is in.', 'zh_CN', '谢谢,您对 {event} 的申请已收到。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktThanksPlain') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '谢谢,您对 {event} 的申请已收到。') WHERE LOWER(code) = LOWER('TktThanksPlain') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktThanksPaid', JSON_OBJECT('en_US', 'Your order {reference} is confirmed.', 'zh_CN', '您的订单 {reference} 已确认。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktThanksPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您的订单 {reference} 已确认。') WHERE LOWER(code) = LOWER('TktThanksPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktThanks', JSON_OBJECT('en_US', 'We have your order {reference}. It is held until you pay.', 'zh_CN', '我们已收到您的订单 {reference},付款前为您保留。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktThanks') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '我们已收到您的订单 {reference},付款前为您保留。') WHERE LOWER(code) = LOWER('TktThanks') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktViewOrder', JSON_OBJECT('en_US', 'View your order', 'zh_CN', '查看订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktViewOrder') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看订单') WHERE LOWER(code) = LOWER('TktViewOrder') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktHowToPay', JSON_OBJECT('en_US', 'How to pay', 'zh_CN', '付款方式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktHowToPay') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款方式') WHERE LOWER(code) = LOWER('TktHowToPay') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPayBy', JSON_OBJECT('en_US', 'Pay by {when}', 'zh_CN', '请于 {when} 前付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPayBy') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请于 {when} 前付款') WHERE LOWER(code) = LOWER('TktPayBy') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicOrder', JSON_OBJECT('en_US', 'Order {reference}', 'zh_CN', '订单 {reference}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicOrder') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单 {reference}') WHERE LOWER(code) = LOWER('TktPublicOrder') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicAwaiting', JSON_OBJECT('en_US', 'Awaiting payment', 'zh_CN', '等待付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicAwaiting') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '等待付款') WHERE LOWER(code) = LOWER('TktPublicAwaiting') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicPaid', JSON_OBJECT('en_US', 'Paid. Your order is confirmed.', 'zh_CN', '已付款,订单已确认。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已付款,订单已确认。') WHERE LOWER(code) = LOWER('TktPublicPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicCancelled', JSON_OBJECT('en_US', 'This order was cancelled.', 'zh_CN', '此订单已取消。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicCancelled') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此订单已取消。') WHERE LOWER(code) = LOWER('TktPublicCancelled') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicExpired', JSON_OBJECT('en_US', 'This order expired before payment arrived.', 'zh_CN', '此订单在收到付款前已过期。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicExpired') AND area = 'A');
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 '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');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '售票活动') WHERE LOWER(code) = LOWER('PagesTicketsEvent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesChooseTicketsEvent', JSON_OBJECT('en_US', 'Choose an event with tickets on', 'zh_CN', '选择已开启售票的活动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChooseTicketsEvent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '选择已开启售票的活动') WHERE LOWER(code) = LOWER('PagesChooseTicketsEvent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTicketsEventHint', JSON_OBJECT('en_US', 'Only events with tickets switched on are listed.', 'zh_CN', '仅列出已开启售票的活动。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTicketsEventHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '仅列出已开启售票的活动。') WHERE LOWER(code) = LOWER('PagesTicketsEventHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCreated', JSON_OBJECT('en_US', 'Created', 'zh_CN', '创建时间'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCreated') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '创建时间') WHERE LOWER(code) = LOWER('TktCreated') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNoOrders', JSON_OBJECT('en_US', 'No orders yet.', 'zh_CN', '尚无订单。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNoOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚无订单。') WHERE LOWER(code) = LOWER('TktNoOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderTitle', JSON_OBJECT('en_US', 'Ticket order', 'zh_CN', '门票订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票订单') WHERE LOWER(code) = LOWER('TktOrderTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderNamed', JSON_OBJECT('en_US', 'Order {reference}', 'zh_CN', '订单 {reference}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderNamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单 {reference}') WHERE LOWER(code) = LOWER('TktOrderNamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderNotFound', JSON_OBJECT('en_US', 'Order not found.', 'zh_CN', '找不到订单。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderNotFound') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '找不到订单。') WHERE LOWER(code) = LOWER('TktOrderNotFound') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktBackToOrders', JSON_OBJECT('en_US', 'Back to orders', 'zh_CN', '返回订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktBackToOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '返回订单') WHERE LOWER(code) = LOWER('TktBackToOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktActionFailed', JSON_OBJECT('en_US', 'The action failed. Try again.', 'zh_CN', '操作失败,请重试。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktActionFailed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '操作失败,请重试。') WHERE LOWER(code) = LOWER('TktActionFailed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktHoldUntil', JSON_OBJECT('en_US', 'Held until', 'zh_CN', '保留至'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktHoldUntil') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保留至') WHERE LOWER(code) = LOWER('TktHoldUntil') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPaymentRef', JSON_OBJECT('en_US', 'Payment reference', 'zh_CN', '付款参考'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPaymentRef') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款参考') WHERE LOWER(code) = LOWER('TktPaymentRef') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPaidBy', JSON_OBJECT('en_US', 'Marked paid by', 'zh_CN', '标记付款者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPaidBy') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '标记付款者') WHERE LOWER(code) = LOWER('TktPaidBy') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelledBy', JSON_OBJECT('en_US', 'Cancelled by', 'zh_CN', '取消者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelledBy') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消者') WHERE LOWER(code) = LOWER('TktCancelledBy') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktExpiredAt', JSON_OBJECT('en_US', 'Expired', 'zh_CN', '过期时间'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktExpiredAt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '过期时间') WHERE LOWER(code) = LOWER('TktExpiredAt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktResend', JSON_OBJECT('en_US', 'Resend email', 'zh_CN', '重新发送电邮'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktResend') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '重新发送电邮') WHERE LOWER(code) = LOWER('TktResend') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktEmailResent', JSON_OBJECT('en_US', 'Email sent again.', 'zh_CN', '电邮已重新发送。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktEmailResent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '电邮已重新发送。') WHERE LOWER(code) = LOWER('TktEmailResent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktMarkPaid', JSON_OBJECT('en_US', 'Mark paid', 'zh_CN', '标记为已付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktMarkPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '标记为已付款') WHERE LOWER(code) = LOWER('TktMarkPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktMarkedPaid', JSON_OBJECT('en_US', 'Order marked paid.', 'zh_CN', '订单已标记为已付款。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktMarkedPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已标记为已付款。') WHERE LOWER(code) = LOWER('TktMarkedPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelOrder', JSON_OBJECT('en_US', 'Cancel order', 'zh_CN', '取消订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelOrder') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消订单') WHERE LOWER(code) = LOWER('TktCancelOrder') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelOrderMessage', JSON_OBJECT('en_US', 'Cancel this order and free its seats? The buyer gets an email.', 'zh_CN', '取消此订单并释放座位?买家将收到电邮。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelOrderMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消此订单并释放座位?买家将收到电邮。') WHERE LOWER(code) = LOWER('TktCancelOrderMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderCancelled', JSON_OBJECT('en_US', 'Order cancelled.', 'zh_CN', '订单已取消。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderCancelled') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已取消。') WHERE LOWER(code) = LOWER('TktOrderCancelled') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelTicket', JSON_OBJECT('en_US', 'Cancel ticket', 'zh_CN', '取消门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消门票') WHERE LOWER(code) = LOWER('TktCancelTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelTicketMessage', JSON_OBJECT('en_US', 'Cancel this ticket, free its seat and lower the order total?', 'zh_CN', '取消此门票、释放座位并降低订单总额?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelTicketMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消此门票、释放座位并降低订单总额?') WHERE LOWER(code) = LOWER('TktCancelTicketMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketCancelled', JSON_OBJECT('en_US', 'Ticket cancelled.', 'zh_CN', '门票已取消。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketCancelled') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票已取消。') WHERE LOWER(code) = LOWER('TktTicketCancelled') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketType', JSON_OBJECT('en_US', 'Ticket type', 'zh_CN', '门票类型'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketType') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票类型') WHERE LOWER(code) = LOWER('TktTicketType') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketActive', JSON_OBJECT('en_US', 'Active', 'zh_CN', '有效'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketActive') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有效') WHERE LOWER(code) = LOWER('TktTicketActive') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketCancelledBy', JSON_OBJECT('en_US', 'Cancelled by {by}, {at}', 'zh_CN', '{by} 于 {at} 取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketCancelledBy') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{by} 于 {at} 取消') WHERE LOWER(code) = LOWER('TktTicketCancelledBy') AND area = 'A';
UPDATE catalog_meta SET version = version + 1, updated_at = NOW() WHERE id = 1; UPDATE catalog_meta SET version = version + 1, updated_at = NOW() WHERE id = 1;
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,44 @@
# Proposal
## Why
The INS sign-up form on the standalone landing page is short: full name, email, phone, company, a single "service" dropdown and the button. Co-Lite's landing-page form is roughly three times as long. Most of that comes from three things: the full English and Malay privacy notice shown in the form, five interest checkboxes, and a job-title field that INS does not ask for. On the rebuilt Hotel technology page, the form card is taller than two screens.
The coloured sections at the end of the page have a second problem: they are separated by pale gaps. The dark call to action and the dark footer therefore read as two footers.
The owner chose the following on 2026-12-04: a collapsed privacy notice, one interest as a dropdown, and no job title on landing pages.
## What Changes
- **Landing-page forms are compact.** This covers the FORM block and a hero's form; QR, invitation and customer sign-up forms are unchanged.
- The interests are a single optional dropdown ("Service interested in"), so a submission carries at most one interest.
- There is no job-title field.
- The privacy notice is folded behind one line, "How we use your details (English / Bahasa Malaysia)", just above the consent box. It opens to the full bilingual notice.
- The consent box itself and its wording do not change.
- **Coloured sections join.** A block with a non-default look (light grey, dark or company colour) counts as full width, like Custom HTML and the full-width hero. Two such blocks next to each other join with no gap.
Not changing:
- The server: it already accepts a submission without a job title and with zero or one interest.
- The QR, invitation and customer forms.
- The notice text, which consent still covers.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`:
- modifies "Full-Width Blocks Join Without Gaps";
- adds "Compact Landing-Page Form".
## Impact
- Portal:
- `RegistrationForm.tsx` gains a `compact` option;
- `LandingForm.tsx` passes it;
- `CmsBlocks.tsx` extends `bleeds()` to banded looks;
- new labels.
- The compliance owner should confirm that a folded notice next to the consent box meets PDPA. The owner was told this when they chose it.
@@ -0,0 +1,45 @@
## ADDED Requirements
### Requirement: Compact Landing-Page Form
A landing page's sign-up form, in a FORM block or a hero, SHALL show name, mobile, email and company, the event's interests as one optional dropdown, the privacy notice folded behind a single line that opens it in full, and the consent box. It SHALL NOT show a job-title field. QR, invitation and customer sign-up forms SHALL keep their full layout.
#### Scenario: Short form on the page
- **GIVEN** a page whose hero has an event with five interests
- **WHEN** a visitor opens the page
- **THEN** the form shows name, mobile, email, company, a "Service interested in" dropdown and the consent box, with no job title and no interest checkboxes
- **AND** the privacy notice is folded behind "How we use your details"
#### Scenario: Pick one service
- **WHEN** the visitor chooses "Cloud IP PABX" in the dropdown and submits
- **THEN** the submission carries that one interest
#### Scenario: Read the notice
- **WHEN** the visitor opens "How we use your details"
- **THEN** the full English and Malay notice shows above the consent box
#### Scenario: QR form unchanged
- **WHEN** a visitor opens an event's QR sign-up form
- **THEN** it shows job title, the interest checkboxes and the full notice as before
## MODIFIED Requirements
### Requirement: Full-Width Blocks Join Without Gaps
A full-width HERO, a Custom HTML block, and a block with a non-default look SHALL join with no gap when two of them are next to each other. Other blocks SHALL keep their usual spacing.
#### Scenario: Top bar runs straight into the hero
- **GIVEN** a Custom HTML top bar followed by a full-width HERO
- **WHEN** a visitor opens the page
- **THEN** the hero starts directly under the top bar, with no gap
#### Scenario: Dark call to action runs into a dark footer
- **GIVEN** a CTA block with the Dark look followed by a text block with the Dark look
- **WHEN** a visitor opens the page
- **THEN** the two bands join with no gap between them
@@ -0,0 +1,9 @@
-- The labels added by add-compact-landing-form, 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 'RegServiceInterest', JSON_OBJECT('en_US', 'Service interested in (optional)', 'zh_CN', '感兴趣的服务(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegServiceInterest') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '感兴趣的服务(可选)') WHERE LOWER(code) = LOWER('RegServiceInterest') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegChooseService', JSON_OBJECT('en_US', 'Choose a service', 'zh_CN', '选择服务'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegChooseService') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '选择服务') WHERE LOWER(code) = LOWER('RegChooseService') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegNoticeSummary', JSON_OBJECT('en_US', 'How we use your details (English / Bahasa Malaysia)', 'zh_CN', '我们如何使用您的资料(English / Bahasa Malaysia)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegNoticeSummary') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '我们如何使用您的资料(English / Bahasa Malaysia)') WHERE LOWER(code) = LOWER('RegNoticeSummary') AND area = 'A';
@@ -0,0 +1,39 @@
# Tasks
## 1. Portal
- [x] 1.1 `RegistrationForm` `compact` option, passed by `LandingForm`:
- no job title;
- interests in one optional `<select>` ("Service interested in", first option "Choose a service"), which sets `interestIds` to `[]` or `[id]`;
- the notice inside a `<details>` with the summary "How we use your details (English / Bahasa Malaysia)", just above the consent box.
Verify: tests for the landing form (fields, one interest posted, the notice folded and openable) and for the QR form (unchanged) fail first, then pass.
- [x] 1.2 `CmsBlocks.tsx` `bleeds()`: a block with a non-default look counts too. Verify: a render test (a dark CTA followed by a dark text block has no gap) fails first, then passes.
- [x] 1.3 Add the labels (`RegServiceInterest`, `RegChooseService`, `RegNoticeSummary`) to `defaultMessages.ts`, `zh_CN.seed.json` and `sql/01-compact-form-labels.sql`, and regenerate the local seed.
## 2. Verification
- [x] 2.1 Use Playwright on port 3001 for `/p/INS/hotel-technology-native` at 1280 px and 390 px:
- check the short form;
- check that the notice opens;
- check that the closing bands join;
- check that an event's QR form (opened from Events) still shows the full form.
- [x] 2.2 Run the full vitest (exit 0), tsc, lint and `openspec validate --strict`. Add a release note.
## Notes (2026-12-04)
- **Red first:**
- the compact-form tests (fields, one service posted, the notice folded) and the band-join test failed first;
- the full-form test passed from the start, as the baseline it guards.
- **Live check** on `/p/INS/hotel-technology-native` (port 3001):
- the hero form shows name, mobile, email, company and "Service interested in", with no job title;
- the notice opens from "How we use your details";
- the hero runs into the trust strip;
- the dark call to action and the dark footer join into one ending.
- **Fix from the live check:** joined bands had lost their colour. `Section` treated every joining block as a full-width hero. Now only a full-width hero skips the page width, and the band test also checks the colour.
- **Not checked live:** the QR form staying full. The `RegistrationForm` test covers it (job title, checkboxes, notice open).
- **Results:** vitest 2002 passed (exit 0); tsc clean; lint 0 errors (the 4 warnings were already there).
## Workflow follow-up
- Open a PR to `main` and merge it. Archive the change on its own branch, with its own PR.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,211 @@
# Design
Product design: `docs/superpowers/specs/2026-12-04-event-ticketing-design.md` (approved 2026-12-04). This file holds the technical contracts for change 1 of 2.
## Context
- Events, event leads, QR registration, landing pages (`cms_page`) and the capacity count (`EventHeadcountService`) live in `solvway-services-counter`.
- `solvway-mobile-api` is the only door for the portal:
- admin endpoints are `/api/admin/**`, gated by module and scoped by company through `loadEvent`;
- public endpoints are `/api/public/**`, rate-limited in Redis through `PublicRegistrationService.limit`.
- The landing page FORM block is the model for TICKETS:
- `PublicPageService.page` enriches a block with `form` or `closed`;
- `PublicPageService.submit` checks the honeypot, applies `reg:submit:<event>:<ip>`, and posts to the counter.
- The api-gateway opens only listed public counter paths.
- The legacy Tastefully tables `orders`/`orders_details` exist and are unused. New tables use other names so the two are never confused.
## Goals / Non-Goals
**Goals:**
- Ticket settings and types.
- The TICKETS block.
- Orders with seat locking.
- The order page.
- Order emails.
- The expiry job.
- Staff order screens.
- The buyer as an event lead.
- Held tickets in the capacity count.
**Non-Goals (change 2, `add-event-tickets`):**
- Ticket QR codes and the `/t/` page.
- Naming attendees and consent.
- Ticket emails.
- Door and self check-in for tickets.
- Invites counted as free tickets.
- Ticket numbers in attendance.
The `ticket` row and its `code` column are created now, so change 2 adds no table.
## Decisions
### 1. Data (SQL in `sql/`)
`01-event-ticket-orders.sql` (service-counter, additive):
- **`event`** gains:
- `tickets_enabled` bit NOT NULL DEFAULT 0;
- `payment_instructions` varchar(1000) NULL;
- `hold_days` int NOT NULL DEFAULT 3.
- **`ticket_type`:**
- Columns: id, company_id, event_uuid, name varchar(80), price_sen int, quantity int, sales_end_date date NULL, sort int, enabled bit, plus the created and updated fields.
- Unique key `(event_uuid, name)`.
- **`shop_order`:**
- Columns:
- id, company_id, event_uuid NULL (null is reserved for a later standalone shop);
- reference varchar(12), token varchar(32);
- buyer_name varchar(100), buyer_email varchar(254), buyer_mobile_e164 varchar(20) NULL, buyer_company varchar(150) NULL;
- lead_id, event_lead_id;
- status varchar(20), total_sen int, hold_until datetime;
- paid_at, paid_by, payment_ref varchar(100), cancelled_at, cancelled_by, expired_at;
- consent_at, consent_notice_id, page_path, utm_source, utm_medium, utm_campaign;
- last_email varchar(20), created_at.
- Unique keys `(company_id, reference)` and `(token)`.
- Indexes `(event_uuid, status)`, `(status, hold_until)` and `(event_uuid, buyer_email, status)`.
- **`shop_order_line`:**
- Columns: id, order_id, kind varchar(10) (`TICKET`; `PICKUP` and `SHIP` are reserved), item_id (the ticket_type id), name varchar(80), unit_price_sen, quantity.
- **`ticket`:**
- Columns: id, company_id, event_uuid, order_id, order_line_id, ticket_type_id, code varchar(32) NULL, attendee_name, attendee_mobile_e164, attendee_email, event_lead_id, status varchar(10) (`ACTIVE` or `CANCELLED`), cancelled_at, cancelled_by, checked_in_at, checked_in_by.
- Index `(ticket_type_id, status)`.
- `code` and the attendee and check-in columns stay null until change 2.
`02-event-tickets-module.sql` (service-system) inserts `(41160000, 'BO_EVENT_TICKETS', 'Event tickets', 'BO', 'M', 40000000, NULL, NULL)`. No role gets it by default.
Both files are mirrored in `local/seed/03-colite.sql`. `99-rollback.sql` drops the new tables and columns, and the module.
**Money** is integer sen everywhere; the portal formats it as `RM 1,234.00`. **References** are `T-` plus 6 characters from `23456789ABCDEFGHJKMNPQRSTUVWXYZ`, retried on a unique-key clash. **Tokens** are 22 URL-safe base64 characters from `SecureRandom`, the same shape as invite tokens.
### 2. Seat locking
`TicketOrderService.request` runs in one transaction:
1. Load the event `FOR UPDATE` (`@Lock(PESSIMISTIC_WRITE)`). Every request for the event is serialised there. A request takes milliseconds, and per-event volume is low.
2. Check the event:
- the event is open;
- each type is enabled and within its sales end date;
- the awaiting-payment count for the email is below 3.
3. Compute held seats per type with one grouped count over `ticket` joined to `shop_order` where the ticket is `ACTIVE` and the order is `AWAITING` or `PAID`.
4. Check each type's seats, then the event capacity before the event days. Registered guests plus walk-ins come from `EventHeadcountService`; held tickets come from the same count.
5. Insert the order, its lines and its tickets.
Staff "mark paid" on an Expired order, and a type's quantity edit, take the same event lock.
`EventHeadcountService` gains `heldTickets`, and the invite registration's capacity check adds it (the MODIFIED requirement).
- *Rejected:* optimistic version counters per type. There would be more retry code, for no benefit at this volume.
- *Rejected:* a stored seats-left column. It can drift, while a count is always right.
### 3. services-counter endpoints
All take JSON. `companyId` is always concrete and is set by mobile-api.
- **Settings:**
- `POST /counter/ticketType/settings {companyId, eventUuid, ticketsEnabled, paymentInstructions, holdDays, doneBy}`. It returns 400 `PAYMENT_INSTRUCTIONS_REQUIRED`, `PAYMENT_INSTRUCTIONS_TOO_LONG` or `HOLD_DAYS_INVALID`.
- `event/save` keeps the stored ticket settings on every edit, and starts a new event with tickets off. This is so a mobile-api event edit, which round-trips the whole event, can never reset them.
- **Ticket types:**
- `POST /counter/ticketType/list {companyId, eventUuid}` returns `[{id, name, priceSen, quantity, salesEndDate, sort, enabled, held, left}]`.
- `POST /counter/ticketType/save {companyId, eventUuid, id?, name, priceSen, quantity, salesEndDate, sort, enabled, doneBy}` returns 409 `QUANTITY_BELOW_HELD` or `NAME_TAKEN`.
- `POST /counter/ticketType/delete {companyId, eventUuid, id, doneBy}` returns 409 `TYPE_HAS_ORDERS`.
- **Public request:**
- `POST /counter/ticketOrder/request {companyId, eventUuid, lines:[{ticketTypeId, quantity}], buyerName, buyerEmail, buyerMobileE164, buyerCompany, consentNoticeId, consentAt, pagePath, utmSource, utmMedium, utmCampaign}`.
- It returns `{reference, token, status, totalSen, holdUntil, lines, paymentInstructions}`.
- It returns 409 with one of these codes:
- `TICKETS_CLOSED`;
- `TYPE_UNAVAILABLE {ticketTypeId, name, left}`;
- `EVENT_FULL {left}`;
- `TOO_MANY_AWAITING`;
- `BAD_QUANTITY`.
- After the insert, it captures the buyer with `RegistrationService.register`, using source `TICKET`, no salesperson, the page path and UTM, and an `orderReference` that is written to the notes when the event lead already existed. It then stores `lead_id` and `event_lead_id` on the order.
- A total of 0 sets the order `PAID` with `paid_by = 'system'`.
- **Public order page:**
- `GET /counter/ticketOrder/byToken/{token}` returns `{companyId, eventUuid, reference, status, buyerName, totalSen, holdUntil, createdAt, lines}`, or 404.
- **Staff:**
- `POST /counter/ticketOrder/list {companyId, eventUuid, status?, q?, page, size≤50}` returns a page of `{id, reference, buyerName, buyerEmail, tickets, totalSen, status, createdAt}`, newest first.
- `POST /counter/ticketOrder/get {companyId, orderId}` returns the full order with lines, tickets, buyer, payment and state history fields.
- `POST /counter/ticketOrder/markPaid {companyId, orderId, paymentRef, doneBy}` returns 409 `NOT_PAYABLE` or `SEATS_GONE`.
- `POST /counter/ticketOrder/cancel {companyId, orderId, doneBy}` returns 409 `NOT_CANCELLABLE`.
- `POST /counter/ticketOrder/cancelTicket {companyId, orderId, ticketId, doneBy}` returns 409 `LAST_TICKET` or `NOT_CANCELLABLE`.
- `POST /counter/ticketOrder/resend {companyId, orderId}`.
- **Expiry job:**
- `TicketOrderExpiryJob` runs `@Scheduled(cron = "${tickets.expiry.cron:0 */10 * * * *}")`, which is within the spec's 15 minutes.
- It moves `AWAITING` orders with `hold_until < now` to `EXPIRED` in batches of 100. Each order is a conditional update `WHERE status='AWAITING'`, so it never races with mark paid.
- It queues the expired email.
### 4. Order emails (services-counter)
- **Sender:** `TicketOrderMailer` sends the emails after commit (`TransactionSynchronization.afterCommit`, as `StaffNotifier` does) through the existing counter `EmailService.send`, which goes to services-email. They are recorded in Emails, with `companyId` set to the event's company.
- **Content:**
- Every user value is HTML-escaped.
- The text is English, then Bahasa Malaysia, as the invite email is.
- The link is `<app.admin-portal-base-url>/o/<token>`. This is a new counter setting. Only the local profile has a default (`http://localhost:3001`); elsewhere it is required.
- **Record:** `last_email` records the latest kind (`RECEIVED`, `PAID`, `EXPIRED` or `CANCELLED`), so resend sends that kind again.
- **Failures:** they are logged with the order id only, and never roll back the order.
### 5. Landing page block (services-counter and mobile-api)
- **`CmsBlockValidator` TICKETS:**
- `eventUuid` is required, belongs to the company, and is enabled, not ended and `tickets_enabled`.
- `heading` is at most 120 characters, `text` at most 1000.
- `eyebrow`, `look` and `anchor` are allowed.
- Every other field is refused with `PagesUnusedField`.
- **`PublicPageService.page`:** for a TICKETS block it adds `tickets: {eventName, startDate, endDate, location, notice, types:[{id, name, priceSen, left, state: ON_SALE|SOLD_OUT|ENDED}]}` when the event accepts requests, else `closed: true`.
- **`POST /api/public/pages/{company}/{slug}/tickets/{block}`:**
- It follows `submit`: the same `page:load` and `reg:submit:<event>:<ip>` limits, the honeypot, and consent from the company's current notice.
- It normalises the inputs with the `PublicRegistrationService` helpers, then posts to counter `ticketOrder/request`.
- On the honeypot it returns a fake success without a token, and the portal shows the thank-you without a link.
- **`GET /api/public/orders/{token}`:**
- It checks the token shape first, then applies `ord:load:<ip>` at 120 per 10 minutes.
- It returns the order with the event's name, dates and location, and the payment instructions only while `AWAITING`. Otherwise it gives 404 `ORDER_INVALID`.
- **Public types:**
- `GET /counter/ticketType/onSale/{eventUuid}` returns only `{ticketsOpen, paymentInstructions, types:[{id, name, priceSen, left, state}]}` for enabled types.
- mobile-api's public calls run without a user token, so they pass through the api-gateway's public path list, as `registration/register` and `cmsPage/findPublished` do.
- The staff `ticketType/list`, which needs a company, stays closed.
- **Gateway:** open these anchored pairs in `JWTAuthFilter`:
- `POST /counter/ticketOrder/request`;
- `GET /counter/ticketOrder/byToken/[A-Za-z0-9_-]{22}`;
- `GET /counter/ticketType/onSale/\d{1,19}`.
### 6. mobile-api admin
- **Endpoints,** gated by `BO_EVENT_TICKETS`, with the company scope from `loadEvent` and `@Audited`:
- `GET` and `PUT /api/admin/events/{uuid}/tickets/settings`;
- `GET`, `POST`, `PUT` and `DELETE /api/admin/events/{uuid}/ticket-types[/{id}]`;
- `GET /api/admin/events/{uuid}/orders?status&q&page`;
- `GET /api/admin/events/{uuid}/orders/{orderId}`;
- `POST /api/admin/events/{uuid}/orders/{orderId}/paid {paymentRef}`;
- `POST .../cancel`, `POST .../tickets/{ticketId}/cancel` and `POST .../resend`.
- **Scoping:** the order is fetched with `companyId` and must belong to `{uuid}`, else 404.
- **Event GET:** it gains `ticketsEnabled` for every reader, so the portal knows when to show the section.
### 7. Portal
- **Event page:**
- A **Tickets** section shows when the user has `BO_EVENT_TICKETS`. It holds the settings form, the ticket types table (with add, edit and disable or delete), and a link to the orders.
- Orders are at `/events/[uuid]/orders`, a listing with a filter and search, and `/events/[uuid]/orders/[orderId]`, the detail page with its actions and confirm dialogs.
- `ROUTE_MODULES` maps both pages to `BO_EVENT_TICKETS`.
- **TICKETS block:**
- It is rendered in `CmsBlocks.tsx` as `TicketsBlock`, with types, quantity steppers, the running total, the buyer fields and the consent. It reuses the `RegistrationForm` field and consent pieces, plus a thank-you state.
- The editors add it to `BLOCK_TYPES`, `emptyBlock` and `BlockFields`, with an event picker limited to events with tickets on, using `ticketsEnabled` from the events list.
- The canvas shows the real types through the preview data.
- **Order page:** `/o/[token]` is public in `routeGuard`, sharing the pattern for `/r/`, `/i/` and `/c/`. Its proxy is `app/api/public/orders/[token]`, which forwards the last X-Forwarded-For hop as the other proxies do.
- **Labels** in `defaultMessages.ts` and `zh_CN.seed.json`, plus `sql/03-*-labels.sql` cut from `npm run i18n:sql`.
## Risks / Trade-offs
- **Event row lock under a rush.** Requests for one event are serialised. That is fine at the expected volume (hundreds per minute). The upgrade path was agreed with the owner on 2026-12-04:
1. A conditional single-statement seat update (`... WHERE held + n <= quantity`), with no event lock.
2. Then a Redis seat counter backed by the database, a CDN-cached event page, a CAPTCHA and a load test.
3. At concert scale: a virtual waiting room, queued order allocation, member-only sales, and ticketing as its own service.
Seats are counted from `ticket` rows on one table, so step 1 is a local change.
- **Seat hoarding.** One email can hold up to 30 seats (3 orders × 10) for the hold days, and many emails can hold more. This is mitigated by the IP limit, the honeypot and staff cancel. A CAPTCHA is deferred.
- **Emails in English and BM only,** matching invites. The zh-CN email text is deferred with the rest of the email localisation.
- **Expired orders may still be paid.** Staff can rescue them only while their seats are free. This is refused clearly otherwise.
## Migration Plan
1. Run `sql/01` and `sql/02` before the new images go live. Only new tables and defaulted columns are added, so the running images are unaffected.
2. Set `app.admin-portal-base-url` on services-counter.
3. Deploy services-counter, mobile-api, api-gateway and admin-portal together.
4. A super admin grants Event tickets to the right roles.
5. Rollback: deploy the previous images; `99-rollback.sql` only if the data should go too.
@@ -0,0 +1,70 @@
# Proposal
## Why
Co-Lite is growing from an event lead-capture tool into an event hosting platform. Some events are free and some are paid. Paid events need tickets: an organiser sets ticket types and prices, and visitors request tickets on the event's landing page. There is no payment gateway yet. Buyers pay outside Co-Lite and staff mark the order paid. Every buyer still becomes a lead on the event, so paid events feed the sales pipeline just as free ones do.
The product design was approved on 2026-12-04: `docs/superpowers/specs/2026-12-04-event-ticketing-design.md`. This is the first of two changes. It covers the order side. The second change, `add-event-tickets`, covers QR tickets, naming attendees, consent and check-in at the door.
## What Changes
- **Event ticket settings:**
- Events gain a Tickets switch, which is off by default. While it is off, the event behaves exactly as today.
- Ticketed events also gain payment instructions and hold days (1 to 14, default 3).
- **Ticket types per event:** each has a name, a price in MYR (0 or more), a quantity, an optional sales end date, a sort order and an enabled flag.
- A type with orders cannot be deleted, only disabled.
- A type's quantity cannot drop below the seats it already holds.
- **New landing-page block TICKETS:**
- It shows the event's ticket types with price and seats left.
- It takes quantities, up to 10 per order, and the buyer's details with the privacy consent.
- It creates an order and shows a thank-you with the payment instructions and the order link.
- **Orders:**
- An order holds lines, one per ticket type, and one ticket row per seat. The line has a `kind` column, `TICKET` for now, so merch can be added later.
- Order states: Awaiting payment, Paid, Cancelled and Expired. Orders that total RM 0 are Paid at once.
- Seats are locked so ticket types never oversell. Held tickets count toward event capacity before the event days.
- At most 3 orders per email per event may await payment at once.
- **Order page:** a public page at `/o/<token>` shows the order's status, lines, total, payment instructions and hold expiry.
- **Expiry job:** a scheduled job expires unpaid orders after the hold and frees their seats.
- **Emails:** order received, order paid, order expired and order cancelled. "Order paid" confirms payment only; the tickets come with change 2.
- **Staff Tickets section on the event, under the new permission `BO_EVENT_TICKETS`:**
- the ticket settings and ticket types;
- an orders list and an order detail page, with these actions: mark paid (with an optional payment reference), cancel order, cancel ticket, and resend email.
- Every action is audited.
- **Buyer as a lead:** the buyer becomes an event lead with the new source `TICKET`, matched as in QR registration.
- **Capacity:** "Capacity before the event" now also counts held tickets.
## Capabilities
### New Capabilities
- `event-ticketing`: ticket types, ticket orders, the order page, order emails, hold expiry and the staff order screens.
### Modified Capabilities
- `landing-pages`: new TICKETS block.
- `event-invitations`: "Capacity before the event" counts held tickets.
- `event-attendance`: walk-ins leave out ticket buyers; the numbers show held tickets, and the total includes them.
## Impact
- **SQL:**
- service-counter: new tables `ticket_type`, `shop_order`, `shop_order_line` and `ticket`; new event columns `tickets_enabled`, `payment_instructions` and `hold_days`.
- service-system: new module `BO_EVENT_TICKETS`.
- **solvway-services-counter:**
- ticket entities and services;
- order creation with seat locking;
- the expiry job;
- `CmsBlockValidator` (TICKETS);
- the capacity count in `EventHeadcountService` and the invite registration.
- **solvway-mobile-api:**
- admin ticket endpoints;
- public TICKETS submit and order page endpoints, with their limits;
- order emails;
- public page data for TICKETS.
- **solvway-api-gateway:** open the new public counter paths.
- **solvway-admin-portal:**
- the Tickets section on the event, plus the order list and detail pages;
- the TICKETS block in the renderer and both editors;
- the `/o/[token]` page and its proxy;
- labels in English and zh-CN.
- **No new dependencies.**
@@ -0,0 +1,17 @@
## MODIFIED Requirements
### Requirement: Event attendance numbers
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
- **GIVEN** `KL Expo` has capacity 100, cap 50, 40 guests of whom 30 registered and 20 attended, plus 15 walk-ins of whom 15 attended
- **WHEN** an admin opens the event page
- **THEN** the event page shows invited 40 of 50, registered 30, attended 35, walk-ins 15, total 45 of 100
#### 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
@@ -0,0 +1,23 @@
## MODIFIED Requirements
### Requirement: Capacity before the event
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
- **GIVEN** `KL Expo` starts next week, has capacity 2, and two registered guests
- **WHEN** a third guest submits their invite
- **THEN** the page says the event is full and nothing is saved
#### Scenario: Not refused on the day
- **GIVEN** the same event on its first day
- **WHEN** the third guest submits their invite
- **THEN** they are registered
#### 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
@@ -0,0 +1,248 @@
## ADDED 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
@@ -0,0 +1,31 @@
## ADDED Requirements
### 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
@@ -0,0 +1,99 @@
-- Co-Lite change add-event-ticket-orders: ticket settings, ticket types, orders and tickets (design decision 1).
-- Target: `service-counter`. Additive only. Run before the new images go live. Needs a user that may alter tables.
-- Money is integer sen. `shop_order` / `shop_order_line` stay apart from the legacy Tastefully `orders` tables.
USE `service-counter`;
ALTER TABLE `event`
ADD COLUMN `tickets_enabled` tinyint(1) NOT NULL DEFAULT 0,
ADD COLUMN `payment_instructions` varchar(1000) NULL,
ADD COLUMN `hold_days` int NOT NULL DEFAULT 3;
CREATE TABLE IF NOT EXISTS `ticket_type` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_uuid` bigint NOT NULL,
`name` varchar(80) NOT NULL,
`price_sen` int NOT NULL,
`quantity` int NOT NULL,
`sales_end_date` date NULL,
`sort` int NOT NULL DEFAULT 0,
`enabled` tinyint(1) NOT NULL DEFAULT 1,
`created_by` varchar(255) NULL,
`created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP,
`updated_by` varchar(255) NULL,
`updated_at` datetime NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_ticket_type_name` (`event_uuid`, `name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `shop_order` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_uuid` bigint NULL COMMENT 'Null is reserved for a later standalone shop',
`reference` varchar(12) NOT NULL,
`token` varchar(32) NOT NULL,
`buyer_name` varchar(100) NOT NULL,
`buyer_email` varchar(254) NOT NULL,
`buyer_mobile_e164` varchar(20) NULL,
`buyer_company` varchar(150) NULL,
`lead_uuid` bigint NULL,
`event_lead_uuid` bigint NULL,
`status` varchar(20) NOT NULL COMMENT 'AWAITING, PAID, CANCELLED, EXPIRED',
`total_sen` int NOT NULL,
`hold_until` datetime NULL,
`paid_at` datetime NULL,
`paid_by` varchar(255) NULL,
`payment_ref` varchar(100) NULL,
`cancelled_at` datetime NULL,
`cancelled_by` varchar(255) NULL,
`expired_at` datetime NULL,
`consent_at` datetime NULL,
`consent_notice_id` bigint NULL,
`page_path` varchar(200) NULL,
`utm_source` varchar(100) NULL,
`utm_medium` varchar(100) NULL,
`utm_campaign` varchar(100) NULL,
`last_email` varchar(20) NULL COMMENT 'RECEIVED, PAID, EXPIRED, CANCELLED',
`created_at` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_shop_order_reference` (`company_id`, `reference`),
UNIQUE KEY `uk_shop_order_token` (`token`),
KEY `idx_shop_order_event_status` (`event_uuid`, `status`),
KEY `idx_shop_order_hold` (`status`, `hold_until`),
KEY `idx_shop_order_buyer` (`event_uuid`, `buyer_email`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `shop_order_line` (
`id` bigint NOT NULL AUTO_INCREMENT,
`order_id` bigint NOT NULL,
`kind` varchar(10) NOT NULL COMMENT 'TICKET; PICKUP and SHIP reserved for merch',
`item_id` bigint NOT NULL COMMENT 'ticket_type.id for TICKET',
`name` varchar(80) NOT NULL,
`unit_price_sen` int NOT NULL,
`quantity` int NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_shop_order_line_order` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `ticket` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_uuid` bigint NOT NULL,
`order_id` bigint NOT NULL,
`order_line_id` bigint NOT NULL,
`ticket_type_id` bigint NOT NULL,
`code` varchar(32) NULL COMMENT 'QR code, issued by add-event-tickets',
`attendee_name` varchar(100) NULL,
`attendee_mobile_e164` varchar(20) NULL,
`attendee_email` varchar(254) NULL,
`event_lead_uuid` bigint NULL,
`status` varchar(10) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE, CANCELLED',
`cancelled_at` datetime NULL,
`cancelled_by` varchar(255) NULL,
`checked_in_at` datetime NULL,
`checked_in_by` varchar(255) 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`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -0,0 +1,6 @@
-- Co-Lite change add-event-ticket-orders: permission-only module for ticket settings, ticket types and orders.
-- Target: `service-system`. No role gets it by default; a super admin grants it under Roles.
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(41160000, 'BO_EVENT_TICKETS', 'Event tickets', 'BO', 'M', 40000000, NULL, NULL);
@@ -0,0 +1,221 @@
-- The labels added by add-event-ticket-orders, 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 'GuestHeldTickets', JSON_OBJECT('en_US', 'Held tickets', 'zh_CN', '已占门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('GuestHeldTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已占门票') WHERE LOWER(code) = LOWER('GuestHeldTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTicketsClosed', JSON_OBJECT('en_US', 'Choose an event that is selling tickets.', 'zh_CN', '请选择正在售票的活动。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTicketsClosed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请选择正在售票的活动。') WHERE LOWER(code) = LOWER('PagesTicketsClosed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTitle', JSON_OBJECT('en_US', 'Tickets', 'zh_CN', '门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票') WHERE LOWER(code) = LOWER('TktTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktViewOrders', JSON_OBJECT('en_US', 'View orders', 'zh_CN', '查看订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktViewOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看订单') WHERE LOWER(code) = LOWER('TktViewOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktLoadFailed', JSON_OBJECT('en_US', 'Could not load the tickets.', 'zh_CN', '无法加载门票。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktLoadFailed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法加载门票。') WHERE LOWER(code) = LOWER('TktLoadFailed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSaveFailed', JSON_OBJECT('en_US', 'Could not save. Try again.', 'zh_CN', '无法保存,请重试。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSaveFailed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法保存,请重试。') WHERE LOWER(code) = LOWER('TktSaveFailed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSettingsSaved', JSON_OBJECT('en_US', 'Ticket settings saved.', 'zh_CN', '门票设置已保存。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSettingsSaved') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票设置已保存。') WHERE LOWER(code) = LOWER('TktSettingsSaved') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSellTickets', JSON_OBJECT('en_US', 'Sell tickets', 'zh_CN', '售卖门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSellTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '售卖门票') WHERE LOWER(code) = LOWER('TktSellTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPaymentInstructions', JSON_OBJECT('en_US', 'Payment instructions', 'zh_CN', '付款说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPaymentInstructions') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款说明') WHERE LOWER(code) = LOWER('TktPaymentInstructions') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPaymentInstructionsHelp', JSON_OBJECT('en_US', 'Shown to buyers after they request tickets, e.g. the bank account and what reference to use.', 'zh_CN', '买家申请门票后显示,例如银行账户及付款备注。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPaymentInstructionsHelp') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '买家申请门票后显示,例如银行账户及付款备注。') WHERE LOWER(code) = LOWER('TktPaymentInstructionsHelp') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktHoldDays', JSON_OBJECT('en_US', 'Hold days', 'zh_CN', '保留天数'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktHoldDays') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保留天数') WHERE LOWER(code) = LOWER('TktHoldDays') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSaveSettings', JSON_OBJECT('en_US', 'Save ticket settings', 'zh_CN', '保存门票设置'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSaveSettings') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存门票设置') WHERE LOWER(code) = LOWER('TktSaveSettings') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPrice', JSON_OBJECT('en_US', 'Price', 'zh_CN', '价格'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPrice') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '价格') WHERE LOWER(code) = LOWER('TktPrice') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPriceRm', JSON_OBJECT('en_US', 'Price (RM)', 'zh_CN', '价格(RM)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPriceRm') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '价格(RM)') WHERE LOWER(code) = LOWER('TktPriceRm') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktQuantity', JSON_OBJECT('en_US', 'Quantity', 'zh_CN', '数量'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktQuantity') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '数量') WHERE LOWER(code) = LOWER('TktQuantity') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktLeft', JSON_OBJECT('en_US', 'Left', 'zh_CN', '剩余'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktLeft') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '剩余') WHERE LOWER(code) = LOWER('TktLeft') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSalesEnd', JSON_OBJECT('en_US', 'Sales end', 'zh_CN', '停售日期'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSalesEnd') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '停售日期') WHERE LOWER(code) = LOWER('TktSalesEnd') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSalesEndHelp', JSON_OBJECT('en_US', 'An empty sales end date means sales end with the event.', 'zh_CN', '停售日期留空表示随活动结束而停售。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSalesEndHelp') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '停售日期留空表示随活动结束而停售。') WHERE LOWER(code) = LOWER('TktSalesEndHelp') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNoTypes', JSON_OBJECT('en_US', 'No ticket types yet.', 'zh_CN', '尚无门票类型。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNoTypes') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚无门票类型。') WHERE LOWER(code) = LOWER('TktNoTypes') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktFree', JSON_OBJECT('en_US', 'Free', 'zh_CN', '免费'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktFree') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '免费') WHERE LOWER(code) = LOWER('TktFree') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktDisable', JSON_OBJECT('en_US', 'Disable', 'zh_CN', '停用'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktDisable') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '停用') WHERE LOWER(code) = LOWER('TktDisable') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktEnable', JSON_OBJECT('en_US', 'Enable', 'zh_CN', '启用'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktEnable') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '启用') WHERE LOWER(code) = LOWER('TktEnable') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktDelete', JSON_OBJECT('en_US', 'Delete', 'zh_CN', '删除'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktDelete') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '删除') WHERE LOWER(code) = LOWER('TktDelete') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTypeName', JSON_OBJECT('en_US', 'Ticket name', 'zh_CN', '门票名称'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTypeName') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票名称') WHERE LOWER(code) = LOWER('TktTypeName') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAddType', JSON_OBJECT('en_US', 'Add ticket type', 'zh_CN', '添加门票类型'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAddType') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加门票类型') WHERE LOWER(code) = LOWER('TktAddType') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSaveType', JSON_OBJECT('en_US', 'Save ticket type', 'zh_CN', '保存门票类型'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSaveType') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存门票类型') WHERE LOWER(code) = LOWER('TktSaveType') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktDeleteTitle', JSON_OBJECT('en_US', 'Delete ticket type', 'zh_CN', '删除门票类型'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktDeleteTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '删除门票类型') WHERE LOWER(code) = LOWER('TktDeleteTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktDeleteMessage', JSON_OBJECT('en_US', 'Delete {name}? This cannot be undone.', 'zh_CN', '删除 {name}?此操作无法撤销。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktDeleteMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '删除 {name}?此操作无法撤销。') WHERE LOWER(code) = LOWER('TktDeleteMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrInstructionsRequired', JSON_OBJECT('en_US', 'Enter the payment instructions before turning tickets on.', 'zh_CN', '开启售票前请填写付款说明。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrInstructionsRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '开启售票前请填写付款说明。') WHERE LOWER(code) = LOWER('TktErrInstructionsRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrInstructionsTooLong', JSON_OBJECT('en_US', 'Payment instructions can be at most 1000 characters.', 'zh_CN', '付款说明最多 1000 个字符。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrInstructionsTooLong') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款说明最多 1000 个字符。') WHERE LOWER(code) = LOWER('TktErrInstructionsTooLong') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrHoldDays', JSON_OBJECT('en_US', 'Hold days must be from 1 to 14.', 'zh_CN', '保留天数须为 1 至 14。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrHoldDays') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保留天数须为 1 至 14。') WHERE LOWER(code) = LOWER('TktErrHoldDays') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrName', JSON_OBJECT('en_US', 'Enter a name of 1 to 80 characters.', 'zh_CN', '请输入 1 至 80 个字符的名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrName') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入 1 至 80 个字符的名称。') WHERE LOWER(code) = LOWER('TktErrName') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrNameTaken', JSON_OBJECT('en_US', 'This event already has a ticket type with this name.', 'zh_CN', '本活动已有同名门票类型。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrNameTaken') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '本活动已有同名门票类型。') WHERE LOWER(code) = LOWER('TktErrNameTaken') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrPrice', JSON_OBJECT('en_US', 'Enter a price from 0.00 to 99999.99.', 'zh_CN', '请输入 0.00 至 99999.99 的价格。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrPrice') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入 0.00 至 99999.99 的价格。') WHERE LOWER(code) = LOWER('TktErrPrice') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrQuantity', JSON_OBJECT('en_US', 'Enter a quantity of at least 1.', 'zh_CN', '数量至少为 1。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrQuantity') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '数量至少为 1。') WHERE LOWER(code) = LOWER('TktErrQuantity') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrQuantityBelowHeld', JSON_OBJECT('en_US', 'The quantity cannot be below the seats already held.', 'zh_CN', '数量不能低于已占座位。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrQuantityBelowHeld') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '数量不能低于已占座位。') WHERE LOWER(code) = LOWER('TktErrQuantityBelowHeld') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrDate', JSON_OBJECT('en_US', 'Enter a valid date.', 'zh_CN', '请输入有效日期。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrDate') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入有效日期。') WHERE LOWER(code) = LOWER('TktErrDate') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrTypeHasOrders', JSON_OBJECT('en_US', 'This ticket type has orders. Disable it instead.', 'zh_CN', '此门票类型已有订单,请改为停用。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrTypeHasOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票类型已有订单,请改为停用。') WHERE LOWER(code) = LOWER('TktErrTypeHasOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrNotPayable', JSON_OBJECT('en_US', 'Only an order awaiting payment or expired can be marked paid.', 'zh_CN', '只有待付款或已过期的订单可标记为已付款。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrNotPayable') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '只有待付款或已过期的订单可标记为已付款。') WHERE LOWER(code) = LOWER('TktErrNotPayable') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrSeatsGone', JSON_OBJECT('en_US', 'The seats of this expired order were taken. It cannot be marked paid.', 'zh_CN', '此过期订单的座位已被占用,无法标记为已付款。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrSeatsGone') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此过期订单的座位已被占用,无法标记为已付款。') WHERE LOWER(code) = LOWER('TktErrSeatsGone') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrPaymentRef', JSON_OBJECT('en_US', 'The payment reference can be at most 100 characters.', 'zh_CN', '付款参考最多 100 个字符。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrPaymentRef') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款参考最多 100 个字符。') WHERE LOWER(code) = LOWER('TktErrPaymentRef') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrNotCancellable', JSON_OBJECT('en_US', 'Only an order awaiting payment or paid can be cancelled.', 'zh_CN', '只有待付款或已付款的订单可取消。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrNotCancellable') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '只有待付款或已付款的订单可取消。') WHERE LOWER(code) = LOWER('TktErrNotCancellable') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktErrLastTicket', JSON_OBJECT('en_US', 'This is the order''s last ticket. Cancel the order instead.', 'zh_CN', '这是订单的最后一张门票,请改为取消订单。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktErrLastTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '这是订单的最后一张门票,请改为取消订单。') WHERE LOWER(code) = LOWER('TktErrLastTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStatusAWAITING', JSON_OBJECT('en_US', 'Awaiting payment', 'zh_CN', '待付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStatusAWAITING') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待付款') WHERE LOWER(code) = LOWER('TktStatusAWAITING') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStatusPAID', JSON_OBJECT('en_US', 'Paid', 'zh_CN', '已付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStatusPAID') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已付款') WHERE LOWER(code) = LOWER('TktStatusPAID') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStatusCANCELLED', JSON_OBJECT('en_US', 'Cancelled', 'zh_CN', '已取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStatusCANCELLED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已取消') WHERE LOWER(code) = LOWER('TktStatusCANCELLED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStatusEXPIRED', JSON_OBJECT('en_US', 'Expired', 'zh_CN', '已过期'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStatusEXPIRED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已过期') WHERE LOWER(code) = LOWER('TktStatusEXPIRED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrdersTitle', JSON_OBJECT('en_US', 'Ticket orders', 'zh_CN', '门票订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrdersTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票订单') WHERE LOWER(code) = LOWER('TktOrdersTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktBackToEvent', JSON_OBJECT('en_US', 'Back to event', 'zh_CN', '返回活动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktBackToEvent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '返回活动') WHERE LOWER(code) = LOWER('TktBackToEvent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderState', JSON_OBJECT('en_US', 'Order state', 'zh_CN', '订单状态'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderState') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单状态') WHERE LOWER(code) = LOWER('TktOrderState') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSearchOrders', JSON_OBJECT('en_US', 'Search orders', 'zh_CN', '搜索订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSearchOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '搜索订单') WHERE LOWER(code) = LOWER('TktSearchOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSearchOrdersHint', JSON_OBJECT('en_US', 'Reference, name, email or mobile', 'zh_CN', '编号、姓名、电邮或手机'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSearchOrdersHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '编号、姓名、电邮或手机') WHERE LOWER(code) = LOWER('TktSearchOrdersHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReference', JSON_OBJECT('en_US', 'Reference', 'zh_CN', '编号'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReference') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '编号') WHERE LOWER(code) = LOWER('TktReference') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktBuyer', JSON_OBJECT('en_US', 'Buyer', 'zh_CN', '买家'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktBuyer') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '买家') WHERE LOWER(code) = LOWER('TktBuyer') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTickets', JSON_OBJECT('en_US', 'Tickets', 'zh_CN', '门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票') WHERE LOWER(code) = LOWER('TktTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTotal', JSON_OBJECT('en_US', 'Total', 'zh_CN', '总额'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTotal') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '总额') WHERE LOWER(code) = LOWER('TktTotal') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSalesEnded', JSON_OBJECT('en_US', 'Sales ended', 'zh_CN', '已停售'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSalesEnded') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已停售') WHERE LOWER(code) = LOWER('TktSalesEnded') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSeatsLeft', JSON_OBJECT('en_US', '{count} left', 'zh_CN', '剩余 {count} 张'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSeatsLeft') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '剩余 {count} 张') WHERE LOWER(code) = LOWER('TktSeatsLeft') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSoldOut', JSON_OBJECT('en_US', 'Sold out', 'zh_CN', '已售罄'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSoldOut') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已售罄') WHERE LOWER(code) = LOWER('TktSoldOut') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktRemoveOne', JSON_OBJECT('en_US', 'Remove one {name}', 'zh_CN', '减少一张 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktRemoveOne') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '减少一张 {name}') WHERE LOWER(code) = LOWER('TktRemoveOne') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAddOne', JSON_OBJECT('en_US', 'Add one {name}', 'zh_CN', '增加一张 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAddOne') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '增加一张 {name}') WHERE LOWER(code) = LOWER('TktAddOne') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPreviewNote', JSON_OBJECT('en_US', 'Visitors choose tickets and fill in their details here.', 'zh_CN', '访客在此选择门票并填写资料。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPreviewNote') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '访客在此选择门票并填写资料。') WHERE LOWER(code) = LOWER('TktPreviewNote') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktSalesClosed', JSON_OBJECT('en_US', 'Ticket sales are closed.', 'zh_CN', '门票销售已结束。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktSalesClosed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票销售已结束。') WHERE LOWER(code) = LOWER('TktSalesClosed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktChooseTickets', JSON_OBJECT('en_US', 'Choose at least one ticket.', 'zh_CN', '请至少选择一张门票。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktChooseTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请至少选择一张门票。') WHERE LOWER(code) = LOWER('TktChooseTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktEmailRequired', JSON_OBJECT('en_US', 'Enter your email.', 'zh_CN', '请输入电子邮件。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktEmailRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入电子邮件。') WHERE LOWER(code) = LOWER('TktEmailRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktConsentRequired', JSON_OBJECT('en_US', 'Tick the box to agree to the privacy notice.', 'zh_CN', '请勾选以同意隐私声明。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktConsentRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请勾选以同意隐私声明。') WHERE LOWER(code) = LOWER('TktConsentRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktMax', JSON_OBJECT('en_US', 'Up to 10 tickets per order.', 'zh_CN', '每笔订单最多 10 张门票。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktMax') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '每笔订单最多 10 张门票。') WHERE LOWER(code) = LOWER('TktMax') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktRequest', JSON_OBJECT('en_US', 'Request tickets', 'zh_CN', '申请门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktRequest') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '申请门票') WHERE LOWER(code) = LOWER('TktRequest') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktThanksPlain', JSON_OBJECT('en_US', 'Thank you. Your request for {event} is in.', 'zh_CN', '谢谢,您对 {event} 的申请已收到。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktThanksPlain') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '谢谢,您对 {event} 的申请已收到。') WHERE LOWER(code) = LOWER('TktThanksPlain') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktThanksPaid', JSON_OBJECT('en_US', 'Your order {reference} is confirmed.', 'zh_CN', '您的订单 {reference} 已确认。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktThanksPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您的订单 {reference} 已确认。') WHERE LOWER(code) = LOWER('TktThanksPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktThanks', JSON_OBJECT('en_US', 'We have your order {reference}. It is held until you pay.', 'zh_CN', '我们已收到您的订单 {reference},付款前为您保留。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktThanks') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '我们已收到您的订单 {reference},付款前为您保留。') WHERE LOWER(code) = LOWER('TktThanks') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktViewOrder', JSON_OBJECT('en_US', 'View your order', 'zh_CN', '查看订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktViewOrder') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看订单') WHERE LOWER(code) = LOWER('TktViewOrder') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktHowToPay', JSON_OBJECT('en_US', 'How to pay', 'zh_CN', '付款方式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktHowToPay') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款方式') WHERE LOWER(code) = LOWER('TktHowToPay') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPayBy', JSON_OBJECT('en_US', 'Pay by {when}', 'zh_CN', '请于 {when} 前付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPayBy') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请于 {when} 前付款') WHERE LOWER(code) = LOWER('TktPayBy') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicOrder', JSON_OBJECT('en_US', 'Order {reference}', 'zh_CN', '订单 {reference}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicOrder') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单 {reference}') WHERE LOWER(code) = LOWER('TktPublicOrder') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicAwaiting', JSON_OBJECT('en_US', 'Awaiting payment', 'zh_CN', '等待付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicAwaiting') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '等待付款') WHERE LOWER(code) = LOWER('TktPublicAwaiting') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicPaid', JSON_OBJECT('en_US', 'Paid. Your order is confirmed.', 'zh_CN', '已付款,订单已确认。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已付款,订单已确认。') WHERE LOWER(code) = LOWER('TktPublicPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicCancelled', JSON_OBJECT('en_US', 'This order was cancelled.', 'zh_CN', '此订单已取消。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicCancelled') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此订单已取消。') WHERE LOWER(code) = LOWER('TktPublicCancelled') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPublicExpired', JSON_OBJECT('en_US', 'This order expired before payment arrived.', 'zh_CN', '此订单在收到付款前已过期。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPublicExpired') AND area = 'A');
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 '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');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '售票活动') WHERE LOWER(code) = LOWER('PagesTicketsEvent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesChooseTicketsEvent', JSON_OBJECT('en_US', 'Choose an event with tickets on', 'zh_CN', '选择已开启售票的活动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChooseTicketsEvent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '选择已开启售票的活动') WHERE LOWER(code) = LOWER('PagesChooseTicketsEvent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTicketsEventHint', JSON_OBJECT('en_US', 'Only events with tickets switched on are listed.', 'zh_CN', '仅列出已开启售票的活动。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTicketsEventHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '仅列出已开启售票的活动。') WHERE LOWER(code) = LOWER('PagesTicketsEventHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCreated', JSON_OBJECT('en_US', 'Created', 'zh_CN', '创建时间'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCreated') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '创建时间') WHERE LOWER(code) = LOWER('TktCreated') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNoOrders', JSON_OBJECT('en_US', 'No orders yet.', 'zh_CN', '尚无订单。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNoOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚无订单。') WHERE LOWER(code) = LOWER('TktNoOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderTitle', JSON_OBJECT('en_US', 'Ticket order', 'zh_CN', '门票订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票订单') WHERE LOWER(code) = LOWER('TktOrderTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderNamed', JSON_OBJECT('en_US', 'Order {reference}', 'zh_CN', '订单 {reference}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderNamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单 {reference}') WHERE LOWER(code) = LOWER('TktOrderNamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderNotFound', JSON_OBJECT('en_US', 'Order not found.', 'zh_CN', '找不到订单。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderNotFound') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '找不到订单。') WHERE LOWER(code) = LOWER('TktOrderNotFound') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktBackToOrders', JSON_OBJECT('en_US', 'Back to orders', 'zh_CN', '返回订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktBackToOrders') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '返回订单') WHERE LOWER(code) = LOWER('TktBackToOrders') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktActionFailed', JSON_OBJECT('en_US', 'The action failed. Try again.', 'zh_CN', '操作失败,请重试。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktActionFailed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '操作失败,请重试。') WHERE LOWER(code) = LOWER('TktActionFailed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktHoldUntil', JSON_OBJECT('en_US', 'Held until', 'zh_CN', '保留至'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktHoldUntil') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保留至') WHERE LOWER(code) = LOWER('TktHoldUntil') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPaymentRef', JSON_OBJECT('en_US', 'Payment reference', 'zh_CN', '付款参考'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPaymentRef') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '付款参考') WHERE LOWER(code) = LOWER('TktPaymentRef') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktPaidBy', JSON_OBJECT('en_US', 'Marked paid by', 'zh_CN', '标记付款者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktPaidBy') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '标记付款者') WHERE LOWER(code) = LOWER('TktPaidBy') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelledBy', JSON_OBJECT('en_US', 'Cancelled by', 'zh_CN', '取消者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelledBy') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消者') WHERE LOWER(code) = LOWER('TktCancelledBy') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktExpiredAt', JSON_OBJECT('en_US', 'Expired', 'zh_CN', '过期时间'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktExpiredAt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '过期时间') WHERE LOWER(code) = LOWER('TktExpiredAt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktResend', JSON_OBJECT('en_US', 'Resend email', 'zh_CN', '重新发送电邮'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktResend') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '重新发送电邮') WHERE LOWER(code) = LOWER('TktResend') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktEmailResent', JSON_OBJECT('en_US', 'Email sent again.', 'zh_CN', '电邮已重新发送。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktEmailResent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '电邮已重新发送。') WHERE LOWER(code) = LOWER('TktEmailResent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktMarkPaid', JSON_OBJECT('en_US', 'Mark paid', 'zh_CN', '标记为已付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktMarkPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '标记为已付款') WHERE LOWER(code) = LOWER('TktMarkPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktMarkedPaid', JSON_OBJECT('en_US', 'Order marked paid.', 'zh_CN', '订单已标记为已付款。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktMarkedPaid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已标记为已付款。') WHERE LOWER(code) = LOWER('TktMarkedPaid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelOrder', JSON_OBJECT('en_US', 'Cancel order', 'zh_CN', '取消订单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelOrder') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消订单') WHERE LOWER(code) = LOWER('TktCancelOrder') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelOrderMessage', JSON_OBJECT('en_US', 'Cancel this order and free its seats? The buyer gets an email.', 'zh_CN', '取消此订单并释放座位?买家将收到电邮。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelOrderMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消此订单并释放座位?买家将收到电邮。') WHERE LOWER(code) = LOWER('TktCancelOrderMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderCancelled', JSON_OBJECT('en_US', 'Order cancelled.', 'zh_CN', '订单已取消。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderCancelled') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已取消。') WHERE LOWER(code) = LOWER('TktOrderCancelled') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelTicket', JSON_OBJECT('en_US', 'Cancel ticket', 'zh_CN', '取消门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelTicket') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消门票') WHERE LOWER(code) = LOWER('TktCancelTicket') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCancelTicketMessage', JSON_OBJECT('en_US', 'Cancel this ticket, free its seat and lower the order total?', 'zh_CN', '取消此门票、释放座位并降低订单总额?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCancelTicketMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '取消此门票、释放座位并降低订单总额?') WHERE LOWER(code) = LOWER('TktCancelTicketMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketCancelled', JSON_OBJECT('en_US', 'Ticket cancelled.', 'zh_CN', '门票已取消。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketCancelled') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票已取消。') WHERE LOWER(code) = LOWER('TktTicketCancelled') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketType', JSON_OBJECT('en_US', 'Ticket type', 'zh_CN', '门票类型'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketType') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票类型') WHERE LOWER(code) = LOWER('TktTicketType') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketActive', JSON_OBJECT('en_US', 'Active', 'zh_CN', '有效'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketActive') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有效') WHERE LOWER(code) = LOWER('TktTicketActive') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketCancelledBy', JSON_OBJECT('en_US', 'Cancelled by {by}, {at}', 'zh_CN', '{by} 于 {at} 取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketCancelledBy') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{by} 于 {at} 取消') WHERE LOWER(code) = LOWER('TktTicketCancelledBy') AND area = 'A';
@@ -0,0 +1,11 @@
-- Co-Lite change add-event-ticket-orders: rollback. Drops every ticket order and ticket. Run only to remove the data too.
USE `service-counter`;
DROP TABLE IF EXISTS `ticket`;
DROP TABLE IF EXISTS `shop_order_line`;
DROP TABLE IF EXISTS `shop_order`;
DROP TABLE IF EXISTS `ticket_type`;
ALTER TABLE `event` DROP COLUMN `tickets_enabled`, DROP COLUMN `payment_instructions`, DROP COLUMN `hold_days`;
USE `service-system`;
DELETE FROM `modules_roles` WHERE `module_id` = 41160000;
DELETE FROM `module` WHERE `id` = 41160000;
@@ -0,0 +1,179 @@
# 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-event-ticket-orders.sql`: the event columns, `ticket_type`, `shop_order`, `shop_order_line` and `ticket`;
- `sql/02-event-tickets-module.sql`: `BO_EVENT_TICKETS`;
- `sql/99-rollback.sql`.
Mirror 01 and 02 in `local/seed/03-colite.sql`, and apply them to the local database.
- Depends on: none
- Scope: `local/seed/**`, `openspec/changes/add-event-ticket-orders/sql/**`
- Verify: `SELECT` shows the tables, keys, event columns and module row.
## 2. services-counter
- [x] 2.1 Ticket entities, settings and ticket types.
- Depends on: 1.1
- Tests first:
- **Entities:** they map to the DDL.
- **Ticket settings** (own endpoint `ticketType/settings`; an event edit keeps the stored settings):
- switching on with blank instructions is refused on the field;
- hold days 0 or 15 are refused;
- a valid save persists.
- **Type save:**
- a duplicate name gives `NAME_TAKEN`;
- a quantity below held gives `QUANTITY_BELOW_HELD`;
- another company's event gives 404.
- **Type delete:** gives `TYPE_HAS_ORDERS` when the type has orders.
- **`list`:** gives the right `held` and `left` with a mix of ACTIVE and CANCELLED tickets and AWAITING, PAID and EXPIRED orders.
- **`onSale`:** gives only enabled types, the right `state` values (`ON_SALE`, `SOLD_OUT`, `ENDED`) and no company data.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
- [x] 2.2 Order request, seat locking, capacity and the buyer as a lead.
- Depends on: 2.1
- Tests first:
- **Request outcomes:**
- a valid request makes an order, its lines and its tickets, with the reference format, the token and the correct total;
- a total of 0 makes the order PAID;
- quantities 0, 11 or negative give `BAD_QUANTITY`;
- a disabled type, a type past its sales end, or a type short of seats gives `TYPE_UNAVAILABLE` with `left`;
- a 4th awaiting order gives `TOO_MANY_AWAITING`;
- Tickets off, a disabled event or an ended event gives `TICKETS_CLOSED`.
- **Capacity:**
- before the event days, guests plus walk-ins plus held tickets over capacity gives `EVENT_FULL` with `left`;
- on the event days it does not.
- **Concurrency:** the unit test proves the event lock is taken before seats are counted. The module has no test database, and adding H2 or Testcontainers would be a new dependency for one test. So the real lock and the JPQL are checked against the local MySQL stack in 5.1: the counter boots, which validates the queries, and two parallel requests race for the last seat.
- **Buyer lead:**
- a new buyer gets an event lead with source `TICKET` and the UTM values;
- a buyer already captured keeps the old source and gets a note naming the reference.
- **Headcount:** it adds `heldTickets`, and the invite registration's capacity check counts held tickets.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
- [x] 2.3 Staff order actions, the expiry job and emails.
- Depends on: 2.2
- Tests first:
- **`list`:** filter, search and paging.
- **`get`:** another company's order gives 404.
- **`markPaid`:**
- from AWAITING;
- from EXPIRED with seats free;
- `SEATS_GONE`;
- `NOT_PAYABLE` from PAID or CANCELLED.
- **`cancel`:** frees the seats; `NOT_CANCELLABLE` from EXPIRED.
- **`cancelTicket`:** lowers the total and frees the seat; `LAST_TICKET`.
- **Expiry job:**
- expires only orders past their hold;
- a conditional update never overwrites PAID.
- **Mailer:**
- sends after commit;
- escapes user values;
- puts the order link in the email;
- records `last_email`;
- a failed send leaves the order changed.
- **`resend`:** sends the `last_email` kind.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
- [x] 2.4 `CmsBlockValidator` TICKETS.
- Depends on: 2.1
- Tests first:
- **Event checks:**
- a TICKETS block without an event is refused;
- another company's event is refused;
- an event with Tickets off is refused;
- an ended event is refused.
- **Field limits:**
- a heading of 121 characters is refused;
- text of 1001 characters is refused;
- an unused field is refused with `PagesUnusedField`.
- **Valid block:** a valid block with eyebrow, look and anchor is accepted.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
## 3. mobile-api and gateway
- [x] 3.1 Admin ticket endpoints.
- Depends on: 2.3
- Tests first:
- **Gating:**
- every endpoint gives 403 without `BO_EVENT_TICKETS`;
- another company's event or order gives 404;
- the event PUT ignores ticket settings without the permission.
- **Audit:** each write is audited.
- **Event GET:** it returns `ticketsEnabled`.
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
- [x] 3.2 Public TICKETS page data, request and order page, and the gateway paths.
- Depends on: 2.4, 3.1
- Tests first:
- **Page data:** the page GET adds `tickets` or `closed` to a TICKETS block.
- **Request:**
- the honeypot gives a fake success and nothing is posted;
- the `reg:submit` limit applies;
- inputs are normalised;
- counter errors map to the right public messages.
- **Order page:**
- a bad token shape gives 404 with no backend call;
- the `ord:load` limit applies;
- the payment instructions appear only while AWAITING.
- **Gateway:** the three paths are open and nothing else changes.
- Scope: `solvway-mobile-api/src/**`, `solvway-api-gateway/src/**`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api,solvway-api-gateway verify`
## 4. Portal
- [x] 4.1 Event Tickets section, orders list and order detail.
- Depends on: 3.1
- Tests first:
- **Visibility:** the section is hidden without `BO_EVENT_TICKETS`.
- **Settings form:** shows the validation errors.
- **Types table:** add, edit and disable, with the delete error shown.
- **Orders list:** filter and search.
- **Order detail actions:**
- mark paid with a reference;
- cancel order and cancel ticket, each with a confirm;
- the `SEATS_GONE` and `LAST_TICKET` messages shown;
- resend.
- **`ROUTE_MODULES`:** the new pages are mapped.
- Scope: `solvway-admin-portal/app/**`
- Verify: `npx vitest run` (check the exit code), `npx tsc --noEmit`, `npm run lint`
- [x] 4.2 The TICKETS block, the editors and the order page.
- Depends on: 3.2, 4.1
- Tests first:
- **Renderer:**
- types, prices, `Free`, sold out and sales ended;
- steppers capped at 10 in total;
- the running total;
- field errors;
- the thank-you with instructions and the order link;
- the free-order confirmation;
- the closed state.
- **Editors:** the block appears in the Add section menu; the event picker lists only events with tickets on.
- **`/o/[token]`:**
- states and instructions;
- the invalid link message;
- the route is public;
- the proxy sends one X-Forwarded-For hop.
- **Labels:** in English and zh-CN, plus the `sql/03-*-labels.sql` file.
- Scope: `solvway-admin-portal/app/**`, `openspec/changes/add-event-ticket-orders/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.
- Sign in as admin.
- Grant Event tickets to the role.
- Click into the test event, turn Tickets on, and add the types.
- Add a TICKETS block to a **draft** test page.
- Open its preview and request tickets with a disposable buyer the owner nominates. Ask before saving any order.
- See the order in staff screens, mark it paid, and cancel a ticket.
- Check the blocked paths: over 10 tickets, sold out, missing consent, and an unknown order link.
- Take screenshots.
- Depends on: 4.2
- [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
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,22 @@
# Design
## Context
Measured at 1920×1080 on the INS page: top bar 69 px, hero 886 px (set by the form card), trust strip about 122 px, 1077 px in all. The hero grid has `pt-16 pb-12`. Bands get `py-12`. The compact form uses `space-y-4`, and its consent box holds two lines of normal-size text (English and Malay).
## Approaches
1. **Trim spacing (chosen).** Trust band padding, hero padding and the compact form's gaps. It is about 150 px in all, with no field taken away and no setting added.
2. **Side-by-side fields** (Mobile and Email on one row on wide screens). That saves about 80 px more, but the fields get narrower, and the hint and errors under Mobile get harder to lay out. It is kept in reserve.
3. **A form-size setting for staff.** This adds UI for something the page should simply get right.
## Decisions
- The trust band padding is `py-5` only for TRUST. Other bands keep `py-12`.
- The full-width hero grid is `pt-8 pb-8`. The editor's image button still fits in the corner, because it is positioned on the section, not in the padding.
- In the compact form: `space-y-3` between fields, the consent box text is `text-sm`, and the form card's gap is `space-y-3`. The 44 px control heights stay, for touch targets.
- The check is a Playwright measurement at 1920×1080: the bottom of the trust strip at or below 950 px from the top. There is no unit test for pixel heights (jsdom has no layout). Render tests pin the classes instead.
## Risks
- **A tighter consent box is still the consent.** Its text, its checkbox and its required state do not change; only the font size does. `text-sm` (14 px) stays readable.
@@ -0,0 +1,33 @@
# Proposal
## Why
On the INS Hotel technology page (`/p/INS/hotel-technology`), the top bar, the full-width hero with its sign-up form, and the trust strip together are 1077 px tall. A visitor on a 1080p or 1440p desktop sees the trust strip cut off at the bottom of the first screen. The owner wants the hero and the trust strip to fit on one desktop screen. Staff have no way to change the form's size, and the form sets the hero's height.
## What Changes
- **Thinner trust strip.** A trust strip shown as a coloured band uses less padding above and below (about 20 px instead of 48 px), close to INS's 22 px.
- **Less padding in the full-width hero.** It is about 32 px top and bottom, instead of 64 px top and 48 px bottom.
- **Tighter compact form.** The landing-page form (the compact form) has smaller gaps between fields, and the consent box uses small text. The fields, the dropdown and the button keep their 44 px height, so they stay easy to tap.
- **Result.** The INS page's top bar, hero and trust strip fit within 950 px, which shows them in full on a 1920×1080 desktop browser.
Not changing:
- QR, invitation and customer forms.
- Heroes that are not full width, and other band looks.
- Phones, where the hero stacks the form below the text.
- Small laptops (768 px tall). There the form alone is taller than the screen, as on INS's own page.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: adds "First Screen Fits The Hero And Trust Strip".
## Impact
- Portal only: `CmsBlocks.tsx` (trust band padding, full-width hero padding, form card gap) and `RegistrationForm.tsx` (compact spacing and consent text).
- No server, API or data change. No new labels.
@@ -0,0 +1,16 @@
## ADDED Requirements
### Requirement: First Screen Fits The Hero And Trust Strip
A page with a top bar, a full-width hero with its sign-up form, and a trust strip SHALL show all three in full within the first 950 px of a desktop browser window. To fit, the trust strip band SHALL use less padding than other bands, and the landing-page form SHALL keep its fields, dropdown and button at least 44 px tall.
#### Scenario: INS page on a 1080p desktop
- **GIVEN** page `/p/INS/hotel-technology` with a top bar, a full-width hero with a form, and a trust strip
- **WHEN** a visitor opens it in a 1920×1080 browser window
- **THEN** the bottom of the trust strip is within 950 px of the top of the page
#### Scenario: Form controls stay easy to tap
- **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
@@ -0,0 +1,26 @@
# Tasks
## 1. Portal
- [x] 1.1 `CmsBlocks.tsx`:
- a TRUST band uses `py-5`; other bands keep `py-12`;
- the full-width hero grid uses `pt-8 pb-8`;
- the hero form card uses `space-y-3`.
`RegistrationForm.tsx`, compact only: `space-y-3` between fields, and `text-sm` in the consent box.
Verify: render tests fail first, then pass; vitest exit 0, tsc and lint clean.
## 2. Verification
- [x] 2.1 Use Playwright on port 3001 to measure `/p/INS/hotel-technology` at 1920×1080: the trust strip's bottom is at most 950 px, and the controls are at least 44 px tall. Take screenshots at 1920×1080, 1280×900 and 390 px.
- [x] 2.2 Run `openspec validate add-hero-fits-screen --strict`.
## Notes (2026-12-04)
- **Red first:** the new render tests failed on the trust band padding, the hero padding, the card gap, the compact form gap and the consent text size.
- **Changed existing tests:** none.
- **Measured** on `/p/INS/hotel-technology` at 1920×1080 with Playwright:
- before: hero 886 px, trust strip bottom 1077 px;
- with `pt-10 pb-10`: 953 px, still over the 950 px target, so the hero padding became `pt-8 pb-8`;
- final: hero 802 px, trust strip bottom 937 px. Every text field, the dropdown and the Register button are 44 px.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,24 @@
# Design
## Context
The company header and the page title are drawn by `LandingPage`, and "hide page header" (`hideHeader`) removes both. Page settings are database columns threaded through services-counter, mobile-api and the portal. Blocks are JSON validated by `CmsBlockValidator`, so a new block or block field needs no schema change.
## Approaches
1. **A Top bar block, used with "hide page header" (chosen).** It is JSON only: no migration, and no changes to the page records in three services. The INS page already uses "hide page header" with a Custom HTML top bar, so this is a native swap for the same layout.
2. **New page settings** ("hide title", header button label and link, heading font). This is the natural model, but it means four new columns and changes to every page DTO, the draft record, the admin and public APIs, and the settings panel. That is about ten times the work for the same result.
3. **Keep the top bar in Custom HTML.** This is what the original page does; the native page exists to avoid it.
## Decisions
- **The top bar is the first block only.** The server refuses it anywhere else (`PagesTopBarFirst`), because a sticky bar in the middle of a page would cover the content as the visitor scrolls past it. The bar is `sticky top-0` with a card background and a bottom border. It runs full width (it counts as bleed), so it joins a full-width hero below it with no gap.
- **Top bar fields.** Only `buttonLabel` and `buttonUrl` (the pair rule, at most 40 characters, a safe link) plus the usual `anchor`. A heading, text, image, cards or look are refused (`PagesUnusedField`). The logo comes from the company's branding, as the default header's does.
- **The label (`eyebrow`).** At most 40 characters, allowed on FEATURES, STEPS, IMAGE_TEXT, FAQ and CTA, and refused on other types. It renders as a `p` above the h2, not as part of the heading, so screen readers read the heading on its own. It can be edited in place on the canvas.
- **Label colour.** On the DARK band it uses `text-primary`, the accent colour. On light backgrounds the accent can be too pale (INS gold on white is about 2:1), so it uses the accent mixed with the foreground colour, `color-mix(in srgb, var(--primary) 60%, var(--foreground))`. On the ACCENT band it uses the band's own text colour.
- **Serif headings.** Section h2s get `font-serif`, Tailwind's system serif, as the full-width hero does. No web font is added. This changes every landing page, CV's included. It is a small change, and it matches the hero.
## Risks
- **CV pages change font.** CV's section headings become serif. If CV wants sans-serif, a later change can make the font a company setting.
- **Sticky bar and same-page links.** A `#name` jump lands with the heading under the bar. `scroll-margin-top` on the named blocks keeps them clear when a top bar exists.
@@ -0,0 +1,42 @@
# Proposal
## Why
The native INS page (`/p/INS/hotel-technology-native`) now matches INS's standalone page in content, but it still looks different at the top and in its section headings:
- INS has a white top bar with the logo on the left and a "Get My Free Consultation" button on the right. The bar stays at the top while the visitor scrolls. Our page has two choices: show the company header and the page title, which INS does not have, or hide both, which also hides the logo.
- INS puts a small gold uppercase label above each section heading ("Services", "How we work", "Why Infinity", "FAQ"). We have no such label.
- INS's section headings are serif. Ours are sans-serif, except for the full-width hero.
## What Changes
- **Top bar block** (`TOPBAR`). It shows the company logo on the left (the company name when there is no logo) and an optional button on the right (`buttonLabel` and `buttonUrl`, with the same link rules as other buttons). It stays at the top of the window while the page scrolls. It may only be the first block. Together with "hide page header", it gives INS's layout: the logo and button stay, and the title and the default header go.
- **Section labels** (`eyebrow`, at most 40 characters). Feature cards, Steps, Image with text, FAQ and Call to action may carry a short label. It shows above the heading in small uppercase letters in the accent colour, darkened on light backgrounds so it stays readable.
- **Serif section headings.** Section headings (h2) on landing pages use the same serif as the full-width hero.
- New editor labels in English and Chinese, with an SQL label file.
Not changing:
- The page settings and the database. "Hide page header" already exists, and the new fields live in the block JSON.
- Card and step layout, and the bullet style in rich text.
- The default company header on pages without a top bar.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: adds "Top Bar Block", "Section Labels" and "Serif Section Headings".
## Impact
- services-counter: `CmsBlock` gains `eyebrow`. `CmsBlockValidator` validates TOPBAR and `eyebrow`.
- mobile-api: none. Public blocks pass through as maps.
- Portal:
- `cmsPages.ts`: the TOPBAR type, its label and empty block, and `eyebrow`;
- `CmsBlocks.tsx`: renders the top bar, the labels and the serif headings;
- `BlockFields.tsx`: the top bar's button and the label field;
- labels in `defaultMessages.ts` and `zh_CN.seed.json`.
- Data: no schema change. The new labels need a SQL label file in this change folder.
@@ -0,0 +1,42 @@
## ADDED Requirements
### Requirement: Top Bar Block
A page's first block MAY be a top bar. The top bar SHALL show the company logo, or the company name when there is no logo, and an optional button, and SHALL stay at the top of the window while the page scrolls. The server SHALL refuse a top bar that is not the first block, or one that carries fields other than its button and link name.
#### Scenario: Logo and button without the page title
- **GIVEN** page `/p/INS/hotel-technology-native` with "hide page header" on, a top bar with the button "Get My Free Consultation" linking to `#consult`, and a full-width hero
- **WHEN** a visitor opens the page and scrolls down
- **THEN** the INS logo and the button stay at the top of the window
- **AND** no page title heading shows, and the hero starts directly under the bar
#### Scenario: Top bar further down is refused
- **WHEN** staff save a page whose top bar is the second block
- **THEN** the save is refused with the reason naming that block
### Requirement: Section Labels
Feature cards, Steps, Image with text, FAQ and Call to action blocks MAY carry a label of at most 40 characters. The page SHALL show the label above the block's heading, in small uppercase letters in the accent colour. The server SHALL refuse a longer label, or a label on any other block type.
#### Scenario: Label above a heading
- **GIVEN** a Feature cards block with the label "Services" and the heading "Everything your guests touch, handled by one team"
- **WHEN** a visitor opens the page
- **THEN** "Services" shows in small uppercase letters directly above the heading
#### Scenario: Type a label in the editor
- **GIVEN** staff editing a Steps block
- **WHEN** they type "How we work" in its label field and save
- **THEN** the page keeps the label
### Requirement: Serif Section Headings
Section headings on landing pages SHALL use the serif typeface that the full-width hero uses.
#### Scenario: Feature heading in serif
- **WHEN** a visitor opens a page with a Feature cards block
- **THEN** its heading uses the serif typeface
@@ -0,0 +1,9 @@
-- The labels added by add-landing-page-polish, 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 'PagesBlockTopBar', JSON_OBJECT('en_US', 'Top bar', 'zh_CN', '顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockTopBar') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '顶栏') WHERE LOWER(code) = LOWER('PagesBlockTopBar') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesEyebrow', JSON_OBJECT('en_US', 'Label', 'zh_CN', '小标签'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesEyebrow') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '小标签') WHERE LOWER(code) = LOWER('PagesEyebrow') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTopBarFirst', JSON_OBJECT('en_US', 'The top bar must be the first section.', 'zh_CN', '顶栏必须是第一个区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTopBarFirst') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '顶栏必须是第一个区块。') WHERE LOWER(code) = LOWER('PagesTopBarFirst') AND area = 'A';
@@ -0,0 +1,55 @@
# Tasks
## 1. Server
- [x] 1.1 services-counter `CmsBlock`: add `eyebrow`. `CmsBlockValidator`:
- TOPBAR is allowed only at index 0 (`PagesTopBarFirst`); it takes the button pair and `anchor` only, and any other field is refused (`PagesUnusedField`);
- `eyebrow` at most 40 characters on FEATURES, STEPS, IMAGE_TEXT, FAQ and CTA, and refused elsewhere (`PagesUnusedField`).
Verify: new validator tests fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
## 2. Portal
- [x] 2.1 `CmsBlocks.tsx`:
- renders TOPBAR (logo or name, optional button, sticky, full width, joins a full-width hero);
- renders the label above section headings, in the accent colour, darkened on light backgrounds;
- renders section h2s in serif;
- named blocks keep clear of a sticky bar when jumped to.
Verify: render tests fail first, then pass; vitest exit 0.
- [x] 2.2 Editor:
- `cmsPages.ts`: TOPBAR type, label and empty block; `eyebrow`;
- `BlockFields.tsx`: the top bar's button fields, and the label field on the five types; the label is editable in place on the canvas;
- labels in `defaultMessages.ts`, `zh_CN.seed.json` and `sql/01-polish-labels.sql`; regenerate `local/seed/04-zh-cn-messages.sql`.
Verify: editor tests fail first, then pass; tsc and lint clean.
## 3. Verification
- [x] 3.1 Rebuild services-counter. Use Playwright on port 3001 to edit `/p/INS/hotel-technology-native` through the editor:
- turn on "hide page header";
- add a top bar first, with "Get My Free Consultation" linking to `#consult`;
- add the labels "Services", "How we work", "Why Infinity" and "FAQ";
- publish.
Check the published page at 1280 px and 390 px against the INS page, including the bar staying put on scroll.
- [x] 3.2 Run the full portal vitest (exit 0), tsc, lint, Maven verify for services-counter, and `openspec validate add-landing-page-polish --strict`.
- [x] 3.3 Add a release note to `docs/deployment.md` (label SQL).
## Notes (2026-12-04)
- **Red first:**
- the validator tests failed on the top bar and the labels;
- the render tests failed on the top bar, the scroll margin, the labels and the serif headings;
- the editor test failed on the label field and the top bar.
- **Changed existing tests:** none. One of my own new render tests changed before going green: the sticky class sits on the top bar's row, not on the header. A sticky element only sticks inside its parent, and the header's parent is just as tall as the header.
- **Live check** (port 3001, rebuilt counter), on `/p/INS/hotel-technology-native` through the editor:
- "hide page header" was already on;
- added a Top bar section, moved it first, and set "Get My Free Consultation" linking to `#consult`;
- typed the labels "Services", "How we work", "Why Infinity" and "FAQ" on the canvas;
- saved and published.
- **Published result:**
- at 1280 px the logo and button sit in a white bar above the full-width hero, with no title, and the bar stays at the top while scrolling;
- the labels show in darkened gold uppercase above serif headings;
- at 390 px the bar keeps the logo and button, and the hero stacks.
- **Not reachable in the UI, covered by the validator tests:** a top bar that is not first is refused (the server rule; the editor's Move up and Move down allow it, and the refusal shows on the canvas).
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,30 @@
# Design
## Context
Landing blocks are JSON validated by `CmsBlockValidator` and rendered by `CmsBlocks.tsx`. Card blocks (FEATURES, STEPS, TRUST, HERO points) share `cards` and the editor's card list in `BlockFields.tsx`. Text is edited in place with `Text`, which renders plain text outside the editor. The landing form's done state is `VisitorState` with the `RegThanks` heading.
## Approaches
1. **A FOOTER block built on `cards` (chosen).** Columns are cards with a title and text, the legal line is the block's `text`. The DTO gains nothing for the footer, and the editor reuses the card list. Staff get a footer that looks right without formatting.
2. **Columns and link colours on the Rich Text block.** This keeps one block type, but staff would have to build columns and links by hand, and every rich text block would gain layout options.
3. **Keep the footer in Custom HTML.** This is what the original page does; the native page exists to avoid it.
For the thank-you text, a field on the form-bearing blocks is the only sensible way: the message belongs to the page, not to the event, because one event can have several pages.
## Decisions
- **Links are found, not typed.** One helper splits plain text into text and links:
- `+` followed by digits, spaces and dashes (at least 8 digits) becomes `tel:` with only `+` and digits;
- an email address becomes `mailto:`;
- `https://…` and `www.…` become `https://` links that open in a new tab with `rel="noopener noreferrer"`.
It builds React elements, never HTML, so text stays text. `Text` gains a `links` flag that uses it outside the editor; in the editor the text stays editable as now.
- **Footer validation.** 1 to 4 cards, each with a required title (80) and required text (300), no icon. `text` at most 300. No heading.
- **Footer look.** `emptyBlock("FOOTER")` sets `look: "DARK"`. Links use the existing link colour (`text-primary`), which is the company's accent colour, so INS's footer links are gold.
- **Thank-you text.** `thanksText` (200) on FORM, and on HERO only with an event, like `formHeading`. `LandingForm` takes it as `thanks` and passes it to `VisitorState`'s text, through the link helper. Choosing "No form" on a hero, or changing company, clears it along with the event.
- **Shade.** The design-token test refuses raw colours, so the shade stays black-based: `from-black/55 to-black/10 to-70%` from the `md` width, and an even `black/60` below it. White text keeps contrast because the text sits on the darker left.
## Risks
- **Phone detection.** Only numbers written with `+` become links. A local number like "03-7623 9807" stays plain text. This is deliberate, to avoid linking dates or prices.
- **Lighter shade over a bright photo.** The headline could lose contrast. The hero heading is large and bold, and INS uses the same shade; staff can pick a darker photo.
@@ -0,0 +1,48 @@
# Proposal
## Why
The INS Hotel technology page is being rebuilt in Co-Lite without Custom HTML, to match INS's standalone page (`~/Projects/ins-landing-page`). After add-compact-landing-form, the content matches, but three things still differ, and marketing staff cannot fix them from the editor:
- After signing up, INS shows "Thanks! Our team will contact you shortly. Prefer to talk now? Call +60 12-833 2775", with the number as a tap-to-call link. Our landing form shows the same generic thank-you on every page.
- INS's footer has up to three columns (company and address, "Talk to us" with phone and email, website). The phone, email and web address are gold links, and the © line sits under a thin divider. Ours is one stacked column of plain rich text.
- INS's hero shade is lighter, so more of the photo shows. Ours is near-black on the text side.
## What Changes
- **Thank-you text.** The FORM block and a HERO with an event MAY carry `thanksText` (at most 200 characters). After a visitor signs up, it shows under the "Thank you" heading. Phone numbers that start with `+`, email addresses, and `https://` or `www.` web addresses in it become links. Without it, the thank-you stays as it is now. The server refuses it on a HERO without an event.
- **Footer block.** A new block type, FOOTER:
- 1 to 4 columns, each a bold title (80 characters) and text (300 characters, line breaks kept);
- an optional legal line (`text`, 300 characters) under a thin divider;
- phone numbers, emails and web addresses in the column text become links in the link colour;
- a new footer starts with the dark look; staff may change the look as on any block.
- **Lighter full-width hero shade.** The full-width hero's shade runs from about half dark on the text side to almost clear at 70% of the width, like INS. On phones, where the text sits over the whole photo, the shade is an even dark layer.
- New editor labels in English and Chinese, with an SQL label file for real environments.
Not changing:
- QR and invitation sign-up thank-you screens.
- The Rich Text block. Existing footers built with it keep working.
- Heroes that are not full width.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: adds "Thank-You Text On Landing Forms" and "Footer Block".
## Impact
- services-counter: `CmsBlock` gains `thanksText`. `CmsBlockValidator` checks `thanksText` on FORM and HERO and validates the FOOTER type.
- mobile-api: none. Public blocks pass through as maps.
- Portal:
- `cmsPages.ts`: the FOOTER type, its empty block and label;
- a small link-finding helper used by the footer and the thank-you text;
- `CmsBlocks.tsx` renders the footer, passes the thank-you text and lightens the shade;
- `LandingForm.tsx` shows the thank-you text;
- `BlockFields.tsx` gets the footer's columns and legal line, and the thank-you field on FORM and HERO;
- labels in `defaultMessages.ts` and `zh_CN.seed.json`.
- Data: no schema change, because the blocks are JSON. The new labels need a SQL label file in this change folder.
@@ -0,0 +1,64 @@
## ADDED Requirements
### Requirement: Thank-You Text On Landing Forms
A FORM block, and a HERO block with an event, MAY carry a thank-you text of at most 200 characters. After a visitor signs up through that block's form, the page SHALL show the text, with contact links, under the thank-you heading. Without it, the thank-you SHALL look as before. The server SHALL refuse an over-long thank-you text, or one on a HERO without an event.
#### Scenario: Visitor sees the page's thank-you text with a call link
- **GIVEN** page `/p/INS/hotel-technology-native` whose hero form has the thank-you text "Prefer to talk now? Call +60 12-833 2775."
- **WHEN** a visitor signs up through the hero form
- **THEN** the page shows the thank-you heading and "Prefer to talk now? Call +60 12-833 2775."
- **AND** "+60 12-833 2775" is a link to `tel:+60128332775`
#### Scenario: No thank-you text keeps today's message
- **WHEN** a visitor signs up through a FORM block without a thank-you text
- **THEN** the page shows only the thank-you heading and the "register another" button, as before
#### Scenario: Thank-you text on a hero without a form is refused
- **WHEN** staff save a HERO block without an event but with a thank-you text
- **THEN** the save is refused with the reason naming the hero's thank-you field
#### Scenario: Set the thank-you text in the editor
- **GIVEN** staff editing a hero that has an event
- **WHEN** they type a thank-you text in the hero's settings and save
- **THEN** the page keeps the text
- **AND** choosing "No form" on the hero clears it
### Requirement: Footer Block
A page MAY hold FOOTER blocks: 1 to 4 columns, each a required title (80 characters) and text (300 characters), and an optional legal line (300 characters). The page SHALL show the columns side by side on wide screens and stacked on phones, keep line breaks, show contact links in the column text, and put the legal line under a thin divider. A new footer SHALL start with the dark look. The server SHALL refuse a footer that breaks these limits, or that has a heading or a column icon.
#### Scenario: Visitor sees a three-column footer with links
- **GIVEN** a published page whose footer has the columns "Infinity Networks Security Sdn Bhd", "Talk to us" with "+603-7623 9807" and "info@infinitynetworks.com.my", and "Website" with "www.infinitynetworks.com.my", and a legal line
- **WHEN** a visitor opens the page in a 1280 px window
- **THEN** the three columns sit side by side on a dark band
- **AND** the phone links to `tel:+60376239807`, the email to `mailto:info@infinitynetworks.com.my`, and the website to `https://www.infinitynetworks.com.my`
- **AND** the legal line sits under a divider
#### Scenario: Add a footer in the editor
- **GIVEN** staff editing a page
- **WHEN** they add a Footer section
- **THEN** the canvas shows a dark footer with two empty columns to type into
- **AND** they can add columns up to 4 and type the legal line
#### Scenario: Footer with five columns is refused
- **WHEN** a page is saved with a footer of 5 columns
- **THEN** the save is refused with the reason naming the footer's columns
### Requirement: Contact Links In Plain Text
Where this spec says text shows contact links, the page SHALL show phone numbers that start with `+` as `tel:` links holding only `+` and digits, email addresses as `mailto:` links, and `https://` or `www.` addresses as `https://` links that open in a new tab. Everything else SHALL stay plain text, never HTML.
#### Scenario: Text with markup stays text
- **GIVEN** a footer column text "<b>Call</b> +60 12-833 2775"
- **WHEN** a visitor opens the page
- **THEN** "<b>Call</b>" shows as written
- **AND** "+60 12-833 2775" links to `tel:+60128332775`
@@ -0,0 +1,13 @@
-- The labels added by add-landing-thanks-and-footer, 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 'PagesThanksText', JSON_OBJECT('en_US', 'Thank-you text', 'zh_CN', '感谢语'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesThanksText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '感谢语') WHERE LOWER(code) = LOWER('PagesThanksText') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockFooter', JSON_OBJECT('en_US', 'Footer', 'zh_CN', '页脚'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockFooter') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页脚') WHERE LOWER(code) = LOWER('PagesBlockFooter') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesColumnN', JSON_OBJECT('en_US', 'Column {number}', 'zh_CN', '第 {number} 栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesColumnN') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '第 {number} 栏') WHERE LOWER(code) = LOWER('PagesColumnN') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddColumn', JSON_OBJECT('en_US', 'Add column', 'zh_CN', '添加栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddColumn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加栏') WHERE LOWER(code) = LOWER('PagesAddColumn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFooterLegal', JSON_OBJECT('en_US', 'Legal line', 'zh_CN', '版权声明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFooterLegal') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '版权声明') WHERE LOWER(code) = LOWER('PagesFooterLegal') AND area = 'A';
@@ -0,0 +1,52 @@
# Tasks
## 1. Server
- [x] 1.1 services-counter `CmsBlock`: add `thanksText`. `CmsBlockValidator`:
- `thanksText` at most 200 on FORM and HERO; refused on a HERO without `eventUuid` and on every other type (`PagesUnusedField`);
- FOOTER: no heading; 1 to 4 cards, each with a required title (80) and required text (300) and no icon; `text` at most 300.
Verify: new validator tests fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
## 2. Portal
- [x] 2.1 Link helper and rendering:
- a helper that turns plain text into text and links (`+` phone numbers, emails, `https://` and `www.` addresses), building elements, never HTML;
- `Text` gains `links`;
- `CmsBlocks.tsx` renders FOOTER (columns, line breaks, legal line under a divider), passes `thanksText` to `LandingForm`, and lightens the full-width hero shade;
- `LandingForm.tsx` shows the thank-you text under the heading.
Verify: render tests fail first, then pass; vitest exit 0.
- [x] 2.2 Editor:
- `cmsPages.ts`: FOOTER type, label and empty block (dark look, two columns);
- `BlockFields.tsx`: the footer's columns (1 to 4) and legal line; the thank-you field on FORM, and on HERO when an event is picked; "No form" and company change clear it;
- labels in `defaultMessages.ts`, `zh_CN.seed.json`, `sql/01-thanks-footer-labels.sql`; regenerate `local/seed/04-zh-cn-messages.sql`.
Verify: editor tests fail first, then pass; tsc and lint clean.
## 3. Verification
- [x] 3.1 Rebuild services-counter. Use Playwright on port 3001 to edit `/p/INS/hotel-technology-native` through the editor:
- set the hero's thank-you text to "Prefer to talk now? Call +60 12-833 2775.";
- replace the rich text footer with a Footer section matching INS;
- publish.
Check the published page at 1280 px and 390 px. The thank-you screen needs a real sign-up, which writes a record: check it in the editor preview path only if it does not save, otherwise ask the owner first.
- [x] 3.2 Run the full portal vitest (exit 0), tsc, lint, Maven verify for services-counter, and `openspec validate add-landing-thanks-and-footer --strict`.
- [x] 3.3 Add a release note to `docs/deployment.md` (label SQL).
## Notes (2026-12-04)
- **Red first:**
- the validator tests failed on the thank-you text and the footer;
- the render tests failed on the thank-you text, the footer and the link helper (missing module);
- the editor tests failed on the Footer section, the hero's thank-you field and the company switch.
- **Changed existing tests:** none. Two of my own new editor tests were fixed before going green: column names shift after a removal, and the Form block has its own thank-you field, so the hero checks are scoped to block 1.
- **Design-token checks:** the phone shade uses an even black gradient (`bg-black/60` is refused), and the divider uses `border-muted-foreground/30` (`border-current/15` is not in Tailwind 3).
- **Live check** (port 3001, rebuilt counter), on `/p/INS/hotel-technology-native` through the editor:
- typed the hero's thank-you text "Prefer to talk now? Call +60 12-833 2775.";
- added a Footer section with three columns and the legal line, and removed the old Text footer;
- saved and published.
- **Published result:** at 1280 px the three columns sit side by side on the dark band with gold tel, mailto and https links, and the legal line sits under a divider; at 390 px they stack. The hero shade is lighter.
- **Not run live:** the thank-you screen itself, because it needs a real sign-up, which writes a record. The render tests cover it (thank-you text and the tel link after a mocked sign-up).
- **Not reachable in the UI, covered by the validator tests:** 5 footer columns (Add column stops at 4), and a thank-you text on a hero without a form (No form clears it).
+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 ### Requirement: Event attendance numbers
The event page SHALL show: 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.
- invited: the number of guests, against the invitation cap when set;
- registered: guests linked to an event lead;
- attended: attended event leads;
- walk-ins: event leads not linked to a guest;
- total: registered guests plus walk-ins, against capacity when set.
The numbers SHALL agree with the guest list and the event leads listing. A total above capacity SHALL be shown, not hidden.
#### Scenario: Numbers #### 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 - **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 - **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 ### 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. 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 ### 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 #### 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 - **WHEN** the third guest submits their invite
- **THEN** they are registered - **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 ### 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. 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
+182 -1
View File
@@ -636,7 +636,7 @@ A HERO block MAY be marked full width. A full-width hero SHALL span the whole wi
### Requirement: Full-Width Blocks Join Without Gaps ### Requirement: Full-Width Blocks Join Without Gaps
A full-width HERO and a Custom HTML block next to each other SHALL join with no gap between them, and so SHALL two Custom HTML blocks next to each other. Other blocks SHALL keep their usual spacing. A full-width HERO, a Custom HTML block, and a block with a non-default look SHALL join with no gap when two of them are next to each other. Other blocks SHALL keep their usual spacing.
#### Scenario: Top bar runs straight into the hero #### Scenario: Top bar runs straight into the hero
@@ -644,6 +644,12 @@ A full-width HERO and a Custom HTML block next to each other SHALL join with no
- **WHEN** a visitor opens the page - **WHEN** a visitor opens the page
- **THEN** the hero starts directly under the top bar, with no gap - **THEN** the hero starts directly under the top bar, with no gap
#### Scenario: Dark call to action runs into a dark footer
- **GIVEN** a CTA block with the Dark look followed by a text block with the Dark look
- **WHEN** a visitor opens the page
- **THEN** the two bands join with no gap between them
### Requirement: Hero Points ### Requirement: Hero Points
A HERO block MAY carry up to 6 points, each a non-empty title of at most 80 characters, with no icon and no text. The hero SHALL show its points as a bulleted list under its text. The server SHALL refuse more than 6 points, an empty or over-long point, and a point with an icon or text, naming the field. A HERO block MAY carry up to 6 points, each a non-empty title of at most 80 characters, with no icon and no text. The hero SHALL show its points as a bulleted list under its text. The server SHALL refuse more than 6 points, an empty or over-long point, and a point with an icon or text, naming the field.
@@ -695,3 +701,178 @@ A Custom HTML block's panel in the editor SHALL offer an image upload for the pa
- **GIVEN** a super admin's new page with no company chosen - **GIVEN** a super admin's new page with no company chosen
- **WHEN** they choose a file under "Upload image" - **WHEN** they choose a file under "Upload image"
- **THEN** nothing is uploaded and the panel asks them to choose a company - **THEN** nothing is uploaded and the panel asks them to choose a company
### Requirement: Compact Landing-Page Form
A landing page's sign-up form, in a FORM block or a hero, SHALL show name, mobile, email and company, the event's interests as one optional dropdown, the privacy notice folded behind a single line that opens it in full, and the consent box. It SHALL NOT show a job-title field. QR, invitation and customer sign-up forms SHALL keep their full layout.
#### Scenario: Short form on the page
- **GIVEN** a page whose hero has an event with five interests
- **WHEN** a visitor opens the page
- **THEN** the form shows name, mobile, email, company, a "Service interested in" dropdown and the consent box, with no job title and no interest checkboxes
- **AND** the privacy notice is folded behind "How we use your details"
#### Scenario: Pick one service
- **WHEN** the visitor chooses "Cloud IP PABX" in the dropdown and submits
- **THEN** the submission carries that one interest
#### Scenario: Read the notice
- **WHEN** the visitor opens "How we use your details"
- **THEN** the full English and Malay notice shows above the consent box
#### Scenario: QR form unchanged
- **WHEN** a visitor opens an event's QR sign-up form
- **THEN** it shows job title, the interest checkboxes and the full notice as before
### Requirement: Thank-You Text On Landing Forms
A FORM block, and a HERO block with an event, MAY carry a thank-you text of at most 200 characters. After a visitor signs up through that block's form, the page SHALL show the text, with contact links, under the thank-you heading. Without it, the thank-you SHALL look as before. The server SHALL refuse an over-long thank-you text, or one on a HERO without an event.
#### Scenario: Visitor sees the page's thank-you text with a call link
- **GIVEN** page `/p/INS/hotel-technology-native` whose hero form has the thank-you text "Prefer to talk now? Call +60 12-833 2775."
- **WHEN** a visitor signs up through the hero form
- **THEN** the page shows the thank-you heading and "Prefer to talk now? Call +60 12-833 2775."
- **AND** "+60 12-833 2775" is a link to `tel:+60128332775`
#### Scenario: No thank-you text keeps today's message
- **WHEN** a visitor signs up through a FORM block without a thank-you text
- **THEN** the page shows only the thank-you heading and the "register another" button, as before
#### Scenario: Thank-you text on a hero without a form is refused
- **WHEN** staff save a HERO block without an event but with a thank-you text
- **THEN** the save is refused with the reason naming the hero's thank-you field
#### Scenario: Set the thank-you text in the editor
- **GIVEN** staff editing a hero that has an event
- **WHEN** they type a thank-you text in the hero's settings and save
- **THEN** the page keeps the text
- **AND** choosing "No form" on the hero clears it
### Requirement: Footer Block
A page MAY hold FOOTER blocks: 1 to 4 columns, each a required title (80 characters) and text (300 characters), and an optional legal line (300 characters). The page SHALL show the columns side by side on wide screens and stacked on phones, keep line breaks, show contact links in the column text, and put the legal line under a thin divider. A new footer SHALL start with the dark look. The server SHALL refuse a footer that breaks these limits, or that has a heading or a column icon.
#### Scenario: Visitor sees a three-column footer with links
- **GIVEN** a published page whose footer has the columns "Infinity Networks Security Sdn Bhd", "Talk to us" with "+603-7623 9807" and "info@infinitynetworks.com.my", and "Website" with "www.infinitynetworks.com.my", and a legal line
- **WHEN** a visitor opens the page in a 1280 px window
- **THEN** the three columns sit side by side on a dark band
- **AND** the phone links to `tel:+60376239807`, the email to `mailto:info@infinitynetworks.com.my`, and the website to `https://www.infinitynetworks.com.my`
- **AND** the legal line sits under a divider
#### Scenario: Add a footer in the editor
- **GIVEN** staff editing a page
- **WHEN** they add a Footer section
- **THEN** the canvas shows a dark footer with two empty columns to type into
- **AND** they can add columns up to 4 and type the legal line
#### Scenario: Footer with five columns is refused
- **WHEN** a page is saved with a footer of 5 columns
- **THEN** the save is refused with the reason naming the footer's columns
### Requirement: Contact Links In Plain Text
Where this spec says text shows contact links, the page SHALL show phone numbers that start with `+` as `tel:` links holding only `+` and digits, email addresses as `mailto:` links, and `https://` or `www.` addresses as `https://` links that open in a new tab. Everything else SHALL stay plain text, never HTML.
#### Scenario: Text with markup stays text
- **GIVEN** a footer column text "<b>Call</b> +60 12-833 2775"
- **WHEN** a visitor opens the page
- **THEN** "<b>Call</b>" shows as written
- **AND** "+60 12-833 2775" links to `tel:+60128332775`
### Requirement: Top Bar Block
A page's first block MAY be a top bar. The top bar SHALL show the company logo, or the company name when there is no logo, and an optional button, and SHALL stay at the top of the window while the page scrolls. The server SHALL refuse a top bar that is not the first block, or one that carries fields other than its button and link name.
#### Scenario: Logo and button without the page title
- **GIVEN** page `/p/INS/hotel-technology-native` with "hide page header" on, a top bar with the button "Get My Free Consultation" linking to `#consult`, and a full-width hero
- **WHEN** a visitor opens the page and scrolls down
- **THEN** the INS logo and the button stay at the top of the window
- **AND** no page title heading shows, and the hero starts directly under the bar
#### Scenario: Top bar further down is refused
- **WHEN** staff save a page whose top bar is the second block
- **THEN** the save is refused with the reason naming that block
### Requirement: Section Labels
Feature cards, Steps, Image with text, FAQ and Call to action blocks MAY carry a label of at most 40 characters. The page SHALL show the label above the block's heading, in small uppercase letters in the accent colour. The server SHALL refuse a longer label, or a label on any other block type.
#### Scenario: Label above a heading
- **GIVEN** a Feature cards block with the label "Services" and the heading "Everything your guests touch, handled by one team"
- **WHEN** a visitor opens the page
- **THEN** "Services" shows in small uppercase letters directly above the heading
#### Scenario: Type a label in the editor
- **GIVEN** staff editing a Steps block
- **WHEN** they type "How we work" in its label field and save
- **THEN** the page keeps the label
### Requirement: Serif Section Headings
Section headings on landing pages SHALL use the serif typeface that the full-width hero uses.
#### Scenario: Feature heading in serif
- **WHEN** a visitor opens a page with a Feature cards block
- **THEN** its heading uses the serif typeface
### Requirement: First Screen Fits The Hero And Trust Strip
A page with a top bar, a full-width hero with its sign-up form, and a trust strip SHALL show all three in full within the first 950 px of a desktop browser window. To fit, the trust strip band SHALL use less padding than other bands, and the landing-page form SHALL keep its fields, dropdown and button at least 44 px tall.
#### Scenario: INS page on a 1080p desktop
- **GIVEN** page `/p/INS/hotel-technology` with a top bar, a full-width hero with a form, and a trust strip
- **WHEN** a visitor opens it in a 1920×1080 browser window
- **THEN** the bottom of the trust strip is within 950 px of the top of the page
#### Scenario: Form controls stay easy to tap
- **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
@@ -0,0 +1,48 @@
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 { DELETE, GET, POST, PUT } from "./events/[uuid]/[...path]/route";
// add-event-ticket-orders: the event proxy forwards the ticket settings, ticket types and order endpoints.
const req = (url = "http://localhost/x", init?: RequestInit) => new Request(url, init) as never;
const p = (uuid: string, ...path: string[]) => ({ params: Promise.resolve({ uuid, path }) });
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("event ticket proxies", () => {
it("forward settings, types and order actions with the token", async () => {
await GET(req(), p("e1", "tickets", "settings"));
await PUT(req("http://localhost/x", { method: "PUT", body: '{"holdDays":3}' }), p("e1", "tickets", "settings"));
await POST(req("http://localhost/x", { method: "POST", body: '{"name":"General"}' }), p("e1", "ticket-types"));
await PUT(req("http://localhost/x", { method: "PUT", body: '{"name":"General"}' }), p("e1", "ticket-types", "2"));
await DELETE(req(), p("e1", "ticket-types", "2"));
await GET(req("http://localhost/x?status=PAID&q=ais&page=1&evil=1"), p("e1", "orders"));
await GET(req("http://localhost/x?status=PAID"), p("e1", "orders", "300"));
await POST(req("http://localhost/x", { method: "POST", body: '{"paymentRef":"MBB"}' }), p("e1", "orders", "300", "paid"));
await POST(req("http://localhost/x", { method: "POST" }), p("e1", "orders", "300", "tickets", "7", "cancel"));
expect(mocks.callMobileApi.mock.calls).toEqual([
["/api/admin/events/e1/tickets/settings", { token: "jwt" }],
["/api/admin/events/e1/tickets/settings", { method: "PUT", body: { holdDays: 3 }, token: "jwt" }],
["/api/admin/events/e1/ticket-types", { method: "POST", body: { name: "General" }, token: "jwt" }],
["/api/admin/events/e1/ticket-types/2", { method: "PUT", body: { name: "General" }, token: "jwt" }],
["/api/admin/events/e1/ticket-types/2", { method: "DELETE", token: "jwt" }],
["/api/admin/events/e1/orders?status=PAID&q=ais&page=1", { token: "jwt" }],
["/api/admin/events/e1/orders/300", { token: "jwt" }],
["/api/admin/events/e1/orders/300/paid", { method: "POST", body: { paymentRef: "MBB" }, token: "jwt" }],
["/api/admin/events/e1/orders/300/tickets/7/cancel", { method: "POST", body: {}, token: "jwt" }],
]);
});
it("refuse other ticket paths", async () => {
for (const path of [["tickets"], ["ticket-types", "x"], ["orders", "300", "refund"], ["orders", "x"]]) {
expect((await GET(req(), p("e1", ...path))).status).toBe(400);
}
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -3,23 +3,34 @@ import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session"; import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// One proxy for the event guest, check-in and attendance endpoints; mobile-api owns validation and the BO_EVENTS / BO_EVENT_GUESTS guards. // One proxy for the event guest, check-in, attendance and ticket endpoints; mobile-api owns validation and the
// BO_EVENTS / BO_EVENT_GUESTS / BO_EVENT_TICKETS guards.
type Ctx = { params: Promise<{ uuid: string; path: string[] }> }; type Ctx = { params: Promise<{ uuid: string; path: string[] }> };
const ALLOWED = /^(guests(\/(send|\d+))?|checkin|attendance)$/; const ALLOWED =
/^(guests(\/(send|\d+))?|checkin|attendance|tickets\/settings|ticket-types(\/\d+)?|orders(\/\d+(\/(paid|cancel|resend|tickets\/\d+\/cancel))?)?)$/;
// Event uuids are strings, not numbers; word characters and hyphens cover them and nothing that can alter the upstream path. // Event uuids are strings, not numbers; word characters and hyphens cover them and nothing that can alter the upstream path.
const EVENT_ID = /^[\w-]+$/; const EVENT_ID = /^[\w-]+$/;
async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "DELETE") { async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "PUT" | "DELETE") {
const token = await getToken(); const token = await getToken();
if (!token) return unauthorized(); if (!token) return unauthorized();
const { uuid, path } = await params; const { uuid, path } = await params;
if (!EVENT_ID.test(uuid) || !ALLOWED.test(path.join("/"))) return badRequest("Invalid path."); if (!EVENT_ID.test(uuid) || !ALLOWED.test(path.join("/"))) return badRequest("Invalid path.");
// Only the preview flag is forwarded; nothing else from the browser's query string. // Only the preview flag, and the orders list's filter and page, are forwarded from the browser's query string.
const preview = new URL(req.url).searchParams.getAll("preview").includes("true") ? "?preview=true" : ""; const query = new URL(req.url).searchParams;
const target = `/api/admin/events/${encodeURIComponent(uuid)}/${path.map(encodeURIComponent).join("/")}${preview}`; const forwarded = new URLSearchParams();
if (query.getAll("preview").includes("true")) forwarded.set("preview", "true");
if (path.join("/") === "orders") {
for (const k of ["status", "q", "page"]) {
const v = query.get(k);
if (v) forwarded.set(k, v);
}
}
const qs = forwarded.size ? `?${forwarded}` : "";
const target = `/api/admin/events/${encodeURIComponent(uuid)}/${path.map(encodeURIComponent).join("/")}${qs}`;
const result = const result =
method === "POST" method === "POST" || method === "PUT"
? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token }) ? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token })
: method : method
? await callMobileApi<unknown>(target, { method, token }) ? await callMobileApi<unknown>(target, { method, token })
@@ -31,4 +42,5 @@ async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "DEL
export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx); export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx);
export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST"); export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST");
export const PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT");
export const DELETE = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "DELETE"); export const DELETE = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "DELETE");
@@ -0,0 +1,4 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
// add-event-ticket-orders: the buyer's order page reads its order by the link token.
export const GET = publicRoute("orders", "", "GET");
@@ -0,0 +1,10 @@
import type { NextRequest } from "next/server";
import { forwardPublic } from "@/app/lib/server/publicProxy";
type Ctx = { params: Promise<{ company: string; slug: string; block: string }> };
// add-event-ticket-orders: a landing page's TICKETS block request (signed out); see publicProxy for the X-Forwarded-For rule.
export async function POST(req: NextRequest, { params }: Ctx) {
const { company, slug, block } = await params;
return forwardPublic(req, `/api/public/pages/${encodeURIComponent(company)}/${encodeURIComponent(slug)}/tickets/${encodeURIComponent(block)}`, "POST");
}
@@ -0,0 +1,39 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
import { GET as orderGet } from "./orders/[token]/route";
import { POST as ticketsPost } from "./pages/[company]/[slug]/tickets/[block]/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: { reference: "T-1" } }));
// add-event-ticket-orders: the order page and the TICKETS block post, signed out, with only the last X-Forwarded-For hop.
describe("public ticket proxies", () => {
it("GET an order by its token", async () => {
const res = await call(orderGet, { token: "tok/1" }, { headers: xff });
expect(await res.json()).toEqual({ reference: "T-1" });
const [p, opts] = mocks.callMobileApi.mock.calls[0];
expect(p).toBe("/api/public/orders/tok%2F1");
expect(opts.headers).toEqual({ "X-Forwarded-For": "203.0.113.7" });
});
it("POST a ticket request to a page block", async () => {
await call(ticketsPost, { company: "INS", slug: "day/1", block: "2" }, { method: "POST", body: JSON.stringify({ a: 1 }), headers: xff });
const [p, opts] = mocks.callMobileApi.mock.calls[0];
expect(p).toBe("/api/public/pages/INS/day%2F1/tickets/2");
expect(opts).toMatchObject({ method: "POST", body: { a: 1 }, headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("passes refusals with status and code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "General has only 1 ticket left.", status: 409, code: "TYPE_UNAVAILABLE" });
const res = await call(ticketsPost, { company: "INS", slug: "d", block: "0" }, { method: "POST", body: "{}" });
expect(res.status).toBe(409);
expect(((await res.json()) as Record<string, unknown>).code).toBe("TYPE_UNAVAILABLE");
});
});
@@ -27,7 +27,7 @@ const GUESTS = [
guest({ id: 3, name: "Cara", registeredAt: "2026-12-02T00:00:00Z", token: "t3" }), guest({ id: 3, name: "Cara", registeredAt: "2026-12-02T00:00:00Z", token: "t3" }),
guest({ id: 4, name: "Dan", registeredAt: "2026-12-02T00:00:00Z", attended: true, token: "t4" }), guest({ id: 4, name: "Dan", registeredAt: "2026-12-02T00:00:00Z", attended: true, token: "t4" }),
]; ];
const ATT = { invited: 4, cap: 10, registered: 2, attended: 1, walkIns: 3, total: 5, capacity: 100 }; const ATT = { invited: 4, cap: 10, registered: 2, attended: 1, walkIns: 3, heldTickets: 6, total: 11, capacity: 100 };
const asAdmin = (guests: boolean) => const asAdmin = (guests: boolean) =>
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" || (guests && m === "BO_EVENT_GUESTS") }); mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" || (guests && m === "BO_EVENT_GUESTS") });
@@ -48,7 +48,7 @@ describe("GuestsCard", () => {
render(<GuestsCard eventUuid="u1" />); render(<GuestsCard eventUuid="u1" />);
const strip = await screen.findByRole("list", { name: "Attendance numbers" }); const strip = await screen.findByRole("list", { name: "Attendance numbers" });
const val = (label: string) => within(strip).getByText(label).nextSibling?.textContent; const val = (label: string) => within(strip).getByText(label).nextSibling?.textContent;
expect(["Invited", "Invitation cap", "Registered", "Attended", "Walk-ins", "Total", "Capacity"].map(val)).toEqual(["4", "10", "2", "1", "3", "5", "100"]); expect(["Invited", "Invitation cap", "Registered", "Attended", "Walk-ins", "Held tickets", "Total", "Capacity"].map(val)).toEqual(["4", "10", "2", "1", "3", "6", "11", "100"]);
expect(mocks.getAttendance).toHaveBeenCalledWith("u1"); expect(mocks.getAttendance).toHaveBeenCalledWith("u1");
}); });
@@ -167,6 +167,7 @@ export function GuestsCard({ eventUuid, team = [] }: { eventUuid: string; team?:
[t("GuestRegistered"), att?.registered], [t("GuestRegistered"), att?.registered],
[t("GuestAttended"), att?.attended], [t("GuestAttended"), att?.attended],
[t("GuestWalkIns"), att?.walkIns], [t("GuestWalkIns"), att?.walkIns],
[t("GuestHeldTickets"), att?.heldTickets],
[t("GuestTotal"), att?.total], [t("GuestTotal"), att?.total],
[t("EvtCapacity"), att?.capacity], [t("EvtCapacity"), att?.capacity],
]; ];
@@ -177,7 +178,7 @@ export function GuestsCard({ eventUuid, team = [] }: { eventUuid: string; team?:
<CardTitle>{t("GuestsTitle")}</CardTitle> <CardTitle>{t("GuestsTitle")}</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<ul aria-label={t("GuestNumbers")} className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-7"> <ul aria-label={t("GuestNumbers")} className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-8">
{numbers.map(([label, value]) => ( {numbers.map(([label, value]) => (
<li key={label} className="rounded-md border p-2"> <li key={label} className="rounded-md border p-2">
<span className="block text-xs text-muted-foreground">{label}</span> <span className="block text-xs text-muted-foreground">{label}</span>
@@ -0,0 +1,12 @@
"use client";
import { Badge } from "@/app/components/ui/badge";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { OrderStatus } from "@/app/lib/services/adminTickets";
const VARIANT = { AWAITING: "warning", PAID: "positive", CANCELLED: "neutral", EXPIRED: "negative" } as const;
export function OrderStatusBadge({ status }: { status: OrderStatus }) {
const t = useT();
return <Badge variant={VARIANT[status] ?? "neutral"}>{t(`TktStatus${status}`)}</Badge>;
}
@@ -0,0 +1,118 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({
getTicketSettings: vi.fn(),
saveTicketSettings: vi.fn(),
listTicketTypes: vi.fn(),
saveTicketType: vi.fn(),
deleteTicketType: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminTickets", async (orig) => ({ ...(await orig<object>()), ...mocks }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import { TicketsCard } from "./TicketsCard";
const TYPES = [
{ id: 1, name: "Early bird", priceSen: 15000, quantity: 20, salesEndDate: "2027-01-10", sort: 0, enabled: true, held: 8, left: 12 },
{ id: 2, name: "Community pass", priceSen: 0, quantity: 50, salesEndDate: null, sort: 1, enabled: false, held: 0, left: 50 },
];
const refused = (code: string, field?: string) =>
new ApiError(code, 400, { error: code, code, ...(field ? { details: { field } } : {}) });
beforeEach(() => {
mocks.getTicketSettings.mockReset().mockResolvedValue({ ticketsEnabled: false, paymentInstructions: null, holdDays: 3 });
mocks.saveTicketSettings.mockReset().mockResolvedValue({});
mocks.listTicketTypes.mockReset().mockResolvedValue(TYPES);
mocks.saveTicketType.mockReset().mockResolvedValue({});
mocks.deleteTicketType.mockReset().mockResolvedValue({});
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" || m === "BO_EVENT_TICKETS" });
});
describe("TicketsCard", () => {
it("is hidden without BO_EVENT_TICKETS", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" });
const { container } = render(<TicketsCard eventUuid="u1" />);
expect(container).toBeEmptyDOMElement();
expect(mocks.getTicketSettings).not.toHaveBeenCalled();
});
it("saves the settings and shows a refusal under its field", async () => {
const user = userEvent.setup();
mocks.saveTicketSettings.mockRejectedValueOnce(refused("PAYMENT_INSTRUCTIONS_REQUIRED", "paymentInstructions"));
render(<TicketsCard eventUuid="u1" />);
await user.click(await screen.findByRole("switch", { name: "Sell tickets" }));
await user.click(screen.getByRole("button", { name: "Save ticket settings" }));
expect(await screen.findByText("Enter the payment instructions before turning tickets on.")).toBeInTheDocument();
await user.type(screen.getByLabelText("Payment instructions"), "Maybank 5140");
await user.clear(screen.getByLabelText("Hold days"));
await user.type(screen.getByLabelText("Hold days"), "5");
await user.click(screen.getByRole("button", { name: "Save ticket settings" }));
await waitFor(() =>
expect(mocks.saveTicketSettings).toHaveBeenLastCalledWith("u1", { ticketsEnabled: true, paymentInstructions: "Maybank 5140", holdDays: 5 }),
);
expect(await screen.findByText("Ticket settings saved.")).toBeInTheDocument();
});
it("lists the types with price, Free, seats left and state", async () => {
render(<TicketsCard eventUuid="u1" />);
const early = await screen.findByRole("row", { name: /Early bird/ });
expect(within(early).getByText("RM 150.00")).toBeInTheDocument();
expect(within(early).getByText("12")).toBeInTheDocument();
const pass = screen.getByRole("row", { name: /Community pass/ });
expect(within(pass).getByText("Free")).toBeInTheDocument();
expect(within(pass).getByText("Disabled")).toBeInTheDocument();
});
it("adds a type with its price in ringgit", async () => {
const user = userEvent.setup();
render(<TicketsCard eventUuid="u1" />);
await screen.findByText("Early bird");
await user.type(screen.getByLabelText("Ticket name"), "General");
await user.type(screen.getByLabelText("Price (RM)"), "250");
await user.type(screen.getByLabelText("Quantity"), "100");
await user.click(screen.getByRole("button", { name: "Add ticket type" }));
await waitFor(() =>
expect(mocks.saveTicketType).toHaveBeenCalledWith("u1", { name: "General", priceSen: 25000, quantity: 100, salesEndDate: null, sort: 2, enabled: true }, undefined),
);
expect(mocks.listTicketTypes).toHaveBeenCalledTimes(2);
});
it("edits a type and shows a quantity refusal", async () => {
const user = userEvent.setup();
mocks.saveTicketType.mockRejectedValueOnce(refused("QUANTITY_BELOW_HELD", "quantity"));
render(<TicketsCard eventUuid="u1" />);
await user.click(within(await screen.findByRole("row", { name: /Early bird/ })).getByRole("button", { name: "Edit" }));
const qty = screen.getByLabelText("Quantity");
await user.clear(qty);
await user.type(qty, "5");
await user.click(screen.getByRole("button", { name: "Save ticket type" }));
expect(await screen.findByText("The quantity cannot be below the seats already held.")).toBeInTheDocument();
expect(mocks.saveTicketType).toHaveBeenCalledWith("u1", expect.objectContaining({ name: "Early bird", quantity: 5, priceSen: 15000 }), 1);
});
it("disables a type", async () => {
const user = userEvent.setup();
render(<TicketsCard eventUuid="u1" />);
await user.click(within(await screen.findByRole("row", { name: /Early bird/ })).getByRole("button", { name: "Disable" }));
await waitFor(() => expect(mocks.saveTicketType).toHaveBeenCalledWith("u1", expect.objectContaining({ name: "Early bird", enabled: false }), 1));
});
it("shows why a type with orders cannot be deleted", async () => {
const user = userEvent.setup();
mocks.deleteTicketType.mockRejectedValueOnce(new ApiError("TYPE_HAS_ORDERS", 409, { error: "TYPE_HAS_ORDERS", code: "TYPE_HAS_ORDERS" }));
render(<TicketsCard eventUuid="u1" />);
await user.click(within(await screen.findByRole("row", { name: /Early bird/ })).getByRole("button", { name: "Delete" }));
await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" }));
expect(await screen.findByText("This ticket type has orders. Disable it instead.")).toBeInTheDocument();
expect(mocks.deleteTicketType).toHaveBeenCalledWith("u1", 1);
});
it("links to the orders", async () => {
render(<TicketsCard eventUuid="u1" />);
expect(await screen.findByRole("link", { name: "View orders" })).toHaveAttribute("href", "/events/u1/orders");
});
});
@@ -0,0 +1,305 @@
"use client";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { DatePicker } from "@/app/components/ui/date-picker";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { ErrorState } from "@/app/components/ui/states";
import { Switch } from "@/app/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import { Textarea } from "@/app/components/ui/textarea";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { ApiError } from "@/app/lib/clientApi";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import {
TICKET_ERRORS,
deleteTicketType,
getTicketSettings,
listTicketTypes,
money,
saveTicketSettings,
saveTicketType,
type TicketSettings,
type TicketType,
type TicketTypeInput,
} from "@/app/lib/services/adminTickets";
type Form = { id?: number; name: string; price: string; quantity: string; salesEndDate: string; enabled: boolean };
const EMPTY: Form = { name: "", price: "", quantity: "", salesEndDate: "", enabled: true };
const PRICE = /^\d{1,5}(\.\d{1,2})?$/;
/** A refusal's label and the field it belongs to; anything unknown falls back to the caller's generic text. */
function refusal(err: unknown): { code?: string; field?: string } {
if (!(err instanceof ApiError) || err.status < 400 || err.status >= 500) return {};
const body = err.data as { code?: string; details?: { field?: string } } | undefined;
return { code: body?.code, field: body?.details?.field };
}
/** add-event-ticket-orders: the event's Tickets section (BO_EVENT_TICKETS): settings, ticket types and a link to the orders. */
export function TicketsCard({ eventUuid }: { eventUuid: string }) {
const { hasModule } = useAdminAuth();
if (!hasModule("BO_EVENT_TICKETS")) return null;
return <TicketsCardContent eventUuid={eventUuid} />;
}
function TicketsCardContent({ eventUuid }: { eventUuid: string }) {
const t = useT();
const [settings, setSettings] = useState<TicketSettings | null>(null);
const [holdDays, setHoldDays] = useState("3");
const [types, setTypes] = useState<TicketType[] | null>(null);
const [loadError, setLoadError] = useState(false);
const [form, setForm] = useState<Form>(EMPTY);
const [errors, setErrors] = useState<Record<string, string>>({});
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [deleting, setDeleting] = useState<TicketType | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
try {
const [s, list] = await Promise.all([getTicketSettings(eventUuid), listTicketTypes(eventUuid)]);
setSettings(s);
setHoldDays(String(s.holdDays ?? 3));
setTypes(list);
setLoadError(false);
} catch {
setLoadError(true);
}
}, [eventUuid]);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- load() fetches from the API; its setState runs after the await.
load();
}, [load]);
/** Runs a save; a refusal goes under its field when it names one, else into the card's error line. */
async function run(action: () => Promise<void>, failed: string) {
setErrors({});
setError(null);
setNotice(null);
setBusy(true);
try {
await action();
} catch (err) {
const { code, field } = refusal(err);
const label = code && TICKET_ERRORS[code] ? t(TICKET_ERRORS[code]) : failed;
if (field) setErrors({ [field]: label });
else setError(label);
} finally {
setBusy(false);
}
}
const saveSettings = (e: React.FormEvent) => {
e.preventDefault();
if (!settings) return;
return run(async () => {
const next = { ...settings, holdDays: Number(holdDays) };
await saveTicketSettings(eventUuid, next);
setSettings(next);
setNotice(t("TktSettingsSaved"));
}, t("TktSaveFailed"));
};
const input = (f: Form): TicketTypeInput | null => {
const bad: Record<string, string> = {};
if (!PRICE.test(f.price.trim())) bad.priceSen = t("TktErrPrice");
if (!/^\d+$/.test(f.quantity.trim())) bad.quantity = t("TktErrQuantity");
if (Object.keys(bad).length) {
setErrors(bad);
return null;
}
const sort = f.id == null ? (types?.length ?? 0) : (types?.find((x) => x.id === f.id)?.sort ?? 0);
return {
name: f.name.trim(),
priceSen: Math.round(Number(f.price.trim()) * 100),
quantity: Number(f.quantity.trim()),
salesEndDate: f.salesEndDate || null,
sort,
enabled: f.enabled,
};
};
const saveType = (e: React.FormEvent) => {
e.preventDefault();
const body = input(form);
if (!body) return;
return run(async () => {
await saveTicketType(eventUuid, body, form.id);
setForm(EMPTY);
await load();
}, t("TktSaveFailed"));
};
const toggle = (x: TicketType) =>
run(async () => {
await saveTicketType(eventUuid, { name: x.name, priceSen: x.priceSen, quantity: x.quantity, salesEndDate: x.salesEndDate, sort: x.sort, enabled: !x.enabled }, x.id);
await load();
}, t("TktSaveFailed"));
const remove = async () => {
const x = deleting;
setDeleting(null);
if (x)
await run(async () => {
await deleteTicketType(eventUuid, x.id);
await load();
}, t("TktSaveFailed"));
};
const edit = (x: TicketType) => {
setErrors({});
setForm({ id: x.id, name: x.name, price: (x.priceSen / 100).toFixed(2), quantity: String(x.quantity), salesEndDate: x.salesEndDate ?? "", enabled: x.enabled });
};
const fieldError = (field: string) => errors[field] && <p className="text-sm text-destructive">{errors[field]}</p>;
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2">
<CardTitle>{t("TktTitle")}</CardTitle>
<Button asChild variant="outline" size="sm">
<Link href={`/events/${encodeURIComponent(eventUuid)}/orders`}>{t("TktViewOrders")}</Link>
</Button>
</CardHeader>
<CardContent className="space-y-6">
{loadError && <ErrorState message={t("TktLoadFailed")} onRetry={load} />}
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
{settings && (
<form onSubmit={saveSettings} className="space-y-3">
<div className="flex items-center gap-2">
<Switch
id="tickets-enabled"
aria-label={t("TktSellTickets")}
checked={settings.ticketsEnabled}
onCheckedChange={(on) => setSettings({ ...settings, ticketsEnabled: on })}
/>
<Label htmlFor="tickets-enabled">{t("TktSellTickets")}</Label>
</div>
<div className="space-y-1">
<Label htmlFor="tickets-instructions">{t("TktPaymentInstructions")}</Label>
<Textarea
id="tickets-instructions"
maxLength={1000}
value={settings.paymentInstructions ?? ""}
onChange={(e) => setSettings({ ...settings, paymentInstructions: e.target.value })}
/>
<p className="text-xs text-muted-foreground">{t("TktPaymentInstructionsHelp")}</p>
{fieldError("paymentInstructions")}
</div>
<div className="max-w-40 space-y-1">
<Label htmlFor="tickets-hold">{t("TktHoldDays")}</Label>
<Input id="tickets-hold" type="number" min={1} max={14} value={holdDays} onChange={(e) => setHoldDays(e.target.value)} />
{fieldError("holdDays")}
</div>
<Button type="submit" disabled={busy}>
{t("TktSaveSettings")}
</Button>
</form>
)}
{types && (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("Name")}</TableHead>
<TableHead>{t("TktPrice")}</TableHead>
<TableHead>{t("TktQuantity")}</TableHead>
<TableHead>{t("TktLeft")}</TableHead>
<TableHead>{t("TktSalesEnd")}</TableHead>
<TableHead>{t("Status")}</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{types.length === 0 && (
<TableRow>
<TableCell colSpan={7} className="text-muted-foreground">
{t("TktNoTypes")}
</TableCell>
</TableRow>
)}
{types.map((x) => (
<TableRow key={x.id}>
<TableCell>{x.name}</TableCell>
<TableCell>{x.priceSen === 0 ? t("TktFree") : money(x.priceSen)}</TableCell>
<TableCell>{x.quantity}</TableCell>
<TableCell>{x.left}</TableCell>
<TableCell>{x.salesEndDate ?? "-"}</TableCell>
<TableCell>
<Badge variant={x.enabled ? "positive" : "neutral"}>{t(x.enabled ? "Enabled" : "Disabled")}</Badge>
</TableCell>
<TableCell className="space-x-1 whitespace-nowrap text-right">
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => edit(x)}>
{t("Edit")}
</Button>
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => toggle(x)}>
{t(x.enabled ? "TktDisable" : "TktEnable")}
</Button>
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => setDeleting(x)}>
{t("TktDelete")}
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<form onSubmit={saveType} className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
<div className="space-y-1">
<Label htmlFor="type-name">{t("TktTypeName")}</Label>
<Input id="type-name" maxLength={80} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
{fieldError("name")}
</div>
<div className="space-y-1">
<Label htmlFor="type-price">{t("TktPriceRm")}</Label>
<Input id="type-price" inputMode="decimal" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} />
{fieldError("priceSen")}
</div>
<div className="space-y-1">
<Label htmlFor="type-quantity">{t("TktQuantity")}</Label>
<Input id="type-quantity" inputMode="numeric" value={form.quantity} onChange={(e) => setForm({ ...form, quantity: e.target.value })} />
{fieldError("quantity")}
</div>
<div className="space-y-1">
<Label htmlFor="type-end">{t("TktSalesEnd")}</Label>
<DatePicker id="type-end" value={form.salesEndDate} onChange={(v) => setForm({ ...form, salesEndDate: v })} />
{fieldError("salesEndDate")}
</div>
<div className="flex items-end gap-2">
<Button type="submit" disabled={busy}>
{t(form.id == null ? "TktAddType" : "TktSaveType")}
</Button>
{form.id != null && (
<Button type="button" variant="outline" disabled={busy} onClick={() => setForm(EMPTY)}>
{t("Cancel")}
</Button>
)}
</div>
</form>
<p className="text-xs text-muted-foreground">{t("TktSalesEndHelp")}</p>
</>
)}
{deleting && (
<ConfirmDialog
title={t("TktDeleteTitle")}
message={t("TktDeleteMessage", { name: deleting.name })}
confirmLabel={t("TktDelete")}
destructive
onConfirm={remove}
onCancel={() => setDeleting(null)}
/>
)}
</CardContent>
</Card>
);
}
@@ -16,16 +16,19 @@ import { CopyAddress } from "./CopyAddress";
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. Every type also shows "anchor". */ /** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. Every type also shows "anchor". */
const INLINE: Record<string, string[]> = { const INLINE: Record<string, string[]> = {
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl", "eventUuid", "fullWidth", "formHeading", "formText", "cards"], HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl", "eventUuid", "fullWidth", "formHeading", "formText", "thanksText", "cards"],
RICH_TEXT: ["html"], RICH_TEXT: ["html"],
IMAGE_TEXT: ["imageId", "imagePosition", "heading", "html", "buttonLabel", "buttonUrl"], IMAGE_TEXT: ["imageId", "imagePosition", "eyebrow", "heading", "html", "buttonLabel", "buttonUrl"],
FAQ: ["heading", "items"], FAQ: ["eyebrow", "heading", "items"],
FORM: ["heading", "eventUuid"], FORM: ["heading", "eventUuid", "thanksText"],
HTML: ["html"], HTML: ["html"],
FEATURES: ["heading", "text", "cards"], FEATURES: ["eyebrow", "heading", "text", "cards"],
STEPS: ["heading", "cards"], STEPS: ["eyebrow", "heading", "cards"],
TRUST: ["cards"], TRUST: ["cards"],
CTA: ["heading", "text", "buttonLabel", "buttonUrl"], CTA: ["eyebrow", "heading", "text", "buttonLabel", "buttonUrl"],
FOOTER: ["cards", "text"],
TOPBAR: ["buttonLabel", "buttonUrl"],
TICKETS: ["eyebrow", "heading", "text", "eventUuid"],
}; };
const LISTED = /^(items\[\d+\]\.(question|answer)|cards\[\d+\]\.(icon|title|text))$/; const LISTED = /^(items\[\d+\]\.(question|answer)|cards\[\d+\]\.(icon|title|text))$/;
@@ -37,17 +40,21 @@ const ICON_LABELS: Record<string, string> = {
users: "PagesIconUsers", calendar: "PagesIconCalendar", star: "PagesIconStar", users: "PagesIconUsers", calendar: "PagesIconCalendar", star: "PagesIconStar",
}; };
// add-hero-full-width: a hero's points are title-only cards, and it may have none. // add-hero-full-width: a hero's points are title-only cards, and it may have none.
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; min: number; empty: CmsCard }> = { // add-landing-thanks-and-footer: a footer's columns are title-and-text cards, 1 to 4.
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, min: 2, empty: { icon: "star", title: "", text: "" } }, const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; min: number; max: number; empty: CmsCard }> = {
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, min: 2, empty: { title: "", text: "" } }, FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, min: 2, max: 6, empty: { icon: "star", title: "", text: "" } },
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, min: 2, empty: { title: "" } }, STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, min: 2, max: 6, empty: { title: "", text: "" } },
HERO: { legend: "PagesPointN", add: "PagesAddPoint", icon: false, text: false, min: 0, empty: { title: "" } }, TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, min: 2, max: 6, empty: { title: "" } },
HERO: { legend: "PagesPointN", add: "PagesAddPoint", icon: false, text: false, min: 0, max: 6, empty: { title: "" } },
FOOTER: { legend: "PagesColumnN", add: "PagesAddColumn", icon: false, text: true, min: 1, max: 4, empty: { title: "", text: "" } },
}; };
const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50"; const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
export interface EventOption { export interface EventOption {
uuid: string; uuid: string;
name: string; name: string;
/** add-event-ticket-orders: only these are offered to a TICKETS block. */
ticketsEnabled?: boolean;
} }
function FieldError({ message }: { message?: string }) { function FieldError({ message }: { message?: string }) {
@@ -89,7 +96,7 @@ export function BlockFields(props: {
const fid = (name: string) => `block-${id}-${name}`; const fid = (name: string) => `block-${id}-${name}`;
const topErrors = Object.entries(errors).filter(([path]) => path !== "anchor" && path !== "look" && !INLINE[block.type]?.includes(path) && !LISTED.test(path)); const topErrors = Object.entries(errors).filter(([path]) => path !== "anchor" && path !== "look" && !INLINE[block.type]?.includes(path) && !LISTED.test(path));
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor" | "formHeading" | "formText", labelCode: string) => ( const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor" | "formHeading" | "formText" | "thanksText" | "eyebrow", labelCode: string) => (
<Field id={fid(name)} label={t(labelCode)} error={errors[name]}> <Field id={fid(name)} label={t(labelCode)} error={errors[name]}>
<Input id={fid(name)} value={block[name] ?? ""} disabled={saving} aria-invalid={!!errors[name]} onChange={(e) => set({ [name]: e.target.value })} /> <Input id={fid(name)} value={block[name] ?? ""} disabled={saving} aria-invalid={!!errors[name]} onChange={(e) => set({ [name]: e.target.value })} />
</Field> </Field>
@@ -121,17 +128,17 @@ export function BlockFields(props: {
const preview = pendingImage?.preview ?? (block.imageId ? imageSrc(block.imageId) : undefined); const preview = pendingImage?.preview ?? (block.imageId ? imageSrc(block.imageId) : undefined);
// The FORM block's event, and the hero's optional sign-up form (add-hero-signup-form): the same picker and hint. // The FORM block's event, and the hero's optional sign-up form (add-hero-signup-form): the same picker and hint.
const eventPicker = (labelCode: string, emptyCode: string) => ( const eventPicker = (labelCode: string, emptyCode: string, options = events, hintCode = "PagesFormEventHint") => (
<Field id={fid("event")} label={t(labelCode)} error={errors.eventUuid}> <Field id={fid("event")} label={t(labelCode)} error={errors.eventUuid}>
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid} <select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
onChange={(e) => set(e.target.value ? { eventUuid: e.target.value } : { eventUuid: null, formHeading: undefined, formText: undefined })}> onChange={(e) => set(e.target.value ? { eventUuid: e.target.value } : { eventUuid: null, formHeading: undefined, formText: undefined, thanksText: undefined })}>
<option value="">{t(emptyCode)}</option> <option value="">{t(emptyCode)}</option>
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)} {options.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? ( {block.eventUuid && !options.some((ev) => ev.uuid === block.eventUuid) ? (
<option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option> <option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option>
) : null} ) : null}
</select> </select>
<p className="text-xs text-muted-foreground">{t("PagesFormEventHint")}</p> <p className="text-xs text-muted-foreground">{t(hintCode)}</p>
</Field> </Field>
); );
const image = ( const image = (
@@ -195,7 +202,7 @@ export function BlockFields(props: {
); );
})} })}
<FieldError message={errors.cards} /> <FieldError message={errors.cards} />
<Button type="button" variant="outline" size="sm" disabled={saving || cards.length >= 6} onClick={() => setCards([...cards, { ...kind.empty }])}> <Button type="button" variant="outline" size="sm" disabled={saving || cards.length >= kind.max} onClick={() => setCards([...cards, { ...kind.empty }])}>
<Plus aria-hidden="true" className="size-4" /> <Plus aria-hidden="true" className="size-4" />
{t(kind.add)} {t(kind.add)}
</Button> </Button>
@@ -238,6 +245,7 @@ export function BlockFields(props: {
<> <>
{text("formHeading", "PagesFormHeading")} {text("formHeading", "PagesFormHeading")}
{text("formText", "PagesFormText")} {text("formText", "PagesFormText")}
{text("thanksText", "PagesThanksText")}
</> </>
) : null} ) : null}
</> </>
@@ -254,6 +262,7 @@ export function BlockFields(props: {
<option value="RIGHT">{t("PagesImageRight")}</option> <option value="RIGHT">{t("PagesImageRight")}</option>
</select> </select>
</Field> </Field>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")} {text("heading", "PagesHeading")}
{richText("PagesText")} {richText("PagesText")}
{text("buttonLabel", "PagesButtonLabel")} {text("buttonLabel", "PagesButtonLabel")}
@@ -263,6 +272,7 @@ export function BlockFields(props: {
{block.type === "FAQ" && ( {block.type === "FAQ" && (
<> <>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")} {text("heading", "PagesHeading")}
{items.map((item, i) => ( {items.map((item, i) => (
<div key={i} className="space-y-2 rounded-md border p-3"> <div key={i} className="space-y-2 rounded-md border p-3">
@@ -318,11 +328,24 @@ export function BlockFields(props: {
<> <>
{text("heading", "PagesHeading")} {text("heading", "PagesHeading")}
{eventPicker("PagesFormEvent", "PagesChooseEvent")} {eventPicker("PagesFormEvent", "PagesChooseEvent")}
{text("thanksText", "PagesThanksText")}
</>
)}
{block.type === "TICKETS" && (
<>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
<Field id={fid("text")} label={t("PagesIntro")} error={errors.text}>
<Textarea id={fid("text")} rows={2} value={block.text ?? ""} disabled={saving} aria-invalid={!!errors.text} onChange={(e) => set({ text: e.target.value })} />
</Field>
{eventPicker("PagesTicketsEvent", "PagesChooseTicketsEvent", events.filter((ev) => ev.ticketsEnabled), "PagesTicketsEventHint")}
</> </>
)} )}
{block.type === "FEATURES" && ( {block.type === "FEATURES" && (
<> <>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")} {text("heading", "PagesHeading")}
<Field id={fid("text")} label={t("PagesIntro")} error={errors.text}> <Field id={fid("text")} label={t("PagesIntro")} error={errors.text}>
<Textarea id={fid("text")} rows={2} value={block.text ?? ""} disabled={saving} aria-invalid={!!errors.text} onChange={(e) => set({ text: e.target.value })} /> <Textarea id={fid("text")} rows={2} value={block.text ?? ""} disabled={saving} aria-invalid={!!errors.text} onChange={(e) => set({ text: e.target.value })} />
@@ -333,6 +356,7 @@ export function BlockFields(props: {
{block.type === "STEPS" && ( {block.type === "STEPS" && (
<> <>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")} {text("heading", "PagesHeading")}
{cardList} {cardList}
</> </>
@@ -340,8 +364,24 @@ export function BlockFields(props: {
{block.type === "TRUST" && cardList} {block.type === "TRUST" && cardList}
{/* add-landing-page-polish: the top bar's button; its logo comes from the company. */}
{block.type === "TOPBAR" && (
<>
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
</>
)}
{block.type === "FOOTER" && (
<>
{cardList}
{text("text", "PagesFooterLegal")}
</>
)}
{block.type === "CTA" && ( {block.type === "CTA" && (
<> <>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")} {text("heading", "PagesHeading")}
{text("text", "PagesText")} {text("text", "PagesText")}
{text("buttonLabel", "PagesButtonLabel")} {text("buttonLabel", "PagesButtonLabel")}
@@ -349,7 +389,7 @@ export function BlockFields(props: {
</> </>
)} )}
{block.type !== "HTML" && ( {block.type !== "HTML" && block.type !== "TOPBAR" && (
<Field id={fid("look")} label={t("PagesLook")} error={errors.look}> <Field id={fid("look")} label={t("PagesLook")} error={errors.look}>
<select id={fid("look")} className={SELECT} value={block.look ?? "DEFAULT"} disabled={saving} aria-invalid={!!errors.look} <select id={fid("look")} className={SELECT} value={block.look ?? "DEFAULT"} disabled={saving} aria-invalid={!!errors.look}
onChange={(e) => set({ look: e.target.value as Look })}> onChange={(e) => set({ look: e.target.value as Look })}>
@@ -143,8 +143,188 @@ describe("LandingPage full-width hero", () => {
}); });
}); });
// add-compact-landing-form: a page's form is the short one, and coloured bands join.
describe("LandingPage compact form and bands", () => {
it("a page's form has no job title and a service dropdown", () => {
render(<LandingPage company={company} page={page([{ type: "FORM", form: { ...info, interests: [{ id: 3, name: "Cloud IP PABX" }] } }])} />);
expect(screen.queryByLabelText("Job title")).not.toBeInTheDocument();
expect(screen.getByRole("combobox", { name: "Service interested in (optional)" })).toBeInTheDocument();
});
it("joins a dark call to action and a dark text block with no gap", () => {
render(<LandingPage company={company} page={page([
{ type: "RICH_TEXT", html: "<p>Intro</p>" },
{ type: "CTA", heading: "Talk to us", look: "DARK" },
{ type: "RICH_TEXT", html: "<p>Footer</p>", look: "DARK" },
])} />);
const rows = Array.from(document.querySelector("main > div")!.children);
expect(rows.map((r) => r.classList.contains("mt-10"))).toEqual([false, true, false]);
expect(rows.slice(1).map((r) => r.querySelector("[data-look]")?.getAttribute("data-look"))).toEqual(["DARK", "DARK"]);
});
});
describe("utmTags", () => { describe("utmTags", () => {
it("reads the three tags, capped at 100 characters", () => { it("reads the three tags, capped at 100 characters", () => {
expect(utmTags("?utm_source=" + "x".repeat(150))).toEqual({ utmSource: "x".repeat(100), utmMedium: undefined, utmCampaign: undefined }); expect(utmTags("?utm_source=" + "x".repeat(150))).toEqual({ utmSource: "x".repeat(100), utmMedium: undefined, utmCampaign: undefined });
}); });
}); });
// add-landing-thanks-and-footer: the page's own thank-you text, and the footer block.
describe("LandingPage thank-you text and footer", () => {
async function signUp() {
const user = userEvent.setup();
await user.type(screen.getByLabelText("Your name"), "Tan");
await user.type(screen.getByLabelText("Mobile number"), "0125550101");
await user.click(screen.getByRole("checkbox"));
await user.click(screen.getByRole("button", { name: "Register" }));
}
it("a hero form shows its thank-you text after sign-up, with the number as a call link", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(new Response("", { status: 201 }));
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77", form: info,
thanksText: "Prefer to talk now? Call +60 12-833 2775." }])} />);
await signUp();
const done = await screen.findByRole("status");
expect(done).toHaveTextContent("Thank you, you're registered for INS enquiries");
expect(done).toHaveTextContent("Prefer to talk now? Call +60 12-833 2775.");
expect(within(done).getByRole("link", { name: "+60 12-833 2775" })).toHaveAttribute("href", "tel:+60128332775");
});
it("a form block without a thank-you text keeps today's thank-you", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(new Response("", { status: 201 }));
render(<LandingPage company={company} page={page([{ type: "FORM", form: info }])} />);
await signUp();
const done = await screen.findByRole("status");
expect(done.querySelector("p")).toBeNull();
expect(within(done).getByRole("button", { name: "Register another person" })).toBeInTheDocument();
});
const footer: PublicBlock = { type: "FOOTER", look: "DARK", text: "© 2026 Infinity Networks Security Sdn Bhd. All rights reserved.", cards: [
{ title: "Infinity Networks Security Sdn Bhd", text: "Unit 2-6, Infinity Tower\nPetaling Jaya, Malaysia" },
{ title: "Talk to us", text: "+603-7623 9807\ninfo@infinitynetworks.com.my" },
{ title: "Website", text: "www.infinitynetworks.com.my" },
] };
it("shows a footer's columns side by side with contact links, and the legal line under a divider", () => {
render(<LandingPage company={company} page={page([footer])} />);
const foot = screen.getByRole("contentinfo");
expect(foot.closest("[data-look]")).toHaveAttribute("data-look", "DARK");
const columns = within(foot).getAllByRole("listitem");
expect(columns).toHaveLength(3);
expect(columns[0].parentElement).toHaveClass("md:grid-cols-3");
expect(within(columns[0]).getByText(/Unit 2-6/)).toHaveClass("whitespace-pre-line");
expect(within(foot).getByRole("link", { name: "+603-7623 9807" })).toHaveAttribute("href", "tel:+60376239807");
expect(within(foot).getByRole("link", { name: "info@infinitynetworks.com.my" })).toHaveAttribute("href", "mailto:info@infinitynetworks.com.my");
const site = within(foot).getByRole("link", { name: "www.infinitynetworks.com.my" });
expect(site).toHaveAttribute("href", "https://www.infinitynetworks.com.my");
expect(site).toHaveAttribute("target", "_blank");
expect(site).toHaveAttribute("rel", "noopener noreferrer");
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");
expect(foot.querySelector("b")).toBeNull();
expect(foot).toHaveTextContent("<b>Call</b> +60 12-833 2775");
expect(within(foot).getByRole("link", { name: "+60 12-833 2775" })).toHaveAttribute("href", "tel:+60128332775");
});
});
// add-landing-page-polish: the top bar, section labels and serif headings.
describe("LandingPage polish", () => {
const bar: PublicBlock = { type: "TOPBAR", buttonLabel: "Get My Free Consultation", buttonUrl: "#consult" };
const hero: PublicBlock = { type: "HERO", heading: "One partner", fullWidth: true };
it("a top bar shows the logo and its button, stays at the top, and joins the hero", () => {
render(<LandingPage company={company} page={{ ...page([bar, hero]), hideHeader: true }} />);
const top = screen.getByRole("banner");
expect(within(top).getByRole("img", { name: "INS Sdn Bhd" })).toHaveAttribute("src", "/api/public/page-images/4");
expect(within(top).getByRole("link", { name: "Get My Free Consultation" })).toHaveAttribute("href", "#consult");
// The row sticks, not the header: a sticky element only sticks inside its parent.
expect(top.closest("main > div > div")).toHaveClass("sticky", "top-0");
expect(top.closest(".max-w-5xl")).toBeNull();
expect(screen.getAllByRole("banner")).toHaveLength(1);
const rows = Array.from(document.querySelector("main > div")!.children);
expect(rows.map((r) => r.classList.contains("mt-10"))).toEqual([false, false]);
});
it("a top bar without a logo shows the company name, and no button without one", () => {
render(<LandingPage company={{ ...company, logoImageId: null }} page={{ ...page([{ type: "TOPBAR" }]), hideHeader: true }} />);
const top = screen.getByRole("banner");
expect(top).toHaveTextContent("INS Sdn Bhd");
expect(within(top).queryByRole("link")).toBeNull();
});
it("named blocks keep clear of a sticky bar when jumped to", () => {
render(<LandingPage company={company} page={page([bar, { type: "FORM", heading: "Join", closed: true, anchor: "consult" }])} />);
expect(document.getElementById("consult")).toHaveClass("scroll-mt-24");
});
it("shows a section's label above its heading, and section headings in serif", () => {
render(<LandingPage company={company} page={page([
{ type: "FEATURES", eyebrow: "Services", heading: "Everything your guests touch", cards: [{ icon: "wifi", title: "WiFi", text: "Fast." }] },
{ type: "FAQ", eyebrow: "FAQ", heading: "Questions hotels ask us", items: [{ question: "Q", answer: "A" }], look: "DARK" },
])} />);
const heading = screen.getByRole("heading", { level: 2, name: "Everything your guests touch" });
expect(heading).toHaveClass("font-serif");
const label = heading.previousElementSibling!;
expect(label).toHaveTextContent("Services");
expect(label).toHaveClass("uppercase");
expect(screen.getByRole("heading", { level: 2, name: "Questions hotels ask us" })).toHaveClass("font-serif");
expect(screen.getByRole("heading", { level: 2, name: "Questions hotels ask us" }).previousElementSibling).toHaveClass("text-primary");
});
});
// add-hero-fits-screen: the top bar, hero and trust strip fit one desktop screen.
describe("LandingPage first screen", () => {
it("gives a trust band less padding than other bands, and the full-width hero less padding", () => {
render(<LandingPage company={company} page={page([
{ type: "HERO", heading: "One partner", fullWidth: true, eventUuid: "77", closed: true },
{ type: "TRUST", look: "MUTED", cards: [{ title: "Design" }, { title: "Local support" }] },
{ type: "CTA", heading: "Talk to us", look: "DARK" },
])} />);
const bands = Array.from(document.querySelectorAll("[data-look]"));
expect(bands[0]).toHaveClass("py-5");
expect(bands[1]).toHaveClass("py-12");
const grid = screen.getByRole("heading", { name: "One partner" }).closest(".grid")!;
expect(grid).toHaveClass("pt-8", "pb-8");
expect(screen.getByText("Sign-up is closed.").closest(".shadow-card")).toHaveClass("space-y-3");
});
});
// add-event-ticket-orders: the TICKETS block, a card with its label and heading, the event's types, or closed.
describe("LandingPage TICKETS block", () => {
const tickets = {
eventName: "KL Hotel Tech Day", startDate: "2027-01-15", endDate: "2027-01-16", location: "KLCC", companyName: "INS",
notice: { id: 9, textEn: "English notice", textMs: "Notis" },
types: [{ id: 1, name: "Early bird", priceSen: 15000, left: 12, state: "ON_SALE" as const }],
};
it("shows the label, heading, text and the ticket types", () => {
render(<LandingPage company={company} page={page([
{ type: "TICKETS", eventUuid: "900", eyebrow: "Tickets", heading: "Get your seat", text: "Seats are limited.", tickets, anchor: "tickets" },
])} />);
const heading = screen.getByRole("heading", { level: 2, name: "Get your seat" });
expect(heading.previousElementSibling).toHaveTextContent("Tickets");
expect(screen.getByText("Seats are limited.")).toBeInTheDocument();
expect(screen.getByRole("group", { name: "Early bird" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Request tickets" })).toBeInTheDocument();
expect(document.getElementById("tickets")).not.toBeNull();
});
it("says sales are closed when the page carries closed", () => {
render(<LandingPage company={company} page={page([{ type: "TICKETS", eventUuid: "900", heading: "Get your seat", closed: true }])} />);
expect(screen.getByText("Ticket sales are closed.")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Request tickets" })).not.toBeInTheDocument();
});
});
@@ -3,6 +3,8 @@ import { ICONS, LOOKS, anchorId, contrastText, imageSrc, isSafeLink, type CmsBlo
import type { RegistrationInfo } from "@/app/lib/services/publicRegistration"; import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { SafeHtml } from "./SafeHtml"; import { SafeHtml } from "./SafeHtml";
import { LandingForm } from "./LandingForm"; import { LandingForm } from "./LandingForm";
import { TicketsBlock } from "./TicketsBlock";
import type { TicketsInfo } from "@/app/lib/services/publicTickets";
import { HtmlFrame } from "./HtmlFrame"; import { HtmlFrame } from "./HtmlFrame";
import { EditContext, EditSection, HeroShade, HtmlSpot, ImageSpot, RichSpot, Text, stopNavigation, type PageEdit } from "./CmsEdit"; import { EditContext, EditSection, HeroShade, HtmlSpot, ImageSpot, RichSpot, Text, stopNavigation, type PageEdit } from "./CmsEdit";
@@ -10,7 +12,7 @@ import { EditContext, EditSection, HeroShade, HtmlSpot, ImageSpot, RichSpot, Tex
// images are this company's uploads; buttons render only for a safe link, checked again here. A Custom HTML block is // images are this company's uploads; buttons render only for a safe link, checked again here. A Custom HTML block is
// never rendered here: it is a sealed frame loaded from its own address (add-custom-html-block). // never rendered here: it is a sealed frame loaded from its own address (add-custom-html-block).
export type PublicBlock = CmsBlock & { form?: RegistrationInfo; closed?: boolean }; export type PublicBlock = CmsBlock & { form?: RegistrationInfo; tickets?: TicketsInfo; closed?: boolean };
export interface Branding { export interface Branding {
code: string; code: string;
@@ -42,6 +44,27 @@ function ButtonLink({ block, index, edit }: { block: CmsBlock; index: number; ed
); );
} }
// add-landing-page-polish: a section's serif heading, with its optional label above. The label is the accent colour,
// darkened toward the text colour on light backgrounds, where a pale accent would be hard to read.
const LABEL_COLOUR: Record<string, string> = {
DARK: "text-primary",
ACCENT: "opacity-80",
LIGHT: "text-[color-mix(in_srgb,var(--primary)_60%,var(--foreground))]",
};
const LABELLED = ["FEATURES", "STEPS", "IMAGE_TEXT", "FAQ", "CTA", "TICKETS"];
function SectionHeading({ block, index, className }: { block: CmsBlock; index: number; className: string }) {
const band = bandOf(block.look);
return (
<>
{LABELLED.includes(block.type) && <Text as="p" index={index} path="eyebrow" value={block.eyebrow} max={40} code="PagesEyebrow"
className={`mb-2 text-xs font-semibold tracking-widest uppercase ${LABEL_COLOUR[band === "DARK" || band === "ACCENT" ? band : "LIGHT"]}`} />}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className={`font-serif font-semibold ${className}`} />
</>
);
}
function Block({ block, index, company, slug, preview, edit }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean; edit?: boolean }) { function Block({ block, index, company, slug, preview, edit }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean; edit?: boolean }) {
const image = block.imageId ? imageSrc(block.imageId) : undefined; const image = block.imageId ? imageSrc(block.imageId) : undefined;
const button = <ButtonLink block={block} index={index} edit={edit} />; const button = <ButtonLink block={block} index={index} edit={edit} />;
@@ -69,25 +92,25 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
// add-hero-signup-form: with an event, the sign-up form sits in a card beside the text (below it on phones). // add-hero-signup-form: with an event, the sign-up form sits in a card beside the text (below it on phones).
// add-hero-full-width: the card may open with its own heading and text. // add-hero-full-width: the card may open with its own heading and text.
const card = block.eventUuid ? ( const card = block.eventUuid ? (
<div className="space-y-4 rounded-lg border bg-card p-6 text-card-foreground shadow-card"> <div className="space-y-3 rounded-lg border bg-card p-6 text-card-foreground shadow-card">
{block.formHeading || block.formText || edit ? ( {block.formHeading || block.formText || edit ? (
<div className="space-y-1"> <div className="space-y-1">
<Text as="h3" index={index} path="formHeading" value={block.formHeading} max={80} code="PagesFormHeading" className="font-serif text-2xl font-semibold" /> <Text as="h3" index={index} path="formHeading" value={block.formHeading} max={80} code="PagesFormHeading" className="font-serif text-2xl font-semibold" />
<Text as="p" index={index} path="formText" value={block.formText} max={200} code="PagesFormText" className="text-sm text-muted-foreground" /> <Text as="p" index={index} path="formText" value={block.formText} max={200} code="PagesFormText" className="text-sm text-muted-foreground" />
</div> </div>
) : null} ) : null}
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} /> <LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} thanks={block.thanksText} />
</div> </div>
) : null; ) : null;
const back = bandOf(block.look) ? "" : "bg-muted"; const back = bandOf(block.look) ? "" : "bg-muted";
if (wide) { if (wide) {
// Edge to edge; the shade is darkest behind the text and clears toward the far side. The text is centred in the // Edge to edge; the shade is darkest behind the text and clears toward the far side. The text is centred in the
// hero's opening height, not beside a long form, so it stays in the first screen. // hero's opening height, not beside a long form, so it stays in the first screen.
const grid = `mx-auto grid w-full max-w-6xl items-start gap-8 px-4 pt-16 pb-12 ${card ? "md:grid-cols-[minmax(0,1fr)_minmax(0,28rem)]" : ""}`; const grid = `mx-auto grid w-full max-w-6xl items-start gap-8 px-4 pt-8 pb-8 ${card ? "md:grid-cols-[minmax(0,1fr)_minmax(0,28rem)]" : ""}`;
return ( return (
<section className={`relative overflow-hidden ${back}`}> <section className={`relative overflow-hidden ${back}`}>
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner /> <ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
<HeroShade index={index} image={!!image} shaded="relative bg-gradient-to-r from-black/75 via-black/45 to-black/10 text-white" plain=""> <HeroShade index={index} image={!!image} shaded="relative bg-gradient-to-r from-black/60 to-black/60 text-white md:from-black/55 md:to-black/10 md:to-70%" plain="">
<div className={grid}> <div className={grid}>
<div className="flex flex-col justify-center gap-4 md:min-h-[32rem]">{words}</div> <div className="flex flex-col justify-center gap-4 md:min-h-[32rem]">{words}</div>
{card} {card}
@@ -133,7 +156,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
</div> </div>
) : null} ) : null}
<div className="space-y-3"> <div className="space-y-3">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" /> <SectionHeading block={block} index={index} className="text-2xl" />
<RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot> <RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot>
{button} {button}
</div> </div>
@@ -142,7 +165,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
case "FAQ": case "FAQ":
return block.items?.length ? ( return block.items?.length ? (
<section className="space-y-3"> <section className="space-y-3">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" /> <SectionHeading block={block} index={index} className="text-2xl" />
<div className="divide-y rounded-lg border"> <div className="divide-y rounded-lg border">
{block.items.map((item, i) => { {block.items.map((item, i) => {
const question = <Text as="span" index={index} path={`items.${i}.question`} value={item.question} max={300} code="PagesQuestionN" n={i + 1} />; const question = <Text as="span" index={index} path={`items.${i}.question`} value={item.question} max={300} code="PagesQuestionN" n={i + 1} />;
@@ -163,15 +186,26 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
case "FORM": case "FORM":
return ( return (
<section className="mx-auto w-full max-w-md space-y-4 rounded-lg border bg-card p-6 shadow-card"> <section className="mx-auto w-full max-w-md space-y-4 rounded-lg border bg-card p-6 shadow-card">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" /> <SectionHeading block={block} index={index} className="text-2xl" />
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} /> <LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} thanks={block.thanksText} />
</section>
);
case "TICKETS":
// add-event-ticket-orders: the event's ticket types and the request form, in a card like FORM.
return (
<section className="mx-auto w-full max-w-lg space-y-4 rounded-lg border bg-card p-6 text-card-foreground shadow-card">
<div className="space-y-2">
<SectionHeading block={block} index={index} className="text-2xl" />
<Text as="p" index={index} path="text" value={block.text} max={1000} code="PagesText" className="text-muted-foreground" />
</div>
<TicketsBlock companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.tickets} preview={preview} eventUuid={block.eventUuid} />
</section> </section>
); );
case "FEATURES": case "FEATURES":
return ( return (
<section className="space-y-6"> <section className="space-y-6">
<div className="max-w-2xl space-y-2"> <div className="max-w-2xl space-y-2">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" /> <SectionHeading block={block} index={index} className="text-2xl sm:text-3xl" />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="text-lg opacity-80" /> <Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="text-lg opacity-80" />
</div> </div>
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3"> <ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
@@ -191,7 +225,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
case "STEPS": case "STEPS":
return ( return (
<section className="space-y-6"> <section className="space-y-6">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" /> <SectionHeading block={block} index={index} className="text-2xl sm:text-3xl" />
<ol className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3"> <ol className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{(block.cards ?? []).map((card, i) => ( {(block.cards ?? []).map((card, i) => (
<li key={i} className="flex gap-4"> <li key={i} className="flex gap-4">
@@ -216,11 +250,26 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
case "CTA": case "CTA":
return ( return (
<section className="flex flex-col items-center gap-4 py-4 text-center"> <section className="flex flex-col items-center gap-4 py-4 text-center">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" /> <SectionHeading block={block} index={index} className="text-2xl sm:text-3xl" />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg opacity-80" /> <Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg opacity-80" />
{button} {button}
</section> </section>
); );
case "FOOTER":
// add-landing-thanks-and-footer: columns of title and text with contact links, the legal line under a divider.
return (
<footer role="contentinfo" className="text-sm [&_a]:text-primary [&_a]:hover:underline">
<ul className={`grid gap-8 ${["", "", "md:grid-cols-2", "md:grid-cols-3", "md:grid-cols-4"][block.cards?.length ?? 0]}`}>
{(block.cards ?? []).map((card, i) => (
<li key={i} className="space-y-1.5">
<Text as="h2" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesCardTitle" className="font-semibold" />
<Text as="p" index={index} path={`cards.${i}.text`} value={card.text} max={300} code="PagesCardText" multiline links className="whitespace-pre-line opacity-80" />
</li>
))}
</ul>
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesFooterLegal" className="mt-8 border-t border-muted-foreground/30 pt-4 text-xs opacity-70" />
</footer>
);
default: default:
return null; return null;
} }
@@ -228,18 +277,39 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
const WIDTH = "mx-auto w-full max-w-5xl px-4"; const WIDTH = "mx-auto w-full max-w-5xl px-4";
/** Blocks that run the full window width: Custom HTML, and a full-width hero. Two of them in a row join with no gap. */ /** add-landing-page-polish: the company logo (or name) and an optional button, kept at the top of the window. */
const bleeds = (block: PublicBlock) => block.type === "HTML" || (block.type === "HERO" && !!block.fullWidth); function TopBar({ block, index, company, edit }: { block: CmsBlock; index: number; company: Branding; edit: boolean }) {
return (
<header role="banner" id={anchorId(block.anchor)} className="border-b bg-card/95 backdrop-blur">
<div className="mx-auto flex max-w-6xl items-center justify-between gap-3 px-4 py-3">
{company.logoImageId ? (
// eslint-disable-next-line @next/next/no-img-element -- the company's uploaded logo
<img src={imageSrc(company.logoImageId)} alt={company.name} className="h-10 w-auto" />
) : (
<span className="text-lg font-semibold">{company.name}</span>
)}
<ButtonLink block={block} index={index} edit={edit} />
</div>
</header>
);
}
/**
* Blocks that run the full window width: Custom HTML, a full-width hero, and a coloured band (add-compact-landing-form).
* Two of them in a row join with no gap.
*/
const bleeds = (block: PublicBlock) => block.type === "HTML" || block.type === "TOPBAR" || (block.type === "HERO" && !!block.fullWidth) || !!bandOf(block.look);
/** A block in the page width; with a non-default look, inside a full-width band of that colour. */ /** A block in the page width; with a non-default look, inside a full-width band of that colour. */
function Section({ block, index, children }: { block: PublicBlock; index: number; children: ReactNode }) { function Section({ block, index, children }: { block: PublicBlock; index: number; children: ReactNode }) {
const band = bandOf(block.look); const band = bandOf(block.look);
// add-hero-full-width: a full-width hero sets its own width. // add-hero-full-width: a full-width hero sets its own width.
if (bleeds(block)) return <EditSection index={index}><div id={anchorId(block.anchor)}>{children}</div></EditSection>; if (block.type === "HERO" && block.fullWidth) return <EditSection index={index}><div id={anchorId(block.anchor)}>{children}</div></EditSection>;
if (!band) return <EditSection index={index}><div id={anchorId(block.anchor)} className={WIDTH}>{children}</div></EditSection>; // add-landing-page-polish: a #name jump lands clear of a sticky top bar.
if (!band) return <EditSection index={index}><div id={anchorId(block.anchor)} className={`scroll-mt-24 ${WIDTH}`}>{children}</div></EditSection>;
return ( return (
<EditSection index={index}> <EditSection index={index}>
<div id={anchorId(block.anchor)} data-look={band} className={`py-12 ${BANDS[band]}`}> <div id={anchorId(block.anchor)} data-look={band} className={`scroll-mt-16 ${block.type === "TRUST" ? "py-5" : "py-12"} ${BANDS[band]}`}>
<div className={WIDTH}>{children}</div> <div className={WIDTH}>{children}</div>
</div> </div>
</EditSection> </EditSection>
@@ -277,12 +347,16 @@ export function LandingPage({ company, page, banner, preview, frameBase, edit }:
)} )}
</div> </div>
</header>} </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> <h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
<div> <div>
{page.blocks.map((block, i) => ( {page.blocks.map((block, i) => (
<div key={i} className={i > 0 && !(bleeds(block) && bleeds(page.blocks[i - 1])) ? "mt-10" : undefined}> // A top bar's row is what sticks: a sticky element only sticks inside its parent, and the rows share the page's.
{block.type === "HTML" <div key={i} className={block.type === "TOPBAR" ? "sticky top-0 z-20" : i > 0 && !(bleeds(block) && bleeds(page.blocks[i - 1])) ? "mt-10" : undefined}>
{block.type === "TOPBAR"
? <EditSection index={i}><TopBar block={block} index={i} company={company} edit={!!edit} /></EditSection>
: block.type === "HTML"
? <HtmlSpot index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot> ? <HtmlSpot index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot>
: <Section block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>} : <Section block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>}
</div> </div>
@@ -4,6 +4,7 @@ import { createContext, useContext, useLayoutEffect, useRef, type ElementType, t
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
import { ImagePlus } from "lucide-react"; import { ImagePlus } from "lucide-react";
import { BLOCK_LABELS, type CmsBlock } from "@/app/lib/cmsPages"; import { BLOCK_LABELS, type CmsBlock } from "@/app/lib/cmsPages";
import { contactLinks } from "@/app/lib/contactLinks";
import { useT } from "@/app/lib/i18n/MessagesProvider"; import { useT } from "@/app/lib/i18n/MessagesProvider";
// add-page-visual-editor: the landing page in edit mode, on the on-page editor's canvas. The public page and the // add-page-visual-editor: the landing page in edit mode, on the on-page editor's canvas. The public page and the
@@ -45,7 +46,7 @@ export function setField(block: CmsBlock, path: string, value: string): CmsBlock
* A plain text field: the text as-is on the public page; in edit mode the same element, typed into in place. It is * A plain text field: the text as-is on the public page; in edit mode the same element, typed into in place. It is
* never re-rendered from its value while focused, so the caret stays where it is. * never re-rendered from its value while focused, so the caret stays where it is.
*/ */
export function Text({ as: Tag, index, path, value, max, code, n, className, multiline }: { export function Text({ as: Tag, index, path, value, max, code, n, className, multiline, links }: {
as: ElementType; as: ElementType;
index: number; index: number;
path: string; path: string;
@@ -56,9 +57,11 @@ export function Text({ as: Tag, index, path, value, max, code, n, className, mul
n?: number; n?: number;
className?: string; className?: string;
multiline?: boolean; multiline?: boolean;
/** Outside the editor, show contact details as links (add-landing-thanks-and-footer). */
links?: boolean;
}) { }) {
const edit = useEdit(); const edit = useEdit();
if (!edit) return value ? <Tag className={className}>{value}</Tag> : null; if (!edit) return value ? <Tag className={className}>{links ? contactLinks(value) : value}</Tag> : null;
return <EditableText as={Tag} edit={edit} index={index} path={path} value={value ?? ""} max={max} code={code} n={n} className={className} multiline={multiline} />; return <EditableText as={Tag} edit={edit} index={index} path={path} value={value ?? ""} max={max} code={code} n={n} className={className} multiline={multiline} />;
} }
@@ -7,6 +7,7 @@ import { VisitorState } from "@/app/components/registration/VisitorCard";
import { RegistrationForm } from "@/app/components/registration/RegistrationForm"; import { RegistrationForm } from "@/app/components/registration/RegistrationForm";
import { publicCall, type RegistrationBody, type RegistrationInfo } from "@/app/lib/services/publicRegistration"; import { publicCall, type RegistrationBody, type RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider"; import { useT } from "@/app/lib/i18n/MessagesProvider";
import { contactLinks } from "@/app/lib/contactLinks";
const UTM = ["utm_source", "utm_medium", "utm_campaign"] as const; const UTM = ["utm_source", "utm_medium", "utm_campaign"] as const;
@@ -18,7 +19,8 @@ export function utmTags(search: string): { utmSource?: string; utmMedium?: strin
} }
// A landing page's FORM block: the QR sign-up form, posting to the page's block, with the visitor's UTM tags. // A landing page's FORM block: the QR sign-up form, posting to the page's block, with the visitor's UTM tags.
export function LandingForm({ companyCode, slug, index, info, preview }: { companyCode: string; slug: string; index: number; info?: RegistrationInfo; preview?: boolean }) { // add-landing-thanks-and-footer: `thanks` is the page's own text under the thank-you, with contact links.
export function LandingForm({ companyCode, slug, index, info, preview, thanks }: { companyCode: string; slug: string; index: number; info?: RegistrationInfo; preview?: boolean; thanks?: string }) {
const t = useT(); const t = useT();
const [phase, setPhase] = useState<"form" | "done" | "closed">(info ? "form" : "closed"); const [phase, setPhase] = useState<"form" | "done" | "closed">(info ? "form" : "closed");
@@ -26,6 +28,7 @@ export function LandingForm({ companyCode, slug, index, info, preview }: { compa
if (phase === "closed" || !info) return <VisitorState icon={AlertCircle} heading={t("PagesFormClosed")} role="status" />; if (phase === "closed" || !info) return <VisitorState icon={AlertCircle} heading={t("PagesFormClosed")} role="status" />;
if (phase === "done") { if (phase === "done") {
return <VisitorState icon={CheckCircle2} heading={t("RegThanks", { event: info.eventName })} role="status" return <VisitorState icon={CheckCircle2} heading={t("RegThanks", { event: info.eventName })} role="status"
text={thanks ? contactLinks(thanks) : undefined}
action={<Button className="h-11" onClick={() => setPhase("form")}>{t("RegAnother")}</Button>} />; action={<Button className="h-11" onClick={() => setPhase("form")}>{t("RegAnother")}</Button>} />;
} }
const submit = (body: RegistrationBody) => const submit = (body: RegistrationBody) =>
@@ -33,5 +36,5 @@ export function LandingForm({ companyCode, slug, index, info, preview }: { compa
method: "POST", method: "POST",
body: JSON.stringify({ ...body, ...utmTags(window.location.search) }), body: JSON.stringify({ ...body, ...utmTags(window.location.search) }),
}); });
return <RegistrationForm info={info} submit={submit} onDone={() => setPhase("done")} onInactive={() => setPhase("closed")} />; return <RegistrationForm info={info} submit={submit} onDone={() => setPhase("done")} onInactive={() => setPhase("closed")} compact />;
} }
@@ -76,6 +76,50 @@ describe("PageEditor: sections", () => {
expect(within(within(block).getByRole("group", { name: "Step 6" })).getByRole("button", { name: "Remove" })).toBeEnabled(); expect(within(within(block).getByRole("group", { name: "Step 6" })).getByRole("button", { name: "Remove" })).toBeEnabled();
}); });
// add-landing-thanks-and-footer: a dark footer of 1 to 4 columns with a legal line.
it("adds a dark footer with columns and a legal line, and keeps 1 to 4 columns", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await screen.findByDisplayValue("How it works");
await user.click(screen.getByRole("button", { name: "Add Footer" }));
const block = group("Block 3: Footer");
expect(within(block).getByLabelText("Look")).toHaveValue("DARK");
const col1 = within(block).getByRole("group", { name: "Column 1" });
await user.type(within(col1).getByLabelText("Title"), "Talk to us");
await user.type(within(col1).getByLabelText("Text"), "+603-7623 9807");
await user.click(within(within(block).getByRole("group", { name: "Column 2" })).getByRole("button", { name: "Remove" }));
expect(within(col1).getByRole("button", { name: "Remove" })).toBeDisabled();
await user.type(within(block).getByLabelText("Legal line"), "© 2026 INS");
const add = within(block).getByRole("button", { name: "Add column" });
for (let i = 0; i < 3; i++) await user.click(add);
expect(add).toBeDisabled();
for (const n of [4, 3, 2]) await user.click(within(within(block).getByRole("group", { name: `Column ${n}` })).getByRole("button", { name: "Remove" }));
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
expect(mocks.savePage.mock.calls[0][1].blocks[2]).toEqual({
type: "FOOTER", look: "DARK", text: "© 2026 INS", cards: [{ title: "Talk to us", text: "+603-7623 9807" }],
});
});
// add-landing-page-polish: the top bar's button, and a label above a section's heading.
it("adds a top bar with a button and no look, and saves a section label", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await screen.findByDisplayValue("How it works");
await user.type(within(group("Block 1: Steps")).getByLabelText("Label"), "How we work");
await user.click(screen.getByRole("button", { name: "Add Top bar" }));
const block = group("Block 3: Top bar");
expect(within(block).queryByLabelText("Look")).not.toBeInTheDocument();
expect(within(block).queryByLabelText("Label")).not.toBeInTheDocument();
await user.type(within(block).getByLabelText("Button label"), "Get My Free Consultation");
await user.type(within(block).getByLabelText("Button link"), "#consult");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
const blocks = mocks.savePage.mock.calls[0][1].blocks;
expect(blocks[0]).toMatchObject({ type: "STEPS", eyebrow: "How we work" });
expect(blocks[2]).toEqual({ type: "TOPBAR", buttonLabel: "Get My Free Consultation", buttonUrl: "#consult" });
});
it("offers no look for a Custom HTML block", async () => { it("offers no look for a Custom HTML block", async () => {
render(<PageEditor pageId={5} />); render(<PageEditor pageId={5} />);
await screen.findByDisplayValue("How it works"); await screen.findByDisplayValue("How it works");
@@ -96,6 +96,26 @@ describe("PageEditor", () => {
expect(mocks.savePage.mock.calls[0][1].blocks[0].imageId).toBe(44); expect(mocks.savePage.mock.calls[0][1].blocks[0].imageId).toBe(44);
}); });
// add-event-ticket-orders: a Tickets section's picker offers only events that sell tickets.
it("adds a Tickets section whose picker offers only events with tickets on", async () => {
mocks.listAdminEvents.mockResolvedValue({ items: [
{ uuid: "3312726793093644288", name: "Website enquiries", endDate: "2099-12-31", enabled: true, location: "", startDate: "", ticketsEnabled: false },
{ uuid: "900", name: "KL Hotel Tech Day", endDate: "2099-12-31", enabled: true, location: "", startDate: "", ticketsEnabled: true },
], total: 2 });
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await screen.findByLabelText("Event");
await user.click(screen.getByRole("button", { name: "Add Tickets" }));
const picker = await screen.findByLabelText("Event selling tickets");
await waitFor(() => expect(within(picker).getByRole("option", { name: "KL Hotel Tech Day" })).toBeInTheDocument());
expect(within(picker).queryByRole("option", { name: "Website enquiries" })).not.toBeInTheDocument();
await user.selectOptions(picker, "900");
await user.type(screen.getAllByLabelText("Heading").at(-1)!, "Get your seat");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
expect(mocks.savePage.mock.calls[0][1].blocks.at(-1)).toMatchObject({ type: "TICKETS", eventUuid: "900", heading: "Get your seat" });
});
it("asks before deleting", async () => { it("asks before deleting", async () => {
mocks.deletePage.mockResolvedValue(undefined); mocks.deletePage.mockResolvedValue(undefined);
const user = userEvent.setup(); const user = userEvent.setup();
@@ -152,6 +172,27 @@ describe("PageEditor", () => {
expect([hero.formHeading, hero.formText]).toEqual([undefined, undefined]); expect([hero.formHeading, hero.formText]).toEqual([undefined, undefined]);
}); });
// add-landing-thanks-and-footer: the hero's thank-you text, only while it has a form.
it("saves a hero's thank-you text; No form drops it", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const picker = await screen.findByLabelText("Sign-up form");
// The FORM block (block 2) has its own thank-you field; these checks are the hero's.
const hero = () => within(screen.getByRole("group", { name: /^Block 1/ }));
expect(hero().queryByLabelText("Thank-you text")).not.toBeInTheDocument();
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
await user.selectOptions(picker, "3312726793093644288");
await user.type(hero().getByLabelText("Thank-you text"), "Call +60 12-833 2775.");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(1));
expect(mocks.savePage.mock.calls[0][1].blocks[0]).toMatchObject({ type: "HERO", thanksText: "Call +60 12-833 2775." });
await user.selectOptions(screen.getByLabelText("Sign-up form"), "");
expect(hero().queryByLabelText("Thank-you text")).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(2));
expect(mocks.savePage.mock.calls[1][1].blocks[0].thanksText).toBeUndefined();
});
it("a super admin must choose a company for a new page", async () => { it("a super admin must choose a company for a new page", async () => {
mocks.useAdminAuth.mockReturnValue({ isSuper: true, companyCode: null }); mocks.useAdminAuth.mockReturnValue({ isSuper: true, companyCode: null });
const user = userEvent.setup(); const user = userEvent.setup();
@@ -0,0 +1,148 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({ publicCall: vi.fn(), listTicketTypes: vi.fn() }));
vi.mock("@/app/lib/services/publicRegistration", async (orig) => ({ ...(await orig<object>()), publicCall: mocks.publicCall }));
vi.mock("@/app/lib/services/adminTickets", async (orig) => ({ ...(await orig<object>()), listTicketTypes: mocks.listTicketTypes }));
import { TicketsBlock } from "./TicketsBlock";
import type { TicketsInfo } from "@/app/lib/services/publicTickets";
const INFO: TicketsInfo = {
eventName: "KL Hotel Tech Day",
startDate: "2027-01-15",
endDate: "2027-01-16",
location: "KLCC",
companyName: "INS",
notice: { id: 9, textEn: "English notice", textMs: "Notis" },
types: [
{ id: 1, name: "Early bird", priceSen: 15000, left: 12, state: "ON_SALE" },
{ id: 2, name: "General", priceSen: 25000, left: 3, state: "ON_SALE" },
{ id: 3, name: "VIP", priceSen: 50000, left: 0, state: "SOLD_OUT" },
{ id: 4, name: "Walk-up", priceSen: 20000, left: 5, state: "ENDED" },
{ id: 5, name: "Community pass", priceSen: 0, left: 50, state: "ON_SALE" },
],
};
const RECEIVED = {
reference: "T-7K3M9Q", token: "abcdefghijklmnopqrstuv", status: "AWAITING", totalSen: 30000, holdUntil: "2027-01-13T12:00:00",
lines: [{ name: "Early bird", unitPriceSen: 15000, quantity: 2 }], paymentInstructions: "Maybank 5140\nRef: your order number", eventName: "KL Hotel Tech Day",
};
beforeEach(() => {
mocks.publicCall.mockReset().mockResolvedValue(RECEIVED);
mocks.listTicketTypes.mockReset();
});
const row = (name: string) => screen.getByRole("group", { name });
const add = (user: ReturnType<typeof userEvent.setup>, name: string, times = 1) =>
(async () => { for (let i = 0; i < times; i++) await user.click(within(row(name)).getByRole("button", { name: `Add one ${name}` })); })();
async function fillBuyer(user: ReturnType<typeof userEvent.setup>) {
await user.type(screen.getByLabelText("Your name"), "Aisyah");
await user.type(screen.getByLabelText("Email"), "aisyah@example.test");
await user.click(screen.getByRole("checkbox"));
}
describe("TicketsBlock", () => {
it("lists the types with prices, Free, sold out and sales ended", () => {
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} info={INFO} />);
expect(within(row("Early bird")).getByText("RM 150.00")).toBeInTheDocument();
expect(within(row("Early bird")).getByText("12 left")).toBeInTheDocument();
expect(within(row("Community pass")).getByText("Free")).toBeInTheDocument();
expect(within(row("VIP")).getByText("Sold out")).toBeInTheDocument();
expect(within(row("VIP")).queryByRole("button", { name: "Add one VIP" })).toBeNull();
expect(within(row("Walk-up")).getByText("Sales ended")).toBeInTheDocument();
expect(within(row("Walk-up")).queryByRole("button", { name: "Add one Walk-up" })).toBeNull();
});
it("keeps a running total and caps the order at ten and each type at its seats", async () => {
const user = userEvent.setup();
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} info={INFO} />);
await add(user, "Early bird", 2);
await add(user, "General", 4);
expect(within(row("General")).getByText("3")).toBeInTheDocument();
expect(within(row("General")).getByRole("button", { name: "Add one General" })).toBeDisabled();
expect(screen.getByTestId("tickets-total")).toHaveTextContent("RM 1,050.00");
await add(user, "Community pass", 5);
expect(within(row("Community pass")).getByText("5")).toBeInTheDocument();
expect(within(row("Early bird")).getByRole("button", { name: "Add one Early bird" })).toBeDisabled();
await user.click(within(row("Early bird")).getByRole("button", { name: "Remove one Early bird" }));
expect(screen.getByTestId("tickets-total")).toHaveTextContent("RM 900.00");
});
it("asks for tickets, name, email and consent before sending", async () => {
const user = userEvent.setup();
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} info={INFO} />);
await user.click(screen.getByRole("button", { name: "Request tickets" }));
expect(screen.getByText("Choose at least one ticket.")).toBeInTheDocument();
expect(screen.getByText("Enter your name.")).toBeInTheDocument();
expect(screen.getByText("Enter your email.")).toBeInTheDocument();
expect(screen.getByText("Tick the box to agree to the privacy notice.")).toBeInTheDocument();
expect(mocks.publicCall).not.toHaveBeenCalled();
});
it("sends the request and thanks with the instructions, hold and order link", async () => {
const user = userEvent.setup();
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} info={INFO} />);
await add(user, "Early bird", 2);
await fillBuyer(user);
await user.click(screen.getByRole("button", { name: "Request tickets" }));
await waitFor(() => expect(mocks.publicCall).toHaveBeenCalled());
const [url, init] = mocks.publicCall.mock.calls[0];
expect(url).toBe("/api/public/pages/INS/tech-day/tickets/1");
expect(JSON.parse(init.body)).toMatchObject({
lines: [{ ticketTypeId: 1, quantity: 2 }], name: "Aisyah", email: "aisyah@example.test", consent: true, website: "",
});
expect(await screen.findByText(/T-7K3M9Q/)).toBeInTheDocument();
expect(screen.getByText(/Maybank 5140/)).toBeInTheDocument();
expect(screen.getByText(/13 Jan 2027/)).toBeInTheDocument();
expect(screen.getByRole("link", { name: "View your order" })).toHaveAttribute("href", "/o/abcdefghijklmnopqrstuv");
});
it("confirms a free order without instructions", async () => {
const user = userEvent.setup();
mocks.publicCall.mockResolvedValue({ ...RECEIVED, status: "PAID", totalSen: 0, holdUntil: null, paymentInstructions: undefined });
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} info={INFO} />);
await add(user, "Community pass", 2);
await fillBuyer(user);
await user.click(screen.getByRole("button", { name: "Request tickets" }));
expect(await screen.findByText("Your order T-7K3M9Q is confirmed.")).toBeInTheDocument();
expect(screen.queryByText(/How to pay/)).toBeNull();
});
it("shows a refusal from the server", async () => {
const user = userEvent.setup();
mocks.publicCall.mockRejectedValue(new ApiError("x", 409, { code: "TYPE_UNAVAILABLE", error: "General has only 1 ticket left." }));
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} info={INFO} />);
await add(user, "General", 2);
await fillBuyer(user);
await user.click(screen.getByRole("button", { name: "Request tickets" }));
expect(await screen.findByRole("alert")).toHaveTextContent("General has only 1 ticket left.");
});
it("shows a field error under its field", async () => {
const user = userEvent.setup();
mocks.publicCall.mockRejectedValue(new ApiError("x", 400, { code: "INVALID_EMAIL", error: "Enter a valid email.", details: { field: "email" } }));
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} info={INFO} />);
await add(user, "General", 1);
await fillBuyer(user);
await user.click(screen.getByRole("button", { name: "Request tickets" }));
expect(await screen.findByText("Enter a valid email.")).toBeInTheDocument();
});
it("says ticket sales are closed", () => {
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} />);
expect(screen.getByRole("status")).toHaveTextContent("Ticket sales are closed.");
});
it("shows the event's real types on the editor canvas", async () => {
mocks.listTicketTypes.mockResolvedValue([{ id: 2, name: "General", priceSen: 25000, quantity: 100, salesEndDate: null, sort: 0, enabled: true, held: 20, left: 80 }]);
render(<TicketsBlock companyCode="INS" slug="tech-day" index={1} preview eventUuid="900" />);
expect(await screen.findByText("General")).toBeInTheDocument();
expect(screen.getByText("RM 250.00")).toBeInTheDocument();
expect(mocks.listTicketTypes).toHaveBeenCalledWith("900");
expect(screen.queryByRole("button", { name: "Request tickets" })).toBeNull();
});
});
@@ -0,0 +1,224 @@
"use client";
import Link from "next/link";
import { useEffect, useState, type FormEvent } from "react";
import { AlertCircle, CheckCircle2, Minus, Plus } 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 { VisitorState } from "@/app/components/registration/VisitorCard";
import { apiData, failMessage } from "@/app/components/registration/RegistrationForm";
import { utmTags } from "./LandingForm";
import { listTicketTypes, money } from "@/app/lib/services/adminTickets";
import { publicCall } from "@/app/lib/services/publicRegistration";
import { when, type PublicTicketType, type TicketRequestResult, type TicketsInfo } from "@/app/lib/services/publicTickets";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const MAX = 10;
type Buyer = { name: string; mobile: string; email: string; companyName: string; consent: boolean; website: string };
const EMPTY: Buyer = { name: "", mobile: "", email: "", companyName: "", consent: false, website: "" };
const FIELDS = ["name", "mobile", "email", "companyName", "consent"];
const NOTICE = "rounded-md bg-muted p-3 text-xs text-muted-foreground";
/** One type's row: name, price and seats, and a stepper while it is on sale. */
function TypeRow({ type, qty, canAdd, onChange, disabled }: { type: PublicTicketType; qty?: number; canAdd?: boolean; onChange?: (n: number) => void; disabled?: boolean }) {
const t = useT();
const onSale = type.state === "ON_SALE" && type.left > 0;
return (
<div role="group" aria-label={type.name} className="flex items-center justify-between gap-3 rounded-md border p-3">
<div className="min-w-0">
<p className="font-medium">{type.name}</p>
<p className="text-sm text-muted-foreground">
<span>{type.priceSen === 0 ? t("TktFree") : money(type.priceSen)}</span>
{" · "}
<span>{type.state === "ENDED" ? t("TktSalesEnded") : onSale ? t("TktSeatsLeft", { count: type.left }) : t("TktSoldOut")}</span>
</p>
</div>
{onSale && onChange && (
<div className="flex items-center gap-2">
<Button type="button" variant="outline" size="icon" className="size-11" aria-label={t("TktRemoveOne", { name: type.name })}
disabled={disabled || !qty} onClick={() => onChange((qty ?? 0) - 1)}>
<Minus className="size-4" aria-hidden="true" />
</Button>
<span className="w-6 text-center tabular-nums" aria-live="polite">{qty ?? 0}</span>
<Button type="button" variant="outline" size="icon" className="size-11" aria-label={t("TktAddOne", { name: type.name })}
disabled={disabled || !canAdd} onClick={() => onChange((qty ?? 0) + 1)}>
<Plus className="size-4" aria-hidden="true" />
</Button>
</div>
)}
</div>
);
}
/** The editor canvas: the event's real types (read with the staff ticket call), with no form. */
function TicketsPreview({ eventUuid }: { eventUuid?: string | null }) {
const t = useT();
const [types, setTypes] = useState<PublicTicketType[] | null>(null);
useEffect(() => {
if (!eventUuid) return;
listTicketTypes(eventUuid)
.then((list) => setTypes(list.filter((x) => x.enabled).map((x) => ({ id: x.id, name: x.name, priceSen: x.priceSen, left: x.left, state: x.left > 0 ? "ON_SALE" : "SOLD_OUT" }))))
.catch(() => setTypes([]));
}, [eventUuid]);
return (
<div className="space-y-3">
{types?.map((x) => <TypeRow key={x.id} type={x} />)}
<p role="status" className="text-sm text-muted-foreground">{t("TktPreviewNote")}</p>
</div>
);
}
/** add-event-ticket-orders: a landing page's TICKETS block. Quantities per type (10 in all), the buyer, the consent; then the thank-you. */
export function TicketsBlock({ companyCode, slug, index, info, preview, eventUuid }: {
companyCode: string; slug: string; index: number; info?: TicketsInfo; preview?: boolean; eventUuid?: string | null;
}) {
const t = useT();
const [qty, setQty] = useState<Record<number, number>>({});
const [buyer, setBuyer] = useState<Buyer>(EMPTY);
const [errors, setErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [done, setDone] = useState<TicketRequestResult | null>(null);
const [closed, setClosed] = useState(false);
if (preview) return <TicketsPreview eventUuid={eventUuid} />;
if (!info || closed) return <VisitorState icon={AlertCircle} heading={t("TktSalesClosed")} role="status" />;
if (done) return <Thanks result={done} />;
const count = Object.values(qty).reduce((a, b) => a + b, 0);
const total = info.types.reduce((sum, x) => sum + (qty[x.id] ?? 0) * x.priceSen, 0);
const set = (patch: Partial<Buyer>) => setBuyer((b) => ({ ...b, ...patch }));
async function onSubmit(e: FormEvent) {
e.preventDefault();
const errs: Record<string, string> = {};
if (count < 1) errs.tickets = t("TktChooseTickets");
if (!buyer.name.trim()) errs.name = t("RegNameRequired");
if (!buyer.email.trim()) errs.email = t("TktEmailRequired");
if (!buyer.consent) errs.consent = t("TktConsentRequired");
setErrors(errs);
setFormError(null);
if (Object.keys(errs).length) return;
setSaving(true);
try {
const lines = info!.types.filter((x) => qty[x.id]).map((x) => ({ ticketTypeId: x.id, quantity: qty[x.id] }));
const body = { lines, ...buyer, name: buyer.name.trim(), mobile: buyer.mobile.trim(), email: buyer.email.trim(), companyName: buyer.companyName.trim() };
setDone(await publicCall<TicketRequestResult>(`/api/public/pages/${encodeURIComponent(companyCode)}/${encodeURIComponent(slug)}/tickets/${index}`, {
method: "POST",
body: JSON.stringify({ ...body, ...utmTags(window.location.search) }),
}));
} catch (err) {
const { status, code, error, field } = apiData(err);
if (code === "TICKETS_CLOSED") setClosed(true);
else if (status === 400 && error && field && FIELDS.includes(field)) setErrors({ [field]: error });
else setFormError(failMessage(t, err));
setSaving(false);
}
}
const fieldError = (id: string) => errors[id] && <p id={`tkt-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>;
const field = (id: "name" | "mobile" | "email" | "companyName", label: string, type = "text") => (
<div className="space-y-1.5">
<Label htmlFor={`tkt-${id}`}>{label}</Label>
<Input id={`tkt-${id}`} className="h-11" type={type} value={buyer[id]} disabled={saving} onChange={(e) => set({ [id]: e.target.value })}
aria-invalid={!!errors[id]} aria-describedby={errors[id] ? `tkt-${id}-error` : undefined} />
{fieldError(id)}
</div>
);
return (
<form onSubmit={onSubmit} className="space-y-4" noValidate>
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
<div className="space-y-2">
{info.types.map((x) => (
<TypeRow key={x.id} type={x} qty={qty[x.id]} disabled={saving}
canAdd={count < MAX && (qty[x.id] ?? 0) < x.left}
onChange={(n) => setQty((q) => ({ ...q, [x.id]: Math.max(0, n) }))} />
))}
<p className="text-xs text-muted-foreground">{t("TktMax")}</p>
{fieldError("tickets")}
</div>
<p className="flex items-baseline justify-between text-lg font-semibold">
<span>{t("TktTotal")}</span>
<span data-testid="tickets-total" className="tabular-nums">{money(total)}</span>
</p>
{field("name", t("RegName"))}
{field("email", t("RegEmail"), "email")}
{field("mobile", t("RegMobile"), "tel")}
{field("companyName", t("RegCompany"))}
<details className={NOTICE}>
<summary className="cursor-pointer font-medium text-foreground">{t("RegNoticeSummary")}</summary>
<div className="mt-2 space-y-2">
<h3 className="font-semibold text-foreground">{t("RegNoticeEn")}</h3>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h3 className="font-semibold text-foreground">{t("RegNoticeMs")}</h3>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
</details>
<Label htmlFor={`tkt-consent-${index}`} className="flex min-h-11 w-full cursor-pointer items-start gap-3 rounded-md border p-3 leading-normal">
<Checkbox id={`tkt-consent-${index}`} className="mt-0.5 size-6" checked={buyer.consent} onCheckedChange={(on) => set({ consent: on === true })}
aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "tkt-consent-error" : undefined} />
<span className="space-y-1 text-sm font-normal">
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
</span>
</Label>
{fieldError("consent")}
{/* Honeypot: people never see or reach it; bots fill it and the server saves nothing. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<input name="website" tabIndex={-1} autoComplete="off" value={buyer.website} onChange={(e) => set({ website: e.target.value })} />
</div>
<Button type="submit" className="h-11 w-full" disabled={saving}>{t("TktRequest")}</Button>
</form>
);
}
/** The thank-you: the order, how and by when to pay while it awaits payment, and its link. */
export function Thanks({ result }: { result: TicketRequestResult }) {
const t = useT();
if (!result.reference || !result.token) return <VisitorState icon={CheckCircle2} heading={t("TktThanksPlain", { event: result.eventName })} role="status" />;
const paid = result.status === "PAID";
return (
<div role="status" className="space-y-4">
<VisitorState icon={CheckCircle2} heading={t(paid ? "TktThanksPaid" : "TktThanks", { reference: result.reference })} />
<OrderSummary lines={result.lines ?? []} totalSen={result.totalSen ?? 0} />
{!paid && result.paymentInstructions && (
<PaymentBox instructions={result.paymentInstructions} holdUntil={result.holdUntil} />
)}
<Button asChild className="h-11 w-full">
<Link href={`/o/${encodeURIComponent(result.token)}`}>{t("TktViewOrder")}</Link>
</Button>
</div>
);
}
export function OrderSummary({ lines, totalSen }: { lines: { name: string; unitPriceSen: number; quantity: number }[]; totalSen: number }) {
const t = useT();
return (
<ul className="divide-y rounded-md border text-sm">
{lines.map((l, i) => (
<li key={i} className="flex justify-between gap-3 p-3">
<span>{l.name} × {l.quantity}</span>
<span className="tabular-nums">{money(l.unitPriceSen * l.quantity)}</span>
</li>
))}
<li className="flex justify-between gap-3 p-3 font-semibold">
<span>{t("TktTotal")}</span>
<span className="tabular-nums">{money(totalSen)}</span>
</li>
</ul>
);
}
export function PaymentBox({ instructions, holdUntil }: { instructions: string; holdUntil?: string | null }) {
const t = useT();
return (
<div className="space-y-2 rounded-md bg-muted p-4 text-sm">
<h3 className="font-semibold">{t("TktHowToPay")}</h3>
<p className="whitespace-pre-line">{instructions}</p>
{holdUntil && <p className="font-medium">{t("TktPayBy", { when: when(holdUntil) })}</p>}
</div>
);
}
@@ -68,6 +68,14 @@ describe("usePageDraft for the on-page editor", () => {
expect(result.current.rows[0].block).toEqual({ type: "HERO", heading: "Hi", eventUuid: null }); expect(result.current.rows[0].block).toEqual({ type: "HERO", heading: "Hi", eventUuid: null });
}); });
// add-landing-thanks-and-footer: a hero's thank-you text goes with its form too.
it("a company switch also drops a hero's thank-you text", async () => {
mocks.getPage.mockResolvedValueOnce({ ...stored, blocks: [{ type: "HERO" as const, heading: "Hi", eventUuid: "77", thanksText: "Call us." }] });
const { result } = await loaded();
act(() => result.current.changeCompany(3));
expect(result.current.rows[0].block).toEqual({ type: "HERO", heading: "Hi", eventUuid: null });
});
it("keeps the company's branding from the loaded page", async () => { it("keeps the company's branding from the loaded page", async () => {
const { result } = await loaded(); const { result } = await loaded();
expect(result.current.branding).toEqual(stored.company); expect(result.current.branding).toEqual(stored.company);
@@ -133,7 +133,7 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
let live = true; let live = true;
const today = malaysiaToday(); const today = malaysiaToday();
listAdminEvents({ enabled: "Y", page: 1, pageSize: 100, sortBy: "name", sortDir: "asc", companyId: eventsCompany }) listAdminEvents({ enabled: "Y", page: 1, pageSize: 100, sortBy: "name", sortDir: "asc", companyId: eventsCompany })
.then((r) => { if (live) setEvents(r.items.filter((e) => !e.endDate || e.endDate >= today).map((e) => ({ uuid: e.uuid, name: e.name }))); }) .then((r) => { if (live) setEvents(r.items.filter((e) => !e.endDate || e.endDate >= today).map((e) => ({ uuid: e.uuid, name: e.name, ticketsEnabled: e.ticketsEnabled }))); })
.catch(() => {}); // the picker stays empty; a saved event still shows as unavailable .catch(() => {}); // the picker stays empty; a saved event still shows as unavailable
return () => { live = false; }; return () => { live = false; };
}, [isSuper, eventsCompany]); }, [isSuper, eventsCompany]);
@@ -193,14 +193,14 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
}; };
/** /**
* A super admin's new page changes company: FORM blocks and hero sign-up forms lose their event, which belongs to the old one, * A super admin's new page changes company: FORM blocks and hero sign-up forms lose their event, which belongs to the old one,
* and a hero's form heading and text go with its form (add-hero-full-width). * and a hero's form heading, form text and thank-you text go with its form (add-hero-full-width, add-landing-thanks-and-footer).
*/ */
const changeCompany = (companyId: number) => { const changeCompany = (companyId: number) => {
step(null); step(null);
setDraft((d) => ({ ...d, companyId })); setDraft((d) => ({ ...d, companyId }));
setRows((rs) => rs.map((r) => { setRows((rs) => rs.map((r) => {
if (!r.block.eventUuid) return r; if (!r.block.eventUuid) return r;
const { formHeading: _h, formText: _t, ...block } = r.block; const { formHeading: _h, formText: _t, thanksText: _k, ...block } = r.block;
return { ...r, block: { ...block, eventUuid: null } }; return { ...r, block: { ...block, eventUuid: null } };
})); }));
}; };
@@ -0,0 +1,63 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { RegistrationForm } from "./RegistrationForm";
// add-compact-landing-form: landing pages use a short form; QR, invitation and customer forms keep the full one.
const info = {
eventName: "INS enquiries", startDate: "2026-12-01", endDate: "2099-12-31", location: "KL", companyName: "INS",
notice: { id: 1, textEn: "English text", textMs: "Teks Melayu" },
interests: [{ id: 11, name: "WiFi Managed Services" }, { id: 12, name: "Cloud IP PABX" }],
};
const base = { info, onDone: () => {}, onInactive: () => {} };
describe("RegistrationForm compact", () => {
it("has no job title, one service dropdown, and the notice folded above the consent box", async () => {
const user = userEvent.setup();
render(<RegistrationForm {...base} submit={async () => undefined} compact />);
expect(screen.queryByLabelText("Job title")).not.toBeInTheDocument();
expect(screen.queryByRole("checkbox", { name: "WiFi Managed Services" })).not.toBeInTheDocument();
const service = screen.getByRole("combobox", { name: "Service interested in (optional)" });
expect(service).toHaveValue("");
expect(screen.getByRole("option", { name: "Choose a service" })).toBeInTheDocument();
const notice = screen.getByText("English text").closest("details")!;
expect(notice).not.toHaveAttribute("open");
await user.click(screen.getByText("How we use your details (English / Bahasa Malaysia)"));
expect(notice).toHaveAttribute("open");
expect(notice.compareDocumentPosition(screen.getByRole("checkbox")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("posts the one chosen service", async () => {
const submit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<RegistrationForm {...base} submit={submit} compact />);
await user.type(screen.getByLabelText("Your name"), "Tan");
await user.type(screen.getByLabelText("Mobile number"), "0125550101");
await user.selectOptions(screen.getByRole("combobox", { name: "Service interested in (optional)" }), "12");
await user.click(screen.getByRole("checkbox"));
await user.click(screen.getByRole("button", { name: "Register" }));
expect(submit.mock.calls[0][0]).toMatchObject({ interestIds: [12], jobTitle: "" });
});
it("keeps the full form without the option", () => {
render(<RegistrationForm {...base} submit={async () => undefined} />);
expect(screen.getByLabelText("Job title")).toBeInTheDocument();
expect(screen.getByRole("checkbox", { name: "WiFi Managed Services" })).toBeInTheDocument();
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
expect(screen.getByText("English text").closest("details")).toBeNull();
});
// add-hero-fits-screen: tighter spacing, but controls stay 44 px (h-11) for touch.
it("is tighter than the full form, with the consent in small text and 44 px controls", () => {
const { container, unmount } = render(<RegistrationForm {...base} submit={async () => undefined} compact />);
expect(container.querySelector("form")).toHaveClass("space-y-3");
expect(screen.getByText(/I agree to INS/).parentElement).toHaveClass("text-sm");
for (const el of [screen.getByLabelText("Your name"), screen.getByLabelText("Mobile number"), screen.getByRole("combobox"), screen.getByRole("button", { name: "Register" })]) {
expect(el).toHaveClass("h-11");
}
unmount();
const full = render(<RegistrationForm {...base} submit={async () => undefined} />);
expect(full.container.querySelector("form")).toHaveClass("space-y-4");
expect(screen.getByText(/I agree to INS/).parentElement).not.toHaveClass("text-sm");
});
});
@@ -15,6 +15,7 @@ const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"]
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3"; const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
const CONSENT_ROW = "flex min-h-11 w-full cursor-pointer items-start gap-3 rounded-md border p-3 leading-normal"; const CONSENT_ROW = "flex min-h-11 w-full cursor-pointer items-start gap-3 rounded-md border p-3 leading-normal";
const BOX = "size-6"; const BOX = "size-6";
const NOTICE = "rounded-md bg-muted p-3 text-xs text-muted-foreground";
export function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } { export function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
if (!(err instanceof ApiError)) return {}; if (!(err instanceof ApiError)) return {};
@@ -40,11 +41,13 @@ interface Props {
onDone: () => void; onDone: () => void;
/** The code or invitation was switched off: the page shows its own message. */ /** The code or invitation was switched off: the page shows its own message. */
onInactive: () => void; onInactive: () => void;
/** add-compact-landing-form: a landing page's short form: no job title, one service dropdown, the notice folded; tighter spacing (add-hero-fits-screen). */
compact?: boolean;
} }
// The visitor registration form shared by /r, /i and /c: fields, bilingual privacy notice and consent. // The visitor registration form shared by /r, /i and /c: fields, bilingual privacy notice and consent.
// The event header comes from the VisitorCard around it. // The event header comes from the VisitorCard around it.
export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, onInactive }: Props) { export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, onInactive, compact }: Props) {
const t = useT(); const t = useT();
const [form, setForm] = useState<RegistrationBody>({ ...EMPTY, ...initial }); const [form, setForm] = useState<RegistrationBody>({ ...EMPTY, ...initial });
const [errors, setErrors] = useState<Record<string, string>>({}); const [errors, setErrors] = useState<Record<string, string>>({});
@@ -94,39 +97,62 @@ export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, on
); );
}; };
const interestBoxes = (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
{info.interests.map((i) => (
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
<Checkbox
className={BOX}
id={`reg-interest-${i.id}`}
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
);
// add-compact-landing-form: a landing page asks for at most one service.
const serviceDropdown = (
<div className="space-y-1.5">
<Label htmlFor="reg-service">{t("RegServiceInterest")}</Label>
<select id="reg-service" className="flex h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm disabled:opacity-50"
value={form.interestIds[0] ?? ""} disabled={saving} onChange={(e) => set({ interestIds: e.target.value ? [Number(e.target.value)] : [] })}>
<option value="">{t("RegChooseService")}</option>
{info.interests.map((i) => <option key={i.id} value={i.id}>{i.name}</option>)}
</select>
</div>
);
const notice = (
<>
<h2 className="font-semibold text-foreground">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-semibold text-foreground">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</>
);
return ( return (
<form onSubmit={onSubmit} className="space-y-4" noValidate> <form onSubmit={onSubmit} className={compact ? "space-y-3" : "space-y-4"} noValidate>
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>} {formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
{field("name", t("RegName"))} {field("name", t("RegName"))}
{field("mobile", t("RegMobile"), "tel", t("RegContactHint"))} {field("mobile", t("RegMobile"), "tel", t("RegContactHint"))}
{field("email", t("RegEmail"), "email")} {field("email", t("RegEmail"), "email")}
{field("companyName", t("RegCompany"))} {field("companyName", t("RegCompany"))}
{field("jobTitle", t("RegJobTitle"))} {compact ? null : field("jobTitle", t("RegJobTitle"))}
{info.interests.length > 0 && ( {info.interests.length > 0 && (compact ? serviceDropdown : interestBoxes)}
<fieldset className="space-y-2"> {compact ? (
<legend className="text-sm font-medium">{t("RegInterests")}</legend> <details className={NOTICE}>
{info.interests.map((i) => ( <summary className="cursor-pointer font-medium text-foreground">{t("RegNoticeSummary")}</summary>
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}> <div className="mt-2 space-y-2">{notice}</div>
<Checkbox </details>
className={BOX} ) : (
id={`reg-interest-${i.id}`} <div className={`space-y-2 ${NOTICE}`}>{notice}</div>
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
)} )}
<div className="space-y-2 rounded-md bg-muted p-3 text-xs text-muted-foreground">
<h2 className="font-semibold text-foreground">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-semibold text-foreground">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
<Label htmlFor="reg-consent" className={CONSENT_ROW}> <Label htmlFor="reg-consent" className={CONSENT_ROW}>
<Checkbox id="reg-consent" className={`${BOX} mt-0.5`} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} /> <Checkbox id="reg-consent" className={`${BOX} mt-0.5`} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
<span className="space-y-1 font-normal"> <span className={`space-y-1 font-normal ${compact ? "text-sm" : ""}`}>
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span> <span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span> <span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
</span> </span>
@@ -34,7 +34,7 @@ export function VisitorCard({ event, title, children }: { event?: EventHeader; t
interface StateProps { interface StateProps {
icon: LucideIcon; icon: LucideIcon;
heading: string; heading: string;
text?: string; text?: ReactNode;
action?: ReactNode; action?: ReactNode;
role?: "status" | "alert"; role?: "status" | "alert";
tone?: "default" | "error"; tone?: "default" | "error";
@@ -52,7 +52,7 @@ export function VisitorState({ icon: Icon, heading, text, action, role, tone = "
<Icon className={`size-6 ${iconClassName ?? ""}`} aria-hidden="true" /> <Icon className={`size-6 ${iconClassName ?? ""}`} aria-hidden="true" />
</span> </span>
<Heading className="text-lg font-semibold text-balance">{heading}</Heading> <Heading className="text-lg font-semibold text-balance">{heading}</Heading>
{text && <p className="text-sm text-muted-foreground">{text}</p>} {text && <p className="text-sm text-muted-foreground [&_a]:font-medium [&_a]:text-primary [&_a]:underline">{text}</p>}
{action} {action}
</div> </div>
); );
@@ -0,0 +1,99 @@
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(),
markOrderPaid: vi.fn(),
cancelOrder: vi.fn(),
cancelTicket: vi.fn(),
resendOrderEmail: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminTickets", async (orig) => ({ ...(await orig<object>()), ...mocks }));
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: "+60125550101",
buyerCompany: "Hotel Seri", totalSen: 75000, holdUntil: "2026-12-07T10:00:00", paidAt: null, paidBy: null, paymentRef: null,
cancelledAt: null, cancelledBy: null, expiredAt: null, createdAt: "2026-12-04T10:00:00",
},
lines: [{ id: 400, name: "General", unitPriceSen: 25000, quantity: 3 }],
tickets: [1, 2, 3].map((id) => ({ id, typeName: "General", status: "ACTIVE", cancelledAt: null, cancelledBy: null })),
});
const refused = (code: string) => new ApiError(code, 409, { error: code, code });
beforeEach(() => {
for (const m of [mocks.markOrderPaid, mocks.cancelOrder, mocks.cancelTicket, mocks.resendOrderEmail]) m.mockReset().mockResolvedValue({});
mocks.getOrder.mockReset().mockResolvedValue(detail("AWAITING"));
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" || m === "BO_EVENT_TICKETS" });
});
describe("OrderPage", () => {
it("shows the lines, tickets and buyer", async () => {
render(<OrderPage />);
expect(await screen.findByRole("heading", { name: /T-7K3M9Q/ })).toBeInTheDocument();
expect(screen.getByText("RM 750.00")).toBeInTheDocument();
expect(screen.getByText("a@example.test")).toBeInTheDocument();
expect(screen.getByText("+60125550101")).toBeInTheDocument();
expect(screen.getAllByRole("row", { name: /General/ }).length).toBeGreaterThanOrEqual(3);
});
it("marks the order paid with a reference", async () => {
const user = userEvent.setup();
render(<OrderPage />);
await user.type(await screen.findByLabelText("Payment reference"), "MBB 0412 883");
await user.click(screen.getByRole("button", { name: "Mark paid" }));
await waitFor(() => expect(mocks.markOrderPaid).toHaveBeenCalledWith("evt-9", "300", "MBB 0412 883"));
expect(mocks.getOrder).toHaveBeenCalledTimes(2);
});
it("explains when an expired order's seats are gone", async () => {
const user = userEvent.setup();
mocks.getOrder.mockResolvedValue(detail("EXPIRED"));
mocks.markOrderPaid.mockRejectedValueOnce(refused("SEATS_GONE"));
render(<OrderPage />);
await user.click(await screen.findByRole("button", { name: "Mark paid" }));
expect(await screen.findByText("The seats of this expired order were taken. It cannot be marked paid.")).toBeInTheDocument();
});
it("cancels the order after a confirm", async () => {
const user = userEvent.setup();
render(<OrderPage />);
await user.click(await screen.findByRole("button", { name: "Cancel order" }));
expect(mocks.cancelOrder).not.toHaveBeenCalled();
await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Cancel order" }));
await waitFor(() => expect(mocks.cancelOrder).toHaveBeenCalledWith("evt-9", "300"));
});
it("cancels one ticket after a confirm and shows the last-ticket refusal", async () => {
const user = userEvent.setup();
mocks.cancelTicket.mockRejectedValueOnce(refused("LAST_TICKET"));
render(<OrderPage />);
const buttons = await screen.findAllByRole("button", { name: "Cancel ticket" });
await user.click(buttons[1]);
await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Cancel ticket" }));
await waitFor(() => expect(mocks.cancelTicket).toHaveBeenCalledWith("evt-9", "300", 2));
expect(await screen.findByText("This is the order's last ticket. Cancel the order instead.")).toBeInTheDocument();
});
it("resends the latest email", async () => {
const user = userEvent.setup();
render(<OrderPage />);
await user.click(await screen.findByRole("button", { name: "Resend email" }));
await waitFor(() => expect(mocks.resendOrderEmail).toHaveBeenCalledWith("evt-9", "300"));
expect(await screen.findByText("Email sent again.")).toBeInTheDocument();
});
it("offers no actions on a cancelled order", async () => {
mocks.getOrder.mockResolvedValue(detail("CANCELLED"));
render(<OrderPage />);
await screen.findByText("Cancelled");
for (const name of ["Mark paid", "Cancel order", "Cancel ticket"]) expect(screen.queryByRole("button", { name })).toBeNull();
});
});
@@ -0,0 +1,202 @@
"use client";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { OrderStatusBadge } from "@/app/components/events/OrderStatusBadge";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import { RequireModule } from "@/app/lib/RequireModule";
import { ApiError } from "@/app/lib/clientApi";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import {
TICKET_ERRORS,
cancelOrder,
cancelTicket,
getOrder,
markOrderPaid,
money,
resendOrderEmail,
type OrderDetail,
} from "@/app/lib/services/adminTickets";
const when = (s: string | null) => (s ? s.replace("T", " ").slice(0, 16) : "-");
function OrderContent() {
const t = useT();
const { uuid, orderId } = useParams<{ uuid: string; orderId: string }>();
const [d, setD] = useState<OrderDetail | null>(null);
const [notFound, setNotFound] = useState(false);
const [loadError, setLoadError] = useState(false);
const [paymentRef, setPaymentRef] = useState("");
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [confirm, setConfirm] = useState<{ ticketId?: number } | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
try {
setD(await getOrder(uuid, orderId));
setLoadError(false);
} catch (err) {
if (err instanceof ApiError && err.status === 404) setNotFound(true);
else setLoadError(true);
}
}, [uuid, orderId]);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- load() fetches from the API; its setState runs after the await.
load();
}, [load]);
async function run(action: () => Promise<void>, done?: string) {
setError(null);
setNotice(null);
setBusy(true);
try {
await action();
if (done) setNotice(t(done));
await load();
} catch (err) {
const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined;
setError(t(code && TICKET_ERRORS[code] ? TICKET_ERRORS[code] : "TktActionFailed"));
} finally {
setBusy(false);
}
}
const doConfirm = () => {
const c = confirm;
setConfirm(null);
if (!c) return;
return c.ticketId == null ? run(() => cancelOrder(uuid, orderId).then(() => {}), "TktOrderCancelled")
: run(() => cancelTicket(uuid, orderId, c.ticketId!).then(() => {}), "TktTicketCancelled");
};
const back = (
<Button asChild variant="outline" size="sm">
<Link href={`/events/${encodeURIComponent(uuid)}/orders`}>{t("TktBackToOrders")}</Link>
</Button>
);
if (notFound) return (<><PageHeader title={t("TktOrderTitle")} actions={back} /><EmptyState title={t("TktOrderNotFound")} /></>);
if (loadError) return (<><PageHeader title={t("TktOrderTitle")} actions={back} /><ErrorState message={t("TktLoadFailed")} onRetry={load} /></>);
if (!d) return <PageHeader title={t("TktOrderTitle")} actions={back} />;
const o = d.order;
const open = o.status === "AWAITING" || o.status === "PAID";
const payable = o.status === "AWAITING" || o.status === "EXPIRED";
const facts: [string, string | null][] = [
[t("TktBuyer"), o.buyerName],
[t("Email"), o.buyerEmail],
[t("LeadMobile"), o.buyerMobileE164],
[t("Company"), o.buyerCompany],
[t("TktCreated"), when(o.createdAt)],
[t("TktHoldUntil"), o.status === "AWAITING" ? when(o.holdUntil) : null],
[t("TktPaymentRef"), o.paymentRef],
[t("TktPaidBy"), o.paidAt ? `${o.paidBy ?? "-"}, ${when(o.paidAt)}` : null],
[t("TktCancelledBy"), o.cancelledAt ? `${o.cancelledBy ?? "-"}, ${when(o.cancelledAt)}` : null],
[t("TktExpiredAt"), o.expiredAt ? when(o.expiredAt) : null],
];
return (
<div className="space-y-4">
<PageHeader title={t("TktOrderNamed", { reference: o.reference })} actions={back} />
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2">
<CardTitle className="flex items-center gap-2">
<OrderStatusBadge status={o.status} /> <span>{money(o.totalSen)}</span>
</CardTitle>
<Button type="button" variant="outline" size="sm" disabled={busy} onClick={() => run(() => resendOrderEmail(uuid, orderId).then(() => {}), "TktEmailResent")}>
{t("TktResend")}
</Button>
</CardHeader>
<CardContent className="space-y-4">
<dl className="grid gap-x-6 gap-y-2 sm:grid-cols-2">
{facts.filter(([, v]) => v).map(([k, v]) => (
<div key={k}>
<dt className="text-xs text-muted-foreground">{k}</dt>
<dd>{v}</dd>
</div>
))}
</dl>
{payable && (
<div className="flex flex-wrap items-end gap-2">
<div className="space-y-1">
<Label htmlFor="payment-ref">{t("TktPaymentRef")}</Label>
<Input id="payment-ref" maxLength={100} value={paymentRef} onChange={(e) => setPaymentRef(e.target.value)} />
</div>
<Button type="button" disabled={busy} onClick={() => run(() => markOrderPaid(uuid, orderId, paymentRef).then(() => {}), "TktMarkedPaid")}>
{t("TktMarkPaid")}
</Button>
</div>
)}
{open && (
<Button type="button" variant="destructive" disabled={busy} onClick={() => setConfirm({})}>
{t("TktCancelOrder")}
</Button>
)}
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle>{t("TktTickets")}</CardTitle></CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("TktTicketType")}</TableHead>
<TableHead>{t("Status")}</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{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 className="text-right">
{open && x.status === "ACTIVE" && (
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => setConfirm({ ticketId: x.id })}>
{t("TktCancelTicket")}
</Button>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
{confirm && (
<ConfirmDialog
title={t(confirm.ticketId == null ? "TktCancelOrder" : "TktCancelTicket")}
message={t(confirm.ticketId == null ? "TktCancelOrderMessage" : "TktCancelTicketMessage")}
confirmLabel={t(confirm.ticketId == null ? "TktCancelOrder" : "TktCancelTicket")}
destructive
busy={busy}
onConfirm={doConfirm}
onCancel={() => setConfirm(null)}
/>
)}
</div>
);
}
/** add-event-ticket-orders: one order with its tickets and the staff actions. */
export default function OrderPage() {
return (
<RequireModule pathname="/event-orders">
<OrderContent />
</RequireModule>
);
}
@@ -0,0 +1,47 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ listOrders: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/services/adminTickets", async (orig) => ({ ...(await orig<object>()), listOrders: mocks.listOrders }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", () => ({ useParams: () => ({ uuid: "evt-9" }) }));
import OrdersPage from "./page";
const ROW = { id: 300, reference: "T-7K3M9Q", buyerName: "Aisyah", buyerEmail: "a@example.test", tickets: 3, totalSen: 75000, status: "AWAITING", createdAt: "2026-12-04T10:00:00" };
beforeEach(() => {
mocks.listOrders.mockReset().mockResolvedValue({ content: [ROW], totalElements: 1, totalPages: 1, number: 0, size: 50 });
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" || m === "BO_EVENT_TICKETS" });
});
describe("OrdersPage", () => {
it("is not reachable without BO_EVENT_TICKETS", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" });
render(<OrdersPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(mocks.listOrders).not.toHaveBeenCalled();
});
it("lists the orders with a link to each", async () => {
render(<OrdersPage />);
const row = await screen.findByRole("row", { name: /T-7K3M9Q/ });
expect(within(row).getByText("Aisyah")).toBeInTheDocument();
expect(within(row).getByText("RM 750.00")).toBeInTheDocument();
expect(within(row).getByText("Awaiting payment")).toBeInTheDocument();
expect(within(row).getByRole("link", { name: "T-7K3M9Q" })).toHaveAttribute("href", "/events/evt-9/orders/300");
expect(mocks.listOrders).toHaveBeenCalledWith("evt-9", { status: "", q: "", page: 0 });
});
it("filters by state and searches", async () => {
const user = userEvent.setup();
render(<OrdersPage />);
await screen.findByText("T-7K3M9Q");
await user.click(screen.getByRole("combobox", { name: "Order state" }));
await user.click(await screen.findByRole("option", { name: "Paid" }));
await waitFor(() => expect(mocks.listOrders).toHaveBeenLastCalledWith("evt-9", { status: "PAID", q: "", page: 0 }));
await user.type(screen.getByRole("searchbox", { name: "Search orders" }), "aisyah");
await waitFor(() => expect(mocks.listOrders).toHaveBeenLastCalledWith("evt-9", { status: "PAID", q: "aisyah", page: 0 }));
});
});
@@ -0,0 +1,117 @@
"use client";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { OrderStatusBadge } from "@/app/components/events/OrderStatusBadge";
import { Button } from "@/app/components/ui/button";
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
import { PageHeader } from "@/app/components/ui/page-header";
import { ErrorState } from "@/app/components/ui/states";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import { TablePager } from "@/app/components/ui/table-pager";
import { RequireModule } from "@/app/lib/RequireModule";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { ORDER_STATUSES, listOrders, money, type OrderPage } from "@/app/lib/services/adminTickets";
const PAGE_SIZE = 50;
function OrdersContent() {
const t = useT();
const { uuid } = useParams<{ uuid: string }>();
const [status, setStatus] = useState("");
const [q, setQ] = useState("");
const [page, setPage] = useState(0);
const [data, setData] = useState<OrderPage | null>(null);
const [error, setError] = useState(false);
const load = useCallback(async () => {
try {
setData(await listOrders(uuid, { status, q, page }));
setError(false);
} catch {
setError(true);
}
}, [uuid, status, q, page]);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- load() fetches from the API; its setState runs after the await.
load();
}, [load]);
const base = `/events/${encodeURIComponent(uuid)}`;
return (
<div className="space-y-4">
<PageHeader
title={t("TktOrdersTitle")}
actions={
<Button asChild variant="outline" size="sm">
<Link href={base}>{t("TktBackToEvent")}</Link>
</Button>
}
/>
<FilterPanel activeCount={(status ? 1 : 0) + (q ? 1 : 0)} onClear={() => { setStatus(""); setQ(""); setPage(0); }}>
<FilterField label={t("TktOrderState")}>
<FilterSelect
aria-label={t("TktOrderState")}
allLabel={t("AllStatuses")}
options={ORDER_STATUSES.map((s) => ({ value: s, label: t(`TktStatus${s}`) }))}
value={status}
onChange={(v) => { setStatus(v); setPage(0); }}
/>
</FilterField>
<FilterField label={t("TktSearchOrders")}>
<FilterSearch aria-label={t("TktSearchOrders")} placeholder={t("TktSearchOrdersHint")} value={q} onChange={(v) => { setQ(v); setPage(0); }} />
</FilterField>
</FilterPanel>
{error && <ErrorState message={t("TktLoadFailed")} onRetry={load} />}
{data && (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("TktReference")}</TableHead>
<TableHead>{t("TktBuyer")}</TableHead>
<TableHead>{t("Email")}</TableHead>
<TableHead>{t("TktTickets")}</TableHead>
<TableHead>{t("TktTotal")}</TableHead>
<TableHead>{t("Status")}</TableHead>
<TableHead>{t("TktCreated")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.content.length === 0 && (
<TableRow>
<TableCell colSpan={7} className="text-muted-foreground">{t("TktNoOrders")}</TableCell>
</TableRow>
)}
{data.content.map((o) => (
<TableRow key={o.id}>
<TableCell>
<Link className="font-medium underline-offset-4 hover:underline" href={`${base}/orders/${o.id}`}>{o.reference}</Link>
</TableCell>
<TableCell>{o.buyerName}</TableCell>
<TableCell>{o.buyerEmail}</TableCell>
<TableCell>{o.tickets}</TableCell>
<TableCell>{money(o.totalSen)}</TableCell>
<TableCell><OrderStatusBadge status={o.status} /></TableCell>
<TableCell>{o.createdAt.replace("T", " ").slice(0, 16)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<TablePager page={page + 1} pageSize={PAGE_SIZE} total={data.totalElements} onPageChange={(p) => setPage(p - 1)} />
</>
)}
</div>
);
}
/** add-event-ticket-orders: an event's ticket orders, newest first, 50 a page. */
export default function OrdersPage() {
return (
<RequireModule pathname="/event-orders">
<OrdersContent />
</RequireModule>
);
}
@@ -8,6 +8,7 @@ import { Skeleton } from "@/app/components/ui/skeleton";
import { EmptyState, ErrorState } from "@/app/components/ui/states"; import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { GuestsCard } from "@/app/components/events/GuestsCard"; import { GuestsCard } from "@/app/components/events/GuestsCard";
import { RegistrationQrCard } from "@/app/components/events/RegistrationQrCard"; import { RegistrationQrCard } from "@/app/components/events/RegistrationQrCard";
import { TicketsCard } from "@/app/components/events/TicketsCard";
import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { RequireModule } from "@/app/lib/RequireModule"; import { RequireModule } from "@/app/lib/RequireModule";
import { ApiError } from "@/app/lib/clientApi"; import { ApiError } from "@/app/lib/clientApi";
@@ -123,6 +124,8 @@ function EditEventPageContent() {
<RegistrationQrCard eventUuid={event.uuid} eventName={event.name} canWrite={hasModule("BO_EVENTS")} /> <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} />
<TicketsCard eventUuid={event.uuid} />
</div> </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

+16 -3
View File
@@ -3,9 +3,9 @@
import { Calendar, Cloud, Headset, Lock, Monitor, Phone, ShieldCheck, Star, Tv, Users, Wifi, Wrench, type LucideIcon } from "lucide-react"; import { Calendar, Cloud, Headset, Lock, Monitor, Phone, ShieldCheck, Star, Tv, Users, Wifi, Wrench, type LucideIcon } from "lucide-react";
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM" | "HTML" | "FEATURES" | "STEPS" | "TRUST" | "CTA"; export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM" | "HTML" | "FEATURES" | "STEPS" | "TRUST" | "CTA" | "FOOTER" | "TOPBAR" | "TICKETS";
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FEATURES", "STEPS", "TRUST", "CTA", "FAQ", "FORM", "HTML"]; export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FEATURES", "STEPS", "TRUST", "CTA", "FAQ", "FORM", "TICKETS", "HTML", "FOOTER", "TOPBAR"];
/** Feature-card icons by the name services-counter accepts (add-page-sections). */ /** Feature-card icons by the name services-counter accepts (add-page-sections). */
export const ICONS: Record<string, LucideIcon> = { export const ICONS: Record<string, LucideIcon> = {
@@ -28,9 +28,12 @@ export const BLOCK_LABELS: Record<BlockType, string> = {
STEPS: "PagesBlockSteps", STEPS: "PagesBlockSteps",
TRUST: "PagesBlockTrust", TRUST: "PagesBlockTrust",
CTA: "PagesBlockCta", CTA: "PagesBlockCta",
FOOTER: "PagesBlockFooter",
TOPBAR: "PagesBlockTopBar",
TICKETS: "PagesBlockTickets",
}; };
/** A FEATURES (icon, title, text), STEPS (title, text) or TRUST (title) card; a HERO's points are title-only cards. */ /** A FEATURES (icon, title, text), STEPS (title, text) or TRUST (title) card; a HERO's points are title-only cards; a FOOTER's columns are title-and-text cards. */
export interface CmsCard { export interface CmsCard {
icon?: string; icon?: string;
title: string; title: string;
@@ -62,6 +65,10 @@ export interface CmsBlock {
fullWidth?: boolean; fullWidth?: boolean;
formHeading?: string; formHeading?: string;
formText?: string; formText?: string;
/** add-landing-thanks-and-footer: text (200) under the thank-you after a sign-up; FORM, or HERO with an event. */
thanksText?: string;
/** add-landing-page-polish: a short label (40) above the heading of FEATURES, STEPS, IMAGE_TEXT, FAQ and CTA. */
eyebrow?: string;
} }
export type PageStatus = "DRAFT" | "PUBLISHED"; export type PageStatus = "DRAFT" | "PUBLISHED";
@@ -122,6 +129,8 @@ export function emptyBlock(type: BlockType): CmsBlock {
return { type, imageId: null, heading: "", html: "", imagePosition: "LEFT", buttonLabel: "", buttonUrl: "" }; return { type, imageId: null, heading: "", html: "", imagePosition: "LEFT", buttonLabel: "", buttonUrl: "" };
case "FORM": case "FORM":
return { type, heading: "", eventUuid: null }; return { type, heading: "", eventUuid: null };
case "TICKETS":
return { type, heading: "", text: "", eventUuid: null };
case "HTML": case "HTML":
return { type, html: "" }; return { type, html: "" };
case "FEATURES": case "FEATURES":
@@ -132,6 +141,10 @@ export function emptyBlock(type: BlockType): CmsBlock {
return { type, cards: [{ title: "" }, { title: "" }] }; return { type, cards: [{ title: "" }, { title: "" }] };
case "CTA": case "CTA":
return { type, heading: "", text: "", buttonLabel: "", buttonUrl: "" }; return { type, heading: "", text: "", buttonLabel: "", buttonUrl: "" };
case "TOPBAR":
return { type, buttonLabel: "", buttonUrl: "" };
case "FOOTER":
return { type, look: "DARK", text: "", cards: [{ title: "", text: "" }, { title: "", text: "" }] };
default: default:
return { type }; return { type };
} }
@@ -0,0 +1,32 @@
import { render } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { contactLinks } from "./contactLinks";
// add-landing-thanks-and-footer: plain text with its phone numbers, emails and web addresses as links.
const links = (text: string) => {
const { container } = render(<p>{contactLinks(text)}</p>);
return { text: container.textContent, hrefs: Array.from(container.querySelectorAll("a")).map((a) => [a.textContent, a.getAttribute("href")]) };
};
describe("contactLinks", () => {
it("links + phone numbers, emails, https and www addresses, and keeps the rest", () => {
const text = "Call +60 12-833 2775 or +603-7623 9807, mail info@ins.my, see https://ins.my/a?b=1 or www.ins.my.";
const out = links(text);
expect(out.text).toBe(text);
expect(out.hrefs).toEqual([
["+60 12-833 2775", "tel:+60128332775"],
["+603-7623 9807", "tel:+60376239807"],
["info@ins.my", "mailto:info@ins.my"],
["https://ins.my/a?b=1", "https://ins.my/a?b=1"],
["www.ins.my", "https://www.ins.my"],
]);
});
it("leaves short numbers, local numbers and dates alone", () => {
expect(links("03-7623 9807 on 2026-12-04, +60 12").hrefs).toEqual([]);
});
it("never makes javascript or http links", () => {
expect(links("javascript:alert(1) http://ins.my").hrefs).toEqual([]);
});
});
@@ -0,0 +1,21 @@
import type { ReactNode } from "react";
// add-landing-thanks-and-footer: + phone numbers (8+ digits), emails, and https:// or www. addresses in plain text become links.
// It builds elements, never HTML, so the text stays text.
const CONTACT = /(\+\d[\d -]{6,}\d)|([\w.+-]+@[\w-]+(?:\.[\w-]+)+)|((?:https:\/\/|www\.)[^\s<>"]*[^\s<>".,;:!?)])/g;
export function contactLinks(text: string): ReactNode[] {
const out: ReactNode[] = [];
let last = 0;
for (const m of text.matchAll(CONTACT)) {
const [whole, phone, email] = m;
if (phone && phone.replace(/\D/g, "").length < 8) continue;
out.push(text.slice(last, m.index));
const href = phone ? `tel:+${phone.replace(/\D/g, "")}` : email ? `mailto:${email}` : whole.startsWith("www.") ? `https://${whole}` : whole;
const external = !phone && !email;
out.push(<a key={m.index} href={href} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}>{whole}</a>);
last = m.index + whole.length;
}
out.push(text.slice(last));
return out;
}
@@ -568,6 +568,9 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
RegContactHint: "Mobile or email is required", RegContactHint: "Mobile or email is required",
RegCompany: "Company", RegCompany: "Company",
RegJobTitle: "Job title", RegJobTitle: "Job title",
RegServiceInterest: "Service interested in (optional)",
RegChooseService: "Choose a service",
RegNoticeSummary: "How we use your details (English / Bahasa Malaysia)",
RegInterests: "Interests (optional)", RegInterests: "Interests (optional)",
RegNoticeEn: "English", RegNoticeEn: "English",
RegNoticeMs: "Bahasa Malaysia", RegNoticeMs: "Bahasa Malaysia",
@@ -875,6 +878,14 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesAddPoint: "Add point", PagesAddPoint: "Add point",
PagesFormHeading: "Form heading", PagesFormHeading: "Form heading",
PagesFormText: "Form text", PagesFormText: "Form text",
PagesThanksText: "Thank-you text",
PagesBlockFooter: "Footer",
PagesColumnN: "Column {number}",
PagesAddColumn: "Add column",
PagesFooterLegal: "Legal line",
PagesBlockTopBar: "Top bar",
PagesEyebrow: "Label",
PagesTopBarFirst: "The top bar must be the first section.",
PagesUploadImage: "Upload image", PagesUploadImage: "Upload image",
PagesUploadImageHint: "PNG, JPEG or WebP up to 2 MB. Paste the link into your HTML, for example in an img tag's src.", PagesUploadImageHint: "PNG, JPEG or WebP up to 2 MB. Paste the link into your HTML, for example in an img tag's src.",
PagesToolbar: "Formatting", PagesToolbar: "Formatting",
@@ -925,4 +936,114 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
CompAccent: "Accent colour", CompAccent: "Accent colour",
CompAccentHint: "Used for buttons on this company's landing pages. Leave empty for the default blue.", CompAccentHint: "Used for buttons on this company's landing pages. Leave empty for the default blue.",
CompBrandingSaveFailed: "Could not save the branding.", CompBrandingSaveFailed: "Could not save the branding.",
// add-event-ticket-orders
GuestHeldTickets: "Held tickets",
PagesTicketsClosed: "Choose an event that is selling tickets.",
TktTitle: "Tickets",
TktViewOrders: "View orders",
TktLoadFailed: "Could not load the tickets.",
TktSaveFailed: "Could not save. Try again.",
TktSettingsSaved: "Ticket settings saved.",
TktSellTickets: "Sell tickets",
TktPaymentInstructions: "Payment instructions",
TktPaymentInstructionsHelp: "Shown to buyers after they request tickets, e.g. the bank account and what reference to use.",
TktHoldDays: "Hold days",
TktSaveSettings: "Save ticket settings",
TktPrice: "Price",
TktPriceRm: "Price (RM)",
TktQuantity: "Quantity",
TktLeft: "Left",
TktSalesEnd: "Sales end",
TktSalesEndHelp: "An empty sales end date means sales end with the event.",
TktNoTypes: "No ticket types yet.",
TktFree: "Free",
TktDisable: "Disable",
TktEnable: "Enable",
TktDelete: "Delete",
TktTypeName: "Ticket name",
TktAddType: "Add ticket type",
TktSaveType: "Save ticket type",
TktDeleteTitle: "Delete ticket type",
TktDeleteMessage: "Delete {name}? This cannot be undone.",
TktErrInstructionsRequired: "Enter the payment instructions before turning tickets on.",
TktErrInstructionsTooLong: "Payment instructions can be at most 1000 characters.",
TktErrHoldDays: "Hold days must be from 1 to 14.",
TktErrName: "Enter a name of 1 to 80 characters.",
TktErrNameTaken: "This event already has a ticket type with this name.",
TktErrPrice: "Enter a price from 0.00 to 99999.99.",
TktErrQuantity: "Enter a quantity of at least 1.",
TktErrQuantityBelowHeld: "The quantity cannot be below the seats already held.",
TktErrDate: "Enter a valid date.",
TktErrTypeHasOrders: "This ticket type has orders. Disable it instead.",
TktErrNotPayable: "Only an order awaiting payment or expired can be marked paid.",
TktErrSeatsGone: "The seats of this expired order were taken. It cannot be marked paid.",
TktErrPaymentRef: "The payment reference can be at most 100 characters.",
TktErrNotCancellable: "Only an order awaiting payment or paid can be cancelled.",
TktErrLastTicket: "This is the order's last ticket. Cancel the order instead.",
TktStatusAWAITING: "Awaiting payment",
TktStatusPAID: "Paid",
TktStatusCANCELLED: "Cancelled",
TktStatusEXPIRED: "Expired",
TktOrdersTitle: "Ticket orders",
TktBackToEvent: "Back to event",
TktOrderState: "Order state",
TktSearchOrders: "Search orders",
TktSearchOrdersHint: "Reference, name, email or mobile",
TktReference: "Reference",
TktBuyer: "Buyer",
TktTickets: "Tickets",
TktTotal: "Total",
TktSalesEnded: "Sales ended",
TktSeatsLeft: "{count} left",
TktSoldOut: "Sold out",
TktRemoveOne: "Remove one {name}",
TktAddOne: "Add one {name}",
TktPreviewNote: "Visitors choose tickets and fill in their details here.",
TktSalesClosed: "Ticket sales are closed.",
TktChooseTickets: "Choose at least one ticket.",
TktEmailRequired: "Enter your email.",
TktConsentRequired: "Tick the box to agree to the privacy notice.",
TktMax: "Up to 10 tickets per order.",
TktRequest: "Request tickets",
TktThanksPlain: "Thank you. Your request for {event} is in.",
TktThanksPaid: "Your order {reference} is confirmed.",
TktThanks: "We have your order {reference}. It is held until you pay.",
TktViewOrder: "View your order",
TktHowToPay: "How to pay",
TktPayBy: "Pay by {when}",
TktPublicOrder: "Order {reference}",
TktPublicAwaiting: "Awaiting payment",
TktPublicPaid: "Paid. Your order is confirmed.",
TktPublicCancelled: "This order was cancelled.",
TktPublicExpired: "This order expired before payment arrived.",
TktOrderInvalid: "This order link is not valid.",
PagesBlockTickets: "Tickets",
PagesTicketsEvent: "Event selling tickets",
PagesChooseTicketsEvent: "Choose an event with tickets on",
PagesTicketsEventHint: "Only events with tickets switched on are listed.",
TktCreated: "Created",
TktNoOrders: "No orders yet.",
TktOrderTitle: "Ticket order",
TktOrderNamed: "Order {reference}",
TktOrderNotFound: "Order not found.",
TktBackToOrders: "Back to orders",
TktActionFailed: "The action failed. Try again.",
TktHoldUntil: "Held until",
TktPaymentRef: "Payment reference",
TktPaidBy: "Marked paid by",
TktCancelledBy: "Cancelled by",
TktExpiredAt: "Expired",
TktResend: "Resend email",
TktEmailResent: "Email sent again.",
TktMarkPaid: "Mark paid",
TktMarkedPaid: "Order marked paid.",
TktCancelOrder: "Cancel order",
TktCancelOrderMessage: "Cancel this order and free its seats? The buyer gets an email.",
TktOrderCancelled: "Order cancelled.",
TktCancelTicket: "Cancel ticket",
TktCancelTicketMessage: "Cancel this ticket, free its seat and lower the order total?",
TktTicketCancelled: "Ticket cancelled.",
TktTicketType: "Ticket type",
TktTicketActive: "Active",
TktTicketCancelledBy: "Cancelled by {by}, {at}",
}; };
@@ -552,6 +552,9 @@
"RegContactHint": "手机或电子邮件为必填项", "RegContactHint": "手机或电子邮件为必填项",
"RegCompany": "公司", "RegCompany": "公司",
"RegJobTitle": "职位", "RegJobTitle": "职位",
"RegServiceInterest": "感兴趣的服务(可选)",
"RegChooseService": "选择服务",
"RegNoticeSummary": "我们如何使用您的资料(English / Bahasa Malaysia)",
"RegInterests": "兴趣(可选)", "RegInterests": "兴趣(可选)",
"RegNoticeEn": "英文", "RegNoticeEn": "英文",
"RegNoticeMs": "马来文", "RegNoticeMs": "马来文",
@@ -860,6 +863,14 @@
"PagesAddPoint": "添加要点", "PagesAddPoint": "添加要点",
"PagesFormHeading": "表单标题", "PagesFormHeading": "表单标题",
"PagesFormText": "表单说明", "PagesFormText": "表单说明",
"PagesThanksText": "感谢语",
"PagesBlockFooter": "页脚",
"PagesColumnN": "第 {number} 栏",
"PagesAddColumn": "添加栏",
"PagesFooterLegal": "版权声明",
"PagesBlockTopBar": "顶栏",
"PagesEyebrow": "小标签",
"PagesTopBarFirst": "顶栏必须是第一个区块。",
"PagesUploadImage": "上传图片", "PagesUploadImage": "上传图片",
"PagesUploadImageHint": "PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。", "PagesUploadImageHint": "PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。",
"PagesToolbar": "格式", "PagesToolbar": "格式",
@@ -908,5 +919,114 @@
"CompLogo": "标志", "CompLogo": "标志",
"CompAccent": "主题色", "CompAccent": "主题色",
"CompAccentHint": "用于本公司网页的按钮。留空则使用默认蓝色。", "CompAccentHint": "用于本公司网页的按钮。留空则使用默认蓝色。",
"CompBrandingSaveFailed": "无法保存品牌设置。" "CompBrandingSaveFailed": "无法保存品牌设置。",
"GuestHeldTickets": "已占门票",
"PagesTicketsClosed": "请选择正在售票的活动。",
"TktTitle": "门票",
"TktViewOrders": "查看订单",
"TktLoadFailed": "无法加载门票。",
"TktSaveFailed": "无法保存,请重试。",
"TktSettingsSaved": "门票设置已保存。",
"TktSellTickets": "售卖门票",
"TktPaymentInstructions": "付款说明",
"TktPaymentInstructionsHelp": "买家申请门票后显示,例如银行账户及付款备注。",
"TktHoldDays": "保留天数",
"TktSaveSettings": "保存门票设置",
"TktPrice": "价格",
"TktPriceRm": "价格(RM)",
"TktQuantity": "数量",
"TktLeft": "剩余",
"TktSalesEnd": "停售日期",
"TktSalesEndHelp": "停售日期留空表示随活动结束而停售。",
"TktNoTypes": "尚无门票类型。",
"TktFree": "免费",
"TktDisable": "停用",
"TktEnable": "启用",
"TktDelete": "删除",
"TktTypeName": "门票名称",
"TktAddType": "添加门票类型",
"TktSaveType": "保存门票类型",
"TktDeleteTitle": "删除门票类型",
"TktDeleteMessage": "删除 {name}?此操作无法撤销。",
"TktErrInstructionsRequired": "开启售票前请填写付款说明。",
"TktErrInstructionsTooLong": "付款说明最多 1000 个字符。",
"TktErrHoldDays": "保留天数须为 1 至 14。",
"TktErrName": "请输入 1 至 80 个字符的名称。",
"TktErrNameTaken": "本活动已有同名门票类型。",
"TktErrPrice": "请输入 0.00 至 99999.99 的价格。",
"TktErrQuantity": "数量至少为 1。",
"TktErrQuantityBelowHeld": "数量不能低于已占座位。",
"TktErrDate": "请输入有效日期。",
"TktErrTypeHasOrders": "此门票类型已有订单,请改为停用。",
"TktErrNotPayable": "只有待付款或已过期的订单可标记为已付款。",
"TktErrSeatsGone": "此过期订单的座位已被占用,无法标记为已付款。",
"TktErrPaymentRef": "付款参考最多 100 个字符。",
"TktErrNotCancellable": "只有待付款或已付款的订单可取消。",
"TktErrLastTicket": "这是订单的最后一张门票,请改为取消订单。",
"TktStatusAWAITING": "待付款",
"TktStatusPAID": "已付款",
"TktStatusCANCELLED": "已取消",
"TktStatusEXPIRED": "已过期",
"TktOrdersTitle": "门票订单",
"TktBackToEvent": "返回活动",
"TktOrderState": "订单状态",
"TktSearchOrders": "搜索订单",
"TktSearchOrdersHint": "编号、姓名、电邮或手机",
"TktReference": "编号",
"TktBuyer": "买家",
"TktTickets": "门票",
"TktTotal": "总额",
"TktSalesEnded": "已停售",
"TktSeatsLeft": "剩余 {count} 张",
"TktSoldOut": "已售罄",
"TktRemoveOne": "减少一张 {name}",
"TktAddOne": "增加一张 {name}",
"TktPreviewNote": "访客在此选择门票并填写资料。",
"TktSalesClosed": "门票销售已结束。",
"TktChooseTickets": "请至少选择一张门票。",
"TktEmailRequired": "请输入电子邮件。",
"TktConsentRequired": "请勾选以同意隐私声明。",
"TktMax": "每笔订单最多 10 张门票。",
"TktRequest": "申请门票",
"TktThanksPlain": "谢谢,您对 {event} 的申请已收到。",
"TktThanksPaid": "您的订单 {reference} 已确认。",
"TktThanks": "我们已收到您的订单 {reference},付款前为您保留。",
"TktViewOrder": "查看订单",
"TktHowToPay": "付款方式",
"TktPayBy": "请于 {when} 前付款",
"TktPublicOrder": "订单 {reference}",
"TktPublicAwaiting": "等待付款",
"TktPublicPaid": "已付款,订单已确认。",
"TktPublicCancelled": "此订单已取消。",
"TktPublicExpired": "此订单在收到付款前已过期。",
"TktOrderInvalid": "此订单链接无效。",
"PagesBlockTickets": "门票",
"PagesTicketsEvent": "售票活动",
"PagesChooseTicketsEvent": "选择已开启售票的活动",
"PagesTicketsEventHint": "仅列出已开启售票的活动。",
"TktCreated": "创建时间",
"TktNoOrders": "尚无订单。",
"TktOrderTitle": "门票订单",
"TktOrderNamed": "订单 {reference}",
"TktOrderNotFound": "找不到订单。",
"TktBackToOrders": "返回订单",
"TktActionFailed": "操作失败,请重试。",
"TktHoldUntil": "保留至",
"TktPaymentRef": "付款参考",
"TktPaidBy": "标记付款者",
"TktCancelledBy": "取消者",
"TktExpiredAt": "过期时间",
"TktResend": "重新发送电邮",
"TktEmailResent": "电邮已重新发送。",
"TktMarkPaid": "标记为已付款",
"TktMarkedPaid": "订单已标记为已付款。",
"TktCancelOrder": "取消订单",
"TktCancelOrderMessage": "取消此订单并释放座位?买家将收到电邮。",
"TktOrderCancelled": "订单已取消。",
"TktCancelTicket": "取消门票",
"TktCancelTicketMessage": "取消此门票、释放座位并降低订单总额?",
"TktTicketCancelled": "门票已取消。",
"TktTicketType": "门票类型",
"TktTicketActive": "有效",
"TktTicketCancelledBy": "{by} 于 {at} 取消"
} }
@@ -48,14 +48,14 @@ describe("guardDecision", () => {
}); });
}); });
describe("visitor pages /r, /i, /c", () => { describe("visitor pages /r, /i, /c, /o", () => {
it("pass signed out and with a reset pending; the bare prefixes and admin paths do not", () => { it("pass signed out and with a reset pending; the bare prefixes and admin paths do not", () => {
const pending = { present: true, resetRequired: true }; const pending = { present: true, resetRequired: true };
for (const p of ["/r/x", "/i/x", "/c/x"]) { for (const p of ["/r/x", "/i/x", "/c/x", "/o/x"]) {
expect(guardDecision(p, null), p).toBeNull(); expect(guardDecision(p, null), p).toBeNull();
expect(guardDecision(p, pending), p).toBeNull(); expect(guardDecision(p, pending), p).toBeNull();
} }
for (const p of ["/events", "/i", "/c/", "/i/", "/c/x/y"]) { for (const p of ["/events", "/i", "/c/", "/i/", "/c/x/y", "/o/", "/o/x/y"]) {
expect(guardDecision(p, null), p).toBe("/login"); expect(guardDecision(p, null), p).toBe("/login");
expect(guardDecision(p, pending), p).toBe("/reset-password"); expect(guardDecision(p, pending), p).toBe("/reset-password");
} }
+3 -2
View File
@@ -8,9 +8,10 @@
// resetPasswordRequired); it is reached right after login, so it stays public. // resetPasswordRequired); it is reached right after login, so it stays public.
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forgot-password"]); 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. // 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).
// (A pattern, so PUBLIC_PATHS stays exact.) // (A pattern, so PUBLIC_PATHS stays exact.)
const VISITOR_PATH = /^\/[ric]\/[^/]+$/; const VISITOR_PATH = /^\/[rico]\/[^/]+$/;
// Published landing pages: /p/<company-code>/<slug>. // Published landing pages: /p/<company-code>/<slug>.
const LANDING_PATH = /^\/p\/[^/]+\/[^/]+$/; const LANDING_PATH = /^\/p\/[^/]+\/[^/]+$/;
// add-custom-html-block: a published page's Custom HTML frame, /p/<company-code>/<slug>/frame/<block>. // add-custom-html-block: a published page's Custom HTML frame, /p/<company-code>/<slug>/frame/<block>.
@@ -8,13 +8,14 @@ describe("routeModules", () => {
expect(requiredModuleFor("/users")).toBe("BO_USERS"); expect(requiredModuleFor("/users")).toBe("BO_USERS");
expect(requiredModuleFor("/roles")).toBe("BO_ROLES"); expect(requiredModuleFor("/roles")).toBe("BO_ROLES");
expect(requiredModuleFor("/events")).toBe("BO_EVENTS"); expect(requiredModuleFor("/events")).toBe("BO_EVENTS");
expect(requiredModuleFor("/event-orders")).toBe("BO_EVENT_TICKETS");
expect(requiredModulesFor("/roles")).toEqual(["BO_ROLES"]); expect(requiredModulesFor("/roles")).toEqual(["BO_ROLES"]);
}); });
it("leaves other routes ungated", () => { it("leaves other routes ungated", () => {
expect(requiredModuleFor("/")).toBeUndefined(); expect(requiredModuleFor("/")).toBeUndefined();
expect(requiredModulesFor("/members")).toBeUndefined(); expect(requiredModulesFor("/members")).toBeUndefined();
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/events", "/interests", "/leads", "/locales", "/login-security", "/messages", "/pages", "/roles", "/users", "/whatsapp"]); expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/event-orders", "/events", "/interests", "/leads", "/locales", "/login-security", "/messages", "/pages", "/roles", "/users", "/whatsapp"]);
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS"); expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
expect(requiredModuleFor("/leads")).toBe("BO_LEADS"); expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
}); });
@@ -6,6 +6,8 @@ export const ROUTE_MODULES: Record<string, string> = {
"/users": "BO_USERS", "/users": "BO_USERS",
"/roles": "BO_ROLES", "/roles": "BO_ROLES",
"/events": "BO_EVENTS", "/events": "BO_EVENTS",
// add-event-ticket-orders: /events/[uuid]/orders and its order pages gate on this key.
"/event-orders": "BO_EVENT_TICKETS",
"/interests": "BO_INTERESTS", "/interests": "BO_INTERESTS",
"/event-leads": "BO_EVENT_LEADS", "/event-leads": "BO_EVENT_LEADS",
"/pages": "BO_PAGES", "/pages": "BO_PAGES",
@@ -39,6 +39,8 @@ export interface Attendance {
registered: number; registered: number;
attended: number; attended: number;
walkIns: number; walkIns: number;
/** add-event-ticket-orders: seats of awaiting and paid ticket orders; part of the total. */
heldTickets: number;
total: number; total: number;
capacity: number | null; capacity: number | null;
} }
@@ -0,0 +1,108 @@
import { apiDelete, apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
// add-event-ticket-orders: an event's ticket settings, ticket types and orders (BO_EVENT_TICKETS).
export interface TicketSettings {
ticketsEnabled: boolean;
paymentInstructions: string | null;
holdDays: number | null;
}
export interface TicketTypeInput {
name: string;
priceSen: number;
quantity: number;
salesEndDate: string | null;
sort: number;
enabled: boolean;
}
export interface TicketType extends TicketTypeInput {
id: number;
held: number;
left: number;
}
export type OrderStatus = "AWAITING" | "PAID" | "CANCELLED" | "EXPIRED";
export const ORDER_STATUSES: OrderStatus[] = ["AWAITING", "PAID", "CANCELLED", "EXPIRED"];
export interface OrderRow {
id: number;
reference: string;
buyerName: string;
buyerEmail: string;
tickets: number;
totalSen: number;
status: OrderStatus;
createdAt: string;
}
export interface OrderPage {
content: OrderRow[];
totalElements: number;
totalPages: number;
number: number;
size: number;
}
export interface OrderDetail {
order: {
id: number;
reference: string;
status: OrderStatus;
buyerName: string;
buyerEmail: string;
buyerMobileE164: string | null;
buyerCompany: string | null;
totalSen: number;
holdUntil: string | null;
paidAt: string | null;
paidBy: string | null;
paymentRef: string | null;
cancelledAt: string | null;
cancelledBy: string | null;
expiredAt: string | null;
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 }[];
}
const base = (uuid: string) => `/api/events/${encodeURIComponent(uuid)}`;
export const getTicketSettings = (uuid: string) => apiGet<TicketSettings>(`${base(uuid)}/tickets/settings`);
export const saveTicketSettings = (uuid: string, s: TicketSettings) => apiPut<unknown>(`${base(uuid)}/tickets/settings`, s);
export const listTicketTypes = (uuid: string) => apiGet<TicketType[]>(`${base(uuid)}/ticket-types`);
export const saveTicketType = (uuid: string, t: TicketTypeInput, id?: number) =>
id == null ? apiPost<unknown>(`${base(uuid)}/ticket-types`, t) : apiPut<unknown>(`${base(uuid)}/ticket-types/${id}`, t);
export const deleteTicketType = (uuid: string, id: number) => apiDelete<unknown>(`${base(uuid)}/ticket-types/${id}`);
export const listOrders = (uuid: string, f: { status?: string; q?: string; page?: number }) => {
const p = new URLSearchParams();
if (f.status) p.set("status", f.status);
if (f.q) p.set("q", f.q);
p.set("page", String(f.page ?? 0));
return apiGet<OrderPage>(`${base(uuid)}/orders?${p}`);
};
export const getOrder = (uuid: string, id: string) => apiGet<OrderDetail>(`${base(uuid)}/orders/${encodeURIComponent(id)}`);
export const markOrderPaid = (uuid: string, id: string, paymentRef: string) =>
apiPost<unknown>(`${base(uuid)}/orders/${encodeURIComponent(id)}/paid`, { paymentRef });
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 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. */
export const money = (sen: number) =>
`RM ${(sen / 100).toLocaleString("en-MY", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
/** The label for a refusal code from the ticket endpoints, else null (the caller shows its generic text). */
export const TICKET_ERRORS: Record<string, string> = {
PAYMENT_INSTRUCTIONS_REQUIRED: "TktErrInstructionsRequired",
PAYMENT_INSTRUCTIONS_TOO_LONG: "TktErrInstructionsTooLong",
HOLD_DAYS_INVALID: "TktErrHoldDays",
NAME_INVALID: "TktErrName",
NAME_TAKEN: "TktErrNameTaken",
PRICE_INVALID: "TktErrPrice",
QUANTITY_INVALID: "TktErrQuantity",
QUANTITY_BELOW_HELD: "TktErrQuantityBelowHeld",
DATE_INVALID: "TktErrDate",
TYPE_HAS_ORDERS: "TktErrTypeHasOrders",
NOT_PAYABLE: "TktErrNotPayable",
SEATS_GONE: "TktErrSeatsGone",
PAYMENT_REF_TOO_LONG: "TktErrPaymentRef",
NOT_CANCELLABLE: "TktErrNotCancellable",
LAST_TICKET: "TktErrLastTicket",
};
@@ -0,0 +1,63 @@
// add-event-ticket-orders: what a TICKETS block, a ticket request and the public order page carry.
import { publicCall } from "@/app/lib/services/publicRegistration";
export interface PublicTicketType {
id: number;
name: string;
priceSen: number;
left: number;
state: "ON_SALE" | "SOLD_OUT" | "ENDED";
}
export interface TicketsInfo {
eventName: string;
startDate: string | null;
endDate: string;
location: string | null;
companyName: string;
notice: { id: number; textEn: string; textMs: string };
types: PublicTicketType[];
}
export interface OrderLine {
name: string;
unitPriceSen: number;
quantity: number;
}
/** A request's answer: a token only when an order was saved (the honeypot gets a thank-you without one). */
export interface TicketRequestResult {
eventName: string;
reference?: string;
token?: string;
status?: "AWAITING" | "PAID";
totalSen?: number;
holdUntil?: string | null;
lines?: OrderLine[];
paymentInstructions?: string;
}
export interface PublicOrder {
reference: string;
status: "AWAITING" | "PAID" | "CANCELLED" | "EXPIRED";
buyerName: string;
totalSen: number;
createdAt: string;
lines: OrderLine[];
eventName: string;
startDate: string | null;
endDate: string | null;
location: string | null;
holdUntil?: string | null;
paymentInstructions?: string | null;
}
/** A Malaysia wall-clock time from the server ("2027-01-13T12:00:00") as "13 Jan 2027, 12:00". */
export function when(s: string | null | undefined): string {
if (!s) return "";
const d = new Date(s);
return Number.isNaN(d.getTime()) ? s : d.toLocaleString("en-GB", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" });
}
export const getPublicOrder = (token: string) => publicCall<PublicOrder>(`/api/public/orders/${encodeURIComponent(token)}`);
+2
View File
@@ -154,6 +154,8 @@ export interface AdminEvent {
companyId?: number; companyId?: number;
capacity?: number | null; capacity?: number | null;
invitationCap?: number | null; invitationCap?: number | null;
/** add-event-ticket-orders: whether the event sells tickets (TICKETS block event picker). */
ticketsEnabled?: boolean;
} }
export interface AdminEventMember { export interface AdminEventMember {
@@ -0,0 +1,52 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
const mocks = vi.hoisted(() => ({ getPublicOrder: vi.fn() }));
vi.mock("@/app/lib/services/publicTickets", async (orig) => ({ ...(await orig<object>()), getPublicOrder: mocks.getPublicOrder }));
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "abcdefghijklmnopqrstuv" }) }));
import { ApiError } from "@/app/lib/clientApi";
import OrderPage from "./page";
const AWAITING = {
reference: "T-7K3M9Q", status: "AWAITING", buyerName: "Aini", totalSen: 30000, createdAt: "2027-01-10T09:00:00",
lines: [{ name: "Early bird", unitPriceSen: 15000, quantity: 2 }],
eventName: "KL Hotel Tech Day", startDate: "2027-01-15", endDate: "2027-01-16", location: "KLCC",
holdUntil: "2027-01-13T12:00:00", paymentInstructions: "Maybank 5140",
};
beforeEach(() => {
mocks.getPublicOrder.mockReset().mockResolvedValue(AWAITING);
});
// add-event-ticket-orders: the buyer's order page /o/<token>.
describe("/o/[token] order page", () => {
it("shows an awaiting order with its lines, how to pay and the pay-by time", async () => {
render(<OrderPage />);
expect(await screen.findByRole("heading", { level: 1, name: "KL Hotel Tech Day" })).toBeInTheDocument();
expect(mocks.getPublicOrder).toHaveBeenCalledWith("abcdefghijklmnopqrstuv");
expect(screen.getByText("Order T-7K3M9Q")).toBeInTheDocument();
expect(screen.getByText("Awaiting payment")).toBeInTheDocument();
expect(screen.getByText("Early bird × 2")).toBeInTheDocument();
expect(screen.getAllByText("RM 300.00")).toHaveLength(2);
expect(screen.getByText("Maybank 5140")).toBeInTheDocument();
expect(screen.getByText("Pay by 13 Jan 2027, 12:00")).toBeInTheDocument();
});
it.each([
["PAID", "Paid. Your order is confirmed."],
["CANCELLED", "This order was cancelled."],
["EXPIRED", "This order expired before payment arrived."],
])("shows a %s order without payment instructions", async (status, text) => {
mocks.getPublicOrder.mockResolvedValue({ ...AWAITING, status, holdUntil: undefined, paymentInstructions: undefined });
render(<OrderPage />);
expect(await screen.findByText(text)).toBeInTheDocument();
expect(screen.queryByText("How to pay")).not.toBeInTheDocument();
});
it("says a bad link is not valid", async () => {
mocks.getPublicOrder.mockRejectedValue(new ApiError("x", 404, { code: "ORDER_INVALID" }));
render(<OrderPage />);
expect(await screen.findByRole("alert")).toHaveTextContent("This order link is not valid.");
});
});
@@ -0,0 +1,62 @@
"use client";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { AlertCircle, CalendarDays, Loader2, MapPin } from "lucide-react";
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 { useT } from "@/app/lib/i18n/MessagesProvider";
const STATUS: Record<PublicOrder["status"], string> = {
AWAITING: "TktPublicAwaiting",
PAID: "TktPublicPaid",
CANCELLED: "TktPublicCancelled",
EXPIRED: "TktPublicExpired",
};
/** add-event-ticket-orders: the buyer's order page, reached from the thank-you and the order emails. */
export default function OrderPage() {
const t = useT();
const { token } = useParams<{ token: string }>();
const [order, setOrder] = useState<PublicOrder | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
getPublicOrder(token)
.then(setOrder)
.catch((err) => {
const code = apiData(err).code;
setError(t(code === "ORDER_INVALID" ? "TktOrderInvalid" : code === "TOO_MANY" ? "RegTooMany" : "RegLoadFailed"));
});
}, [token, t]);
if (error) return <VisitorCard><VisitorState h1 icon={AlertCircle} heading={error} role="alert" tone="error" /></VisitorCard>;
if (!order) return <VisitorCard><VisitorState h1 icon={Loader2} iconClassName="motion-safe:animate-spin" heading={t("UiLoading")} role="status" /></VisitorCard>;
const dates = [order.startDate, order.endDate].filter(Boolean).join(" - ");
return (
<VisitorCard>
<header className="space-y-2">
<h1 className="text-2xl font-semibold">{order.eventName}</h1>
{dates && (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<CalendarDays className="size-4 shrink-0" aria-hidden="true" /><span>{dates}</span>
</p>
)}
{order.location && (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<MapPin className="size-4 shrink-0" aria-hidden="true" /><span>{order.location}</span>
</p>
)}
</header>
<div className="space-y-1">
<p className="font-semibold">{t("TktPublicOrder", { reference: order.reference })}</p>
<p role="status" className={order.status === "AWAITING" || order.status === "PAID" ? "text-sm" : "text-sm text-destructive"}>{t(STATUS[order.status])}</p>
</div>
<OrderSummary lines={order.lines} totalSen={order.totalSen} />
{order.status === "AWAITING" && order.paymentInstructions && <PaymentBox instructions={order.paymentInstructions} holdUntil={order.holdUntil} />}
</VisitorCard>
);
}
-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

@@ -60,6 +60,10 @@ public class JWTAuthFilter implements GlobalFilter, Ordered {
publicPath(HttpMethod.GET, "/counter/cmsPage/findPublished/\\d+/[A-Za-z0-9-]{1,80}"), publicPath(HttpMethod.GET, "/counter/cmsPage/findPublished/\\d+/[A-Za-z0-9-]{1,80}"),
publicPath(HttpMethod.GET, "/counter/pageImage/\\d+"), publicPath(HttpMethod.GET, "/counter/pageImage/\\d+"),
publicPath(HttpMethod.GET, "/company/branding/[A-Za-z0-9-]{2,20}"), publicPath(HttpMethod.GET, "/company/branding/[A-Za-z0-9-]{2,20}"),
// Ticket orders (add-event-ticket-orders): a request, an order by its link token, and the on-sale types. Staff calls need a token.
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}"),
// Password hint on public password screens: switched-on rule names and numbers only, no user data // Password hint on public password screens: switched-on rule names and numbers only, no user data
publicPath(HttpMethod.GET, "/passwordRule/adminActive"), publicPath(HttpMethod.GET, "/passwordRule/adminActive"),
// WhatsApp webhook forward from mobile-api: no user token; the service re-verifies Meta's signature itself // WhatsApp webhook forward from mobile-api: no user token; the service re-verifies Meta's signature itself
@@ -0,0 +1,84 @@
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-ticket-orders: a ticket request, an order by its link token and the on-sale ticket types are open; staff ticket calls stay closed. */
class JWTAuthFilterTicketsPathTest {
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 publicTicketCallsNeedNoUserToken() {
for (String[] c : new String[][] {
{"POST", "/counter/ticketOrder/request"},
{"GET", "/counter/ticketOrder/byToken/abcdefghijklmnopqrstu_"},
{"GET", "/counter/ticketType/onSale/3312726793093644288"} }) {
assertThat(passes(call(HttpMethod.valueOf(c[0]), c[1]))).as(c[0] + " " + c[1]).isTrue();
}
}
@Test
void everythingElseAboutTicketsNeedsAUserToken() {
for (String[] c : new String[][] {
{"GET", "/counter/ticketOrder/request"},
{"POST", "/counter/ticketOrder/request/x"},
{"GET", "/counter/ticketOrder/byToken/short"},
{"GET", "/counter/ticketOrder/byToken/abcdefghijklmnopqrstuvw"},
{"POST", "/counter/ticketOrder/byToken/abcdefghijklmnopqrstu_"},
{"GET", "/counter/ticketType/onSale/x"},
{"GET", "/counter/ticketType/onSale/12345678901234567890"},
{"POST", "/counter/ticketType/list"},
{"POST", "/counter/ticketType/settings"},
{"POST", "/counter/ticketOrder/list"},
{"POST", "/counter/ticketOrder/markPaid"} }) {
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);
}
}
}
@@ -46,6 +46,20 @@ public class RestApiCounterServiceConstants {
public static final String API_REST_COUNTER_CHECKIN_LOOKUP = "/counter/checkin/lookup"; public static final String API_REST_COUNTER_CHECKIN_LOOKUP = "/counter/checkin/lookup";
public static final String API_REST_COUNTER_CHECKIN_BY_GUEST = "/counter/checkin/byGuest"; public static final String API_REST_COUNTER_CHECKIN_BY_GUEST = "/counter/checkin/byGuest";
public static final String API_REST_COUNTER_EVENT_ATTENDANCE = "/counter/event/attendance"; public static final String API_REST_COUNTER_EVENT_ATTENDANCE = "/counter/event/attendance";
// add-event-ticket-orders
public static final String API_REST_COUNTER_TICKET_SETTINGS = "/counter/ticketType/settings";
public static final String API_REST_COUNTER_TICKET_TYPE_LIST = "/counter/ticketType/list";
public static final String API_REST_COUNTER_TICKET_TYPE_SAVE = "/counter/ticketType/save";
public static final String API_REST_COUNTER_TICKET_TYPE_DELETE = "/counter/ticketType/delete";
public static final String API_REST_COUNTER_TICKET_ORDER_LIST = "/counter/ticketOrder/list";
public static final String API_REST_COUNTER_TICKET_ORDER_GET = "/counter/ticketOrder/get";
public static final String API_REST_COUNTER_TICKET_ORDER_MARK_PAID = "/counter/ticketOrder/markPaid";
public static final String API_REST_COUNTER_TICKET_ORDER_CANCEL = "/counter/ticketOrder/cancel";
public static final String API_REST_COUNTER_TICKET_ORDER_CANCEL_TICKET = "/counter/ticketOrder/cancelTicket";
public static final String API_REST_COUNTER_TICKET_ORDER_RESEND = "/counter/ticketOrder/resend";
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_EVENT_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}"; 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_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace";
public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}"; public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}";
@@ -0,0 +1,130 @@
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/** add-event-ticket-orders: ticket settings, types and orders of an event. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin/events/{uuid}")
@RequiredArgsConstructor
public class AdminTicketController {
private final AdminTicketService tickets;
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@GetMapping("/tickets/settings")
public ResponseEntity<Map<String, Object>> settings(@PathVariable String uuid) {
return ResponseEntity.ok(tickets.settings(uuid));
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited(targetVariable = "uuid")
@PutMapping("/tickets/settings")
public ResponseEntity<Void> saveSettings(@PathVariable String uuid, @RequestBody AdminTicketService.SettingsBody body) {
tickets.saveSettings(uuid, body);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@GetMapping("/ticket-types")
public ResponseEntity<List<Map<String, Object>>> types(@PathVariable String uuid) {
return ResponseEntity.ok(tickets.types(uuid));
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited(targetVariable = "uuid")
@PostMapping("/ticket-types")
public ResponseEntity<Void> addType(@PathVariable String uuid, @RequestBody AdminTicketService.TypeBody body) {
tickets.saveType(uuid, null, body);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@PutMapping("/ticket-types/{id}")
public ResponseEntity<Void> updateType(@PathVariable String uuid, @PathVariable String id, @RequestBody AdminTicketService.TypeBody body) {
tickets.saveType(uuid, id, body);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@DeleteMapping("/ticket-types/{id}")
public ResponseEntity<Void> deleteType(@PathVariable String uuid, @PathVariable String id) {
tickets.deleteType(uuid, id);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@GetMapping("/orders")
public ResponseEntity<Map<String, Object>> orders(@PathVariable String uuid, @RequestParam(required = false) String status,
@RequestParam(required = false) String q, @RequestParam(defaultValue = "0") int page) {
return ResponseEntity.ok(tickets.orders(uuid, status, q, page));
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@GetMapping("/orders/{orderId}")
public ResponseEntity<Map<String, Object>> order(@PathVariable String uuid, @PathVariable String orderId) {
return ResponseEntity.ok(tickets.order(uuid, orderId));
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@PostMapping("/orders/{orderId}/paid")
public ResponseEntity<Void> markPaid(@PathVariable String uuid, @PathVariable String orderId,
@RequestBody(required = false) AdminTicketService.PayBody body) {
tickets.markPaid(uuid, orderId, body);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@PostMapping("/orders/{orderId}/cancel")
public ResponseEntity<Void> cancel(@PathVariable String uuid, @PathVariable String orderId) {
tickets.cancel(uuid, orderId);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited(targetVariable = "orderId")
@PostMapping("/orders/{orderId}/tickets/{ticketId}/cancel")
public ResponseEntity<Void> cancelTicket(@PathVariable String uuid, @PathVariable String orderId, @PathVariable String ticketId) {
tickets.cancelTicket(uuid, orderId, ticketId);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@PostMapping("/orders/{orderId}/resend")
public ResponseEntity<Void> resend(@PathVariable String uuid, @PathVariable String orderId) {
tickets.resend(uuid, orderId);
return ResponseEntity.noContent().build();
}
}
@@ -2,6 +2,7 @@ package com.solvway.mobile.api.controller.publicapi;
import com.solvway.core.annotation.AppAuth; import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.PublicPageFormRequest; 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.PublicPageService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -32,6 +33,19 @@ public class PublicPageController {
return ResponseEntity.ok(pages.submit(company, slug, block, request)); return ResponseEntity.ok(pages.submit(company, slug, block, request));
} }
@AppAuth(skipValidate = true)
@PostMapping("/api/public/pages/{company}/{slug}/tickets/{block}")
public ResponseEntity<Map<String, Object>> tickets(@PathVariable String company, @PathVariable String slug,
@PathVariable int block, @RequestBody PublicTicketRequest request) {
return ResponseEntity.ok(pages.tickets(company, slug, block, request));
}
@AppAuth(skipValidate = true)
@GetMapping("/api/public/orders/{token}")
public ResponseEntity<Map<String, Object>> order(@PathVariable String token) {
return ResponseEntity.ok(pages.order(token));
}
@AppAuth(skipValidate = true) @AppAuth(skipValidate = true)
@GetMapping("/api/public/page-images/{id}") @GetMapping("/api/public/page-images/{id}")
public ResponseEntity<byte[]> image(@PathVariable long id) { public ResponseEntity<byte[]> image(@PathVariable long id) {
@@ -0,0 +1,10 @@
package com.solvway.mobile.api.dto;
import java.util.List;
/** A visitor's ticket request from a TICKETS block (add-event-ticket-orders). {@code website} is the honeypot. */
public record PublicTicketRequest(List<Line> lines, String name, String mobile, String email, String companyName, Boolean consent,
String website, String utmSource, String utmMedium, String utmCampaign) {
public record Line(Long ticketTypeId, Integer quantity) {}
}
@@ -11,4 +11,8 @@ public class CompanyEvent extends Event {
private Long companyId; private Long companyId;
private Integer capacity; private Integer capacity;
private Integer invitationCap; private Integer invitationCap;
/** add-event-ticket-orders: read here; changed only through the ticket settings call (event/save keeps the stored values). */
private Boolean ticketsEnabled;
private String paymentInstructions;
private Integer holdDays;
} }
@@ -273,6 +273,7 @@ public class AdminEventService {
m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString()); m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString()); m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
m.put("enabled", e.getEnabled() == GeneralEnum.FlagYesNo.Y); m.put("enabled", e.getEnabled() == GeneralEnum.FlagYesNo.Y);
m.put("ticketsEnabled", Boolean.TRUE.equals(e.getTicketsEnabled()));
return m; return m;
} }
@@ -0,0 +1,169 @@
package com.solvway.mobile.api.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants.*;
/**
* add-event-ticket-orders: ticket settings, ticket types and orders of one event. Every call resolves the event through
* AdminEventLeadService.loadEvent, so another company's event is a 404; the counter checks the order belongs to that event.
* The counter validates; its refusal codes pass through with their status. Never log a buyer's name, mobile or email.
*/
@Service
@RequiredArgsConstructor
public class AdminTicketService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
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 final RestTemplateCustomUtil rest;
private final AdminEventLeadService leads;
public record SettingsBody(Boolean ticketsEnabled, String paymentInstructions, Integer holdDays) {}
public record TypeBody(String name, Integer priceSen, Integer quantity, String salesEndDate, Integer sort, Boolean enabled) {}
public record PayBody(String paymentRef) {}
public Map<String, Object> settings(String uuid) {
CompanyEvent e = leads.loadEvent(uuid, null);
Map<String, Object> out = new LinkedHashMap<>();
out.put("ticketsEnabled", Boolean.TRUE.equals(e.getTicketsEnabled()));
out.put("paymentInstructions", e.getPaymentInstructions());
out.put("holdDays", e.getHoldDays());
return out;
}
public void saveSettings(String uuid, SettingsBody b) {
Map<String, Object> body = write(uuid);
body.put("ticketsEnabled", b != null && Boolean.TRUE.equals(b.ticketsEnabled()));
body.put("paymentInstructions", b == null ? null : b.paymentInstructions());
body.put("holdDays", b == null ? null : b.holdDays());
post(API_REST_COUNTER_TICKET_SETTINGS, MAP, body);
}
public List<Map<String, Object>> types(String uuid) {
List<Map<String, Object>> types = post(API_REST_COUNTER_TICKET_TYPE_LIST, MAP_LIST, read(uuid));
return types == null ? List.of() : types;
}
public void saveType(String uuid, String id, TypeBody b) {
Map<String, Object> body = write(uuid);
if (b == null) throw AdminEventLeadService.required(List.of("name"));
if (b.salesEndDate() != null && !b.salesEndDate().isBlank()) {
try {
LocalDate.parse(b.salesEndDate());
} catch (DateTimeParseException e) {
throw AdminEventLeadService.error(HttpStatus.BAD_REQUEST, "Sales end date is not a date", "DATE_INVALID", "salesEndDate");
}
}
body.put("id", id == null ? null : AdminEventLeadService.parseOr(id, AdminTicketService::typeNotFound));
body.put("name", b.name());
body.put("priceSen", b.priceSen());
body.put("quantity", b.quantity());
body.put("salesEndDate", b.salesEndDate() == null || b.salesEndDate().isBlank() ? null : b.salesEndDate());
body.put("sort", b.sort() == null ? 0 : b.sort());
body.put("enabled", b.enabled() == null || b.enabled());
post(API_REST_COUNTER_TICKET_TYPE_SAVE, MAP, body);
}
public void deleteType(String uuid, String id) {
Map<String, Object> body = write(uuid);
body.put("id", AdminEventLeadService.parseOr(id, AdminTicketService::typeNotFound));
post(API_REST_COUNTER_TICKET_TYPE_DELETE, MAP, body);
}
public Map<String, Object> orders(String uuid, String status, String q, int page) {
Map<String, Object> body = read(uuid);
body.put("status", status);
body.put("q", q);
body.put("page", Math.max(page, 0));
body.put("size", PAGE_SIZE);
return post(API_REST_COUNTER_TICKET_ORDER_LIST, MAP, body);
}
public Map<String, Object> order(String uuid, String orderId) {
return post(API_REST_COUNTER_TICKET_ORDER_GET, MAP, orderBody(read(uuid), orderId));
}
public void markPaid(String uuid, String orderId, PayBody b) {
Map<String, Object> body = orderBody(write(uuid), orderId);
body.put("paymentRef", b == null ? null : b.paymentRef());
post(API_REST_COUNTER_TICKET_ORDER_MARK_PAID, MAP, body);
}
public void cancel(String uuid, String orderId) {
post(API_REST_COUNTER_TICKET_ORDER_CANCEL, MAP, orderBody(write(uuid), orderId));
}
public void cancelTicket(String uuid, String orderId, String ticketId) {
Map<String, Object> body = orderBody(write(uuid), orderId);
body.put("ticketId", AdminEventLeadService.parseOr(ticketId,
() -> AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Ticket not found", "TICKET_NOT_FOUND", null)));
post(API_REST_COUNTER_TICKET_ORDER_CANCEL_TICKET, MAP, body);
}
public void resend(String uuid, String orderId) {
post(API_REST_COUNTER_TICKET_ORDER_RESEND, MAP, orderBody(read(uuid), orderId));
}
private Map<String, Object> read(String uuid) {
CompanyEvent e = leads.loadEvent(uuid, null);
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", e.getCompanyId());
body.put("eventUuid", e.getUuid());
return body;
}
private Map<String, Object> write(String uuid) {
Map<String, Object> body = read(uuid);
body.put("doneBy", leads.caller().getUsername());
return body;
}
private static Map<String, Object> orderBody(Map<String, Object> body, String orderId) {
body.put("orderId", AdminEventLeadService.parseOr(orderId,
() -> AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Order not found", "ORDER_NOT_FOUND", null)));
return body;
}
private static com.solvway.mobile.api.errorhandler.CodedResponseStatusException typeNotFound() {
return AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Ticket type not found", "TYPE_NOT_FOUND", null);
}
/** A counter refusal keeps its status; the counter's ProblemDetail "detail" is the reason code. */
private <T> T post(String api, ParameterizedTypeReference<T> type, Map<String, Object> body) {
try {
return rest.postForEntity(rest.getURLforApiService(api), type, body).getBody();
} catch (HttpClientErrorException e) {
String code = "REFUSED";
try {
JsonNode n = JSON.readTree(e.getResponseBodyAsString());
code = n.path("detail").asText(code);
} catch (Exception ignored) {
// not a ProblemDetail: keep the generic code
}
throw AdminEventLeadService.error(HttpStatus.valueOf(e.getStatusCode().value()), code, code, FIELDS.get(code));
}
}
}
@@ -4,6 +4,8 @@ import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.dto.PublicPageFormRequest; import com.solvway.mobile.api.dto.PublicPageFormRequest;
import com.solvway.mobile.api.dto.PublicRegistrationRequest; import com.solvway.mobile.api.dto.PublicRegistrationRequest;
import com.solvway.mobile.api.dto.PublicTicketRequest;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil; import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -13,8 +15,13 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Duration; import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@@ -26,6 +33,7 @@ import java.util.regex.Pattern;
* Public landing pages: a published page with its company's branding, and its form blocks' sign-ups. * Public landing pages: a published page with its company's branding, and its form blocks' sign-ups.
* A form block registers under the QR rules (PublicRegistrationService): same event checks, form validation, * A form block registers under the QR rules (PublicRegistrationService): same event checks, form validation,
* honeypot and abuse limits, with source WEB, no salesperson, the page address and the UTM tags. * honeypot and abuse limits, with source WEB, no salesperson, the page address and the UTM tags.
* add-event-ticket-orders: a TICKETS block's types and ticket requests follow the same rules, and an order's link shows the order.
*/ */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -35,7 +43,11 @@ public class PublicPageService {
private static final Pattern SLUG = Pattern.compile("[A-Za-z0-9-]{1,80}"); private static final Pattern SLUG = Pattern.compile("[A-Za-z0-9-]{1,80}");
private static final int LOAD_LIMIT = 300; private static final int LOAD_LIMIT = 300;
private static final int SUBMIT_LIMIT = 60; private static final int SUBMIT_LIMIT = 60;
private static final int ORDER_LOAD_LIMIT = 120;
private static final String TOO_MANY_SUBMITS = "Too many registrations from this device. Try again later.";
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {}; private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<CompanyEvent> EVENT = new ParameterizedTypeReference<>() {};
private static final ObjectMapper JSON = new ObjectMapper();
private final RestTemplateCustomUtil rest; private final RestTemplateCustomUtil rest;
private final PublicRegistrationService registration; private final PublicRegistrationService registration;
@@ -52,6 +64,10 @@ public class PublicPageService {
PublicRegistrationService.Open o = open(f.companyId(), block); PublicRegistrationService.Open o = open(f.companyId(), block);
if (o == null) block.put("closed", true); if (o == null) block.put("closed", true);
else block.put("form", registration.eventView(o)); else block.put("form", registration.eventView(o));
} else if ("TICKETS".equals(block.get("type"))) {
Map<String, Object> t = ticketsView(f.companyId(), block);
if (t == null) block.put("closed", true);
else block.put("tickets", t);
} }
blocks.add(block); blocks.add(block);
} }
@@ -84,7 +100,7 @@ public class PublicPageService {
PublicRegistrationRequest form = r.registration(); PublicRegistrationRequest form = r.registration();
if (PublicRegistrationService.honeypot(form)) return done; // look like success, store nothing if (PublicRegistrationService.honeypot(form)) return done; // look like success, store nothing
registration.limit("reg:submit:" + o.event().getUuid() + ":" + PublicRegistrationService.ip(), SUBMIT_LIMIT, registration.limit("reg:submit:" + o.event().getUuid() + ":" + PublicRegistrationService.ip(), SUBMIT_LIMIT,
"Too many registrations from this device. Try again later."); TOO_MANY_SUBMITS);
Map<String, Object> body = registration.form(o, form); Map<String, Object> body = registration.form(o, form);
body.put("eventUuid", o.event().getUuid()); body.put("eventUuid", o.event().getUuid());
body.put("salespersonUserId", null); body.put("salespersonUserId", null);
@@ -97,6 +113,161 @@ public class PublicPageService {
return done; return done;
} }
/** A TICKETS block's event and on-sale types, or null when the event no longer takes ticket requests. */
private Map<String, Object> ticketsView(long companyId, Map<String, Object> block) {
PublicRegistrationService.Open o = open(companyId, block);
if (o == null) return null;
Map<String, Object> sale = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_TYPE_ON_SALE), MAP, o.event().getUuid()).getBody());
if (sale == null || !Boolean.TRUE.equals(sale.get("ticketsOpen"))) return null;
CompanyEvent e = o.event();
Map<String, Object> out = new LinkedHashMap<>();
out.put("eventName", e.getName());
out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
out.put("endDate", e.getDateEnd().toLocalDate().toString());
out.put("location", e.getLocation());
out.put("companyName", o.companyName());
out.put("notice", Map.of("id", o.notice().get("id"), "textEn", String.valueOf(o.notice().get("textEn")),
"textMs", String.valueOf(o.notice().get("textMs"))));
out.put("types", sale.get("types") instanceof List<?> l ? l : List.of());
return out;
}
/** A ticket request from a TICKETS block: QR limits and honeypot, inputs normalised here, seats and prices checked by the counter. */
public Map<String, Object> tickets(String companyCode, String slug, int blockIndex, PublicTicketRequest r) {
registration.limit("page:load:" + PublicRegistrationService.ip(), LOAD_LIMIT, "Too many requests from this device. Try again later.");
Found f = find(companyCode, slug);
List<?> blocks = blocks(f.page());
if (blockIndex < 0 || blockIndex >= blocks.size() || !"TICKETS".equals(((Map<?, ?>) blocks.get(blockIndex)).get("type"))) {
throw notFound();
}
PublicRegistrationService.Open o = open(f.companyId(), (Map<String, Object>) blocks.get(blockIndex));
if (o == null) throw new CodedResponseStatusException(HttpStatus.CONFLICT, "Ticket sales are closed.", "TICKETS_CLOSED");
Map<String, Object> done = PublicRegistrationService.done(o.event());
if (r == null || r.website() != null && !r.website().isBlank()) return done; // look like success, store nothing
registration.limit("reg:submit:" + o.event().getUuid() + ":" + PublicRegistrationService.ip(), SUBMIT_LIMIT, TOO_MANY_SUBMITS);
String name = AdminEventLeadService.trimmed(r.name());
String email = AdminEventLeadService.email(r.email());
List<String> missing = new ArrayList<>();
if (name == null) missing.add("name");
if (email == null) missing.add("email");
if (!missing.isEmpty()) throw AdminEventLeadService.required(missing);
AdminEventLeadService.maxLength("name", name, 100);
AdminEventLeadService.maxLength("email", email, 254);
String mobile = AdminEventLeadService.mobile(r.mobile());
String companyName = AdminEventLeadService.maxLength("companyName", AdminEventLeadService.trimmed(r.companyName()), 150);
if (!Boolean.TRUE.equals(r.consent())) {
throw AdminEventLeadService.error(HttpStatus.BAD_REQUEST, "Please agree to the privacy notice", "CONSENT_REQUIRED", "consent");
}
List<Map<String, Object>> lines = new ArrayList<>();
for (PublicTicketRequest.Line l : r.lines() == null ? List.<PublicTicketRequest.Line>of() : r.lines()) {
Map<String, Object> line = new LinkedHashMap<>();
line.put("ticketTypeId", l == null ? null : l.ticketTypeId());
line.put("quantity", l == null ? null : l.quantity());
lines.add(line);
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", o.event().getCompanyId());
body.put("eventUuid", o.event().getUuid());
body.put("lines", lines);
body.put("buyerName", name);
body.put("buyerEmail", email);
body.put("buyerMobileE164", mobile);
body.put("buyerCompany", companyName);
body.put("consentNoticeId", o.notice().get("id"));
body.put("consentAt", LocalDateTime.now(PublicRegistrationService.MALAYSIA).toString());
body.put("pagePath", "/p/" + f.company().get("code") + "/" + f.page().get("slug"));
body.put("utmSource", r.utmSource());
body.put("utmMedium", r.utmMedium());
body.put("utmCampaign", r.utmCampaign());
Map<String, Object> result;
try {
result = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ORDER_REQUEST), MAP, body).getBody();
} catch (HttpClientErrorException e) {
throw ticketRefusal(e, o);
}
Map<String, Object> out = new LinkedHashMap<>(result == null ? Map.of() : result);
if (!"AWAITING".equals(out.get("status"))) out.remove("paymentInstructions"); // a free order is confirmed at once
out.put("eventName", o.event().getName());
return out;
}
/** The counter's refusal ("CODE" or "CODE|typeId|left" or "CODE|left") as the message a visitor reads. */
private CodedResponseStatusException ticketRefusal(HttpClientErrorException e, PublicRegistrationService.Open o) {
String detail = "";
try {
JsonNode n = JSON.readTree(e.getResponseBodyAsString());
detail = n.path("detail").asText("");
} catch (Exception ignored) {
// not a ProblemDetail
}
String[] p = detail.split("\\|");
HttpStatus status = HttpStatus.valueOf(e.getStatusCode().value());
CodedResponseStatusException out = switch (p[0]) {
case "TYPE_UNAVAILABLE" -> {
long id = p.length > 1 ? Long.parseLong(p[1]) : 0;
long left = p.length > 2 ? Long.parseLong(p[2]) : 0;
String name = typeName(o.event().getUuid(), id);
CodedResponseStatusException x = new CodedResponseStatusException(status, left == 0 ? name + " is no longer available."
: name + " has only " + left + (left == 1 ? " ticket left." : " tickets left."), "TYPE_UNAVAILABLE");
x.getBody().setProperty("details", Map.of("ticketTypeId", id, "left", left));
yield x;
}
case "EVENT_FULL" -> {
long left = p.length > 1 ? Long.parseLong(p[1]) : 0;
CodedResponseStatusException x = new CodedResponseStatusException(status, left == 0 ? "This event is full."
: "Only " + left + (left == 1 ? " seat is" : " seats are") + " left for this event.", "EVENT_FULL");
x.getBody().setProperty("details", Map.of("left", left));
yield x;
}
case "TOO_MANY_AWAITING" -> new CodedResponseStatusException(status, "You already have orders awaiting payment for this event.", p[0]);
case "BAD_QUANTITY" -> new CodedResponseStatusException(status, "Choose from 1 to 10 tickets.", p[0]);
case "TICKETS_CLOSED", "EVENT_NOT_FOUND" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "Ticket sales are closed.", "TICKETS_CLOSED");
default -> new CodedResponseStatusException(status, "Your request could not be completed.", p[0].isEmpty() ? "REFUSED" : p[0]);
};
return out;
}
private String typeName(long eventUuid, long typeId) {
Map<String, Object> sale = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_TYPE_ON_SALE), MAP, eventUuid).getBody());
if (sale != null && sale.get("types") instanceof List<?> types) {
for (Object t : types) {
if (t instanceof Map<?, ?> m && m.get("id") instanceof Number n && n.longValue() == typeId) return String.valueOf(m.get("name"));
}
}
return "This ticket type";
}
/** An order by its link token: the buyer's name but no other personal details; instructions and hold only while awaiting payment. */
public Map<String, Object> order(String token) {
if (token == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(token).matches()) throw orderInvalid();
registration.limit("ord:load:" + PublicRegistrationService.ip(), ORDER_LOAD_LIMIT, "Too many requests from this device. Try again later.");
Map<String, Object> o = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ORDER_BY_TOKEN), MAP, token).getBody());
if (o == null || !(o.get("eventUuid") instanceof Number uuid)) throw orderInvalid();
CompanyEvent e = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, uuid.longValue()).getBody());
if (e == null) throw orderInvalid();
Map<String, Object> out = new LinkedHashMap<>();
for (String k : List.of("reference", "status", "buyerName", "totalSen", "createdAt", "lines")) out.put(k, o.get(k));
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());
if ("AWAITING".equals(o.get("status"))) {
out.put("holdUntil", o.get("holdUntil"));
out.put("paymentInstructions", e.getPaymentInstructions());
}
return out;
}
private static CodedResponseStatusException orderInvalid() {
return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "This order link is not valid.", "ORDER_INVALID");
}
/** An image's bytes with the counter's type and long cache; a missing one is 404. Image ids are not secret. */ /** An image's bytes with the counter's type and long cache; a missing one is 404. Image ids are not secret. */
public ResponseEntity<byte[]> image(long id) { public ResponseEntity<byte[]> image(long id) {
ResponseEntity<byte[]> r = PublicRegistrationService.found(() -> rest.getForEntity( ResponseEntity<byte[]> r = PublicRegistrationService.found(() -> rest.getForEntity(
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more