@tribe-nest/forge 3.21.0 → 3.22.0

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.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/src/data/queries/_tests/passTransfers.spec.ts +100 -4
  3. package/src/data/queries/useEvents.ts +66 -4
  4. package/src/data/queries/useMembership.ts +8 -2
  5. package/src/data/queries/useMyBookings.ts +12 -0
  6. package/src/data/queries/useMyTickets.ts +112 -0
  7. package/src/data/queries/useOrders.ts +10 -0
  8. package/src/data/queries/usePassTransfers.ts +73 -13
  9. package/src/server/index.ts +52 -0
  10. package/src/types/models.ts +151 -0
  11. package/src/ui/format/_tests/attendees.spec.ts +231 -0
  12. package/src/ui/format/_tests/membershipGate.spec.ts +220 -0
  13. package/src/ui/format/attendees.ts +187 -0
  14. package/src/ui/format/membershipGate.ts +209 -0
  15. package/src/ui/headless/calendar/_tests/useAddToCalendar.spec.ts +83 -0
  16. package/src/ui/headless/calendar/useAddToCalendar.ts +46 -5
  17. package/src/ui/headless/checkout/_tests/inventoryHold.spec.ts +111 -0
  18. package/src/ui/headless/checkout/inventoryHold.ts +83 -0
  19. package/src/ui/headless/checkout/useCheckout.ts +72 -0
  20. package/src/ui/headless/checkout/useInventoryHold.ts +104 -0
  21. package/src/ui/headless/event/useEventCheckout.ts +133 -2
  22. package/src/ui/headless/event/usePresaleCode.ts +181 -0
  23. package/src/ui/headless/index.ts +25 -0
  24. package/src/ui/headless/membership/useMembershipGateNotice.ts +83 -0
  25. package/src/ui/headless/offer/OfferContext.tsx +55 -0
  26. package/src/ui/index.ts +42 -0
  27. package/src/ui/styled/AccountDashboard.tsx +70 -8
  28. package/src/ui/styled/AddToCalendar.tsx +34 -10
  29. package/src/ui/styled/Checkout.tsx +18 -1
  30. package/src/ui/styled/CoachingConfirmation.tsx +4 -0
  31. package/src/ui/styled/CourseDetail.tsx +30 -1
  32. package/src/ui/styled/EventConfirmation.tsx +2 -0
  33. package/src/ui/styled/EventDetail.tsx +53 -22
  34. package/src/ui/styled/EventTickets.tsx +156 -5
  35. package/src/ui/styled/HoldNotice.tsx +192 -0
  36. package/src/ui/styled/MembershipGateNotice.tsx +159 -0
  37. package/src/ui/styled/OfferButton.tsx +23 -0
  38. package/src/ui/styled/PresaleCode.tsx +174 -0
  39. package/src/ui/styled/ProductDetail.tsx +75 -5
  40. package/src/ui/styled/ProductGrid.tsx +26 -0
  41. package/src/ui/styled/TicketTransfer.tsx +69 -40
  42. package/src/ui/styled/_tests/AddToCalendar.spec.tsx +88 -0
  43. package/src/ui/styled/_tests/EventConfirmation.spec.tsx +5 -1
  44. package/src/ui/styled/_tests/PresaleCode.spec.tsx +106 -0
  45. package/src/utils/_tests/presaleCode.spec.ts +168 -0
  46. package/src/utils/_tests/structuredData.spec.ts +275 -0
  47. package/src/utils/presaleCode.ts +96 -0
  48. package/src/utils/structuredData.ts +361 -27
@@ -0,0 +1,187 @@
1
+ import type { IEvent, ITicket } from "../../types/models";
2
+
3
+ /**
4
+ * Events 2.1 — asking the buyer WHO IS COMING, on both rendering stacks.
5
+ *
6
+ * The operator toggle ("Ask for each attendee's name at checkout") and the
7
+ * server that accepts the answer both shipped; nothing ever asked. Every pass
8
+ * of a four-ticket order was therefore issued in the purchaser's name, and the
9
+ * setting looked broken because it was silent.
10
+ *
11
+ * ## Why the logic is here and not in a component
12
+ *
13
+ * There are two storefronts — `apps/client` (the PWA) and `packages/forge`'s
14
+ * own `<EventTickets>` (code sites) — and each renders its own checkout. The
15
+ * one thing they must NOT each derive for themselves is the shape of the
16
+ * request: `attendees` is keyed by ticket id and positional WITHIN a tier, and
17
+ * a list whose length does not equal that tier's quantity is refused outright
18
+ * by `validateAttendeeList` on the server. So slot construction, the buyer
19
+ * default, validation and the payload all live in these pure functions, and
20
+ * both stacks only decide what the inputs look like.
21
+ *
22
+ * ## Names only — deliberately
23
+ *
24
+ * The endpoint also accepts a per-attendee `email`, and that field is not a
25
+ * contact detail: `owner_email` is WHO HOLDS the pass, so naming a different
26
+ * address hands that seat to that person, who may then rename or transfer it
27
+ * instead of the buyer (`db/types/attendee.ts`, `commands/passTransfer.ts`).
28
+ * The operator toggle asks for a name and says so. Sending only names keeps
29
+ * every pass in the buyer's account — which is exactly the branch the backend
30
+ * documents as "what a storefront that only asks for names produces" — and
31
+ * leaves handing a ticket to somebody else to the transfer flow, which has a
32
+ * claim token, an expiry and an audit trail.
33
+ *
34
+ * ## A blank must never pass
35
+ *
36
+ * A missing name here is a person turned away at a door. The server's per-slot
37
+ * fallback would quietly put the BUYER's name on an unfilled seat rather than
38
+ * error, so a half-filled form would produce a wrong door list with a 200.
39
+ * `validateAttendeeNames` is what stops that before the request is made.
40
+ */
41
+
42
+ /** Matches `validation.event.attendee_name.max` and the server's own cap. */
43
+ export const MAX_ATTENDEE_NAME_LENGTH = 240;
44
+
45
+ /**
46
+ * Trim and collapse internal whitespace — the same normalisation the server
47
+ * applies (`normalizeAttendeeName`), so " Jane Doe " and "Jane Doe" cannot
48
+ * sort into two places on a printed door list.
49
+ */
50
+ export const normalizeAttendeeName = (raw?: string | null): string => (raw ?? "").replace(/\s+/g, " ").trim();
51
+
52
+ /** Does this event ask for attendee names at all? Absent field means no. */
53
+ export const collectsAttendees = (event?: Pick<IEvent, "collectAttendeeDetails"> | null): boolean =>
54
+ !!event?.collectAttendeeDetails;
55
+
56
+ /** The buyer's own name, as the first seat's default. Empty until they type it. */
57
+ export const buyerFullName = (input: { firstName?: string | null; lastName?: string | null }): string =>
58
+ normalizeAttendeeName(`${input.firstName ?? ""} ${input.lastName ?? ""}`);
59
+
60
+ /** ticketId → the names typed so far, positional within that tier. */
61
+ export type AttendeeNames = Record<string, (string | undefined)[]>;
62
+
63
+ /** One seat the buyer has to name. */
64
+ export type AttendeeSlot = {
65
+ ticketId: string;
66
+ ticketTitle: string;
67
+ /** 0-based position WITHIN this tier — the index the request is keyed on. */
68
+ index: number;
69
+ /** 1-based position within this tier, for a label. */
70
+ number: number;
71
+ /** How many seats of this tier are in the cart. */
72
+ ticketQuantity: number;
73
+ /**
74
+ * The very first seat in the cart. It defaults to the buyer, so the common
75
+ * case — one ticket, bought for yourself — asks for nothing already known.
76
+ */
77
+ isBuyer: boolean;
78
+ /** What the input should show: what they typed, else the buyer default. */
79
+ value: string;
80
+ /** "General Admission — Attendee 2 of 3", or just the tier on a single seat. */
81
+ label: string;
82
+ };
83
+
84
+ /**
85
+ * Every seat in the cart, in tier order then issue order.
86
+ *
87
+ * Derived from the CURRENT quantities on every call rather than stored, so a
88
+ * buyer who drops from four tickets to two cannot leave two orphan names behind
89
+ * (which the server would reject as a count mismatch) and one who goes back up
90
+ * to four gets what they already typed back.
91
+ *
92
+ * `undefined` and `""` are different on purpose: an untouched first seat shows
93
+ * the buyer's name, a first seat the buyer CLEARED stays empty and fails
94
+ * validation. Snapping it back would silently overrule a deliberate edit.
95
+ */
96
+ export function buildAttendeeSlots(input: {
97
+ tickets: Pick<ITicket, "id" | "title">[];
98
+ quantities: Record<string, number>;
99
+ names: AttendeeNames;
100
+ /** Pre-fills the first seat only. Pass "" when the buyer has not typed a name yet. */
101
+ buyerName: string;
102
+ }): AttendeeSlot[] {
103
+ const slots: AttendeeSlot[] = [];
104
+
105
+ for (const ticket of input.tickets) {
106
+ const quantity = Math.max(0, Math.floor(input.quantities[ticket.id] ?? 0));
107
+ for (let index = 0; index < quantity; index += 1) {
108
+ const isBuyer = slots.length === 0;
109
+ const typed = input.names[ticket.id]?.[index];
110
+ slots.push({
111
+ ticketId: ticket.id,
112
+ ticketTitle: ticket.title,
113
+ index,
114
+ number: index + 1,
115
+ ticketQuantity: quantity,
116
+ isBuyer,
117
+ value: typed !== undefined ? typed : isBuyer ? input.buyerName : "",
118
+ label: quantity > 1 ? `${ticket.title} — Attendee ${index + 1} of ${quantity}` : ticket.title,
119
+ });
120
+ }
121
+ }
122
+
123
+ return slots;
124
+ }
125
+
126
+ /** Write one seat's name back into the positional map. */
127
+ export function setAttendeeName(names: AttendeeNames, ticketId: string, index: number, value: string): AttendeeNames {
128
+ const existing = names[ticketId] ?? [];
129
+ const next = existing.slice();
130
+ // A sparse array would serialise its holes as `null`; fill so every earlier
131
+ // seat stays `undefined` (= "not touched") rather than becoming a value.
132
+ while (next.length < index) next.push(undefined);
133
+ next[index] = value;
134
+ return { ...names, [ticketId]: next };
135
+ }
136
+
137
+ export type AttendeeProblem = "name_required" | "name_too_long";
138
+
139
+ export type AttendeeCheck = { ok: true } | { ok: false; reason: AttendeeProblem; slot: AttendeeSlot; message: string };
140
+
141
+ /**
142
+ * Every seat named, and no name over the cap.
143
+ *
144
+ * Returns the OFFENDING SLOT, not just a boolean, so a storefront can point at
145
+ * the field rather than say "something is missing" above a list of eight
146
+ * inputs.
147
+ */
148
+ export function validateAttendeeNames(slots: AttendeeSlot[]): AttendeeCheck {
149
+ for (const slot of slots) {
150
+ const name = normalizeAttendeeName(slot.value);
151
+ if (name.length === 0) {
152
+ return {
153
+ ok: false,
154
+ reason: "name_required",
155
+ slot,
156
+ message: `Please enter a name for ${slot.label}.`,
157
+ };
158
+ }
159
+ if (name.length > MAX_ATTENDEE_NAME_LENGTH) {
160
+ return {
161
+ ok: false,
162
+ reason: "name_too_long",
163
+ slot,
164
+ message: `The name for ${slot.label} is too long (max ${MAX_ATTENDEE_NAME_LENGTH} characters).`,
165
+ };
166
+ }
167
+ }
168
+ return { ok: true };
169
+ }
170
+
171
+ /**
172
+ * The `attendees` map for `POST /public/events/:id/orders`.
173
+ *
174
+ * Built from the SLOTS, which is what guarantees exactly `quantity` entries per
175
+ * tier — the one shape the server refuses. Returns `undefined` when there is
176
+ * nothing to send, so an event that does not collect posts the body it always
177
+ * did (and the server does not read the field on that branch anyway).
178
+ */
179
+ export function attendeesPayload(slots: AttendeeSlot[]): Record<string, { name: string }[]> | undefined {
180
+ if (slots.length === 0) return undefined;
181
+ const out: Record<string, { name: string }[]> = {};
182
+ for (const slot of slots) {
183
+ const list = (out[slot.ticketId] ??= []);
184
+ list[slot.index] = { name: normalizeAttendeeName(slot.value) };
185
+ }
186
+ return out;
187
+ }
@@ -0,0 +1,209 @@
1
+ import { safeRedirectPath } from "../../utils/safeRedirect";
2
+ import type { MembershipGateReason, PublicMembershipGate } from "../../types/models";
3
+
4
+ /**
5
+ * Members-only things, as a buyer has to see them (S.4, (c)).
6
+ *
7
+ * ## The defect this module exists to close
8
+ *
9
+ * The gate shipped ENFORCED and UNANNOUNCED. A logged-out buyer saw an ordinary
10
+ * ticket, chose a seat, typed their name and their email twice, and was refused
11
+ * on the last screen with a `MEMBERSHIP_GATE` 400 — the restriction was
12
+ * discoverable only by failing it. And the "members save X, sign in" funnel the
13
+ * feature was justified by existed on no surface at all, because nothing drew a
14
+ * way OUT of the refusal.
15
+ *
16
+ * ## Why it is pure, and why it lives in `format/`
17
+ *
18
+ * There are two rendering stacks — `apps/client` and the Forge SDK that code
19
+ * websites build against — and a members-only badge that says one thing on an
20
+ * artist's PWA and another on their website is the same bug twice. So the words
21
+ * and the resolving ACTION are decided once, here, with no React and no client;
22
+ * each stack owns only how it looks. `apps/client` imports this from
23
+ * `@tribe-nest/forge/ui`, exactly as it already does for the PWYW arithmetic.
24
+ *
25
+ * Pure and total also means the whole mapping is testable without a DOM or a
26
+ * session — and getting the two reasons backwards is the failure mode that
27
+ * matters most: telling someone who is already signed in to "sign in" is a loop
28
+ * with no exit, and telling a logged-out visitor to "upgrade" asks them to buy a
29
+ * membership they may already hold.
30
+ */
31
+
32
+ // The wire shapes live in `types/models` beside the payloads that carry them;
33
+ // re-exported here so a site importing the renderer gets the type with it.
34
+ export type { MembershipGateReason, PublicMembershipGate };
35
+
36
+ /** The API's stable machine-readable refusal code. Switch on this, never on prose. */
37
+ export const MEMBERSHIP_GATE_CODE = "MEMBERSHIP_GATE";
38
+
39
+ /** A `MEMBERSHIP_GATE` response, unpacked. */
40
+ export type MembershipGateRefusal = {
41
+ reason: MembershipGateReason;
42
+ requiredTierIds: string[];
43
+ /** `event`, `event_ticket`, `course`, `product`, `post`. */
44
+ targetType: string;
45
+ targetId: string;
46
+ /** The API's own sentence, when it sent one. */
47
+ message: string | null;
48
+ };
49
+
50
+ type ApiErrorShape = {
51
+ response?: {
52
+ data?: {
53
+ code?: string;
54
+ message?: string;
55
+ details?: {
56
+ reason?: string;
57
+ requiredTierIds?: unknown;
58
+ targetType?: unknown;
59
+ targetId?: unknown;
60
+ };
61
+ };
62
+ };
63
+ };
64
+
65
+ const asStringArray = (value: unknown): string[] =>
66
+ Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];
67
+
68
+ /**
69
+ * A thrown request → the gate refusal inside it, or `null` for anything else.
70
+ *
71
+ * Matched on `code`, not on the status: a checkout refusal is 400 and a read
72
+ * refusal is 401 or 403, and a client that switched on the status would render
73
+ * the members-only prompt as a session timeout on one of them.
74
+ *
75
+ * The `reason` is validated rather than cast. An unrecognised value falls back
76
+ * to `membership_required`, which is the safe half: it offers a way to BUY
77
+ * access, whereas a wrong `sign_in_required` offers a signed-in member a sign-in
78
+ * button that changes nothing.
79
+ */
80
+ export function parseMembershipGateError(error: unknown): MembershipGateRefusal | null {
81
+ const data = (error as ApiErrorShape)?.response?.data;
82
+ if (!data || data.code !== MEMBERSHIP_GATE_CODE) return null;
83
+
84
+ const details = data.details ?? {};
85
+ return {
86
+ reason: details.reason === "sign_in_required" ? "sign_in_required" : "membership_required",
87
+ requiredTierIds: asStringArray(details.requiredTierIds),
88
+ targetType: typeof details.targetType === "string" ? details.targetType : "",
89
+ targetId: typeof details.targetId === "string" ? details.targetId : "",
90
+ message: typeof data.message === "string" && data.message.trim() ? data.message : null,
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Is this thing refused to the caller looking at it?
96
+ *
97
+ * `null` means "nothing gates it" — which is also what every read returns while
98
+ * the `membership_entitlement_gates` switch is off. Treating an absent gate as
99
+ * "gated and permitted" would badge every item on every site the day the field
100
+ * shipped, so absent must read as false here and nowhere else.
101
+ */
102
+ export function isMembershipGateLocked(gate: PublicMembershipGate | null | undefined): boolean {
103
+ return !!gate && !gate.allowed;
104
+ }
105
+
106
+ /** What a surface draws in place of, or beside, a gated thing. */
107
+ export type MembershipGateNotice = {
108
+ reason: MembershipGateReason;
109
+ /** Two words for a list row, where a sentence does not fit. */
110
+ badge: string;
111
+ title: string;
112
+ body: string;
113
+ /** Primary CTA label — the way OUT of the refusal, which is the whole point. */
114
+ actionLabel: string;
115
+ /**
116
+ * Where the CTA goes. `null` only when the caller passed no path to send them
117
+ * to; a surface with a null href should render the notice without a button
118
+ * rather than a button that goes nowhere.
119
+ */
120
+ actionHref: string | null;
121
+ };
122
+
123
+ /** Default sign-in path. Overridden per site — code websites mount theirs under `/i`. */
124
+ export const MEMBERSHIP_GATE_LOGIN_PATH = "/login";
125
+ /** Default tier-listing path, i.e. where "become a member" actually leads. */
126
+ export const MEMBERSHIP_GATE_MEMBERSHIP_PATH = "/membership";
127
+
128
+ /** "Gold", "Gold or Platinum", "Gold, Silver or Bronze" — ANY one unlocks, hence "or". */
129
+ export function joinTierNames(names: string[]): string {
130
+ const clean = names.map((name) => name.trim()).filter(Boolean);
131
+ if (clean.length === 0) return "";
132
+ if (clean.length === 1) return clean[0];
133
+ return `${clean.slice(0, -1).join(", ")} or ${clean[clean.length - 1]}`;
134
+ }
135
+
136
+ /** `path?redirect=<here>` — a sign-in that lands back on the thing they wanted. */
137
+ export function membershipSignInHref(loginPath: string, currentPath: string): string {
138
+ const target = safeRedirectPath(currentPath, "");
139
+ return target ? `${loginPath}?redirect=${encodeURIComponent(target)}` : loginPath;
140
+ }
141
+
142
+ export interface BuildMembershipGateNoticeInput {
143
+ /** The announced gate from a listing/detail read. */
144
+ gate?: PublicMembershipGate | null;
145
+ /** A `MEMBERSHIP_GATE` refusal from a failed purchase. Wins over `gate` — it is the newer fact. */
146
+ refusal?: MembershipGateRefusal | null;
147
+ /**
148
+ * Names for `requiredTierIds`, already resolved by the caller (both stacks
149
+ * already fetch the public tier list). Ids are never shown: "you need tier
150
+ * 8f3c-…" is not a sentence anyone can act on.
151
+ */
152
+ tierNames?: string[];
153
+ /** What the thing IS, in the buyer's words — "This ticket", "This course". */
154
+ itemLabel?: string;
155
+ loginPath?: string;
156
+ membershipPath?: string;
157
+ /** Path (+ search) to return to after signing in. */
158
+ currentPath?: string;
159
+ }
160
+
161
+ /**
162
+ * The notice for a gated thing, or `null` when there is nothing to say.
163
+ *
164
+ * A `refusal` beats a `gate` because it is the more recent read of the same
165
+ * fact: the page may have rendered `allowed: true` from a stale cache, or the
166
+ * buyer's membership may have lapsed between the page load and the pay button,
167
+ * and the server's "no" at the moment of purchase is what actually happened.
168
+ */
169
+ export function buildMembershipGateNotice(
170
+ input: BuildMembershipGateNoticeInput,
171
+ ): MembershipGateNotice | null {
172
+ const reason = input.refusal?.reason ?? (isMembershipGateLocked(input.gate) ? input.gate!.reason : null);
173
+ if (!reason) return null;
174
+
175
+ const item = input.itemLabel?.trim() || "This";
176
+ const tiers = joinTierNames(input.tierNames ?? []);
177
+ const loginPath = input.loginPath ?? MEMBERSHIP_GATE_LOGIN_PATH;
178
+ const membershipPath = input.membershipPath ?? MEMBERSHIP_GATE_MEMBERSHIP_PATH;
179
+
180
+ if (reason === "sign_in_required") {
181
+ return {
182
+ reason,
183
+ badge: "Members only",
184
+ title: "Members only",
185
+ // The API's own sentence is deliberately NOT used for this half. It is
186
+ // written for the refusal ("You must be a member to buy this"), and what
187
+ // an anonymous visitor needs first is the possibility that they already
188
+ // are one — which is the difference between a dead end and a funnel.
189
+ body: tiers
190
+ ? `${item} is for ${tiers} members. Already one? Sign in and it unlocks.`
191
+ : `${item} is for members. Already one? Sign in and it unlocks.`,
192
+ actionLabel: "Sign in",
193
+ actionHref: membershipSignInHref(loginPath, input.currentPath ?? ""),
194
+ };
195
+ }
196
+
197
+ return {
198
+ reason,
199
+ badge: "Members only",
200
+ title: "Members only",
201
+ body: tiers
202
+ ? `${item} is for ${tiers} members. Your current plan doesn't include it.`
203
+ : `${item} is for members. Your current plan doesn't include it.`,
204
+ // NOT "sign in" — they already are, and offering it again is a loop with no
205
+ // exit. The only move that changes anything is joining the tier.
206
+ actionLabel: tiers ? `View ${tiers}` : "View membership",
207
+ actionHref: membershipPath,
208
+ };
209
+ }
@@ -0,0 +1,83 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { buildAddToCalendarLinks } from "../useAddToCalendar";
3
+
4
+ /**
5
+ * The Apple half of "add to calendar", which for a long time did not exist.
6
+ *
7
+ * Google and Microsoft publish TEMPLATE URLs — the whole event travels in the
8
+ * query string and no server is involved. Apple publishes nothing of the kind:
9
+ * Calendar takes a FILE, and Safari on iOS treats an https `.ics` as a file it
10
+ * cannot open. `webcal://` is the scheme iOS and macOS route to the Calendar
11
+ * app, so it is the only thing that makes an Apple option possible at all.
12
+ *
13
+ * This file is about the derivation, because that is where a mistake would be
14
+ * silent: a mangled scheme still renders a chip, and the failure only shows up
15
+ * on somebody's phone.
16
+ */
17
+ describe("buildAddToCalendarLinks — the Apple routes", () => {
18
+ const base = { title: "Night Show", start: "2026-03-15T20:00:00.000Z" };
19
+
20
+ const ICS = "https://api.tribenest.co/public/calendar/events/abc/tok.ics";
21
+
22
+ it("offers neither route when the host has no .ics to point at", () => {
23
+ const links = buildAddToCalendarLinks(base)!;
24
+
25
+ // A site pinned to an older API build must degrade to the three template
26
+ // providers, not draw a dead Apple chip.
27
+ expect(links.ics).toBeNull();
28
+ expect(links.webcal).toBeNull();
29
+ expect(links.google).toContain("calendar.google.com");
30
+ });
31
+
32
+ it("derives webcal:// from the https address when only that is supplied", () => {
33
+ const links = buildAddToCalendarLinks({ ...base, icsUrl: ICS })!;
34
+
35
+ expect(links.ics).toBe(ICS);
36
+ // Scheme-only swap: the path, the id and the HMAC token must survive
37
+ // untouched, or the link resolves to a different document (or to nothing).
38
+ expect(links.webcal).toBe("webcal://api.tribenest.co/public/calendar/events/abc/tok.ics");
39
+ });
40
+
41
+ it("prefers the server's own webcal URL over the derivation", () => {
42
+ const links = buildAddToCalendarLinks({
43
+ ...base,
44
+ icsUrl: ICS,
45
+ webcalUrl: "webcal://cdn.example.com/other.ics",
46
+ })!;
47
+
48
+ // The API composes both; if it ever puts them on different hosts, the
49
+ // client must not quietly out-vote it.
50
+ expect(links.webcal).toBe("webcal://cdn.example.com/other.ics");
51
+ });
52
+
53
+ it("derives from http as well as https", () => {
54
+ const links = buildAddToCalendarLinks({ ...base, icsUrl: "http://localhost:8000/public/calendar/events/a/t.ics" })!;
55
+ expect(links.webcal).toBe("webcal://localhost:8000/public/calendar/events/a/t.ics");
56
+ });
57
+
58
+ it("refuses to invent a webcal URL from something that is not absolute", () => {
59
+ // `calendarFeedUrl` falls back to a bare PATH when `API_URL` is unset, and
60
+ // "webcal:///public/calendar/…" is not an address any client can resolve.
61
+ // Better no Apple option than a broken one.
62
+ const links = buildAddToCalendarLinks({ ...base, icsUrl: "/public/calendar/events/abc/tok.ics" })!;
63
+
64
+ expect(links.ics).toBe("/public/calendar/events/abc/tok.ics");
65
+ expect(links.webcal).toBeNull();
66
+ });
67
+
68
+ it("passes an already-webcal address through unchanged", () => {
69
+ const links = buildAddToCalendarLinks({ ...base, webcalUrl: "webcal://api.tribenest.co/a.ics" })!;
70
+ expect(links.webcal).toBe("webcal://api.tribenest.co/a.ics");
71
+ // No https form was supplied, so no download is offered.
72
+ expect(links.ics).toBeNull();
73
+ });
74
+
75
+ it("leaves the three template providers untouched by any of this", () => {
76
+ const withIcs = buildAddToCalendarLinks({ ...base, icsUrl: ICS })!;
77
+ const without = buildAddToCalendarLinks(base)!;
78
+
79
+ expect(withIcs.google).toBe(without.google);
80
+ expect(withIcs.outlook).toBe(without.outlook);
81
+ expect(withIcs.office365).toBe(without.office365);
82
+ });
83
+ });
@@ -26,11 +26,29 @@ export type AddToCalendarInput = {
26
26
  /** Canonical page for the event; appended to the description body when present. */
27
27
  url?: string | null;
28
28
  /**
29
- * Absolute URL to a downloadable `.ics` (what Apple Calendar / Outlook desktop
30
- * want). Forge does not synthesize this the host passes the endpoint it has.
31
- * When absent, `ics` comes back `null` and no Apple option is offered.
29
+ * Absolute URL to a downloadable `.ics` what Outlook desktop, Thunderbird
30
+ * and a Mac that would rather have the file all want.
31
+ *
32
+ * Forge does not synthesize this and cannot: the platform's `.ics` address
33
+ * carries a keyed HMAC, so it is deliberately not derivable from an event id.
34
+ * The host passes the field the API gave it (`calendarUrl`). When absent,
35
+ * `ics` comes back `null` and no download option is offered.
32
36
  */
33
37
  icsUrl?: string | null;
38
+ /**
39
+ * The same `.ics`, under `webcal://` — the API's `calendarWebcalUrl`.
40
+ *
41
+ * **This is the Apple route, and there is no other.** Apple publishes no
42
+ * "add to calendar" template URL the way Google and Microsoft do, which is
43
+ * exactly why every control in this product used to offer three providers and
44
+ * no Apple option. Safari on iOS treats an https `.ics` as a file it cannot
45
+ * open; the same address under `webcal:` is handed straight to Calendar.
46
+ *
47
+ * Optional, and derived from {@link icsUrl} when omitted — a host on an older
48
+ * API build that only carries the https form still gets a working Apple
49
+ * option, because the two differ only by scheme.
50
+ */
51
+ webcalUrl?: string | null;
34
52
  };
35
53
 
36
54
  export type AddToCalendarLinks = {
@@ -42,8 +60,14 @@ export type AddToCalendarLinks = {
42
60
  office365: string;
43
61
  /** Yahoo Calendar. */
44
62
  yahoo: string;
45
- /** Pass-through of `icsUrl` — the Apple/desktop route. `null` when not supplied. */
63
+ /** Pass-through of `icsUrl` — the download route. `null` when not supplied. */
46
64
  ics: string | null;
65
+ /**
66
+ * The `webcal://` address, for the Apple option. Falls back to `icsUrl` with
67
+ * its scheme swapped, so supplying either one is enough. `null` when neither
68
+ * is available.
69
+ */
70
+ webcal: string | null;
47
71
  startsAt: Date;
48
72
  endsAt: Date;
49
73
  };
@@ -97,6 +121,20 @@ export function stripHtml(html: string, maxLength: number = MAX_DESCRIPTION_CHAR
97
121
 
98
122
  const enc = encodeURIComponent;
99
123
 
124
+ /**
125
+ * The `webcal://` form, preferring what the host was given.
126
+ *
127
+ * The swap is scheme-only and is applied to an https address, never to an
128
+ * arbitrary string: a relative or already-`webcal:` URL is passed through
129
+ * untouched rather than being mangled into something a calendar client would
130
+ * refuse.
131
+ */
132
+ function toWebcal(webcalUrl?: string | null, icsUrl?: string | null): string | null {
133
+ if (webcalUrl) return webcalUrl;
134
+ if (!icsUrl) return null;
135
+ return /^https?:\/\//i.test(icsUrl) ? icsUrl.replace(/^https?:\/\//i, "webcal://") : null;
136
+ }
137
+
100
138
  /**
101
139
  * Build every provider URL for one calendar entry. Returns `null` when the
102
140
  * start is missing or unparseable — callers render nothing rather than a link
@@ -156,6 +194,7 @@ export function buildAddToCalendarLinks(input: AddToCalendarInput): AddToCalenda
156
194
  `&desc=${enc(body)}` +
157
195
  `&in_loc=${enc(location)}`,
158
196
  ics: input.icsUrl || null,
197
+ webcal: toWebcal(input.webcalUrl, input.icsUrl),
159
198
  startsAt,
160
199
  endsAt,
161
200
  };
@@ -177,6 +216,7 @@ export function useAddToCalendar(input: AddToCalendarInput | null | undefined):
177
216
  const location = input?.location;
178
217
  const url = input?.url;
179
218
  const icsUrl = input?.icsUrl;
219
+ const webcalUrl = input?.webcalUrl;
180
220
 
181
221
  return useMemo(() => {
182
222
  if (!start) return null;
@@ -189,6 +229,7 @@ export function useAddToCalendar(input: AddToCalendarInput | null | undefined):
189
229
  location,
190
230
  url,
191
231
  icsUrl,
232
+ webcalUrl,
192
233
  });
193
- }, [title, start, end, defaultDurationMinutes, description, location, url, icsUrl]);
234
+ }, [title, start, end, defaultDurationMinutes, description, location, url, icsUrl, webcalUrl]);
194
235
  }
@@ -0,0 +1,111 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ HOLD_EXPIRED_CODE,
4
+ formatHoldRemaining,
5
+ holdExpiredMessage,
6
+ holdMsRemaining,
7
+ isHoldExpiredError,
8
+ } from "../inventoryHold";
9
+
10
+ /**
11
+ * The inventory hold, as both rendering stacks read it.
12
+ *
13
+ * Every case here is a bug the checkout shipped with before this existed: a
14
+ * buyer told "sold out" for an item that was not sold out, a countdown drawn
15
+ * over an order that had no reservation at all, and a timer that read "0:00"
16
+ * for a whole second while the payment was still perfectly good.
17
+ *
18
+ * Pure, so they run with no provider tree — the same reason `bundleCoupon`'s
19
+ * helpers live outside the hook.
20
+ */
21
+
22
+ const apiError = (data: Record<string, unknown>, status = 409) => ({ response: { status, data } });
23
+
24
+ describe("isHoldExpiredError", () => {
25
+ it("recognises the 409 the hold endpoints throw", () => {
26
+ expect(isHoldExpiredError(apiError({ code: HOLD_EXPIRED_CODE, message: "…expired…" }))).toBe(true);
27
+ });
28
+
29
+ it("does NOT treat sold-out as an expired hold", () => {
30
+ // The whole point of splitting the error out: sold-out has no retry that
31
+ // can work, an expired hold usually does. Offering the wrong one is the
32
+ // regression this guards.
33
+ expect(isHoldExpiredError(apiError({ message: "This ticket is sold out." }, 400))).toBe(false);
34
+ });
35
+
36
+ it("does not fire on a bare 409 with no code", () => {
37
+ // A 409 is a generic conflict any future endpoint could answer with;
38
+ // switching on the status alone would offer a retry that cannot help.
39
+ expect(isHoldExpiredError(apiError({ message: "Conflict" }))).toBe(false);
40
+ });
41
+
42
+ it("is safe on the shapes an unexpected failure actually arrives as", () => {
43
+ expect(isHoldExpiredError(undefined)).toBe(false);
44
+ expect(isHoldExpiredError(null)).toBe(false);
45
+ expect(isHoldExpiredError(new Error("Network Error"))).toBe(false);
46
+ expect(isHoldExpiredError({})).toBe(false);
47
+ });
48
+ });
49
+
50
+ describe("holdExpiredMessage", () => {
51
+ it("prefers the API's own localised words", () => {
52
+ const message = "Your ticket reservation expired before payment finished.";
53
+ expect(holdExpiredMessage(apiError({ code: HOLD_EXPIRED_CODE, message }), "fallback")).toBe(message);
54
+ });
55
+
56
+ it("falls back only when the response carried nothing", () => {
57
+ expect(holdExpiredMessage(apiError({ code: HOLD_EXPIRED_CODE }), "fallback")).toBe("fallback");
58
+ expect(holdExpiredMessage(new Error("boom"), "fallback")).toBe("fallback");
59
+ });
60
+ });
61
+
62
+ describe("holdMsRemaining", () => {
63
+ const now = Date.parse("2026-08-09T12:00:00.000Z");
64
+
65
+ it("measures the window from now", () => {
66
+ expect(holdMsRemaining("2026-08-09T12:10:00.000Z", now)).toBe(600_000);
67
+ });
68
+
69
+ it("returns null — NOT zero — when no hold was taken", () => {
70
+ // `null` is "there is no reservation" (holds switched off for the profile,
71
+ // a digital-only cart, an already-settled free order); `0` is "a real one
72
+ // ran out". A surface that conflated them would draw an expired countdown
73
+ // on every order for every profile with the feature off.
74
+ expect(holdMsRemaining(null, now)).toBeNull();
75
+ expect(holdMsRemaining(undefined, now)).toBeNull();
76
+ expect(holdMsRemaining("", now)).toBeNull();
77
+ });
78
+
79
+ it("returns null for an unparseable instant rather than a bogus countdown", () => {
80
+ expect(holdMsRemaining("not-a-date", now)).toBeNull();
81
+ });
82
+
83
+ it("clamps a past instant to zero instead of counting up", () => {
84
+ expect(holdMsRemaining("2026-08-09T11:59:00.000Z", now)).toBe(0);
85
+ });
86
+ });
87
+
88
+ describe("formatHoldRemaining", () => {
89
+ it("renders m:ss", () => {
90
+ expect(formatHoldRemaining(600_000)).toBe("10:00");
91
+ expect(formatHoldRemaining(65_000)).toBe("1:05");
92
+ expect(formatHoldRemaining(9_000)).toBe("0:09");
93
+ });
94
+
95
+ it("rounds UP, so the clock only reads 0:00 when it is genuinely over", () => {
96
+ // Rounding down put "0:00" on screen for the last whole second of a hold
97
+ // that was still perfectly valid — a small lie the buyer acts on.
98
+ expect(formatHoldRemaining(1)).toBe("0:01");
99
+ expect(formatHoldRemaining(999)).toBe("0:01");
100
+ expect(formatHoldRemaining(0)).toBe("0:00");
101
+ });
102
+
103
+ it("grows to h:mm:ss for a long window", () => {
104
+ expect(formatHoldRemaining(3_600_000)).toBe("1:00:00");
105
+ expect(formatHoldRemaining(3_725_000)).toBe("1:02:05");
106
+ });
107
+
108
+ it("never renders a negative clock", () => {
109
+ expect(formatHoldRemaining(-5_000)).toBe("0:00");
110
+ });
111
+ });