@semics-tech/emdash-events 0.0.0-stage → 1.0.0-rc.1
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 +21 -0
- package/README.md +83 -2
- package/dist/index.d.mts +5 -0
- package/dist/index.mjs +416 -0
- package/dist/manifest.json +425 -0
- package/dist/plugin.d.mts +11 -0
- package/dist/plugin.mjs +7 -0
- package/dist/ts/astro/lib/call.d.ts +54 -0
- package/dist/ts/astro/lib/call.js +121 -0
- package/dist/ts/integration/index.d.ts +48 -0
- package/dist/ts/integration/index.js +76 -0
- package/dist/ts/ui/index.d.ts +6 -0
- package/dist/ts/ui/index.js +46 -0
- package/emdash-plugin.jsonc +222 -0
- package/package.json +78 -3
- package/src/astro/AddToCalendar.astro +47 -0
- package/src/astro/AttendeeList.astro +157 -0
- package/src/astro/BookingBlock.astro +30 -0
- package/src/astro/BookingPage.astro +230 -0
- package/src/astro/BookingStatus.astro +112 -0
- package/src/astro/BookingWidget.astro +776 -0
- package/src/astro/CheckIn.astro +186 -0
- package/src/astro/DoorSignPage.astro +62 -0
- package/src/astro/EventCard.astro +81 -0
- package/src/astro/EventList.astro +83 -0
- package/src/astro/OptOutPage.astro +58 -0
- package/src/astro/PaymentReturn.astro +96 -0
- package/src/astro/TicketPass.astro +95 -0
- package/src/astro/checkout-endpoint.ts +11 -0
- package/src/astro/index.js +18 -0
- package/src/astro/lib/attendees.ts +170 -0
- package/src/astro/lib/call.ts +185 -0
- package/src/astro/lib/checkout-form.ts +271 -0
- package/src/astro/lib/list.ts +99 -0
- package/src/astro/lib/opt-out.ts +49 -0
- package/src/astro/lib/pass.ts +35 -0
- package/src/astro/lib/payment.ts +73 -0
- package/src/astro/lib/picker.ts +245 -0
- package/src/astro/lib/promo.ts +162 -0
- package/src/astro/lib/questions.ts +107 -0
- package/src/astro/lib/receipt.ts +132 -0
- package/src/astro/lib/waitlist.ts +72 -0
- package/src/astro/lib/widget.ts +299 -0
- package/src/astro/promo-endpoint.ts +11 -0
- package/src/astro/virtual.d.ts +16 -0
- package/src/astro/waitlist-endpoint.ts +12 -0
- package/src/client/booking.ts +190 -0
- package/src/client/checkin.ts +260 -0
- package/src/client/payment.ts +76 -0
- package/src/client/picker.ts +143 -0
- package/src/client/receipt.ts +75 -0
- package/src/i18n/ar.ts +251 -0
- package/src/i18n/en.ts +255 -0
- package/src/i18n/index.ts +121 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// The UI ships as source, so it cannot import the private @semics-tech/shared (scripts/ui-imports.test.mjs).
|
|
2
|
+
function isValidTimeZone(timeZone: string): boolean {
|
|
3
|
+
try {
|
|
4
|
+
new Intl.DateTimeFormat("en-GB", { timeZone });
|
|
5
|
+
return true;
|
|
6
|
+
} catch {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function formatInZone(utcMs: number, timeZone: string, locale: string, options: Intl.DateTimeFormatOptions): string {
|
|
12
|
+
return new Intl.DateTimeFormat(locale, { ...options, timeZone }).format(new Date(utcMs));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
import { t } from "../../i18n/index";
|
|
16
|
+
import { formatMoney } from "./widget";
|
|
17
|
+
|
|
18
|
+
/** One row of `public/events` (T046): public fields only, never counters. */
|
|
19
|
+
export interface PublicEventSummary {
|
|
20
|
+
eventId: string;
|
|
21
|
+
title: string;
|
|
22
|
+
status: "on_sale" | "paused" | "closed" | "cancelled";
|
|
23
|
+
startsAt: string;
|
|
24
|
+
endsAt?: string | null;
|
|
25
|
+
timezone?: string | null;
|
|
26
|
+
venue?: string | null;
|
|
27
|
+
currency: string;
|
|
28
|
+
priceFromMinor?: number;
|
|
29
|
+
/** Seats left (never negative). */
|
|
30
|
+
available: number;
|
|
31
|
+
/** The entry's slug (T056); absent for an event whose info predates it. */
|
|
32
|
+
slug?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Where a card links by default: the site's `/events/<slug>` page, or nowhere without a slug. */
|
|
36
|
+
export const EVENTS_PATH = "/events";
|
|
37
|
+
export function eventHref(event: Pick<PublicEventSummary, "slug">): string | undefined {
|
|
38
|
+
return event.slug ? `${EVENTS_PATH}/${encodeURIComponent(event.slug)}` : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface CardView {
|
|
42
|
+
eventId: string;
|
|
43
|
+
title: string;
|
|
44
|
+
/** Start in the event's own zone, with the zone's short name. */
|
|
45
|
+
when: string;
|
|
46
|
+
/** The start as an ISO instant, for `<time datetime>`. */
|
|
47
|
+
datetime: string;
|
|
48
|
+
venue: string | null;
|
|
49
|
+
price: string | null;
|
|
50
|
+
/** "Sold out", "Cancelled", ... or `null` when the event can be booked. */
|
|
51
|
+
badge: string | null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const WHEN: Intl.DateTimeFormatOptions = {
|
|
55
|
+
weekday: "short",
|
|
56
|
+
day: "numeric",
|
|
57
|
+
month: "short",
|
|
58
|
+
year: "numeric",
|
|
59
|
+
hour: "2-digit",
|
|
60
|
+
minute: "2-digit",
|
|
61
|
+
hourCycle: "h23",
|
|
62
|
+
timeZoneName: "short",
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const BADGES = { cancelled: "list.badge.cancelled", closed: "list.badge.closed", paused: "list.badge.paused" } as const;
|
|
66
|
+
|
|
67
|
+
/** The start in the event's own zone; a missing or unknown zone shows UTC rather than failing. */
|
|
68
|
+
export function eventWhen(startsAt: string, timezone: string | null | undefined, locale: string): string {
|
|
69
|
+
const zone = timezone && isValidTimeZone(timezone) ? timezone : "UTC";
|
|
70
|
+
return formatInZone(Date.parse(startsAt), zone, locale, WHEN);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function cardView(event: PublicEventSummary, locale: string): CardView {
|
|
74
|
+
const badge =
|
|
75
|
+
event.status !== "on_sale"
|
|
76
|
+
? t(locale, BADGES[event.status])
|
|
77
|
+
: event.available === 0
|
|
78
|
+
? t(locale, "list.badge.soldOut")
|
|
79
|
+
: null;
|
|
80
|
+
let price: string | null = null;
|
|
81
|
+
if (event.priceFromMinor !== undefined) {
|
|
82
|
+
const from = formatMoney(event.priceFromMinor, event.currency, locale);
|
|
83
|
+
price = event.priceFromMinor === 0 ? from : t(locale, "list.priceFrom", { price: from });
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
eventId: event.eventId,
|
|
87
|
+
title: event.title,
|
|
88
|
+
when: eventWhen(event.startsAt, event.timezone, locale),
|
|
89
|
+
datetime: event.startsAt,
|
|
90
|
+
venue: event.venue ?? null,
|
|
91
|
+
price,
|
|
92
|
+
badge,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The first `limit` events (as `public/events` sorted them: soonest first) as cards. */
|
|
97
|
+
export function listView(events: PublicEventSummary[], options: { limit: number; locale: string }): CardView[] {
|
|
98
|
+
return events.slice(0, Math.max(0, options.limit)).map((event) => cardView(event, options.locale));
|
|
99
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The opt-out page for reminder and update emails (EV-FR-08, T083, R57). Events Pro's reminders and
|
|
3
|
+
* update notices link to `/_events/opt-out?ref=<booking ref>&w=<recipient>&s=<signature>`. Opening the
|
|
4
|
+
* link changes nothing (a mail scanner that prefetches it unsubscribes no one); the page shows a
|
|
5
|
+
* button whose same-site POST asks the core's `public/mail/opt-out`. The route is Events Pro's: a Free
|
|
6
|
+
* core answers NOT_FOUND, which the page shows as an invalid link. Cancellation notices are always sent.
|
|
7
|
+
*/
|
|
8
|
+
import { t } from "../../i18n/index";
|
|
9
|
+
import { callPublicRoute, type PublicRouteContext } from "./call";
|
|
10
|
+
|
|
11
|
+
export const OPT_OUT_PATH = "/_events/opt-out";
|
|
12
|
+
|
|
13
|
+
export interface OptOutLink {
|
|
14
|
+
bookingRef: string;
|
|
15
|
+
/** `buyer`, or the seat's attendee id. */
|
|
16
|
+
who: string;
|
|
17
|
+
sig: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The outcomes in English (the page shows `optOut.<outcome>` in its language, T102). */
|
|
21
|
+
export const OPT_OUT_MESSAGES = { done: t("en", "optOut.done"), invalid: t("en", "optOut.invalid") } as const;
|
|
22
|
+
|
|
23
|
+
const REF = /^[0-9A-Z]{10}$/;
|
|
24
|
+
const WHO = /^[\w-]{1,120}$/;
|
|
25
|
+
const SIG = /^[0-9a-f]{32}$/;
|
|
26
|
+
|
|
27
|
+
/** The link's values from the page's query (GET) or its form (POST); null when malformed. */
|
|
28
|
+
export function readOptOutLink(source: { get(name: string): unknown }): OptOutLink | null {
|
|
29
|
+
const [bookingRef, who, sig] = ["ref", "w", "s"].map((k) => {
|
|
30
|
+
const v = source.get(k);
|
|
31
|
+
return typeof v === "string" ? v : "";
|
|
32
|
+
}) as [string, string, string];
|
|
33
|
+
return REF.test(bookingRef) && WHO.test(who) && SIG.test(sig) ? { bookingRef, who, sig } : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The button's POST: `done`, or `invalid` for any refusal (also a core without the route). */
|
|
37
|
+
export async function optOut(
|
|
38
|
+
ctx: PublicRouteContext,
|
|
39
|
+
link: OptOutLink,
|
|
40
|
+
options: { pluginId?: string },
|
|
41
|
+
): Promise<keyof typeof OPT_OUT_MESSAGES> {
|
|
42
|
+
const result = await callPublicRoute(ctx, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
path: "public/mail/opt-out",
|
|
45
|
+
pluginId: options.pluginId,
|
|
46
|
+
body: link,
|
|
47
|
+
});
|
|
48
|
+
return result.ok ? "done" : "invalid";
|
|
49
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Draws a ticket pass's QR code (EV-FR-11, T082). The matrix comes from the core: Events Pro's
|
|
3
|
+
* `public/booking` adds `qr: { size, bits }` beside each pass's `code` (row-major modules, four per
|
|
4
|
+
* hex digit, most significant first, 1 = dark); Free sends none and the pass shows the code as text
|
|
5
|
+
* only. This only turns a well-formed matrix into an SVG path of horizontal runs; anything else is
|
|
6
|
+
* `null`, so nothing but numbers and path commands ever reaches the markup.
|
|
7
|
+
*/
|
|
8
|
+
export interface QrPath {
|
|
9
|
+
size: number;
|
|
10
|
+
d: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** QR sizes run from 21 (version 1) to 177 (version 40) modules, in steps of 4. */
|
|
14
|
+
export function qrPath(qr: unknown): QrPath | null {
|
|
15
|
+
if (!qr || typeof qr !== "object") return null;
|
|
16
|
+
const { size, bits } = qr as { size?: unknown; bits?: unknown };
|
|
17
|
+
if (typeof size !== "number" || !Number.isInteger(size) || size < 21 || size > 177 || (size - 17) % 4 !== 0) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
if (typeof bits !== "string" || bits.length !== Math.ceil((size * size) / 4) || !/^[0-9a-f]+$/.test(bits)) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
const dark = (i: number) => ((Number.parseInt(bits[i >> 2] as string, 16) >> (3 - (i & 3))) & 1) === 1;
|
|
24
|
+
let d = "";
|
|
25
|
+
for (let y = 0; y < size; y++) {
|
|
26
|
+
for (let x = 0; x < size; x++) {
|
|
27
|
+
if (!dark(y * size + x)) continue;
|
|
28
|
+
let run = 1;
|
|
29
|
+
while (x + run < size && dark(y * size + x + run)) run++;
|
|
30
|
+
d += `M${x} ${y}h${run}v1h-${run}z`;
|
|
31
|
+
x += run;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return { size, d };
|
|
35
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the booking page says about a paid booking (EU-FR-09). Pure: the state comes only from the
|
|
3
|
+
* core's `public/booking` answer. Stripe sends the buyer back to `/booking?ref=` on success and on
|
|
4
|
+
* cancel alike, with nothing in the URL to trust, so "paid", "abandoned" and "webhook still on its
|
|
5
|
+
* way" are told apart by asking the core, never by a query parameter.
|
|
6
|
+
*/
|
|
7
|
+
import { type MessageKey, t } from "../../i18n/index";
|
|
8
|
+
import type { BookingView } from "./widget";
|
|
9
|
+
|
|
10
|
+
export type PaymentState = "confirmed" | "pending" | "expired" | "cancelled" | "refunded" | "refunded_unavailable";
|
|
11
|
+
|
|
12
|
+
export interface PaymentView {
|
|
13
|
+
state: PaymentState;
|
|
14
|
+
heading: string;
|
|
15
|
+
body: string;
|
|
16
|
+
/** The page re-reads the booking for a while (the webhook has not arrived yet). */
|
|
17
|
+
poll: boolean;
|
|
18
|
+
/** Offer "Pay now": the seats are still held and the payment has not been confirmed. */
|
|
19
|
+
resume: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const utc = (iso: string, locale: string) => {
|
|
23
|
+
try {
|
|
24
|
+
const at = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" });
|
|
25
|
+
return t(locale, "time.utc", { time: at.format(new Date(iso)) });
|
|
26
|
+
} catch {
|
|
27
|
+
return iso;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** The provider's payment page is followed only when it is an `https:` URL (never `javascript:` or `//host`). */
|
|
32
|
+
export function isPayUrl(value: unknown): value is string {
|
|
33
|
+
if (typeof value !== "string" || !value.startsWith("https://")) return false;
|
|
34
|
+
try {
|
|
35
|
+
return new URL(value).protocol === "https:";
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const final = (state: PaymentState, locale: string): PaymentView => ({
|
|
42
|
+
state,
|
|
43
|
+
heading: t(locale, `payment.${state}.heading` as MessageKey),
|
|
44
|
+
body: t(locale, `payment.${state}.body` as MessageKey),
|
|
45
|
+
poll: false,
|
|
46
|
+
resume: false,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
/** The payment section for a booking, or `null` when there is nothing to say about money. */
|
|
50
|
+
export function paymentView(booking: BookingView, locale = "en-GB"): PaymentView | null {
|
|
51
|
+
const paid = booking.totals.totalMinor > 0;
|
|
52
|
+
switch (booking.status) {
|
|
53
|
+
case "awaiting_payment":
|
|
54
|
+
return {
|
|
55
|
+
state: "pending",
|
|
56
|
+
heading: t(locale, "payment.pending.heading"),
|
|
57
|
+
body: booking.holdExpiresAt
|
|
58
|
+
? t(locale, "payment.pending.bodyUntil", { time: utc(booking.holdExpiresAt, locale) })
|
|
59
|
+
: t(locale, "payment.pending.body"),
|
|
60
|
+
poll: true,
|
|
61
|
+
resume: true,
|
|
62
|
+
};
|
|
63
|
+
case "confirmed":
|
|
64
|
+
case "expired":
|
|
65
|
+
case "cancelled":
|
|
66
|
+
return paid ? final(booking.status, locale) : null;
|
|
67
|
+
case "refunded":
|
|
68
|
+
case "refunded_unavailable":
|
|
69
|
+
return final(booking.status, locale);
|
|
70
|
+
default:
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The booking form's day-then-time picker (T130, EV-FR-17): pure helpers for `<BookingWidget>`.
|
|
3
|
+
*
|
|
4
|
+
* An event with a slot schedule, or with more than one start on a local day, is booked by picking a
|
|
5
|
+
* day on a month calendar, then one of that day's times. The page renders both the calendar and, for
|
|
6
|
+
* visitors without JavaScript, a plain `<select>` of the same month's dates grouped by day
|
|
7
|
+
* (`<optgroup>`); `src/client/picker.ts` swaps one for the other. Days are the event's local days
|
|
8
|
+
* (`timezone`, else UTC), so a slot at 23:30 in New York sits on that evening's day, and both runs of a
|
|
9
|
+
* repeated DST hour stay on their day.
|
|
10
|
+
*
|
|
11
|
+
* Paging: `public/event` answers up to 200 upcoming open slots from `from` (closed ones never), with
|
|
12
|
+
* `more` when there are further ones. The widget shows one month, starting at its `booking_from.<eventId>` query
|
|
13
|
+
* parameter (a local `YYYY-MM-DD`, today when absent or past); it asks the core from that day's earliest
|
|
14
|
+
* possible local midnight (UTC+14) and skips what falls before the day. A truncated answer's last day
|
|
15
|
+
* may be partial, so it is left for the next page, which starts on it.
|
|
16
|
+
*/
|
|
17
|
+
import { translator } from "../../i18n/index";
|
|
18
|
+
import { anchorId, WIDGET_PARAMS } from "./widget";
|
|
19
|
+
|
|
20
|
+
/** The query parameter holding the first local day the picker shows (prefix: one per widget). */
|
|
21
|
+
export const PICKER_PARAM = "booking_from";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* One widget's `booking_from` parameter, keyed by its event (`booking_from.<eventId>`, T134), so two
|
|
25
|
+
* pickers on a page page independently, with or without JavaScript (paging is a plain link).
|
|
26
|
+
*/
|
|
27
|
+
export const pickerParam = (eventId: string) => `${PICKER_PARAM}.${eventId.replace(/[^A-Za-z0-9_-]/g, "_")}`;
|
|
28
|
+
|
|
29
|
+
const DAY_KEY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
30
|
+
const HOUR = 3_600_000;
|
|
31
|
+
/** The earliest a local midnight can be, relative to UTC midnight of the same date (UTC+14). */
|
|
32
|
+
const EARLIEST_OFFSET = 14 * HOUR;
|
|
33
|
+
|
|
34
|
+
export interface PickerOccurrence {
|
|
35
|
+
id: string;
|
|
36
|
+
startsAt: string;
|
|
37
|
+
endsAt?: string | null;
|
|
38
|
+
available?: number | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface PickerSlot {
|
|
42
|
+
id: string;
|
|
43
|
+
/** The start's local time (`09:30`). */
|
|
44
|
+
time: string;
|
|
45
|
+
/** "3 places left" or "Full"; empty when the core does not say. */
|
|
46
|
+
places: string;
|
|
47
|
+
full: boolean;
|
|
48
|
+
/** What a screen reader hears: time and places. */
|
|
49
|
+
label: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface PickerDay {
|
|
53
|
+
/** The local day, `YYYY-MM-DD`. */
|
|
54
|
+
key: string;
|
|
55
|
+
/** Day of the month. */
|
|
56
|
+
day: number;
|
|
57
|
+
/** The full date ("Wednesday 4 November 2026"). */
|
|
58
|
+
label: string;
|
|
59
|
+
/** The day button's accessible name: the date, plus "fully booked" when no slot has room. */
|
|
60
|
+
buttonLabel: string;
|
|
61
|
+
slots: PickerSlot[];
|
|
62
|
+
/** Some slot has room. */
|
|
63
|
+
open: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A calendar cell: a day of the month (with no slots: `slots` is empty), or `null` before/after it. */
|
|
67
|
+
export type PickerCell = PickerDay | null;
|
|
68
|
+
|
|
69
|
+
export interface PickerView {
|
|
70
|
+
month: { key: string; label: string };
|
|
71
|
+
weekdays: Array<{ short: string; long: string }>;
|
|
72
|
+
/** Weeks of seven cells, Monday first. */
|
|
73
|
+
weeks: PickerCell[][];
|
|
74
|
+
/** The month's days that have slots, earliest first. */
|
|
75
|
+
days: PickerDay[];
|
|
76
|
+
/** The day button that takes focus first (roving tabindex): the first open day, else the first day. */
|
|
77
|
+
focusDay?: string;
|
|
78
|
+
/** `booking_from` values for the earlier and later pages. */
|
|
79
|
+
prev?: string;
|
|
80
|
+
next?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function formatter(locale: string, zone: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
|
|
84
|
+
try {
|
|
85
|
+
return new Intl.DateTimeFormat(locale, { ...options, timeZone: zone });
|
|
86
|
+
} catch {
|
|
87
|
+
return new Intl.DateTimeFormat(locale, { ...options, timeZone: "UTC" });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const pad = (n: number) => String(n).padStart(2, "0");
|
|
92
|
+
|
|
93
|
+
/** The local day (`YYYY-MM-DD`) of an instant in a zone (UTC for an unknown zone). */
|
|
94
|
+
export function localDay(ms: number, zone: string): string {
|
|
95
|
+
const parts = formatter("en-US", zone, { year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(ms);
|
|
96
|
+
const get = (type: string) => Number(parts.find((p) => p.type === type)?.value);
|
|
97
|
+
return `${get("year")}-${pad(get("month"))}-${pad(get("day"))}`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A real calendar date `YYYY-MM-DD` as UTC midnight (ms), else `null`. */
|
|
101
|
+
function dayMs(key: string | null | undefined): number | null {
|
|
102
|
+
const m = DAY_KEY.exec(key ?? "");
|
|
103
|
+
if (!m) return null;
|
|
104
|
+
const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
|
|
105
|
+
return new Date(ms).toISOString().slice(0, 10) === key ? ms : null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const keyOf = (ms: number) => new Date(ms).toISOString().slice(0, 10);
|
|
109
|
+
const monthFirst = (month: string, delta = 0) => {
|
|
110
|
+
const [y, m] = month.split("-").map(Number) as [number, number];
|
|
111
|
+
return keyOf(Date.UTC(y, m - 1 + delta, 1));
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/** Whether the form books through the picker: a slot schedule, or two starts on one local day. */
|
|
115
|
+
export function usesPicker(
|
|
116
|
+
event: { occurrences?: PickerOccurrence[]; slots?: boolean; timezone?: string } | undefined,
|
|
117
|
+
zone = event?.timezone ?? "UTC",
|
|
118
|
+
): boolean {
|
|
119
|
+
if (!event) return false;
|
|
120
|
+
if (event.slots === true) return true;
|
|
121
|
+
const seen = new Set<string>();
|
|
122
|
+
for (const o of event.occurrences ?? []) {
|
|
123
|
+
const day = localDay(Date.parse(o.startsAt), zone);
|
|
124
|
+
if (seen.has(day)) return true;
|
|
125
|
+
seen.add(day);
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The occurrences grouped by local day, earliest first, with their times and places left. */
|
|
131
|
+
export function groupByDay(occurrences: readonly PickerOccurrence[], zone: string, locale: string): PickerDay[] {
|
|
132
|
+
const { t, plural } = translator(locale);
|
|
133
|
+
const time = formatter(locale, zone, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
|
|
134
|
+
const date = formatter(locale, "UTC", { dateStyle: "full" });
|
|
135
|
+
const days = new Map<string, PickerDay>();
|
|
136
|
+
const sorted = occurrences
|
|
137
|
+
.map((o) => ({ o, ms: Date.parse(o.startsAt) }))
|
|
138
|
+
.filter(({ ms }) => Number.isFinite(ms))
|
|
139
|
+
.sort((a, b) => a.ms - b.ms);
|
|
140
|
+
for (const { o, ms } of sorted) {
|
|
141
|
+
const key = localDay(ms, zone);
|
|
142
|
+
let day = days.get(key);
|
|
143
|
+
if (!day) {
|
|
144
|
+
const label = date.format(dayMs(key) ?? ms);
|
|
145
|
+
day = { key, day: Number(key.slice(8)), label, buttonLabel: label, slots: [], open: false };
|
|
146
|
+
days.set(key, day);
|
|
147
|
+
}
|
|
148
|
+
const known = typeof o.available === "number";
|
|
149
|
+
const full = known && (o.available as number) <= 0;
|
|
150
|
+
const places = !known ? "" : full ? t("widget.picker.full") : plural("widget.picker.left", o.available as number);
|
|
151
|
+
const at = time.format(ms);
|
|
152
|
+
day.slots.push({ id: o.id, time: at, places, full, label: places ? `${at}, ${places}` : at });
|
|
153
|
+
if (!full) day.open = true;
|
|
154
|
+
}
|
|
155
|
+
for (const day of days.values()) {
|
|
156
|
+
if (!day.open) day.buttonLabel = t("widget.picker.dayFull", { date: day.label });
|
|
157
|
+
}
|
|
158
|
+
return [...days.values()];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The `from` to ask `public/event` for, for a `booking_from` day: its earliest possible local midnight. */
|
|
162
|
+
export function pickerFetchFrom(start: string | null | undefined): string | undefined {
|
|
163
|
+
const ms = dayMs(start);
|
|
164
|
+
return ms === null ? undefined : new Date(ms - EARLIEST_OFFSET).toISOString();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* A link to another page of one event's picker: the current page's query without widget errors (other
|
|
169
|
+
* widgets' pages kept), and that widget's anchor.
|
|
170
|
+
*/
|
|
171
|
+
export function pickerHref(url: URL, start: string, eventId: string): string {
|
|
172
|
+
const next = new URL(url.href);
|
|
173
|
+
for (const name of Object.values(WIDGET_PARAMS)) next.searchParams.delete(name);
|
|
174
|
+
next.searchParams.set(pickerParam(eventId), start);
|
|
175
|
+
return `${next.pathname}${next.search}#${anchorId(eventId)}`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export interface PickerOptions {
|
|
179
|
+
zone: string;
|
|
180
|
+
locale: string;
|
|
181
|
+
/** The `booking_from` parameter (a local `YYYY-MM-DD`), if any. */
|
|
182
|
+
start: string | null | undefined;
|
|
183
|
+
now: number;
|
|
184
|
+
/** `public/event` said there are more slots after the ones it sent. */
|
|
185
|
+
more?: boolean;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** One month of the picker: its calendar, its days with slots, and the paging links. */
|
|
189
|
+
export function pickerView(occurrences: readonly PickerOccurrence[], opts: PickerOptions): PickerView {
|
|
190
|
+
const today = localDay(opts.now, opts.zone);
|
|
191
|
+
const asked = dayMs(opts.start) === null ? today : (opts.start as string);
|
|
192
|
+
const start = asked > today ? asked : today;
|
|
193
|
+
const startMonth = start.slice(0, 7);
|
|
194
|
+
|
|
195
|
+
const grouped = groupByDay(occurrences, opts.zone, opts.locale).filter((d) => d.key >= start);
|
|
196
|
+
const partial = opts.more && grouped.length > 1 ? grouped.pop() : undefined;
|
|
197
|
+
const month = grouped.some((d) => d.key.startsWith(startMonth))
|
|
198
|
+
? startMonth
|
|
199
|
+
: (grouped[0]?.key.slice(0, 7) ?? startMonth);
|
|
200
|
+
const days = grouped.filter((d) => d.key.startsWith(month));
|
|
201
|
+
const following = monthFirst(month, 1);
|
|
202
|
+
|
|
203
|
+
let next: string | undefined;
|
|
204
|
+
if (partial?.key.startsWith(month)) next = partial.key;
|
|
205
|
+
else if (partial || grouped.some((d) => d.key >= following)) next = following;
|
|
206
|
+
|
|
207
|
+
let prev: string | undefined;
|
|
208
|
+
if (start > today) {
|
|
209
|
+
const back = start > monthFirst(startMonth) ? monthFirst(startMonth) : monthFirst(startMonth, -1);
|
|
210
|
+
prev = back > today ? back : today;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const [y, m] = month.split("-").map(Number) as [number, number];
|
|
214
|
+
const first = Date.UTC(y, m - 1, 1);
|
|
215
|
+
const length = new Date(Date.UTC(y, m, 0)).getUTCDate();
|
|
216
|
+
const byDay = new Map(days.map((d) => [d.day, d]));
|
|
217
|
+
const date = formatter(opts.locale, "UTC", { dateStyle: "full" });
|
|
218
|
+
const cells: PickerCell[] = Array.from({ length: (new Date(first).getUTCDay() + 6) % 7 }, () => null);
|
|
219
|
+
for (let d = 1; d <= length; d++) {
|
|
220
|
+
const key = `${month}-${pad(d)}`;
|
|
221
|
+
const label = date.format(Date.UTC(y, m - 1, d));
|
|
222
|
+
cells.push(byDay.get(d) ?? { key, day: d, label, buttonLabel: label, slots: [], open: false });
|
|
223
|
+
}
|
|
224
|
+
while (cells.length % 7 !== 0) cells.push(null);
|
|
225
|
+
const weeks = Array.from({ length: cells.length / 7 }, (_, i) => cells.slice(i * 7, i * 7 + 7));
|
|
226
|
+
|
|
227
|
+
const short = formatter(opts.locale, "UTC", { weekday: "short" });
|
|
228
|
+
const long = formatter(opts.locale, "UTC", { weekday: "long" });
|
|
229
|
+
// 5 January 2026 is a Monday.
|
|
230
|
+
const weekdays = Array.from({ length: 7 }, (_, i) => {
|
|
231
|
+
const ms = Date.UTC(2026, 0, 5 + i);
|
|
232
|
+
return { short: short.format(ms), long: long.format(ms) };
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
const focus = days.find((d) => d.open) ?? days[0];
|
|
236
|
+
return {
|
|
237
|
+
month: { key: month, label: formatter(opts.locale, "UTC", { month: "long", year: "numeric" }).format(first) },
|
|
238
|
+
weekdays,
|
|
239
|
+
weeks,
|
|
240
|
+
days,
|
|
241
|
+
...(focus ? { focusDay: focus.key } : {}),
|
|
242
|
+
...(prev ? { prev } : {}),
|
|
243
|
+
...(next ? { next } : {}),
|
|
244
|
+
};
|
|
245
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Promo codes in the booking widget (EV-FR-14, T078). The codes are Events Pro's: reserve takes
|
|
3
|
+
* `promoCode`, and `public/promo/check` says whether a code works for an event and, for an unlock
|
|
4
|
+
* code, which hidden ticket types it reveals. This module is the Free UI's side, and touches the core
|
|
5
|
+
* only through those public routes:
|
|
6
|
+
*
|
|
7
|
+
* - `POST /_events/promo` (the widget's "Apply" button, a plain form post that works without
|
|
8
|
+
* JavaScript): refuses cross-site posts, asks `public/promo/check`, keeps an accepted code in an
|
|
9
|
+
* HttpOnly cookie for this event and goes back to the widget. The code never goes into a URL (an
|
|
10
|
+
* unlock code is a credential for hidden tickets): refusals go back as an error code only.
|
|
11
|
+
* - `promoView`: what the widget shows for the cookie's code (the hidden types and a note), asked
|
|
12
|
+
* afresh on every render so a code that stopped working stops showing.
|
|
13
|
+
*
|
|
14
|
+
* The widget shows the field only when `public/event` says the core takes codes (`promoCodes`, set by
|
|
15
|
+
* Pro), so a Free site never offers one; and checkout sends `promoCode` only when a code was typed.
|
|
16
|
+
*/
|
|
17
|
+
import { t } from "../../i18n/index";
|
|
18
|
+
import { callPublicRoute, type PublicRouteContext } from "./call";
|
|
19
|
+
import { type CheckoutEndpointContext, crossSiteResponse, isCrossSiteRequest } from "./checkout-form";
|
|
20
|
+
import { anchorId, formatMoney, promoRefusal, safeReturnTo, widgetErrorLocation } from "./widget";
|
|
21
|
+
|
|
22
|
+
export const PROMO_PATH = "/_events/promo";
|
|
23
|
+
/** How long an applied code is remembered for the event (it is checked again on every render). */
|
|
24
|
+
export const PROMO_COOKIE_SECONDS = 30 * 60;
|
|
25
|
+
const MAX_CODE = 60;
|
|
26
|
+
|
|
27
|
+
export interface PromoHiddenType {
|
|
28
|
+
id: string;
|
|
29
|
+
name: string;
|
|
30
|
+
priceMinor: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What `public/promo/check` answers for a code that works. */
|
|
34
|
+
export interface PromoCheck {
|
|
35
|
+
kind: "percent" | "fixed" | "unlock";
|
|
36
|
+
/** Basis points (`percent`) or minor units (`fixed`). */
|
|
37
|
+
value?: number;
|
|
38
|
+
currency?: string;
|
|
39
|
+
hiddenTypes: PromoHiddenType[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface PromoView {
|
|
43
|
+
code: string;
|
|
44
|
+
note: string;
|
|
45
|
+
hiddenTypes: PromoHiddenType[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const promoCookieName = (eventId: string) => `semics_promo_${eventId.replace(/[^A-Za-z0-9_-]/g, "_")}`;
|
|
49
|
+
|
|
50
|
+
/** The applied-code cookie: HttpOnly, the whole site (the widget can be on any page), 30 minutes. */
|
|
51
|
+
export function promoCookieOptions(url: URL) {
|
|
52
|
+
return {
|
|
53
|
+
path: "/",
|
|
54
|
+
httpOnly: true,
|
|
55
|
+
sameSite: "lax" as const,
|
|
56
|
+
secure: url.protocol === "https:",
|
|
57
|
+
maxAge: PROMO_COOKIE_SECONDS,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A typed code, trimmed; "" when there is none or it is too long to be one. */
|
|
62
|
+
export function promoCodeOf(raw: unknown): string {
|
|
63
|
+
const code = typeof raw === "string" ? raw.trim() : "";
|
|
64
|
+
return code.length <= MAX_CODE ? code : "";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The refusal codes the widget has messages for; anything else (Free has no such route) is PROMO_INVALID. */
|
|
68
|
+
const KEPT = new Set(["PROMO_EXHAUSTED", "PROMO_UNAVAILABLE", "RATE_LIMITED"]);
|
|
69
|
+
|
|
70
|
+
async function checkCode(
|
|
71
|
+
ctx: PublicRouteContext,
|
|
72
|
+
input: { eventId: string; code: string },
|
|
73
|
+
pluginId: string | undefined,
|
|
74
|
+
): Promise<{ ok: true; check: PromoCheck } | { ok: false; code: string }> {
|
|
75
|
+
const result = await callPublicRoute<PromoCheck>(ctx, {
|
|
76
|
+
method: "POST",
|
|
77
|
+
path: "public/promo/check",
|
|
78
|
+
pluginId,
|
|
79
|
+
body: { eventId: input.eventId, code: input.code },
|
|
80
|
+
});
|
|
81
|
+
if (!result.ok) {
|
|
82
|
+
const code = promoRefusal(result.error.code);
|
|
83
|
+
return { ok: false, code: KEPT.has(code) ? code : "PROMO_INVALID" };
|
|
84
|
+
}
|
|
85
|
+
const hiddenTypes = Array.isArray(result.data.hiddenTypes) ? result.data.hiddenTypes : [];
|
|
86
|
+
return { ok: true, check: { ...result.data, hiddenTypes } };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The line the widget shows under an applied code. */
|
|
90
|
+
export function promoNote(check: PromoCheck, currency: string, locale = "en-GB"): string {
|
|
91
|
+
const value = typeof check.value === "number" ? check.value : 0;
|
|
92
|
+
if (check.kind === "percent" && value > 0) {
|
|
93
|
+
const percent = new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 2 }).format(value / 10000);
|
|
94
|
+
return t(locale, "promo.percent", { percent });
|
|
95
|
+
}
|
|
96
|
+
if (check.kind === "fixed" && value > 0) {
|
|
97
|
+
return t(locale, "promo.fixed", { amount: formatMoney(value, check.currency ?? currency, locale) });
|
|
98
|
+
}
|
|
99
|
+
return t(locale, check.hiddenTypes.length > 0 ? "promo.unlocked" : "promo.applied");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The widget's view of the code in the cookie, or `null` (no code, Free, or it no longer works). */
|
|
103
|
+
export async function promoView(
|
|
104
|
+
ctx: PublicRouteContext,
|
|
105
|
+
input: { eventId: string; code: string; currency?: string; locale?: string },
|
|
106
|
+
options: { pluginId?: string },
|
|
107
|
+
): Promise<PromoView | null> {
|
|
108
|
+
const code = promoCodeOf(input.code);
|
|
109
|
+
if (!code) return null;
|
|
110
|
+
const checked = await checkCode(ctx, { eventId: input.eventId, code }, options.pluginId);
|
|
111
|
+
if (!checked.ok) return null;
|
|
112
|
+
return {
|
|
113
|
+
code,
|
|
114
|
+
note: promoNote(checked.check, input.currency ?? "GBP", input.locale),
|
|
115
|
+
hiddenTypes: checked.check.hiddenTypes,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface PromoEndpointContext extends Omit<CheckoutEndpointContext, "cookies"> {
|
|
120
|
+
cookies: {
|
|
121
|
+
set(name: string, value: string, options: Record<string, unknown>): void;
|
|
122
|
+
delete(name: string, options: Record<string, unknown>): void;
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const text = (form: FormData, key: string) => {
|
|
127
|
+
const value = form.get(key);
|
|
128
|
+
return typeof value === "string" ? value.trim() : "";
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/** `POST /_events/promo`: refuse cross-site posts, check the code, remember or forget it, back to the widget (303). */
|
|
132
|
+
export async function handlePromoRequest(
|
|
133
|
+
{ request, url, locals, redirect, cookies }: PromoEndpointContext,
|
|
134
|
+
options: { pluginId?: string },
|
|
135
|
+
): Promise<Response> {
|
|
136
|
+
if (isCrossSiteRequest(request, url)) return crossSiteResponse();
|
|
137
|
+
const form = await request.formData().catch(() => new FormData());
|
|
138
|
+
const eventId = text(form, "eventId");
|
|
139
|
+
// Parsed once more and rebuilt from its path: `safeReturnTo` lets `/.//host` through as `//host`
|
|
140
|
+
// (phase 3 review F11), which as a Location would leave the site.
|
|
141
|
+
const parsed = new URL(safeReturnTo(text(form, "returnTo"), url.origin) ?? "/", "http://x");
|
|
142
|
+
const returnTo = `${parsed.pathname}${parsed.search}`;
|
|
143
|
+
const back = `${returnTo}#${anchorId(eventId)}`;
|
|
144
|
+
if (!eventId || eventId.length > 200) return redirect(returnTo, 303);
|
|
145
|
+
const cookie = promoCookieName(eventId);
|
|
146
|
+
const forget = () => cookies.delete(cookie, { path: "/" });
|
|
147
|
+
const raw = text(form, "promoCode");
|
|
148
|
+
if (!raw) {
|
|
149
|
+
forget();
|
|
150
|
+
return redirect(back, 303);
|
|
151
|
+
}
|
|
152
|
+
const code = promoCodeOf(raw);
|
|
153
|
+
const checked = code
|
|
154
|
+
? await checkCode({ locals, url, request }, { eventId, code }, options.pluginId)
|
|
155
|
+
: { ok: false as const, code: "PROMO_INVALID" };
|
|
156
|
+
if (!checked.ok) {
|
|
157
|
+
forget();
|
|
158
|
+
return redirect(widgetErrorLocation(returnTo, eventId, checked.code, ["promo"]), 303);
|
|
159
|
+
}
|
|
160
|
+
cookies.set(cookie, code, promoCookieOptions(url));
|
|
161
|
+
return redirect(back, 303);
|
|
162
|
+
}
|