# 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::`, 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/event/save` accepts `ticketsEnabled`, `paymentInstructions` and `holdDays`. It returns 400 on the field when switching on with blank instructions or when hold days are outside 1 to 14. mobile-api passes these only for callers with `BO_EVENT_TICKETS`. - **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 `/o/`. 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::` 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:` 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 (tens per minute). If a big launch needs more, move to per-type locks. - **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.