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

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.
package/LICENSE ADDED
@@ -0,0 +1,109 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ > This licence covers the repository except the directories listed in NOTICE. In particular, the
4
+ > assistant packages `packages/agent-*` (agent-core, agent-a2ui, agent-voice, agent-plugins) are
5
+ > licensed under the MIT License; see the LICENSE file in each of those directories (ADR 0350).
6
+
7
+ ## Abbreviation
8
+
9
+ FSL-1.1-ALv2
10
+
11
+ ## Notice
12
+
13
+ Copyright 2026 Tim O'Connell
14
+
15
+ ## Terms and Conditions
16
+
17
+ ### Licensor ("We")
18
+
19
+ The party offering the Software under these Terms and Conditions.
20
+
21
+ ### The Software
22
+
23
+ The "Software" is each version of the software that we make available under
24
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
25
+ Conditions with the Software.
26
+
27
+ ### License Grant
28
+
29
+ Subject to your compliance with this License Grant and the Patents,
30
+ Redistribution and Trademark clauses below, we hereby grant you the right to
31
+ use, copy, modify, create derivative works, publicly perform, publicly display
32
+ and redistribute the Software for any Permitted Purpose identified below.
33
+
34
+ ### Permitted Purpose
35
+
36
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
37
+ means making the Software available to others in a commercial product or
38
+ service that:
39
+
40
+ 1. substitutes for the Software;
41
+
42
+ 2. substitutes for any other product or service we offer using the Software
43
+ that exists as of the date we make the Software available; or
44
+
45
+ 3. offers the same or substantially similar functionality as the Software.
46
+
47
+ Permitted Purposes specifically include using the Software:
48
+
49
+ 1. for your internal use and access;
50
+
51
+ 2. for non-commercial education;
52
+
53
+ 3. for non-commercial research; and
54
+
55
+ 4. in connection with professional services that you provide to a licensee
56
+ using the Software in accordance with these Terms and Conditions.
57
+
58
+ ### Patents
59
+
60
+ To the extent your use for a Permitted Purpose would necessarily infringe our
61
+ patents, the license grant above includes a license under our patents. If you
62
+ make a claim against any party that the Software infringes or contributes to
63
+ the infringement of any patent, then your patent license to the Software ends
64
+ immediately.
65
+
66
+ ### Redistribution
67
+
68
+ The Terms and Conditions apply to all copies, modifications and derivatives of
69
+ the Software.
70
+
71
+ If you redistribute any copies, modifications or derivatives of the Software,
72
+ you must include a copy of or a link to these Terms and Conditions and not
73
+ remove any copyright notices provided in or with the Software.
74
+
75
+ ### Disclaimer
76
+
77
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
78
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
79
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
80
+
81
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
82
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
83
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
84
+
85
+ ### Trademarks
86
+
87
+ Except for displaying the License Details and identifying us as the origin of
88
+ the Software, you have no right under these Terms and Conditions to use our
89
+ trademarks, trade names, service marks or product names.
90
+
91
+ ## Grant of Future License
92
+
93
+ We hereby irrevocably grant you an additional license to use the Software under
94
+ the Apache License, Version 2.0 that is effective on the second anniversary of
95
+ the date we make the Software available. On or after that date, you may use the
96
+ Software under the Apache License, Version 2.0, in which case the following
97
+ will apply:
98
+
99
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
100
+ this file except in compliance with the License.
101
+
102
+ You may obtain a copy of the License at
103
+
104
+ http://www.apache.org/licenses/LICENSE-2.0
105
+
106
+ Unless required by applicable law or agreed to in writing, software distributed
107
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
108
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
109
+ specific language governing permissions and limitations under the License.
@@ -0,0 +1,72 @@
1
+ /** Most buyers reminded in one run of the daily balance reminders; the rest wait a day. */
2
+ export declare const BALANCE_BATCH = 200;
3
+ /**
4
+ * When an event starts, as its holders read it: the day and time in the event's own zone, and
5
+ * the zone, so a camp in Bangkok sold from Sydney says Bangkok's time (ADR 0460).
6
+ */
7
+ export declare function eventTimeText(iso: string | null, zone: string | null): string | null;
8
+ export declare const ticketsByEmail: import("@composable-os/sdk").AutomationSpec<{
9
+ readonly type: "fieldChanged";
10
+ readonly object: "order";
11
+ readonly field: "state";
12
+ readonly from: {
13
+ readonly in: readonly ["pending", "expired"];
14
+ };
15
+ readonly to: {
16
+ readonly in: readonly ["paid", "part_paid"];
17
+ };
18
+ }>;
19
+ export declare const eventReminder: import("@composable-os/sdk").AutomationSpec<{
20
+ readonly type: "dateRelative";
21
+ readonly object: "ticketing.event";
22
+ readonly field: "startsAt";
23
+ readonly offsetDays: -1;
24
+ readonly zoneField: "timezone";
25
+ }>;
26
+ export declare const eventEnded: import("@composable-os/sdk").AutomationSpec<{
27
+ readonly type: "dateRelative";
28
+ readonly object: "ticketing.event";
29
+ readonly field: "endsAt";
30
+ readonly offsetDays: 1;
31
+ readonly zoneField: "timezone";
32
+ }>;
33
+ /**
34
+ * Part-paid orders with a ticket on them whose balance falls due in exactly 7 or 1 days, counted
35
+ * in UTC days from the run's period. Read over the host's order views.
36
+ */
37
+ export declare const BALANCE_SQL = "\nSELECT o.id AS id, o.email AS email, o.balance AS balance, o.currency AS currency,\n o.balance_due_at AS due\nFROM rec_order o\nWHERE o.state = 'part_paid' AND o.balance > 0 AND o.email IS NOT NULL\n AND substr(o.balance_due_at, 1, 10) IN (?1, ?2)\n AND EXISTS (SELECT 1 FROM rec_order_line l WHERE l.order_id = o.id AND l.object_type = 'ticketing.tickettype')\nORDER BY o.balance_due_at, o.id\nLIMIT 200";
38
+ export declare const balanceReminders: import("@composable-os/sdk").AutomationSpec<{
39
+ readonly type: "schedule";
40
+ readonly cron: "0 9 * * *";
41
+ }>;
42
+ export declare const ticketingAutomations: {
43
+ ticketsByEmail: import("@composable-os/sdk").AutomationSpec<{
44
+ readonly type: "fieldChanged";
45
+ readonly object: "order";
46
+ readonly field: "state";
47
+ readonly from: {
48
+ readonly in: readonly ["pending", "expired"];
49
+ };
50
+ readonly to: {
51
+ readonly in: readonly ["paid", "part_paid"];
52
+ };
53
+ }>;
54
+ eventReminder: import("@composable-os/sdk").AutomationSpec<{
55
+ readonly type: "dateRelative";
56
+ readonly object: "ticketing.event";
57
+ readonly field: "startsAt";
58
+ readonly offsetDays: -1;
59
+ readonly zoneField: "timezone";
60
+ }>;
61
+ eventEnded: import("@composable-os/sdk").AutomationSpec<{
62
+ readonly type: "dateRelative";
63
+ readonly object: "ticketing.event";
64
+ readonly field: "endsAt";
65
+ readonly offsetDays: 1;
66
+ readonly zoneField: "timezone";
67
+ }>;
68
+ balanceReminders: import("@composable-os/sdk").AutomationSpec<{
69
+ readonly type: "schedule";
70
+ readonly cron: "0 9 * * *";
71
+ }>;
72
+ };
@@ -0,0 +1,347 @@
1
+ // The Ticketing automations (stage 27, step 4). They send the buyer's mail through the email-send
2
+ // gatekeeper (a connection an admin binds when the pack is installed, so a person approves what
3
+ // the pack may send), move an event to ended, and add no rule of their own: what is paid, what is
4
+ // owed and when is the host's. Each declares its steps, so the host renders the summary from them.
5
+ import { defineAutomation } from "@composable-os/sdk";
6
+ const EVENT = "ticketing.event";
7
+ const TICKET = "ticketing.ticket";
8
+ const TICKET_TYPE = "ticketing.tickettype";
9
+ const DAY_MS = 86_400_000;
10
+ /** Most buyers reminded in one run of the daily balance reminders; the rest wait a day. */
11
+ export const BALANCE_BATCH = 200;
12
+ /** The email-send connection every mail goes through. */
13
+ const MAIL = {
14
+ id: "mail",
15
+ gatekeeper: "email-send",
16
+ purpose: "Send buyers their tickets and reminders",
17
+ };
18
+ const text = (value) => value === null || value === undefined || value === "" ? null : String(value);
19
+ /** The pack's settings an admin set (Settings → Extensions), by name. */
20
+ async function settings(ctx) {
21
+ const { items } = await ctx.ops.call("extensionSettings.list");
22
+ return items.find((item) => item.id === "ticketing")?.values ?? {};
23
+ }
24
+ /** A link with `?order=<id>`, or the page alone. */
25
+ function withOrder(base, orderId) {
26
+ const url = text(base);
27
+ if (!url)
28
+ return null;
29
+ return `${url}${url.includes("?") ? "&" : "?"}order=${encodeURIComponent(orderId)}`;
30
+ }
31
+ /** Sends one email to one buyer through the bound email-send connection. */
32
+ async function sendMail(ctx, message) {
33
+ const gatekeeper = ctx.gatekeeper("email-send");
34
+ const connections = await gatekeeper.connections();
35
+ const resource = connections.find((c) => c.id === MAIL.id)?.resources[0]?.bindingName ??
36
+ connections[0]?.resources[0]?.bindingName ??
37
+ "SENDER";
38
+ const result = await gatekeeper.call(MAIL.id, resource, "send", {
39
+ to: [message.to],
40
+ subject: message.subject,
41
+ text: message.text,
42
+ ...(message.related?.length ? { relatedRecords: message.related.slice(0, 20) } : {}),
43
+ });
44
+ return result.value;
45
+ }
46
+ const money = (minor, currency) => `${(minor / 100).toFixed(2)} ${currency}`;
47
+ /**
48
+ * When an event starts, as its holders read it: the day and time in the event's own zone, and
49
+ * the zone, so a camp in Bangkok sold from Sydney says Bangkok's time (ADR 0460).
50
+ */
51
+ export function eventTimeText(iso, zone) {
52
+ if (!iso)
53
+ return null;
54
+ const at = new Date(iso);
55
+ if (Number.isNaN(at.getTime()))
56
+ return iso;
57
+ const timeZone = zone ?? "UTC";
58
+ try {
59
+ const local = new Intl.DateTimeFormat("en-GB", {
60
+ timeZone,
61
+ weekday: "long",
62
+ day: "numeric",
63
+ month: "long",
64
+ year: "numeric",
65
+ hour: "2-digit",
66
+ minute: "2-digit",
67
+ hourCycle: "h23",
68
+ }).format(at);
69
+ return `${local} (${timeZone.replace(/_/g, " ")} time)`;
70
+ }
71
+ catch {
72
+ return iso;
73
+ }
74
+ }
75
+ // --- Tickets by email ---------------------------------------------------------------------------
76
+ export const ticketsByEmail = defineAutomation({
77
+ label: "Tickets by email",
78
+ description: "When an order is first paid (in full, or its deposit), emails the buyer their tickets: " +
79
+ "one line per ticket with its code, and the page where they can show them.",
80
+ trigger: {
81
+ type: "fieldChanged",
82
+ object: "order",
83
+ field: "state",
84
+ from: { in: ["pending", "expired"] },
85
+ to: { in: ["paid", "part_paid"] },
86
+ },
87
+ connections: [MAIL],
88
+ steps: [
89
+ {
90
+ name: "findTickets",
91
+ label: "Find the order's tickets",
92
+ reads: [TICKET, EVENT],
93
+ calls: ["order.get", "extensionSettings.list"],
94
+ },
95
+ { name: "sendTickets", label: "Email the buyer their tickets" },
96
+ ],
97
+ async run(event, step, ctx) {
98
+ const orderId = event.record?.id;
99
+ if (!orderId)
100
+ return { skipped: "no order" };
101
+ const found = await step.do("findTickets", async () => {
102
+ const order = await ctx.ops.call("order.get", {
103
+ id: orderId,
104
+ });
105
+ const tickets = await ctx.ops.call("record.list", {
106
+ object: TICKET,
107
+ filter: { field: "order", op: "eq", value: orderId },
108
+ limit: 100,
109
+ });
110
+ const { ticketsUrl } = await settings(ctx);
111
+ // The events the tickets are for, with when each starts in its own zone.
112
+ const eventIds = [...new Set(tickets.items.map((t) => text(t.values.event)))].filter((id) => Boolean(id));
113
+ const events = [];
114
+ for (const id of eventIds) {
115
+ const ev = await ctx.ops.call("record.get", { object: EVENT, id });
116
+ const when = eventTimeText(text(ev.values.startsAt), text(ev.values.timezone));
117
+ const venue = text(ev.values.venue);
118
+ events.push(`${text(ev.values.name) ?? "Your event"}${when ? `: ${when}` : ""}${venue ? `, ${venue}` : ""}`);
119
+ }
120
+ return {
121
+ email: order.email,
122
+ events,
123
+ page: withOrder(ticketsUrl, orderId),
124
+ tickets: tickets.items.map((t) => ({
125
+ id: t.id,
126
+ name: text(t.values.name) ?? "Ticket",
127
+ code: text(t.values.code) ?? "",
128
+ })),
129
+ };
130
+ });
131
+ // An order of something else, or with no address: nothing to send.
132
+ if (!found.tickets.length || !found.email)
133
+ return { sent: false, tickets: 0 };
134
+ return step.do("sendTickets", async () => {
135
+ const lines = found.tickets.map((t) => `${t.name}: ${t.code}`);
136
+ await sendMail(ctx, {
137
+ to: found.email,
138
+ subject: found.tickets.length === 1 ? "Your ticket" : `Your ${found.tickets.length} tickets`,
139
+ text: [
140
+ "Thank you. Your tickets are below: show the code at the door.",
141
+ ...(found.events.length ? ["", ...found.events] : []),
142
+ "",
143
+ ...lines,
144
+ ...(found.page ? ["", `See them any time: ${found.page}`] : []),
145
+ ].join("\n"),
146
+ related: [orderId, ...found.tickets.map((t) => t.id)],
147
+ });
148
+ return { sent: true, tickets: found.tickets.length };
149
+ });
150
+ },
151
+ });
152
+ // --- The day before ------------------------------------------------------------------------------
153
+ export const eventReminder = defineAutomation({
154
+ label: "Event reminder",
155
+ description: "The day before an event on sale starts, counted in the event's own time zone, emails each " +
156
+ "holder of a valid ticket a reminder with the time (in that zone) and the venue.",
157
+ trigger: {
158
+ type: "dateRelative",
159
+ object: EVENT,
160
+ field: "startsAt",
161
+ offsetDays: -1,
162
+ zoneField: "timezone",
163
+ },
164
+ conditions: { field: "status", op: "eq", value: "on_sale" },
165
+ connections: [MAIL],
166
+ steps: [
167
+ {
168
+ name: "findHolders",
169
+ label: "Find the holders of valid tickets",
170
+ reads: [TICKET, "person"],
171
+ },
172
+ { name: "sendReminders", label: "Email each holder" },
173
+ ],
174
+ async run(event, step, ctx) {
175
+ const eventId = event.record?.id;
176
+ if (!eventId)
177
+ return { skipped: "no event" };
178
+ const data = event.record?.data ?? {};
179
+ const holders = await step.do("findHolders", async () => {
180
+ const emails = new Map();
181
+ let cursor = null;
182
+ do {
183
+ const page = await ctx.ops.call("record.list", {
184
+ object: TICKET,
185
+ filter: {
186
+ and: [
187
+ { field: "event", op: "eq", value: eventId },
188
+ { field: "state", op: "eq", value: "valid" },
189
+ ],
190
+ },
191
+ limit: 200,
192
+ ...(cursor ? { cursor } : {}),
193
+ });
194
+ for (const ticket of page.items) {
195
+ const holder = text(ticket.values.holder);
196
+ if (!holder)
197
+ continue;
198
+ emails.set(holder, [...(emails.get(holder) ?? []), ticket.id]);
199
+ }
200
+ cursor = page.nextCursor;
201
+ } while (cursor);
202
+ const out = [];
203
+ for (const [personId, tickets] of emails) {
204
+ const person = await ctx.ops.call("person.get", {
205
+ id: personId,
206
+ });
207
+ if (person?.primaryEmail)
208
+ out.push({ email: person.primaryEmail, tickets });
209
+ }
210
+ return out;
211
+ });
212
+ if (!holders.length)
213
+ return { sent: 0 };
214
+ return step.do("sendReminders", async () => {
215
+ const name = text(data.name) ?? "Your event";
216
+ const when = eventTimeText(text(data.startsAt), text(data.timezone));
217
+ const venue = text(data.venue);
218
+ for (const holder of holders) {
219
+ await sendMail(ctx, {
220
+ to: holder.email,
221
+ subject: `Tomorrow: ${name}`,
222
+ text: [
223
+ `${name} is tomorrow${when ? `, starting ${when}` : ""}${venue ? ` at ${venue}` : ""}.`,
224
+ `You have ${holder.tickets.length === 1 ? "a ticket" : `${holder.tickets.length} tickets`}: bring the code.`,
225
+ ].join("\n"),
226
+ related: [eventId, ...holder.tickets],
227
+ });
228
+ }
229
+ return { sent: holders.length };
230
+ });
231
+ },
232
+ });
233
+ // --- The day after -------------------------------------------------------------------------------
234
+ export const eventEnded = defineAutomation({
235
+ label: "Event ended",
236
+ description: "The day after an event on sale ends, counted in the event's own time zone, moves it to ended.",
237
+ trigger: {
238
+ type: "dateRelative",
239
+ object: EVENT,
240
+ field: "endsAt",
241
+ offsetDays: 1,
242
+ zoneField: "timezone",
243
+ },
244
+ conditions: { field: "status", op: "eq", value: "on_sale" },
245
+ steps: [
246
+ {
247
+ name: "markEnded",
248
+ label: "Move the event to ended",
249
+ writes: [{ object: EVENT, action: "update", count: 1 }],
250
+ },
251
+ ],
252
+ async run(event, step, ctx) {
253
+ const eventId = event.record?.id;
254
+ if (!eventId)
255
+ return { skipped: "no event" };
256
+ return step.do("markEnded", async () => {
257
+ // Only out of on_sale: if staff moved it meanwhile, the host refuses and nothing changes.
258
+ try {
259
+ await ctx.ops.call("record.update", {
260
+ object: EVENT,
261
+ id: eventId,
262
+ from: "on_sale",
263
+ values: { status: "ended" },
264
+ });
265
+ return { ended: true };
266
+ }
267
+ catch (error) {
268
+ if (error.code === "conflict")
269
+ return { ended: false };
270
+ throw error;
271
+ }
272
+ });
273
+ },
274
+ });
275
+ // --- Balance reminders ---------------------------------------------------------------------------
276
+ /**
277
+ * Part-paid orders with a ticket on them whose balance falls due in exactly 7 or 1 days, counted
278
+ * in UTC days from the run's period. Read over the host's order views.
279
+ */
280
+ export const BALANCE_SQL = `
281
+ SELECT o.id AS id, o.email AS email, o.balance AS balance, o.currency AS currency,
282
+ o.balance_due_at AS due
283
+ FROM rec_order o
284
+ WHERE o.state = 'part_paid' AND o.balance > 0 AND o.email IS NOT NULL
285
+ AND substr(o.balance_due_at, 1, 10) IN (?1, ?2)
286
+ AND EXISTS (SELECT 1 FROM rec_order_line l WHERE l.order_id = o.id AND l.object_type = '${TICKET_TYPE}')
287
+ ORDER BY o.balance_due_at, o.id
288
+ LIMIT ${BALANCE_BATCH}`;
289
+ const isoDay = (ms) => new Date(ms).toISOString().slice(0, 10);
290
+ /** The day a schedule run is for (`2026-11-05` or `2026-11-05T09:00`) as epoch ms. */
291
+ function periodMs(period) {
292
+ const parsed = period ? Date.parse(period.length === 10 ? `${period}T00:00:00Z` : period) : NaN;
293
+ return Number.isNaN(parsed) ? Date.now() : parsed;
294
+ }
295
+ export const balanceReminders = defineAutomation({
296
+ label: "Balance reminders",
297
+ description: "Every morning, emails the buyer of a part-paid ticket order whose balance is due in a week " +
298
+ "or tomorrow: how much is owed, when, and the link to pay.",
299
+ trigger: { type: "schedule", cron: "0 9 * * *" },
300
+ connections: [MAIL],
301
+ steps: [
302
+ {
303
+ name: "findDue",
304
+ label: "Find part-paid orders due in a week or tomorrow",
305
+ calls: ["query.sql", "extensionSettings.list"],
306
+ },
307
+ { name: "sendReminders", label: "Email each buyer the balance and the link to pay" },
308
+ ],
309
+ async run(event, step, ctx) {
310
+ const due = await step.do("findDue", async () => {
311
+ const today = periodMs(event.period);
312
+ const { rows } = await ctx.ops.call("query.sql", {
313
+ sql: BALANCE_SQL,
314
+ params: [isoDay(today + 7 * DAY_MS), isoDay(today + DAY_MS)],
315
+ maxRows: BALANCE_BATCH,
316
+ });
317
+ const { payUrl } = await settings(ctx);
318
+ return rows.map((row) => ({ ...row, link: withOrder(payUrl, row.id) }));
319
+ });
320
+ if (!due.length)
321
+ return { sent: 0 };
322
+ return step.do("sendReminders", async () => {
323
+ for (const order of due) {
324
+ const day = order.due.slice(0, 10);
325
+ await sendMail(ctx, {
326
+ to: order.email,
327
+ subject: `Balance due ${day}`,
328
+ text: [
329
+ `The balance on your tickets, ${money(order.balance, order.currency)}, is due on ${day}.`,
330
+ order.link
331
+ ? `Pay it here (sign in with this email address): ${order.link}`
332
+ : "Reply to this email to pay it.",
333
+ "You can pay it in one go or in parts.",
334
+ ].join("\n"),
335
+ related: [order.id],
336
+ });
337
+ }
338
+ return { sent: due.length };
339
+ });
340
+ },
341
+ });
342
+ export const ticketingAutomations = {
343
+ ticketsByEmail,
344
+ eventReminder,
345
+ eventEnded,
346
+ balanceReminders,
347
+ };
@@ -0,0 +1,25 @@
1
+ import type { EventOnSale, StartedOrder, TicketingHooks } from "@composable-os/pack-ticketing/client";
2
+ /**
3
+ * The picker and checkout. `signedIn`: the buyer is a signed-in customer (no email asked).
4
+ * `returnUrl`: the confirmation page, on one of the deployment's allowed sites; it gets the order
5
+ * (and a guest's token) from `onStarted`, which is called before the buyer leaves.
6
+ */
7
+ export declare function TicketPicker({ ticketing, event, signedIn, returnUrl, onStarted, }: {
8
+ ticketing: Pick<TicketingHooks, "useCheckout" | "useOrder" | "useStartOrder" | "useTicketPicker">;
9
+ event: EventOnSale;
10
+ signedIn: boolean;
11
+ returnUrl: string;
12
+ onStarted: (order: StartedOrder) => void;
13
+ }): import("react").JSX.Element;
14
+ /**
15
+ * Paying what is still owed on a part-paid order, in one go or a part of it. The host decides
16
+ * what may be charged (a part at least its minimum, never more than the balance).
17
+ */
18
+ export declare function BalancePayment({ ticketing, order, returnUrl, }: {
19
+ ticketing: Pick<TicketingHooks, "useCheckout" | "useOrder" | "useStartOrder" | "useTicketPicker">;
20
+ order: {
21
+ id: string;
22
+ token?: string | null;
23
+ };
24
+ returnUrl: string;
25
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,77 @@
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
+ import { availabilityLabel, eventCurrency, formatMoney, formatPrice, minorFromInput, } from "@composable-os/pack-ticketing/client";
3
+ import { useState } from "react";
4
+ import { Button } from "../ui-button/button.js";
5
+ import { Input } from "../ui-input/input.js";
6
+ import { Label } from "../ui-label/label.js";
7
+ /** What the host said when it refused, in the buyer's words. */
8
+ function refusal(error) {
9
+ if (!error)
10
+ return null;
11
+ const rule = error.details;
12
+ switch (rule?.details?.rule ?? rule?.rule) {
13
+ case "capacity":
14
+ return "There are not enough places left for that many. Choose fewer.";
15
+ case "sale_window":
16
+ return "These tickets are not on sale right now.";
17
+ case "max_per_order":
18
+ return "That is more than one order may hold. Choose fewer.";
19
+ default:
20
+ return "We could not start your order. Try again in a moment.";
21
+ }
22
+ }
23
+ /**
24
+ * The picker and checkout. `signedIn`: the buyer is a signed-in customer (no email asked).
25
+ * `returnUrl`: the confirmation page, on one of the deployment's allowed sites; it gets the order
26
+ * (and a guest's token) from `onStarted`, which is called before the buyer leaves.
27
+ */
28
+ export function TicketPicker({ ticketing, event, signedIn, returnUrl, onStarted, }) {
29
+ const picker = ticketing.useTicketPicker(event);
30
+ // The currency is the host's, given with the prices; the picker states none of its own.
31
+ const currency = eventCurrency(event);
32
+ const start = ticketing.useStartOrder();
33
+ const checkout = ticketing.useCheckout();
34
+ const [email, setEmail] = useState("");
35
+ const [pay, setPay] = useState("full");
36
+ const byDeposit = picker.estimate.deposit !== null;
37
+ async function submit(e) {
38
+ e.preventDefault();
39
+ const order = await start.mutateAsync({
40
+ lines: picker.lines,
41
+ pay: byDeposit ? pay : "full",
42
+ ...(signedIn ? {} : { email }),
43
+ });
44
+ onStarted(order);
45
+ const page = await checkout.mutateAsync({
46
+ id: order.id,
47
+ ...(order.token ? { token: order.token } : {}),
48
+ returnUrl,
49
+ });
50
+ window.location.assign(page.url);
51
+ }
52
+ return (_jsxs("form", { onSubmit: submit, className: "grid gap-4", children: [event.ticketTypes.map((type) => (_jsxs("div", { className: "grid gap-1", children: [_jsxs(Label, { htmlFor: `qty-${type.id}`, children: [type.name, " \u00B7 ", formatPrice(type.price, currency), type.deposit !== null ? ` (deposit ${formatPrice(type.deposit, currency)})` : ""] }), _jsx(Input, { id: `qty-${type.id}`, type: "number", inputMode: "numeric", min: 0, max: picker.max(type), disabled: picker.max(type) === 0, value: picker.quantities[type.id] ?? 0, onChange: (e) => picker.set(type.id, Number(e.target.value)) }), availabilityLabel(type.availability) ? (_jsx("span", { className: "text-sm text-muted-foreground", children: availabilityLabel(type.availability) })) : null] }, type.id))), byDeposit ? (_jsxs("fieldset", { className: "grid gap-2", children: [_jsx("legend", { children: "How would you like to pay?" }), _jsxs("label", { children: [_jsx("input", { type: "radio", name: "pay", checked: pay === "full", onChange: () => setPay("full") }), " ", "In full: ", formatMoney(picker.estimate.full, currency)] }), _jsxs("label", { children: [_jsx("input", { type: "radio", name: "pay", checked: pay === "deposit", onChange: () => setPay("deposit") }), " ", "A deposit now: ", formatMoney(picker.estimate.deposit ?? 0, currency), ", the rest by the date on your ticket type"] })] })) : (_jsx("p", { children: picker.empty ? "Choose your tickets." : formatMoney(picker.estimate.full, currency) })), signedIn ? null : (_jsxs("div", { className: "grid gap-1", children: [_jsx(Label, { htmlFor: "buyer-email", children: "Email (your tickets are sent here)" }), _jsx(Input, { id: "buyer-email", type: "email", autoComplete: "email", required: true, value: email, onChange: (e) => setEmail(e.target.value) })] })), refusal(start.error ?? checkout.error) ? (_jsx("p", { role: "alert", children: refusal(start.error ?? checkout.error) })) : null, _jsx(Button, { type: "submit", disabled: picker.empty || start.isPending || checkout.isPending, children: start.isPending || checkout.isPending ? "Opening the payment page…" : "Pay" })] }));
53
+ }
54
+ /**
55
+ * Paying what is still owed on a part-paid order, in one go or a part of it. The host decides
56
+ * what may be charged (a part at least its minimum, never more than the balance).
57
+ */
58
+ export function BalancePayment({ ticketing, order, returnUrl, }) {
59
+ const current = ticketing.useOrder(order);
60
+ const checkout = ticketing.useCheckout();
61
+ const [part, setPart] = useState("");
62
+ const data = current.data;
63
+ if (!data)
64
+ return current.isPending ? _jsx("p", { "aria-busy": "true", children: "Loading your order\u2026" }) : null;
65
+ if (data.state !== "part_paid")
66
+ return null;
67
+ async function open(amount) {
68
+ const page = await checkout.mutateAsync({
69
+ id: order.id,
70
+ ...(order.token ? { token: order.token } : {}),
71
+ returnUrl,
72
+ ...(amount === null ? {} : { amount }),
73
+ });
74
+ window.location.assign(page.url);
75
+ }
76
+ return (_jsxs("div", { className: "grid gap-3", children: [_jsxs("p", { children: ["Still to pay: ", formatMoney(data.balance, data.currency), data.balanceDueAt ? `, by ${new Date(data.balanceDueAt).toLocaleDateString()}` : "", "."] }), _jsx(Button, { onClick: () => open(data.balance), disabled: checkout.isPending, children: "Pay it all" }), _jsxs("div", { className: "grid gap-1", children: [_jsx(Label, { htmlFor: "part", children: "Or pay part of it" }), _jsx(Input, { id: "part", inputMode: "decimal", value: part, onChange: (e) => setPart(e.target.value) }), _jsx(Button, { onClick: () => open(minorFromInput(part, data.currency)), disabled: checkout.isPending || minorFromInput(part, data.currency) === null, children: "Pay this amount" })] }), checkout.error ? (_jsx("p", { role: "alert", children: "That amount cannot be paid. It must be at least the minimum, and no more than you owe." })) : null] }));
77
+ }
@@ -0,0 +1,15 @@
1
+ import type { EventOnSale, TicketingHooks } from "@composable-os/pack-ticketing/client";
2
+ import type { ReactNode } from "react";
3
+ /** Every event on sale, soonest first, each with a button to open it. */
4
+ export declare function EventList({ ticketing, onOpen, }: {
5
+ ticketing: Pick<TicketingHooks, "useEventsOnSale">;
6
+ onOpen: (event: EventOnSale) => void;
7
+ }): import("react").JSX.Element;
8
+ /**
9
+ * One event's details and its ticket types, with room for the picker below. Prices show in the
10
+ * currency the host gives with them.
11
+ */
12
+ export declare function EventSection({ event, children }: {
13
+ event: EventOnSale;
14
+ children?: ReactNode;
15
+ }): import("react").JSX.Element;