@composable-os/pack-ticketing 0.0.0-stage → 0.1.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,288 @@
1
+ // The Ticketing pack's headless entry (stage 27, step 5; ADR 0418): functions and hooks over the
2
+ // typed client, no markup. A client app imports it as `@composable-os/pack-ticketing/client` and
3
+ // hands it its generated client; the ticketing blocks render what it returns.
4
+ //
5
+ // As every pack's entry: the operations are typed from the pack's own tool schemas, it takes the
6
+ // client and the app's `useQuery`, `useMutation` and `useState` as arguments (no React or TanStack
7
+ // import), and it holds no rules. Prices, limits, places, what may be bought and whether an order
8
+ // is paid are the host's. The one sum here, `estimate`, is a preview of what the host will
9
+ // charge, shown before the order starts; the order the host returns is what is paid.
10
+ import { packHooks } from "@composable-os/client";
11
+ // --- Plain functions ------------------------------------------------------------------------------
12
+ /**
13
+ * How many decimal places `currency` has (2 for AUD, 0 for JPY), for display. The currency is
14
+ * always the host's, from the data (a ticket type's `currency`, an order's): never the app's.
15
+ */
16
+ export function currencyDigits(currency) {
17
+ if (!currency)
18
+ return 2;
19
+ try {
20
+ return (new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions()
21
+ .maximumFractionDigits ?? 2);
22
+ }
23
+ catch {
24
+ return 2;
25
+ }
26
+ }
27
+ /** An amount in the minor unit as the buyer reads it: `450.00 AUD`. Display only. */
28
+ export function formatMoney(minor, currency) {
29
+ const digits = currencyDigits(currency);
30
+ return `${(minor / 10 ** digits).toFixed(digits)}${currency ? ` ${currency}` : ""}`;
31
+ }
32
+ /** A ticket type's price (major unit, as the record holds it) as the buyer reads it. */
33
+ export function formatPrice(price, currency) {
34
+ return price === null
35
+ ? ""
36
+ : `${price.toFixed(currencyDigits(currency))}${currency ? ` ${currency}` : ""}`;
37
+ }
38
+ /** The viewer's own time zone, as their device reports it. */
39
+ export function viewerTimeZone() {
40
+ try {
41
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
42
+ }
43
+ catch {
44
+ return "UTC";
45
+ }
46
+ }
47
+ /**
48
+ * When an event starts (or ends, with `at: "endsAt"`), as a buyer or holder reads it: the day and
49
+ * time in the event's own zone (ADR 0460), never the device's, so a camp in Bangkok reads as
50
+ * Bangkok's time on a phone in Sydney. When the event's zone is not the viewer's, the zone is
51
+ * said (`… (Bangkok time)`). Display only.
52
+ */
53
+ export function eventTime(event, options = {}) {
54
+ const iso = options.at === "endsAt" ? (event.endsAt ?? null) : event.startsAt;
55
+ if (!iso)
56
+ return "";
57
+ const at = new Date(iso);
58
+ if (Number.isNaN(at.getTime()))
59
+ return "";
60
+ const viewer = options.viewer ?? viewerTimeZone();
61
+ const zone = event.timeZone ?? viewer;
62
+ let text;
63
+ try {
64
+ text = new Intl.DateTimeFormat(options.locale, {
65
+ timeZone: zone,
66
+ dateStyle: "medium",
67
+ timeStyle: "short",
68
+ }).format(at);
69
+ }
70
+ catch {
71
+ return at.toISOString();
72
+ }
73
+ if (zone === viewer || sameOffset(at, zone, viewer))
74
+ return text;
75
+ const city = zone.split("/").pop()?.replace(/_/g, " ") ?? zone;
76
+ return `${text} (${city} time)`;
77
+ }
78
+ /** Whether two zones show the same wall-clock time at `at` (then saying the zone adds nothing). */
79
+ function sameOffset(at, a, b) {
80
+ try {
81
+ const wall = (timeZone) => new Intl.DateTimeFormat("en-US", {
82
+ timeZone,
83
+ hourCycle: "h23",
84
+ year: "numeric",
85
+ month: "2-digit",
86
+ day: "2-digit",
87
+ hour: "2-digit",
88
+ minute: "2-digit",
89
+ }).format(at);
90
+ return wall(a) === wall(b);
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
96
+ /** The day an event starts on in its own zone (`2027-03-01`), for grouping or a calendar. */
97
+ export function eventDay(event) {
98
+ if (!event.startsAt)
99
+ return "";
100
+ const at = new Date(event.startsAt);
101
+ if (Number.isNaN(at.getTime()))
102
+ return "";
103
+ try {
104
+ const parts = new Intl.DateTimeFormat("en-CA", {
105
+ timeZone: event.timeZone ?? viewerTimeZone(),
106
+ year: "numeric",
107
+ month: "2-digit",
108
+ day: "2-digit",
109
+ }).format(at);
110
+ return parts;
111
+ }
112
+ catch {
113
+ return event.startsAt.slice(0, 10);
114
+ }
115
+ }
116
+ /** The currency an event's prices are in, as the host gave it with its ticket types. */
117
+ export function eventCurrency(event) {
118
+ return event.ticketTypes.find((type) => type.currency)?.currency ?? null;
119
+ }
120
+ /**
121
+ * An amount a buyer typed (`120`, `120.50`) in the minor unit of `currency`, or null when it is
122
+ * not one. The host decides whether it may be charged (at least the set minimum, at most the
123
+ * balance).
124
+ */
125
+ export function minorFromInput(text, currency = null) {
126
+ const value = Number(text.trim().replace(",", "."));
127
+ return Number.isFinite(value) && value > 0
128
+ ? Math.round(value * 10 ** currencyDigits(currency))
129
+ : null;
130
+ }
131
+ /** What the picker shows of a ticket type's places: "Sold out", "Only 3 left", or nothing. */
132
+ export function availabilityLabel(availability) {
133
+ if (availability.status === "sold_out")
134
+ return "Sold out";
135
+ if (availability.status === "low" && typeof availability.available === "number") {
136
+ return `Only ${availability.available} left`;
137
+ }
138
+ return null;
139
+ }
140
+ /** The lines `orderStart` takes, from what was chosen. */
141
+ export function pickerLines(quantities) {
142
+ return Object.entries(quantities)
143
+ .filter(([, quantity]) => quantity > 0)
144
+ .map(([ticketTypeId, quantity]) => ({ ticketTypeId, quantity }));
145
+ }
146
+ /**
147
+ * A preview of the order, in the minor unit, from the prices the host published: what to show
148
+ * while choosing. The host prices the order when it starts; show its total after that.
149
+ */
150
+ export function estimate(event, quantities) {
151
+ const currency = eventCurrency(event);
152
+ const scale = 10 ** currencyDigits(currency);
153
+ let full = 0;
154
+ let deposit = 0;
155
+ let everyLineOffersDeposit = true;
156
+ for (const type of event.ticketTypes) {
157
+ const quantity = quantities[type.id] ?? 0;
158
+ if (quantity <= 0)
159
+ continue;
160
+ full += Math.round((type.price ?? 0) * scale) * quantity;
161
+ if (type.deposit === null || type.balanceDue === null)
162
+ everyLineOffersDeposit = false;
163
+ else
164
+ deposit += Math.round(type.deposit * scale) * quantity;
165
+ }
166
+ return { full, deposit: full > 0 && everyLineOffersDeposit ? deposit : null, currency };
167
+ }
168
+ /** The most the picker offers of one type: its declared most per order, or 10 as the host does. */
169
+ export function pickerMax(type) {
170
+ if (type.availability.status === "sold_out")
171
+ return 0;
172
+ return type.maxPerOrder ?? 10;
173
+ }
174
+ /** What the confirmation page says about an order, from its real state. */
175
+ export function orderStatus(order) {
176
+ switch (order.state) {
177
+ case "pending":
178
+ return { kind: "waiting", title: "Waiting for your payment to be confirmed", waiting: true };
179
+ case "paid":
180
+ return {
181
+ kind: "paid",
182
+ title: "Paid. Your tickets are on their way by email.",
183
+ waiting: false,
184
+ };
185
+ case "part_paid":
186
+ return {
187
+ kind: "part_paid",
188
+ title: "Deposit paid. Your tickets are on their way by email.",
189
+ waiting: false,
190
+ };
191
+ default:
192
+ return {
193
+ kind: "closed",
194
+ title: `This order is ${order.state.replace("_", " ")}.`,
195
+ waiting: false,
196
+ };
197
+ }
198
+ }
199
+ /** How often the confirmation page asks again while an order is pending. */
200
+ export const WAITING_POLL_MS = 2000;
201
+ /**
202
+ * The operations each hook calls (ADR 0453). A client gets the hooks whose operations it holds:
203
+ * the door role's client gets `useCheckIn`, `useUndoCheckIn` and `useTicketPicker`, a customer's
204
+ * client the buying hooks, the staff client all of them.
205
+ */
206
+ export const TICKETING_HOOKS_CALL = {
207
+ useEventsOnSale: ["x.ticketing.eventsOnSale"],
208
+ useTicketPicker: [],
209
+ useStartOrder: ["x.ticketing.orderStart"],
210
+ useCheckout: ["order.checkout"],
211
+ useOrder: ["order.view", "order.get"],
212
+ useMyTickets: ["x.ticketing.myTickets"],
213
+ useCheckIn: ["x.ticketing.checkIn"],
214
+ useUndoCheckIn: ["x.ticketing.undoCheckIn"],
215
+ };
216
+ /**
217
+ * Hooks for a React or React Native app:
218
+ * `const ticketing = createTicketingHooks({ useQuery, useMutation, useState }, api)`. `api` is any
219
+ * generated client: the customer's, a pack role's (`roles/ticketing.door.ts`) or the staff one.
220
+ * The hooks it cannot back are not there, and calling one does not compile.
221
+ */
222
+ export function createTicketingHooks(react, client) {
223
+ return packHooks(client, TICKETING_HOOKS_CALL, (api) => allTicketingHooks(react, api));
224
+ }
225
+ function allTicketingHooks(react, api) {
226
+ const { useQuery, useMutation, useState } = react;
227
+ return {
228
+ /** The events on sale (or one), with their ticket types and places. */
229
+ useEventsOnSale(input = {}) {
230
+ return useQuery(api.query("x.ticketing.eventsOnSale", input));
231
+ },
232
+ /** Quantities for one event's ticket types, the lines to start with and the preview. */
233
+ useTicketPicker(event) {
234
+ const [quantities, setQuantities] = useState({});
235
+ const set = (ticketTypeId, quantity) => {
236
+ const type = event?.ticketTypes.find((t) => t.id === ticketTypeId);
237
+ const max = type ? pickerMax(type) : 0;
238
+ setQuantities((previous) => ({
239
+ ...previous,
240
+ [ticketTypeId]: Math.max(0, Math.min(Math.trunc(quantity), max)),
241
+ }));
242
+ };
243
+ const lines = pickerLines(quantities);
244
+ return {
245
+ quantities,
246
+ set,
247
+ lines,
248
+ estimate: event ? estimate(event, quantities) : { full: 0, deposit: null, currency: null },
249
+ empty: lines.length === 0,
250
+ max: (type) => pickerMax(type),
251
+ clear: () => setQuantities({}),
252
+ };
253
+ },
254
+ /** Starts the order through the host, which prices it and holds the places. */
255
+ useStartOrder() {
256
+ return useMutation(api.mutation("x.ticketing.orderStart"));
257
+ },
258
+ /** Opens the payment provider's page for an order (the first payment, or a balance). */
259
+ useCheckout() {
260
+ return useMutation(api.mutation("order.checkout"));
261
+ },
262
+ /** One order as its buyer sees it, asked again while it is waiting for the provider. */
263
+ useOrder(order) {
264
+ const options = order
265
+ ? order.token
266
+ ? api.query("order.view", { id: order.id, token: order.token })
267
+ : api.query("order.get", { id: order.id })
268
+ : { queryKey: ["order.none"], queryFn: async () => undefined };
269
+ return useQuery({
270
+ ...options,
271
+ enabled: order !== null,
272
+ refetchInterval: (query) => query.state.data && orderStatus(query.state.data).waiting ? WAITING_POLL_MS : false,
273
+ });
274
+ },
275
+ /** The signed-in customer's own tickets. */
276
+ useMyTickets(input = {}) {
277
+ return useQuery(api.query("x.ticketing.myTickets", input));
278
+ },
279
+ /** Checks a ticket in by its code (staff, or a door account). */
280
+ useCheckIn() {
281
+ return useMutation(api.mutation("x.ticketing.checkIn"));
282
+ },
283
+ /** Undoes a check-in made by mistake. */
284
+ useUndoCheckIn() {
285
+ return useMutation(api.mutation("x.ticketing.undoCheckIn"));
286
+ },
287
+ };
288
+ }
@@ -0,0 +1,5 @@
1
+ import type { DashboardDeclaration } from "@composable-os/sdk";
2
+ export declare const ticketSales: DashboardDeclaration;
3
+ export declare const ticketingDashboards: {
4
+ ticketSales: DashboardDeclaration;
5
+ };
@@ -0,0 +1,91 @@
1
+ const SOLD = "o.state IN ('paid', 'part_paid')";
2
+ const PAID_IN = "o.paid_at >= :paid_from AND o.paid_at < :paid_to";
3
+ const LINES = `FROM rec_order_line l JOIN rec_order o ON o.id = l.order_id
4
+ JOIN rec_x_ticketing_tickettype tt ON tt.id = l.record_id
5
+ JOIN rec_x_ticketing_event e ON e.id = tt.event
6
+ WHERE l.object_type = 'ticketing.tickettype' AND ${SOLD} AND ${PAID_IN}`;
7
+ export const ticketSales = {
8
+ title: "Ticket sales",
9
+ description: "Revenue and tickets sold by event and by day, and the places each event has left.",
10
+ filters: [{ type: "dateRange", id: "paid", label: "Paid", default: "this_quarter" }],
11
+ widgets: [
12
+ {
13
+ id: "revenue",
14
+ type: "kpi",
15
+ title: "Revenue",
16
+ description: "Line totals of ticket orders paid in full or by deposit in the period.",
17
+ sql: `SELECT coalesce(sum(l.line_total), 0) / 100.0 AS value ${LINES}`,
18
+ mapping: { value: "value" },
19
+ options: { compare: true, format: "currency" },
20
+ layout: { w: 4, h: 1 },
21
+ },
22
+ {
23
+ id: "sold",
24
+ type: "kpi",
25
+ title: "Tickets sold",
26
+ description: "Tickets on orders paid in full or by deposit in the period.",
27
+ sql: `SELECT coalesce(sum(l.quantity), 0) AS value ${LINES}`,
28
+ mapping: { value: "value" },
29
+ options: { compare: true },
30
+ layout: { w: 4, h: 1 },
31
+ },
32
+ {
33
+ id: "unused",
34
+ type: "kpi",
35
+ title: "Valid tickets not yet used",
36
+ description: "Tickets that are valid and not checked in, for every event.",
37
+ sql: "SELECT count(*) AS value FROM rec_x_ticketing_ticket t WHERE t.state = 'valid'",
38
+ mapping: { value: "value" },
39
+ options: { compare: false },
40
+ clickThrough: {
41
+ object: "ticketing.ticket",
42
+ filter: { field: "state", op: "eq", value: "valid" },
43
+ },
44
+ layout: { w: 4, h: 1 },
45
+ },
46
+ {
47
+ id: "by-event",
48
+ type: "bar",
49
+ title: "Sold by event",
50
+ description: "Tickets sold and revenue per event in the period.",
51
+ sql: `SELECT e.id AS event_id, e.name AS event, sum(l.quantity) AS tickets,
52
+ sum(l.line_total) / 100.0 AS revenue ${LINES}
53
+ GROUP BY e.id, e.name ORDER BY tickets DESC LIMIT 20`,
54
+ mapping: { x: "event", y: ["tickets"] },
55
+ clickThrough: {
56
+ object: "ticketing.ticket",
57
+ filter: { field: "event", op: "eq", value: { $row: "event_id" } },
58
+ },
59
+ layout: { w: 6, h: 2 },
60
+ },
61
+ {
62
+ id: "by-day",
63
+ type: "line",
64
+ title: "Sold by day",
65
+ description: "Tickets sold per day in the period, by when the order was paid.",
66
+ sql: `SELECT substr(o.paid_at, 1, 10) AS day, sum(l.quantity) AS tickets ${LINES}
67
+ GROUP BY day ORDER BY day`,
68
+ mapping: { x: "day", y: ["tickets"] },
69
+ layout: { w: 6, h: 2 },
70
+ },
71
+ {
72
+ id: "places",
73
+ type: "table",
74
+ title: "Places left",
75
+ description: "Each event on sale: its places, how many are taken or held, and how many are left.",
76
+ // Places are the host's counters (rec_capacity), not columns of the event's own view.
77
+ sql: `SELECT e.id AS id, e.name AS event, e.starts_at AS starts, c.places AS places,
78
+ c.taken AS taken, c.held AS held, c.available AS available
79
+ FROM rec_x_ticketing_event e
80
+ LEFT JOIN rec_capacity c ON c.object_type = 'ticketing.event' AND c.record_id = e.id
81
+ WHERE e.status = 'on_sale' ORDER BY e.starts_at LIMIT 50`,
82
+ mapping: { columns: ["event", "starts", "places", "taken", "held", "available"] },
83
+ clickThrough: {
84
+ object: "ticketing.event",
85
+ filter: { field: "id", op: "eq", value: { $row: "id" } },
86
+ },
87
+ layout: { w: 12, h: 2 },
88
+ },
89
+ ],
90
+ };
91
+ export const ticketingDashboards = { ticketSales };