@wix/himalaya-cli 0.1642.0 → 0.1644.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.
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +6 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/validator.d.ts +3 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +3 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +3 -1
- package/dist/browser-plane/assets.json +5 -5
- package/dist/browser-plane/preview-deferred/{3361f61ce6b490c8b7b252658ea67f733d88c6e9f95906d0e31eea4827141df3.bin → 155f61519885c85d61a39fa595197071a3ca07680da56055ccb1dcff2e709cd1.bin} +1 -1
- package/dist/browser-plane/sw.js +6 -6
- package/dist/cli.mjs +358 -144
- package/dist/preview-assets.generated.bin +0 -0
- package/guides/component-reference.json +1 -1
- package/guides/component-reference.md +6 -0
- package/guides/designing-himi-screens.md +18 -0
- package/guides/offline-reading.md +1 -1
- package/guides/recipe-four-state.md +17 -0
- package/guides/release-notes.md +21 -0
- package/guides/sdk-reference.json +1 -1
- package/package.json +2 -2
- package/template-icons/conference.png +0 -0
- package/templates/beauty-salon/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/beauty-salon/tier5-src/himi-store-product/index.ts +6 -3
- package/templates/branded-lite/dev/index.ts +152 -88
- package/templates/branded-lite/l10n/en.json +1 -1
- package/templates/branded-lite/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/branded-lite/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/branded-lite/tier5-src/himi-events-detail/index.ts +93 -11
- package/templates/branded-lite/tier5-src/himi-store-product/index.ts +7 -3
- package/templates/community-club/dev/index.ts +152 -88
- package/templates/community-club/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/community-club/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/community-club/tier5-src/himi-events-detail/index.ts +93 -11
- package/templates/conference/README.md +53 -0
- package/templates/conference/config.ts +321 -0
- package/templates/conference/dev/index.ts +17252 -0
- package/templates/conference/himalaya.content.json +46 -0
- package/templates/conference/himalaya.template.json +15 -0
- package/templates/conference/icon.png +0 -0
- package/templates/conference/platforms.json +1 -0
- package/templates/conference/tier5-src/_shared/agenda-stars.ts +64 -0
- package/templates/conference/tier5-src/_shared/app-locale.ts +61 -0
- package/templates/conference/tier5-src/_shared/branded-lite-hosted.ts +279 -0
- package/templates/conference/tier5-src/_shared/branded-load-state.ts +109 -0
- package/templates/conference/tier5-src/_shared/business-chat-copy.ts +40 -0
- package/templates/conference/tier5-src/_shared/business-chat-history.ts +51 -0
- package/templates/conference/tier5-src/_shared/business-chat-message-model.ts +177 -0
- package/templates/conference/tier5-src/_shared/business-chat-model.ts +56 -0
- package/templates/conference/tier5-src/_shared/business-chat-presenter.ts +576 -0
- package/templates/conference/tier5-src/_shared/business-chat-transport.ts +148 -0
- package/templates/conference/tier5-src/_shared/collection-contract.ts +229 -0
- package/templates/conference/tier5-src/_shared/collection-query.ts +193 -0
- package/templates/conference/tier5-src/_shared/collection-service.ts +400 -0
- package/templates/conference/tier5-src/_shared/engine-intl.ts +508 -0
- package/templates/conference/tier5-src/_shared/event-agenda.ts +122 -0
- package/templates/conference/tier5-src/_shared/event-registration.ts +86 -0
- package/templates/conference/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/conference/tier5-src/_shared/himi-account.ts +164 -0
- package/templates/conference/tier5-src/_shared/himi-copy.ts +89 -0
- package/templates/conference/tier5-src/_shared/himi-events.ts +65 -0
- package/templates/conference/tier5-src/_shared/himi-store.ts +7 -0
- package/templates/conference/tier5-src/_shared/hosted-checkout.ts +70 -0
- package/templates/conference/tier5-src/_shared/iap-attendance-form.ts +106 -0
- package/templates/conference/tier5-src/_shared/iap-attendance-purchase.ts +211 -0
- package/templates/conference/tier5-src/_shared/iap-attendance.ts +38 -0
- package/templates/conference/tier5-src/_shared/iap-worker.ts +125 -0
- package/templates/conference/tier5-src/_shared/inbox-rooms.ts +68 -0
- package/templates/conference/tier5-src/_shared/local-preferences.ts +38 -0
- package/templates/conference/tier5-src/_shared/member-access.ts +52 -0
- package/templates/conference/tier5-src/_shared/member-account-routes.ts +52 -0
- package/templates/conference/tier5-src/_shared/member-read.ts +52 -0
- package/templates/conference/tier5-src/_shared/member-screen.ts +99 -0
- package/templates/conference/tier5-src/_shared/offset-page.ts +10 -0
- package/templates/conference/tier5-src/_shared/online-actions.ts +76 -0
- package/templates/conference/tier5-src/_shared/owner-load-error.ts +348 -0
- package/templates/conference/tier5-src/_shared/payment-setup.ts +6 -0
- package/templates/conference/tier5-src/_shared/rich-body.ts +78 -0
- package/templates/conference/tier5-src/_shared/rich-content-link.ts +34 -0
- package/templates/conference/tier5-src/_shared/sign-in-sheet.ts +18 -0
- package/templates/conference/tier5-src/business-chat/index.ts +724 -0
- package/templates/conference/tier5-src/himi-conference-agenda/index.ts +183 -0
- package/templates/conference/tier5-src/himi-conference-home/index.ts +389 -0
- package/templates/conference/tier5-src/himi-events-account/index.ts +219 -0
- package/templates/conference/tier5-src/himi-events-detail/index.ts +1304 -0
- package/templates/conference/tier5-src/himi-events-list/index.ts +124 -0
- package/templates/conference/tier5-src/himi-events-my-events/index.ts +225 -0
- package/templates/conference/tier5-src/himi-events-rsvp/index.ts +230 -0
- package/templates/conference/tier5-src/himi-store-account/index.ts +998 -0
- package/templates/conference/tokens.json +365 -0
- package/templates/events-meetups/dev/index.ts +152 -88
- package/templates/events-meetups/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/events-meetups/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/events-meetups/tier5-src/himi-events-detail/index.ts +93 -11
- package/templates/gym-fitness/dev/index.ts +152 -88
- package/templates/gym-fitness/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/gym-fitness/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/gym-fitness/tier5-src/himi-events-detail/index.ts +93 -11
- package/templates/gym-fitness/tier5-src/himi-store-product/index.ts +6 -3
- package/templates/nonprofit-cause/dev/index.ts +152 -88
- package/templates/nonprofit-cause/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/nonprofit-cause/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/nonprofit-cause/tier5-src/himi-events-detail/index.ts +93 -11
- package/templates/podcast-creator/dev/index.ts +152 -88
- package/templates/podcast-creator/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/podcast-creator/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/podcast-creator/tier5-src/himi-events-detail/index.ts +93 -11
- package/templates/portfolio-creative/dev/index.ts +152 -88
- package/templates/portfolio-creative/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/portfolio-creative/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/portfolio-creative/tier5-src/himi-events-detail/index.ts +93 -11
- package/templates/portfolio-creative/tier5-src/himi-store-product/index.ts +6 -3
- package/templates/restaurant/dev/index.ts +152 -88
- package/templates/restaurant/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/restaurant/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/restaurant/tier5-src/himi-events-detail/index.ts +93 -11
- package/templates/retail-store/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/retail-store/tier5-src/himi-store-product/index.ts +7 -3
- package/templates/yoga-studio/dev/index.ts +152 -88
- package/templates/yoga-studio/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/yoga-studio/tier5-src/_shared/iap-presentation.ts +5 -2
- package/templates/yoga-studio/tier5-src/himi-events-detail/index.ts +93 -11
|
@@ -0,0 +1,1304 @@
|
|
|
1
|
+
import { paymentSetupMessage } from "../_shared/payment-setup.js";
|
|
2
|
+
// Tier-5 bundle: himi-events — event detail.
|
|
3
|
+
import { calendarDay, formatClock, formatCurrency, formatWeekdayDateTime, formatWeekdayMonthDay, formatTimeZoneLabel } from "../_shared/engine-intl.js";
|
|
4
|
+
import { defineService as registerService } from "@himalaya/state";
|
|
5
|
+
import { dispatch } from "@himalaya/dispatch";
|
|
6
|
+
import { withOnlineWrites } from "../_shared/online-actions.js";
|
|
7
|
+
import { hostedSitePageOpener, isHostedWorker } from "../_shared/hosted-checkout.js";
|
|
8
|
+
import { createEvent, getPermissionStatus, requestPermission } from "@himalaya/calendar";
|
|
9
|
+
import { open } from "@himalaya/open-url";
|
|
10
|
+
import { share as shareSheet } from "@himalaya/share";
|
|
11
|
+
import { createRedirectSession } from "@himalaya/wix-redirects";
|
|
12
|
+
import {
|
|
13
|
+
checkoutReservation,
|
|
14
|
+
createTicketReservation,
|
|
15
|
+
getEvent,
|
|
16
|
+
queryAvailableTickets,
|
|
17
|
+
type WixAvailableTicket,
|
|
18
|
+
type WixEventFieldset,
|
|
19
|
+
type WixEvent,
|
|
20
|
+
} from "@himalaya/wix-events";
|
|
21
|
+
import { session as wixPlatformSession } from "@himalaya/wix-platform";
|
|
22
|
+
import { isPaymentSetupFailure, payCashierOrder } from "@himalaya/checkout";
|
|
23
|
+
import { get, upsert, type DbEntity } from "@himalaya/local-db";
|
|
24
|
+
import {
|
|
25
|
+
currentInputId,
|
|
26
|
+
forgetRsvp,
|
|
27
|
+
eventDescription,
|
|
28
|
+
eventImage,
|
|
29
|
+
eventLocation,
|
|
30
|
+
eventAddress,
|
|
31
|
+
eventMapUrl,
|
|
32
|
+
eventStartMillis,
|
|
33
|
+
eventWhen,
|
|
34
|
+
normalizeEvent,
|
|
35
|
+
type EventRow,
|
|
36
|
+
} from "../_shared/himi-events";
|
|
37
|
+
import { stashCopy, copyParam } from "../_shared/himi-copy.js";
|
|
38
|
+
import { readFeaturedEvent } from "../_shared/featured-event.js";
|
|
39
|
+
import { eventPageUrlOf, eventStatus, registrationKindOf, registrationUi, registrationUrlOf, type RegistrationKind } from "../_shared/event-registration.js";
|
|
40
|
+
export { eventPageUrlOf, registrationKindOf, registrationUrlOf, type RegistrationKind };
|
|
41
|
+
import { openRichLink } from "../_shared/rich-content-link.js";
|
|
42
|
+
import { descriptionBody } from "../_shared/rich-body.js";
|
|
43
|
+
import { mayUseRegularTicketCheckout } from "../_shared/iap-attendance.js";
|
|
44
|
+
import { ATTENDANCE_INITIAL, ATTENDANCE_NOT_HYDRATED, createAttendancePurchase, type AttendancePurchaseFields } from "../_shared/iap-attendance-purchase.js";
|
|
45
|
+
import { resetUnhydratedKeysOnOlderRuntime } from "../_shared/iap-worker.js";
|
|
46
|
+
|
|
47
|
+
let ticketCheckoutAllowed = false;
|
|
48
|
+
let ticketCheckoutDenied = false;
|
|
49
|
+
let paymentEvent: unknown;
|
|
50
|
+
let paymentTickets = new Map<string, WixAvailableTicket>();
|
|
51
|
+
let ticketSelectionVersion = 0;
|
|
52
|
+
let ticketCheckoutInFlight = false;
|
|
53
|
+
let ticketSelectionQueue: Promise<void> = Promise.resolve();
|
|
54
|
+
let ticketSelectionState: S | undefined;
|
|
55
|
+
let lastReady: S | undefined;
|
|
56
|
+
let cancelRsvpInFlight = false;
|
|
57
|
+
const applePurchase = createAttendancePurchase({ kind: "eventsTicket", prefix: "event", pollAction: "himiEventDetail.iapPoll", onChange: () => { void svc.iapPublish(); } });
|
|
58
|
+
async function priceTicket(event: unknown, id: string, version: number, ticket = paymentTickets.get(id)): Promise<boolean> {
|
|
59
|
+
if (version !== ticketSelectionVersion) return false;
|
|
60
|
+
await applePurchase.ticket(id, event, ticket);
|
|
61
|
+
return version === ticketSelectionVersion;
|
|
62
|
+
}
|
|
63
|
+
let hostedOpenInFlight = false;
|
|
64
|
+
|
|
65
|
+
/** One buyer-visible ticket tier. */
|
|
66
|
+
interface TicketTierRow {
|
|
67
|
+
id: string;
|
|
68
|
+
ticketDefinitionId?: string;
|
|
69
|
+
pricingOptionId?: string;
|
|
70
|
+
guestPrice?: string;
|
|
71
|
+
minPrice?: number;
|
|
72
|
+
minimumPriceLabel?: string;
|
|
73
|
+
isGuestPrice?: boolean;
|
|
74
|
+
name: string;
|
|
75
|
+
/** Formatted price, or the free label. */
|
|
76
|
+
priceLine: string;
|
|
77
|
+
/** "" unless the tier is off-sale, in which case it says why. */
|
|
78
|
+
unavailableNote: string;
|
|
79
|
+
available: boolean;
|
|
80
|
+
/** Selection is rendered by the row itself (bound to `$item.isSelected`). */
|
|
81
|
+
isSelected: boolean;
|
|
82
|
+
notSelected: boolean;
|
|
83
|
+
quantity?: number;
|
|
84
|
+
feeNote?: string;
|
|
85
|
+
description?: string;
|
|
86
|
+
policy?: string;
|
|
87
|
+
priceAmount?: number;
|
|
88
|
+
maxQuantity?: number;
|
|
89
|
+
rowLimit?: number;
|
|
90
|
+
noPolicy?: boolean;
|
|
91
|
+
notAvailable?: boolean;
|
|
92
|
+
/** Its "Ticket terms" disclosure is open (`toggleDisclosure` with `terms:<id>`). */
|
|
93
|
+
termsOpen?: boolean;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Offline-first (data-offline): the event detail is a read-through single-item read —
|
|
97
|
+
// it shares the `events` entity written by the list, and also write-throughs its own
|
|
98
|
+
// fetched row so a deep-linked detail is cached for the next offline open. On a failed
|
|
99
|
+
// fetch it falls back to the last-synced cached row (get("events", id)) before erroring.
|
|
100
|
+
// DEGRADES GRACEFULLY: every local-db call is wrapped, so an app that hasn't granted
|
|
101
|
+
// `local_database` (+ declared the `events` entity) just keeps today's online-only path.
|
|
102
|
+
/** Wix Events appDefId — the vertical that owns a ticket order, so the `appId`
|
|
103
|
+
* its cashier order is paid under (mirrors AppDefId.EVENTS in Wix's RN apps). */
|
|
104
|
+
const WIX_EVENTS_APP_ID = "140603ad-af8d-84a5-2c80-a0f60cb47351";
|
|
105
|
+
|
|
106
|
+
const ENTITY = "events";
|
|
107
|
+
async function readCachedRow(id: string): Promise<EventRow | null> {
|
|
108
|
+
try { return (await get(ENTITY, id)) as unknown as EventRow | null; } catch { return null; }
|
|
109
|
+
}
|
|
110
|
+
async function writeCachedRow(row: EventRow): Promise<void> {
|
|
111
|
+
try { await upsert(ENTITY, row as unknown as DbEntity); } catch { /* capability not granted → online-only */ }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
interface S extends AttendancePurchaseFields {
|
|
115
|
+
status: "loading" | "ready";
|
|
116
|
+
id: string;
|
|
117
|
+
title: string;
|
|
118
|
+
when: string;
|
|
119
|
+
location: string;
|
|
120
|
+
/** The plain-text description: RichContent's fallback, the calendar notes, and what shows with no document. */
|
|
121
|
+
description: string;
|
|
122
|
+
/** [rico] #3372 — the v3 Ricos `description` (read with `fields=TEXTS`) as ONE document string for
|
|
123
|
+
* RichContent; "" when the event has none or the encoder rejected it. */
|
|
124
|
+
descriptionJson: string;
|
|
125
|
+
/** descriptionJson !== "" — gates the plain text, because RichContent draws nothing for "". */
|
|
126
|
+
hasDescriptionJson: boolean;
|
|
127
|
+
image: string;
|
|
128
|
+
hasImage: boolean;
|
|
129
|
+
noImage: boolean;
|
|
130
|
+
mapUrl: string;
|
|
131
|
+
place: string;
|
|
132
|
+
placeIcon: string;
|
|
133
|
+
noPlace: boolean;
|
|
134
|
+
hidePlaceStatic: boolean;
|
|
135
|
+
price: string;
|
|
136
|
+
zone: string;
|
|
137
|
+
noPrice: boolean;
|
|
138
|
+
hideMapTap: boolean;
|
|
139
|
+
shortDescription: string;
|
|
140
|
+
noShortDescription: boolean;
|
|
141
|
+
noDescription: boolean;
|
|
142
|
+
noDate: boolean;
|
|
143
|
+
dateNotTappable: boolean;
|
|
144
|
+
hideDateStatic: boolean;
|
|
145
|
+
registrationState: string;
|
|
146
|
+
footerLabel: string;
|
|
147
|
+
footerAction: string;
|
|
148
|
+
footerCaption: string;
|
|
149
|
+
hideFooter: boolean;
|
|
150
|
+
noFooterButton: boolean;
|
|
151
|
+
noFooterCaption: boolean;
|
|
152
|
+
notice: string;
|
|
153
|
+
exploreLabel: string;
|
|
154
|
+
noNotice: boolean;
|
|
155
|
+
rsvpLabel: string;
|
|
156
|
+
rsvpId: string;
|
|
157
|
+
rsvpState: "none" | "going" | "waitlist";
|
|
158
|
+
hideRsvpChip: boolean;
|
|
159
|
+
hideGoingChip: boolean;
|
|
160
|
+
hideWaitlistedChip: boolean;
|
|
161
|
+
hideCancelRsvp: boolean;
|
|
162
|
+
hideCancelConfirm: boolean;
|
|
163
|
+
hideRsvpOptions: boolean;
|
|
164
|
+
ticketSheetOpen: boolean;
|
|
165
|
+
rsvpActionsOpen: boolean;
|
|
166
|
+
cancelConfirmOpen: boolean;
|
|
167
|
+
ticketTotal: string;
|
|
168
|
+
ticketCountLabel: string;
|
|
169
|
+
checkoutDisabled: boolean;
|
|
170
|
+
schedule: Array<{ time: string; name: string; detail: string }>;
|
|
171
|
+
fullSchedule: Array<{ time: string; name: string; detail: string }>;
|
|
172
|
+
noSchedule: boolean;
|
|
173
|
+
noFullSchedule: boolean;
|
|
174
|
+
moreDates: Array<{ id: string; date: string }>;
|
|
175
|
+
allDates: Array<{ id: string; date: string }>;
|
|
176
|
+
noMoreDates: boolean;
|
|
177
|
+
noAllDates: boolean;
|
|
178
|
+
policies: Array<{ name: string; text: string }>;
|
|
179
|
+
noPolicies: boolean;
|
|
180
|
+
hideWaitlist: boolean;
|
|
181
|
+
hideScheduled: boolean;
|
|
182
|
+
memberOnly: boolean;
|
|
183
|
+
hideMemberRsvp: boolean;
|
|
184
|
+
hideMemberWaitlist: boolean;
|
|
185
|
+
hideMemberTickets: boolean;
|
|
186
|
+
hideMemberScheduled: boolean;
|
|
187
|
+
/** CTA variant flags — exactly one of {RSVP, tickets, external} shows, or
|
|
188
|
+
* none for NO_REGISTRATION. Unknown/absent registration keeps RSVP (the
|
|
189
|
+
* historical default). */
|
|
190
|
+
registrationKind: RegistrationKind;
|
|
191
|
+
showRsvp: boolean;
|
|
192
|
+
hideRsvp: boolean;
|
|
193
|
+
showTickets: boolean;
|
|
194
|
+
hideTickets: boolean;
|
|
195
|
+
showExternal: boolean;
|
|
196
|
+
hideExternal: boolean;
|
|
197
|
+
/** Buyer-visible ticket tiers for a ticketed event (empty otherwise). Loaded
|
|
198
|
+
* alongside the event so the price is on screen BEFORE the CTA is tapped. */
|
|
199
|
+
ticketTiers: TicketTierRow[];
|
|
200
|
+
/** The ids of the open disclosures: "fullSchedule", "allDates", "policies", `terms:<tier id>`.
|
|
201
|
+
* A DisclosureGroup is worker-controlled on every renderer (`expandedPath` + `onToggle`):
|
|
202
|
+
* one with neither never opens. */
|
|
203
|
+
openDisclosures: string[];
|
|
204
|
+
fullScheduleOpen: boolean;
|
|
205
|
+
allDatesOpen: boolean;
|
|
206
|
+
policiesOpen: boolean;
|
|
207
|
+
ticketCurrency: string;
|
|
208
|
+
ticketLimitPerOrder: number;
|
|
209
|
+
ticketPurchaseBlocked: boolean;
|
|
210
|
+
regularTicketsHidden: boolean;
|
|
211
|
+
hasTiers: boolean;
|
|
212
|
+
noTiers: boolean;
|
|
213
|
+
/** More than one tier ⇒ the picker is worth showing; exactly one ⇒ the CTA
|
|
214
|
+
* alone is honest (there is nothing to choose). */
|
|
215
|
+
showTierPicker: boolean;
|
|
216
|
+
hideTierPicker: boolean;
|
|
217
|
+
/** The tier the CTA will reserve. Defaults to the cheapest on-sale tier so the
|
|
218
|
+
* button is never dead, and follows the buyer's tap after that. */
|
|
219
|
+
selectedTierId: string;
|
|
220
|
+
/** "General · $25" — echoed next to the CTA so the choice is visible. */
|
|
221
|
+
selectedTierLabel: string;
|
|
222
|
+
/** External/ticketed registration URL when the payload carries one. */
|
|
223
|
+
registrationUrl: string;
|
|
224
|
+
/** Event slug for hosted eventsCheckout redirect (ticketed events). */
|
|
225
|
+
eventSlug: string;
|
|
226
|
+
/** Share payload — event page URL when the payload carries one. */
|
|
227
|
+
shareUrl: string;
|
|
228
|
+
calendarStart: number;
|
|
229
|
+
calendarEnd: number;
|
|
230
|
+
snackbarMessage: string;
|
|
231
|
+
noSnackbar: boolean;
|
|
232
|
+
isAddingCalendar: boolean;
|
|
233
|
+
emptyText: string;
|
|
234
|
+
errored: boolean;
|
|
235
|
+
notErrored: boolean;
|
|
236
|
+
isLoading: boolean;
|
|
237
|
+
notLoading: boolean;
|
|
238
|
+
noEmpty: boolean;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function inputId(): string {
|
|
242
|
+
return currentInputId(["himi_event_"]);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** `featured: "1"` (an onAppear param): a screen with no event id — a conference app's Tickets
|
|
246
|
+
* tab — shows the site's featured event (the one on now, else the next to start). */
|
|
247
|
+
const featuredRequested = (arg: unknown): boolean => (arg as { featured?: unknown } | undefined)?.featured === "1";
|
|
248
|
+
// The last featured open found no live or upcoming event: the empty state says so, not "not found".
|
|
249
|
+
let noFeaturedEvent = false;
|
|
250
|
+
// This worker serves a featured screen: set by the first `featured` onAppear, kept for its Retry
|
|
251
|
+
// (the retry block's load carries no params, and must read the featured event again).
|
|
252
|
+
let featuredMode = false;
|
|
253
|
+
|
|
254
|
+
/** Money for a tier, or the free label. */
|
|
255
|
+
function tierPrice(t: WixAvailableTicket): string {
|
|
256
|
+
const raw = t.price?.amount;
|
|
257
|
+
if (t.free || raw == null || raw === "" || Number(raw) === 0) {
|
|
258
|
+
return copyParam("event.tierFree", "Free");
|
|
259
|
+
}
|
|
260
|
+
// Was a bare `Intl.NumberFormat` in a try/catch whose catch returned `String(raw)`. On the
|
|
261
|
+
// wrist (QuickJS-ng, no ECMA-402 at all) that catch fired every time, so a $25 ticket rendered
|
|
262
|
+
// as "25" — a price that reads as a quantity, and nothing downstream could tell it was a
|
|
263
|
+
// formatting failure. `formatCurrency` uses real Intl where it exists and a symbol-carrying
|
|
264
|
+
// fallback where it does not, diffed against ECMA-402 in engine-intl-fallback.test.ts.
|
|
265
|
+
return formatCurrency(Number(raw), t.price?.currency || "USD");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function tierAvailable(t: WixAvailableTicket): boolean {
|
|
269
|
+
const salesDetails = (t as WixAvailableTicket & { salesDetails?: { soldOut?: boolean } }).salesDetails;
|
|
270
|
+
return !!t.id && !salesDetails?.soldOut && !/SALE_SCHEDULED|SALE_ENDED|CANCELED|SOLD_OUT/i.test(t.saleStatus ?? "");
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Map the buyer-visible tiers onto rows, cheapest first (so the default pick is
|
|
274
|
+
* the first row and the ordering matches the price the CTA quotes). */
|
|
275
|
+
function tierRows(defs: WixAvailableTicket[], selectedId: string): TicketTierRow[] {
|
|
276
|
+
return defs
|
|
277
|
+
.filter((t) => !!t.id)
|
|
278
|
+
.flatMap((t) => {
|
|
279
|
+
const raw = t as WixAvailableTicket & { pricingOptions?: Array<{ id?: string; optionId?: string; name?: string; price?: { amount?: string; value?: string; currency?: string } }>; pricingMethod?: { type?: string; pricingOptions?: { optionDetails?: Array<{ id?: string; optionId?: string; name?: string; price?: { amount?: string; value?: string; currency?: string } }> } } };
|
|
280
|
+
const options = raw.pricingOptions ?? raw.pricingMethod?.pricingOptions?.optionDetails ?? [];
|
|
281
|
+
return options.length ? options.map((option) => ({ ...t, id: `${t.id}:${option.optionId ?? option.id}`, name: [t.name, option.name].filter(Boolean).join(" · "), price: { ...t.price, amount: option.price?.amount ?? option.price?.value ?? t.price?.amount, currency: option.price?.currency ?? t.price?.currency }, __optionId: option.optionId ?? option.id })) : [t as WixAvailableTicket & { __optionId?: string }];
|
|
282
|
+
})
|
|
283
|
+
.slice()
|
|
284
|
+
.sort((a, b) => Number(a.orderIndex ?? 0) - Number(b.orderIndex ?? 0))
|
|
285
|
+
.map((t) => {
|
|
286
|
+
const available = tierAvailable(t);
|
|
287
|
+
const selected = t.id === selectedId;
|
|
288
|
+
const originalId = t.id?.split(":")[0] ?? "";
|
|
289
|
+
const optionId = (t as WixAvailableTicket & { __optionId?: string }).__optionId;
|
|
290
|
+
const raw = t as WixAvailableTicket & { pricingMethod?: { type?: string; pricingType?: string; guestPrice?: { value?: string } }; pricing?: { pricingType?: string } };
|
|
291
|
+
const isGuestPrice = raw.pricingMethod?.guestPrice != null || /guestPrice/i.test(raw.pricingMethod?.type ?? raw.pricingMethod?.pricingType ?? raw.pricing?.pricingType ?? "");
|
|
292
|
+
const minPrice = Number(raw.pricingMethod?.guestPrice?.value ?? 0);
|
|
293
|
+
return {
|
|
294
|
+
id: t.id ?? "",
|
|
295
|
+
ticketDefinitionId: originalId,
|
|
296
|
+
pricingOptionId: optionId,
|
|
297
|
+
guestPrice: "",
|
|
298
|
+
minPrice,
|
|
299
|
+
name: (t.name || copyParam("event.tierFallbackName", "Ticket")).trim(),
|
|
300
|
+
priceLine: tierPrice(t),
|
|
301
|
+
unavailableNote: available ? "" : /SALE_SCHEDULED/i.test(t.saleStatus ?? "") ? copyParam("event.onSaleFrom", "On sale {date}").replace("{date}", t.salePeriod?.startDate ? formatWeekdayDateTime(new Date(t.salePeriod.startDate)) : "") : copyParam("event.soldOut", "Sold out"),
|
|
302
|
+
available,
|
|
303
|
+
isSelected: selected,
|
|
304
|
+
notSelected: !selected,
|
|
305
|
+
priceAmount: Number(t.price?.amount ?? 0),
|
|
306
|
+
...(isGuestPrice ? { priceLine: detailCopy("event.payWhatYouWant", "Pay what you want") } : {}),
|
|
307
|
+
...(isGuestPrice ? { priceAmount: minPrice, isGuestPrice: true } : {}),
|
|
308
|
+
...(isGuestPrice ? { minimumPriceLabel: detailCopy("event.minPrice", "Minimum {price}").replace("{price}", formatCurrency(minPrice, t.price?.currency || "USD")) } : {}),
|
|
309
|
+
};
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function loadedTiers(defs: WixAvailableTicket[]): { rows: TicketTierRow[]; tickets: Map<string, WixAvailableTicket> } {
|
|
314
|
+
const tickets = new Map(defs.filter((t) => t.id).map((t) => [t.id!, t]));
|
|
315
|
+
const cheapestAvailable = defs
|
|
316
|
+
.filter(tierAvailable)
|
|
317
|
+
.slice()
|
|
318
|
+
.sort((a, b) => Number(a.price?.amount ?? 0) - Number(b.price?.amount ?? 0))[0];
|
|
319
|
+
const rows = tierRows(defs, cheapestAvailable?.id ?? "").map((row) => {
|
|
320
|
+
const ticket = tickets.get(row.ticketDefinitionId ?? row.id);
|
|
321
|
+
if (!ticket) return { ...row, quantity: 0, description: "", feeNote: "", policy: "", noPolicy: true, notAvailable: !row.available, notGuestPrice: !row.isGuestPrice, maxQuantity: 0 };
|
|
322
|
+
const policy = (ticket as unknown as { policy?: string; policyText?: string }).policyText || (ticket as unknown as { policy?: string }).policy || "";
|
|
323
|
+
return { ...row, quantity: 0, description: descriptionBody(ticket.description).bodyText, feeNote: ((ticket as unknown as { wixFeeConfig?: { type?: string }; feeType?: string }).wixFeeConfig?.type ?? (ticket as unknown as { feeType?: string }).feeType) === "FEE_ADDED_AT_CHECKOUT" ? detailCopy("event.serviceFee", "+ ticket service fee") : "", policy, noPolicy: !policy, notAvailable: !row.available, notGuestPrice: !row.isGuestPrice, priceAmount: row.priceAmount ?? Number(ticket.price?.amount ?? 0), rowLimit: row.available ? ticket.limitPerCheckout ?? 99 : 0, maxQuantity: row.available ? ticket.limitPerCheckout ?? 99 : 0 };
|
|
324
|
+
});
|
|
325
|
+
return { rows, tickets };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Classify the buyer's selected option or bid, rather than the definition's cheapest price. */
|
|
329
|
+
function selectedPaymentTicket(row: TicketTierRow, tickets = paymentTickets): WixAvailableTicket | undefined {
|
|
330
|
+
const ticket = tickets.get(row.ticketDefinitionId ?? row.id);
|
|
331
|
+
if (!ticket) return;
|
|
332
|
+
const priced = tierRows([ticket], row.id).find((next) => next.id === row.id);
|
|
333
|
+
if (!priced) return;
|
|
334
|
+
const amount = priced.isGuestPrice ? Number(row.guestPrice || priced.minPrice || 0) : priced.priceAmount ?? 0;
|
|
335
|
+
return { ...ticket, free: amount === 0, price: { ...ticket.price, amount: String(amount) } };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Best-effort tier read — never sinks the screen if the tier endpoint fails. */
|
|
339
|
+
async function loadTiers(eventId: string): Promise<{ rows: TicketTierRow[]; tickets: Map<string, WixAvailableTicket> }> {
|
|
340
|
+
try {
|
|
341
|
+
return loadedTiers((await queryAvailableTickets(eventId)).definitions ?? []);
|
|
342
|
+
} catch {
|
|
343
|
+
return { rows: [], tickets: new Map() };
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function derive(s: S): S {
|
|
348
|
+
// A price refresh can publish a ready snapshot captured before checkout's
|
|
349
|
+
// guard denied the selection. Keep that denial visible until a new selection
|
|
350
|
+
// or load clears it, including across delayed StoreKit publications.
|
|
351
|
+
const snackbarMessage = s.snackbarMessage || (ticketCheckoutDenied ? copyParam("event.purchaseUnavailable", "Purchasing is temporarily unavailable.") : "");
|
|
352
|
+
const hasContent = !!s.title;
|
|
353
|
+
const count = s.ticketTiers.reduce((n, row) => n + (row.quantity ?? 0), 0);
|
|
354
|
+
const total = s.ticketTiers.reduce((n, row) => n + (row.isGuestPrice ? Number(row.guestPrice || row.minPrice || 0) : row.priceAmount ?? 0) * (row.quantity ?? 0), 0);
|
|
355
|
+
const open = new Set(s.openDisclosures ?? []);
|
|
356
|
+
const ticketTiers = s.ticketTiers.map((row) => {
|
|
357
|
+
const definitionId = row.ticketDefinitionId ?? row.id;
|
|
358
|
+
const sameDefinitionElsewhere = s.ticketTiers.reduce((n, other) => n + ((other.ticketDefinitionId ?? other.id) === definitionId && other.id !== row.id ? other.quantity ?? 0 : 0), 0);
|
|
359
|
+
const selectedElsewhere = s.ticketTiers.reduce((n, other) => n + (other.id === row.id ? 0 : other.quantity ?? 0), 0);
|
|
360
|
+
return { ...row, termsOpen: open.has(`terms:${row.id}`), maxQuantity: Math.max(0, Math.min((row.rowLimit ?? 99) - sameDefinitionElsewhere, s.ticketLimitPerOrder - selectedElsewhere)) };
|
|
361
|
+
});
|
|
362
|
+
const chosenRows = s.ticketTiers.filter((row) => (row.quantity ?? 0) > 0);
|
|
363
|
+
const singleTicketSelected = chosenRows.length === 1 && chosenRows[0]!.quantity === 1;
|
|
364
|
+
const purchase = applePurchase.fields(singleTicketSelected);
|
|
365
|
+
const regularRoute = ticketCheckoutAllowed || applePurchase.usesRegularPlatform();
|
|
366
|
+
const next = {
|
|
367
|
+
...s,
|
|
368
|
+
ticketTiers,
|
|
369
|
+
...purchase,
|
|
370
|
+
iapBuyHidden: !singleTicketSelected || purchase.iapBuyHidden,
|
|
371
|
+
// The shared attendance purchase produces a one-shot native poll directive.
|
|
372
|
+
// Let it through once; its commerce adapter consumes it, so later derives
|
|
373
|
+
// cannot replay it from a cached ready state.
|
|
374
|
+
regularTicketsHidden: s.registrationKind !== "tickets" || (singleTicketSelected && !purchase.iapBuyHidden),
|
|
375
|
+
ticketPurchaseBlocked: ticketCheckoutDenied || (s.registrationKind === "tickets" && !regularRoute && purchase.iapBuyHidden),
|
|
376
|
+
hasDescriptionJson: s.descriptionJson !== "",
|
|
377
|
+
noPlace: !s.place,
|
|
378
|
+
noDate: !s.when,
|
|
379
|
+
dateNotTappable: !s.calendarStart,
|
|
380
|
+
hideDateStatic: !s.when || !!s.calendarStart,
|
|
381
|
+
hidePlaceStatic: !s.place || !!s.mapUrl,
|
|
382
|
+
noPrice: !s.price,
|
|
383
|
+
hideMapTap: !s.place || !s.mapUrl,
|
|
384
|
+
noShortDescription: !s.shortDescription || s.shortDescription.trim() === s.description.trim(),
|
|
385
|
+
noDescription: !s.description && !s.descriptionJson,
|
|
386
|
+
showRsvp: s.registrationState === "rsvp",
|
|
387
|
+
hideRsvp: s.registrationState !== "rsvp" || s.memberOnly,
|
|
388
|
+
hasTiers: s.ticketTiers.length > 0,
|
|
389
|
+
noTiers: s.ticketTiers.length === 0,
|
|
390
|
+
// One tier is not a choice — showing a single-row "picker" would be noise.
|
|
391
|
+
showTierPicker: s.ticketTiers.length > 1,
|
|
392
|
+
hideTierPicker: s.ticketTiers.length <= 1,
|
|
393
|
+
selectedTierLabel: (() => {
|
|
394
|
+
const picked = s.ticketTiers.find((t) => t.id === s.selectedTierId);
|
|
395
|
+
return picked ? [picked.name, picked.priceLine].filter(Boolean).join(" · ") : "";
|
|
396
|
+
})(),
|
|
397
|
+
showTickets: s.registrationState === "tickets",
|
|
398
|
+
hideTickets: s.registrationState !== "tickets" || s.memberOnly,
|
|
399
|
+
showExternal: s.registrationState === "external",
|
|
400
|
+
hideExternal: s.registrationState !== "external" || s.memberOnly,
|
|
401
|
+
noNotice: !s.notice,
|
|
402
|
+
snackbarMessage,
|
|
403
|
+
noSnackbar: !snackbarMessage,
|
|
404
|
+
hideWaitlist: s.registrationState !== "waitlist" || s.memberOnly,
|
|
405
|
+
hideScheduled: s.registrationState !== "scheduled",
|
|
406
|
+
memberOnly: s.memberOnly,
|
|
407
|
+
hideMemberRsvp: !s.memberOnly || s.registrationState !== "rsvp",
|
|
408
|
+
hideMemberWaitlist: !s.memberOnly || s.registrationState !== "waitlist",
|
|
409
|
+
hideMemberTickets: !s.memberOnly || s.registrationState !== "tickets",
|
|
410
|
+
// Scheduled registration uses the shared disabled footer, including for members.
|
|
411
|
+
hideMemberScheduled: true,
|
|
412
|
+
hideRsvpChip: s.rsvpState !== "waitlist",
|
|
413
|
+
hideGoingChip: s.rsvpState !== "going",
|
|
414
|
+
hideWaitlistedChip: s.rsvpState !== "waitlist",
|
|
415
|
+
hideCancelRsvp: !s.rsvpId,
|
|
416
|
+
hideCancelConfirm: !s.cancelConfirmOpen,
|
|
417
|
+
hideRsvpOptions: s.cancelConfirmOpen,
|
|
418
|
+
noFooterButton: !s.footerLabel,
|
|
419
|
+
noFooterCaption: !s.footerCaption,
|
|
420
|
+
hideFooter: s.status !== "ready" || s.errored || !s.footerLabel || s.rsvpState !== "none",
|
|
421
|
+
checkoutDisabled: count === 0 || count > s.ticketLimitPerOrder || ticketCheckoutInFlight || !ticketCheckoutAllowed || s.ticketTiers.some((row) => row.isGuestPrice && (row.quantity ?? 0) > 0 && (!String(row.guestPrice ?? "").trim() || Number(row.guestPrice) < (row.minPrice ?? 0) || !Number.isFinite(Number(row.guestPrice)))) || s.ticketTiers.some((row) => (row.quantity ?? 0) > (row.maxQuantity ?? 99)),
|
|
422
|
+
ticketTotal: formatCurrency(total, s.ticketCurrency || "USD"),
|
|
423
|
+
ticketCountLabel: copyParam("event.ticketCount", "{n} tickets, plus fees").replace("{n}", String(count)),
|
|
424
|
+
noSchedule: s.schedule.length === 0,
|
|
425
|
+
noFullSchedule: s.fullSchedule.length === 0,
|
|
426
|
+
noMoreDates: s.moreDates.length === 0,
|
|
427
|
+
noAllDates: s.allDates.length === 0,
|
|
428
|
+
openDisclosures: [...open],
|
|
429
|
+
fullScheduleOpen: open.has("fullSchedule"),
|
|
430
|
+
allDatesOpen: open.has("allDates"),
|
|
431
|
+
policiesOpen: open.has("policies"),
|
|
432
|
+
isLoading: s.status === "loading",
|
|
433
|
+
notLoading: s.status !== "loading",
|
|
434
|
+
notErrored: !s.errored,
|
|
435
|
+
noEmpty: s.status === "loading" || s.errored || hasContent,
|
|
436
|
+
emptyText: hasContent
|
|
437
|
+
? ""
|
|
438
|
+
: (s.errored
|
|
439
|
+
? copyParam("event.errorText", "Event could not be loaded.")
|
|
440
|
+
: noFeaturedEvent
|
|
441
|
+
? copyParam("event.noUpcomingText", "No upcoming event.")
|
|
442
|
+
: copyParam("event.notFoundText", "Event not found.")),
|
|
443
|
+
};
|
|
444
|
+
return next;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function calendarStamp(ms: number): string {
|
|
448
|
+
return new Date(ms).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Build the Google Calendar "render" (TEMPLATE) fallback URL.
|
|
452
|
+
*
|
|
453
|
+
* Uses encodeURIComponent (core ECMAScript) — NOT URLSearchParams, which the JavaScriptCore
|
|
454
|
+
* worker engine on iOS/macOS does not provide, nor does the wrist's QuickJS-ng (measured by the
|
|
455
|
+
* engine-parity runners, #1367; only Android's WebView has it). This was the worst possible
|
|
456
|
+
* place for that global: both callers sit inside `addToCalendar`'s try/catch and are reached
|
|
457
|
+
* ONLY when the native calendar path already failed, so the RECOVERY path was the broken one —
|
|
458
|
+
* iOS showed a generic toast where Android opened the calendar, and the dry-run could not see
|
|
459
|
+
* it because the checker injected URLSearchParams even under deviceParity.
|
|
460
|
+
*
|
|
461
|
+
* `wix-spaces-event-detail` builds the same URL the same way and has said so in a comment since
|
|
462
|
+
* before this bug existed; this is that pattern, not a new invention. */
|
|
463
|
+
function calendarFallbackUrl(s: S, end: number): string {
|
|
464
|
+
const parts = [
|
|
465
|
+
"action=TEMPLATE",
|
|
466
|
+
`text=${encodeURIComponent(s.title || "Event")}`,
|
|
467
|
+
`dates=${calendarStamp(s.calendarStart)}/${calendarStamp(end)}`,
|
|
468
|
+
];
|
|
469
|
+
if (s.location) parts.push(`location=${encodeURIComponent(s.location)}`);
|
|
470
|
+
const details = s.description || s.when;
|
|
471
|
+
if (details) parts.push(`details=${encodeURIComponent(details)}`);
|
|
472
|
+
return `https://calendar.google.com/calendar/render?${parts.join("&")}`;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** The Events v3 fieldsets the detail reads (see `WixEventFieldset`). DETAILS carries mainImage and
|
|
476
|
+
* shortDescription: REGISTRATION fills eventType, which skips the query enrichment that used to supply them. */
|
|
477
|
+
export const EVENT_DETAIL_FIELDSETS: WixEventFieldset[] = ["DETAILS", "TEXTS", "REGISTRATION", "URLS", "FORM", "AGENDA"];
|
|
478
|
+
|
|
479
|
+
function detailCopy(key: string, fallback: string): string { return copyParam(key, fallback); }
|
|
480
|
+
|
|
481
|
+
function detailDate(e: WixEvent): { line: string; zone: string; start: number; end: number } {
|
|
482
|
+
const raw = e as unknown as {
|
|
483
|
+
dateAndTimeSettings?: { startDate?: string; endDate?: string; dateAndTimeTbd?: boolean; dateAndTimeTbdMessage?: string; timeZoneId?: string; showTimeZone?: boolean; hideEndDate?: boolean };
|
|
484
|
+
scheduling?: { startDate?: string; endDate?: string; timeZoneId?: string; tbd?: string; endDateHidden?: boolean; config?: { startDate?: string; endDate?: string; timeZoneId?: string } };
|
|
485
|
+
};
|
|
486
|
+
const settings = raw.dateAndTimeSettings ?? {};
|
|
487
|
+
const schedule = raw.scheduling;
|
|
488
|
+
const startValue = settings.startDate ?? schedule?.config?.startDate ?? schedule?.startDate;
|
|
489
|
+
const endValue = settings.endDate ?? schedule?.config?.endDate ?? schedule?.endDate;
|
|
490
|
+
const timeZoneId = settings.timeZoneId ?? schedule?.config?.timeZoneId ?? schedule?.timeZoneId;
|
|
491
|
+
const start = startValue ? new Date(startValue) : null;
|
|
492
|
+
const end = endValue ? new Date(endValue) : null;
|
|
493
|
+
const validStart = start && !Number.isNaN(start.getTime());
|
|
494
|
+
if (settings.dateAndTimeTbd || (!validStart && schedule?.tbd)) return { line: settings.dateAndTimeTbdMessage || schedule?.tbd || detailCopy("event.dateTbd", "Date to be announced"), zone: "", start: 0, end: 0 };
|
|
495
|
+
if (!validStart) return { line: "", zone: "", start: 0, end: 0 };
|
|
496
|
+
const zone = timeZoneId;
|
|
497
|
+
const format = (d: Date): string => formatWeekdayDateTime(d, "en-US", zone);
|
|
498
|
+
const a = format(start);
|
|
499
|
+
const b = end && !Number.isNaN(end.getTime()) ? format(end) : "";
|
|
500
|
+
const parts = (date: Date) => {
|
|
501
|
+
const time = formatClock(date, "en-US", zone);
|
|
502
|
+
const clock = time.match(/^(\d{1,2}):(\d{2})\s*(AM|PM)?$/i);
|
|
503
|
+
return { day: formatWeekdayMonthDay(date, "en-US", zone), hour: clock?.[1] ?? "", minute: clock?.[2] ?? "", period: clock?.[3] ?? "", time, calendarDay: calendarDay(date, zone) };
|
|
504
|
+
};
|
|
505
|
+
const startParts = parts(start);
|
|
506
|
+
const endParts = end && !Number.isNaN(end.getTime()) ? parts(end) : undefined;
|
|
507
|
+
const startDisplayDay = startParts.day.replace(/, \d{4}$/, "");
|
|
508
|
+
const hideEndDate = settings.hideEndDate ?? schedule?.endDateHidden;
|
|
509
|
+
const line = hideEndDate || !endParts ? `${startDisplayDay} at ${startParts.time}` : startParts.calendarDay === endParts.calendarDay
|
|
510
|
+
? `${startDisplayDay} · ${startParts.hour}:${startParts.minute}${startParts.period !== endParts.period ? ` ${startParts.period}` : ""} – ${endParts.time}`
|
|
511
|
+
: `${a} – ${b}`;
|
|
512
|
+
let zoneLine = "";
|
|
513
|
+
if (settings.showTimeZone && zone) zoneLine = formatTimeZoneLabel(start, zone, "en");
|
|
514
|
+
return { line, zone: zoneLine, start: start.getTime(), end: end?.getTime() ?? start.getTime() + 3600000 };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
type EventDetailMoney = { formattedValue?: string; value?: string; currency?: string };
|
|
518
|
+
|
|
519
|
+
function detailMoney(money?: EventDetailMoney): string {
|
|
520
|
+
if (money?.formattedValue) return money.formattedValue;
|
|
521
|
+
const value = money?.value;
|
|
522
|
+
if (value == null || String(value).trim() === "" || !money?.currency || !Number.isFinite(Number(value))) return "";
|
|
523
|
+
return formatCurrency(Number(value), money.currency);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function detailPlace(e: WixEvent): { value: string; mapUrl: string; hideMapTap: boolean; icon: string } {
|
|
527
|
+
const raw = e as unknown as { location?: { type?: string; name?: string; locationTbd?: boolean; address?: { formattedAddress?: string; formatted?: string } | string } };
|
|
528
|
+
const place = raw.location;
|
|
529
|
+
const type = (place?.type ?? "").toUpperCase();
|
|
530
|
+
if (place?.locationTbd) return { value: place.name || detailCopy("event.locationTbd", "Location to be announced"), mapUrl: "", hideMapTap: true, icon: "location" };
|
|
531
|
+
if (type === "ONLINE") return { value: detailCopy("event.onlineEvent", "Online event"), mapUrl: "", hideMapTap: true, icon: "globe" };
|
|
532
|
+
const address = eventAddress({ ...e, location: { ...e.location, name: "" } } as WixEvent);
|
|
533
|
+
const value = [place?.name, address].filter(Boolean).join(", ") || place?.name || "";
|
|
534
|
+
const geo = (e.location as unknown as { coordinates?: { latitude?: number; longitude?: number; lat?: number; lng?: number }; location?: { latitude?: number; longitude?: number; lat?: number; lng?: number } })?.coordinates
|
|
535
|
+
?? (e.location as unknown as { location?: { latitude?: number; longitude?: number; lat?: number; lng?: number } })?.location;
|
|
536
|
+
const hasCoordinates = typeof (geo?.latitude ?? geo?.lat) === "number" && typeof (geo?.longitude ?? geo?.lng) === "number";
|
|
537
|
+
const mapped = address || hasCoordinates ? eventMapUrl(e) : "";
|
|
538
|
+
return { value, mapUrl: mapped, hideMapTap: !mapped, icon: "location" };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Event slug for createRedirectSession({ eventsCheckout }) — "" when absent. */
|
|
542
|
+
export function eventSlugOf(e: WixEvent): string {
|
|
543
|
+
const slug = e.slug ?? (e as unknown as { slug?: string }).slug;
|
|
544
|
+
return typeof slug === "string" ? slug.trim() : "";
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/** The description pair: the v3 Ricos `description` for RichContent, and its plain text. A string description
|
|
548
|
+
* (or none) keeps `eventDescription`'s legacy read, with no document. */
|
|
549
|
+
function eventBody(e: WixEvent): { description: string; descriptionJson: string } {
|
|
550
|
+
const legacy = eventDescription({ ...e, description: undefined });
|
|
551
|
+
const { bodyJson, bodyText } = descriptionBody((e as unknown as { description?: unknown }).description, descriptionBody(legacy).bodyText);
|
|
552
|
+
return { description: bodyText, descriptionJson: bodyJson };
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
type WixCall = (method: string, path: string, body?: unknown) => Promise<unknown>;
|
|
556
|
+
function wixCall(): WixCall | undefined { return (globalThis as { himalaya?: { wixApi?: { call?: WixCall } } }).himalaya?.wixApi?.call; }
|
|
557
|
+
type OptionalRead = { ok: true; value: Record<string, unknown> } | { ok: false; code: "unavailable" };
|
|
558
|
+
async function bestEffort(method: string, path: string, body?: unknown): Promise<OptionalRead> {
|
|
559
|
+
try {
|
|
560
|
+
const call = wixCall();
|
|
561
|
+
return call ? { ok: true, value: await call(method, path, body) as Record<string, unknown> } : { ok: false, code: "unavailable" };
|
|
562
|
+
} catch {
|
|
563
|
+
return { ok: false, code: "unavailable" };
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
async function signedInMember(): Promise<boolean> {
|
|
567
|
+
try { const identity = await dispatch("himi.wix.memberIdentity") as { email?: string } | null; return !!identity?.email; } catch { return false; }
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const defineService = withOnlineWrites(registerService, ["buyApple", "openRegistration", "checkout", "cancelRsvp"], {
|
|
571
|
+
derive,
|
|
572
|
+
messageFields: ["snackbarMessage"],
|
|
573
|
+
requiresConnectivity: (action, state) => action !== "openRegistration"
|
|
574
|
+
|| (state.registrationKind === "tickets" && !!state.id && !isHostedWorker()),
|
|
575
|
+
});
|
|
576
|
+
type DetailActions = {
|
|
577
|
+
load: (s: S, arg?: unknown) => Promise<S | undefined>;
|
|
578
|
+
openMap: (s: S) => Promise<S>;
|
|
579
|
+
openTickets: (s: S) => Promise<S | undefined>;
|
|
580
|
+
closeTickets: (s: S) => S;
|
|
581
|
+
toggleDisclosure: (s: S, arg?: unknown) => S;
|
|
582
|
+
setQuantity: (s: S, arg?: unknown) => Promise<S | undefined>;
|
|
583
|
+
setGuestPrice: (s: S, arg?: unknown) => S;
|
|
584
|
+
checkout: (s: S) => Promise<S | undefined>;
|
|
585
|
+
openRsvpActions: (s: S) => S;
|
|
586
|
+
closeRsvpActions: (s: S) => S;
|
|
587
|
+
beginCancelRsvp: (s: S) => S;
|
|
588
|
+
keepRsvp: (s: S) => S;
|
|
589
|
+
cancelRsvp: (s: S) => Promise<S>;
|
|
590
|
+
noop: (s: S) => S;
|
|
591
|
+
openRegistration: (s: S) => Promise<S>;
|
|
592
|
+
share: (s: S) => Promise<S>;
|
|
593
|
+
addToCalendar: (s: S) => Promise<S>;
|
|
594
|
+
/** [rico] #3372 — RichContent's on_link: `{ url }` of the tapped link. */
|
|
595
|
+
openLink: (s: S, arg?: unknown) => Promise<S>;
|
|
596
|
+
buyApple: (s: S) => Promise<S>;
|
|
597
|
+
setIapField: (s: S, arg?: unknown) => S;
|
|
598
|
+
iapPublish: (s: S) => S;
|
|
599
|
+
iapRefresh: (s: S) => Promise<S>;
|
|
600
|
+
iapPoll: (s: S) => Promise<S>;
|
|
601
|
+
};
|
|
602
|
+
/** The state before any event is read — also where a featured open starts when it finds no event,
|
|
603
|
+
* or a different one, so nothing of the previous event (its footer, tiers, About) carries over. */
|
|
604
|
+
function bootState(): S {
|
|
605
|
+
return derive({
|
|
606
|
+
...ATTENDANCE_INITIAL,
|
|
607
|
+
status: "loading",
|
|
608
|
+
id: inputId(),
|
|
609
|
+
title: "",
|
|
610
|
+
when: "",
|
|
611
|
+
location: "",
|
|
612
|
+
place: "",
|
|
613
|
+
placeIcon: "location",
|
|
614
|
+
noPlace: true,
|
|
615
|
+
hidePlaceStatic: true,
|
|
616
|
+
price: "",
|
|
617
|
+
zone: "",
|
|
618
|
+
noPrice: true,
|
|
619
|
+
hideMapTap: true,
|
|
620
|
+
shortDescription: "",
|
|
621
|
+
noShortDescription: true,
|
|
622
|
+
noDescription: true,
|
|
623
|
+
noDate: true,
|
|
624
|
+
dateNotTappable: true,
|
|
625
|
+
hideDateStatic: true,
|
|
626
|
+
registrationState: "none",
|
|
627
|
+
footerLabel: "",
|
|
628
|
+
footerAction: "",
|
|
629
|
+
footerCaption: "",
|
|
630
|
+
hideFooter: true,
|
|
631
|
+
noFooterButton: true,
|
|
632
|
+
noFooterCaption: true,
|
|
633
|
+
notice: "",
|
|
634
|
+
exploreLabel: detailCopy("event.exploreCta", "Explore Events"),
|
|
635
|
+
noNotice: true,
|
|
636
|
+
rsvpLabel: "",
|
|
637
|
+
rsvpId: "",
|
|
638
|
+
rsvpState: "none",
|
|
639
|
+
hideRsvpChip: true,
|
|
640
|
+
hideGoingChip: true,
|
|
641
|
+
hideWaitlistedChip: true,
|
|
642
|
+
hideCancelRsvp: true,
|
|
643
|
+
hideCancelConfirm: true,
|
|
644
|
+
hideRsvpOptions: false,
|
|
645
|
+
ticketSheetOpen: false,
|
|
646
|
+
rsvpActionsOpen: false,
|
|
647
|
+
cancelConfirmOpen: false,
|
|
648
|
+
ticketTotal: formatCurrency(0, "USD"),
|
|
649
|
+
ticketCountLabel: copyParam("event.ticketCount", "{n} tickets, plus fees").replace("{n}", "0"),
|
|
650
|
+
checkoutDisabled: true,
|
|
651
|
+
schedule: [],
|
|
652
|
+
fullSchedule: [],
|
|
653
|
+
noSchedule: true,
|
|
654
|
+
noFullSchedule: true,
|
|
655
|
+
moreDates: [],
|
|
656
|
+
allDates: [],
|
|
657
|
+
noMoreDates: true,
|
|
658
|
+
noAllDates: true,
|
|
659
|
+
policies: [],
|
|
660
|
+
noPolicies: true,
|
|
661
|
+
openDisclosures: [],
|
|
662
|
+
fullScheduleOpen: false,
|
|
663
|
+
allDatesOpen: false,
|
|
664
|
+
policiesOpen: false,
|
|
665
|
+
description: "",
|
|
666
|
+
descriptionJson: "",
|
|
667
|
+
hasDescriptionJson: false,
|
|
668
|
+
image: "",
|
|
669
|
+
hasImage: false,
|
|
670
|
+
noImage: true,
|
|
671
|
+
mapUrl: "",
|
|
672
|
+
registrationKind: "rsvp",
|
|
673
|
+
ticketPurchaseBlocked: true,
|
|
674
|
+
showRsvp: true,
|
|
675
|
+
hideRsvp: false,
|
|
676
|
+
showTickets: false,
|
|
677
|
+
hideTickets: true,
|
|
678
|
+
showExternal: false,
|
|
679
|
+
hideExternal: true,
|
|
680
|
+
hideScheduled: true,
|
|
681
|
+
hideWaitlist: true,
|
|
682
|
+
memberOnly: false,
|
|
683
|
+
hideMemberRsvp: true,
|
|
684
|
+
hideMemberWaitlist: true,
|
|
685
|
+
hideMemberTickets: true,
|
|
686
|
+
hideMemberScheduled: true,
|
|
687
|
+
ticketTiers: [],
|
|
688
|
+
ticketCurrency: "USD",
|
|
689
|
+
ticketLimitPerOrder: 99,
|
|
690
|
+
regularTicketsHidden: true,
|
|
691
|
+
hasTiers: false,
|
|
692
|
+
noTiers: true,
|
|
693
|
+
showTierPicker: false,
|
|
694
|
+
hideTierPicker: true,
|
|
695
|
+
selectedTierId: "",
|
|
696
|
+
selectedTierLabel: "",
|
|
697
|
+
registrationUrl: "",
|
|
698
|
+
eventSlug: "",
|
|
699
|
+
shareUrl: "",
|
|
700
|
+
calendarStart: 0,
|
|
701
|
+
calendarEnd: 0,
|
|
702
|
+
snackbarMessage: "",
|
|
703
|
+
noSnackbar: true,
|
|
704
|
+
isAddingCalendar: false,
|
|
705
|
+
emptyText: "",
|
|
706
|
+
errored: false,
|
|
707
|
+
notErrored: true,
|
|
708
|
+
isLoading: true,
|
|
709
|
+
notLoading: false,
|
|
710
|
+
noEmpty: true,
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
const svc: ReturnType<typeof defineService<S, DetailActions>> = defineService<S, DetailActions>("himiEventDetail", {
|
|
715
|
+
notHydrated: [...ATTENDANCE_NOT_HYDRATED, "ticketPurchaseBlocked", "ticketSheetOpen", "rsvpActionsOpen", "cancelConfirmOpen", "rsvpId", "rsvpState", "rsvpLabel"],
|
|
716
|
+
state: bootState(),
|
|
717
|
+
actions: {
|
|
718
|
+
openTickets: async (s) => {
|
|
719
|
+
if (s.ticketTiers.length) return derive({ ...s, ticketSheetOpen: true });
|
|
720
|
+
const version = ticketSelectionVersion;
|
|
721
|
+
const loaded = await loadTiers(s.id);
|
|
722
|
+
const current = svc.getState();
|
|
723
|
+
if (version !== ticketSelectionVersion || current.id !== s.id) return;
|
|
724
|
+
if (!loaded.rows.length) return derive({ ...current, ticketSheetOpen: false, snackbarMessage: detailCopy("event.purchaseUnavailable", "Purchasing is temporarily unavailable.") });
|
|
725
|
+
paymentTickets = loaded.tickets;
|
|
726
|
+
ticketSelectionState = derive({ ...current, ticketTiers: loaded.rows.map((row) => ({ ...row, rowLimit: Math.min(row.rowLimit ?? 99, s.ticketLimitPerOrder) })), ticketCurrency: loaded.tickets.values().next().value?.price?.currency || s.ticketCurrency, ticketSheetOpen: true, snackbarMessage: "" });
|
|
727
|
+
lastReady = ticketSelectionState;
|
|
728
|
+
return ticketSelectionState;
|
|
729
|
+
},
|
|
730
|
+
closeTickets: (s) => derive({ ...s, ticketSheetOpen: false }),
|
|
731
|
+
// Open or close one disclosure by its id (see `openDisclosures`).
|
|
732
|
+
toggleDisclosure: (s, arg) => {
|
|
733
|
+
const base = String((arg as { id?: unknown } | undefined)?.id ?? "");
|
|
734
|
+
// A row's disclosure names its row in its own param: the web renderer substitutes a whole
|
|
735
|
+
// `$item.` value only, never one inside a longer string ("terms:$item.id").
|
|
736
|
+
const row = String((arg as { tier?: unknown } | undefined)?.tier ?? "");
|
|
737
|
+
const id = base && row ? `${base}:${row}` : base;
|
|
738
|
+
if (!id) return s;
|
|
739
|
+
const open = new Set(s.openDisclosures ?? []);
|
|
740
|
+
if (open.has(id)) open.delete(id); else open.add(id);
|
|
741
|
+
return derive({ ...s, openDisclosures: [...open] });
|
|
742
|
+
},
|
|
743
|
+
openRsvpActions: (s) => derive({ ...s, rsvpActionsOpen: true, cancelConfirmOpen: false, snackbarMessage: "" }),
|
|
744
|
+
closeRsvpActions: (s) => derive({ ...s, rsvpActionsOpen: false, cancelConfirmOpen: false }),
|
|
745
|
+
beginCancelRsvp: (s) => derive({ ...s, cancelConfirmOpen: !!s.rsvpId, snackbarMessage: "" }),
|
|
746
|
+
keepRsvp: (s) => derive({ ...s, cancelConfirmOpen: false }),
|
|
747
|
+
cancelRsvp: async (s): Promise<S> => {
|
|
748
|
+
if (!s.rsvpId || !s.id || cancelRsvpInFlight) return derive({ ...s, rsvpActionsOpen: false, cancelConfirmOpen: false });
|
|
749
|
+
cancelRsvpInFlight = true;
|
|
750
|
+
try {
|
|
751
|
+
const call = wixCall();
|
|
752
|
+
if (!call) throw new Error("Wix API is unavailable");
|
|
753
|
+
await call("DELETE", `/events/v2/rsvps/${encodeURIComponent(s.rsvpId)}`);
|
|
754
|
+
forgetRsvp(s.id);
|
|
755
|
+
return derive({
|
|
756
|
+
...s,
|
|
757
|
+
rsvpId: "",
|
|
758
|
+
rsvpState: "none",
|
|
759
|
+
rsvpLabel: "",
|
|
760
|
+
rsvpActionsOpen: false,
|
|
761
|
+
cancelConfirmOpen: false,
|
|
762
|
+
snackbarMessage: copyParam("event.rsvpCanceled", "Your RSVP is canceled."),
|
|
763
|
+
});
|
|
764
|
+
} catch {
|
|
765
|
+
return derive({
|
|
766
|
+
...s,
|
|
767
|
+
rsvpActionsOpen: false,
|
|
768
|
+
cancelConfirmOpen: false,
|
|
769
|
+
snackbarMessage: copyParam("event.cancelFailed", "Couldn't cancel your RSVP. Try again."),
|
|
770
|
+
});
|
|
771
|
+
} finally {
|
|
772
|
+
cancelRsvpInFlight = false;
|
|
773
|
+
}
|
|
774
|
+
},
|
|
775
|
+
noop: (s) => derive(s),
|
|
776
|
+
setQuantity: async (inputState, arg): Promise<S | undefined> => {
|
|
777
|
+
if (ticketCheckoutInFlight) return derive(inputState);
|
|
778
|
+
const input = arg as { id?: string; value?: number; quantity?: number } | undefined;
|
|
779
|
+
const id = typeof input === "string" ? input : input?.id;
|
|
780
|
+
const next = Number(input?.value ?? input?.quantity ?? 0);
|
|
781
|
+
if (!id || !Number.isFinite(next)) return derive(inputState);
|
|
782
|
+
// Invalidate the previous Apple form synchronously with the row action.
|
|
783
|
+
// A purchase tapped before the async route/price checks finish must not
|
|
784
|
+
// submit details belonging to the ticket that was selected previously.
|
|
785
|
+
const version = ++ticketSelectionVersion;
|
|
786
|
+
ticketCheckoutDenied = false;
|
|
787
|
+
applePurchase.invalidate();
|
|
788
|
+
ticketSelectionQueue = ticketSelectionQueue.catch(() => {}).then(async () => {
|
|
789
|
+
if (ticketCheckoutInFlight) return;
|
|
790
|
+
// Worker actions can overlap while capability checks await. Start each
|
|
791
|
+
// update from the last selection so edits to independent rows compose.
|
|
792
|
+
const serviceState = svc.getState();
|
|
793
|
+
const base = serviceState.status === "ready" && serviceState.id === inputState.id ? { ...inputState, ...serviceState } : inputState;
|
|
794
|
+
const s = ticketSelectionState?.status === "ready" && ticketSelectionState.id === base.id
|
|
795
|
+
? { ...base, selectedTierId: ticketSelectionState.selectedTierId, ticketTiers: ticketSelectionState.ticketTiers }
|
|
796
|
+
: base;
|
|
797
|
+
const ticketTiers = s.ticketTiers.map((row) => row.id !== id || !row.available ? row : { ...row, quantity: Math.max(0, Math.min(row.maxQuantity ?? 99, Math.floor(next))) });
|
|
798
|
+
const chosen = ticketTiers.filter((row) => (row.quantity ?? 0) > 0);
|
|
799
|
+
let selectedTierId = s.selectedTierId;
|
|
800
|
+
if (chosen.length === 1) selectedTierId = chosen[0]!.id;
|
|
801
|
+
else if (chosen.length === 0 && id === selectedTierId) selectedTierId = ticketTiers.find((row) => row.available)?.id ?? "";
|
|
802
|
+
const selected = ticketTiers.find((row) => row.id === selectedTierId);
|
|
803
|
+
let regularAllowed: boolean;
|
|
804
|
+
if (chosen.length <= 1 && (chosen.length === 0 || chosen[0]!.quantity === 1)) {
|
|
805
|
+
regularAllowed = await mayUseRegularTicketCheckout(paymentEvent, selected ? selectedPaymentTicket(selected) : undefined);
|
|
806
|
+
} else {
|
|
807
|
+
regularAllowed = (await Promise.all(chosen.map((row) => mayUseRegularTicketCheckout(paymentEvent, selectedPaymentTicket(row))))).every(Boolean);
|
|
808
|
+
}
|
|
809
|
+
if (version === ticketSelectionVersion) ticketCheckoutAllowed = regularAllowed;
|
|
810
|
+
const selectionState = derive({ ...s, selectedTierId, ticketTiers: ticketTiers.map((row) => ({ ...row, isSelected: row.id === selectedTierId, notSelected: row.id !== selectedTierId })) });
|
|
811
|
+
ticketSelectionState = selectionState;
|
|
812
|
+
if (selectionState.status === "ready") lastReady = selectionState;
|
|
813
|
+
if (version === ticketSelectionVersion && selectedTierId && chosen.length === 1 && !regularAllowed) {
|
|
814
|
+
const ticketId = selected?.ticketDefinitionId ?? selectedTierId;
|
|
815
|
+
if (!await priceTicket(paymentEvent, ticketId, version, selected ? selectedPaymentTicket(selected) : undefined)) return;
|
|
816
|
+
}
|
|
817
|
+
// Keep edits and sheet state made while route and price checks awaited.
|
|
818
|
+
const currentServiceState = svc.getState();
|
|
819
|
+
const latest = currentServiceState.status === "ready" && currentServiceState.id === s.id ? { ...s, ...currentServiceState } : s;
|
|
820
|
+
const quantities = new Map(ticketTiers.map((row) => [row.id, row.quantity ?? 0]));
|
|
821
|
+
const latestRows = latest.ticketTiers.map((row) => ({ ...row, quantity: quantities.get(row.id) ?? row.quantity ?? 0, isSelected: row.id === selectedTierId, notSelected: row.id !== selectedTierId }));
|
|
822
|
+
ticketSelectionState = derive({ ...latest, selectedTierId, ticketTiers: latestRows });
|
|
823
|
+
if (ticketSelectionState.status === "ready") lastReady = ticketSelectionState;
|
|
824
|
+
});
|
|
825
|
+
await ticketSelectionQueue;
|
|
826
|
+
return ticketSelectionState;
|
|
827
|
+
},
|
|
828
|
+
setGuestPrice: (s, arg) => {
|
|
829
|
+
if (ticketCheckoutInFlight) return derive(s);
|
|
830
|
+
const input = arg as { id?: string; value?: string; text?: string } | undefined;
|
|
831
|
+
const id = input?.id;
|
|
832
|
+
const value = String(input?.value ?? input?.text ?? "").replace(/[^\d.]/g, "");
|
|
833
|
+
if (!id || !/^\d*(?:\.\d{0,2})?$/.test(value)) return derive(s);
|
|
834
|
+
ticketSelectionState = derive({ ...s, ticketTiers: s.ticketTiers.map((row) => row.id === id ? { ...row, guestPrice: value, priceAmount: Number(value || row.minPrice || 0) } : row) });
|
|
835
|
+
if (ticketSelectionState.status === "ready") lastReady = ticketSelectionState;
|
|
836
|
+
return ticketSelectionState;
|
|
837
|
+
},
|
|
838
|
+
checkout: async (initial) => {
|
|
839
|
+
if (ticketCheckoutInFlight) return derive(initial);
|
|
840
|
+
// A Stepper action can still be awaiting its IAP/price route check when
|
|
841
|
+
// Checkout is tapped. Wait until the selection queue stops growing, then
|
|
842
|
+
// take the service's latest state before validating or reserving.
|
|
843
|
+
while (true) {
|
|
844
|
+
const pendingSelection = ticketSelectionQueue;
|
|
845
|
+
await pendingSelection;
|
|
846
|
+
if (pendingSelection === ticketSelectionQueue) break;
|
|
847
|
+
}
|
|
848
|
+
if (ticketCheckoutInFlight) return derive(svc.getState());
|
|
849
|
+
const current = svc.getState();
|
|
850
|
+
let s = ticketSelectionState?.status === "ready" && ticketSelectionState.id === initial.id
|
|
851
|
+
? ticketSelectionState
|
|
852
|
+
: current.status === "ready" && current.id === initial.id ? current : initial;
|
|
853
|
+
const quantities = s.ticketTiers.filter((row) => row.available && (row.quantity ?? 0) > 0).map((row) => ({ ticketDefinitionId: row.ticketDefinitionId ?? row.id, quantity: row.quantity ?? 0, ...(row.isGuestPrice ? { priceOverride: row.guestPrice } : {}), ...(row.pricingOptionId ? { ticketDetails: [{ pricingOptionId: row.pricingOptionId }] } : {}) }));
|
|
854
|
+
const guestPriceInvalid = s.ticketTiers.some((row) => row.isGuestPrice && (row.quantity ?? 0) > 0 && (!String(row.guestPrice ?? "").trim() || !Number.isFinite(Number(row.guestPrice)) || Number(row.guestPrice) < (row.minPrice ?? 0)));
|
|
855
|
+
const aggregateInvalid = s.ticketTiers.some((row) => {
|
|
856
|
+
const definitionId = row.ticketDefinitionId ?? row.id;
|
|
857
|
+
const definitionQuantity = s.ticketTiers.reduce((sum, other) => sum + ((other.ticketDefinitionId ?? other.id) === definitionId ? other.quantity ?? 0 : 0), 0);
|
|
858
|
+
return (row.quantity ?? 0) > (row.maxQuantity ?? 99) || definitionQuantity > (row.rowLimit ?? 99);
|
|
859
|
+
});
|
|
860
|
+
if (ticketCheckoutInFlight) return derive(s);
|
|
861
|
+
if (quantities.length === 0) return derive({ ...s, snackbarMessage: detailCopy("event.purchaseUnavailable", "Purchasing is temporarily unavailable.") });
|
|
862
|
+
if (guestPriceInvalid || aggregateInvalid || quantities.reduce((sum, row) => sum + row.quantity, 0) > s.ticketLimitPerOrder) return derive(s);
|
|
863
|
+
ticketCheckoutInFlight = true;
|
|
864
|
+
let reservationId = "";
|
|
865
|
+
let result: S | undefined;
|
|
866
|
+
try {
|
|
867
|
+
// Re-read ticket definitions immediately before checkout. A free ticket
|
|
868
|
+
// can become paid (or an IAP ticket) while this screen is open; in that
|
|
869
|
+
// case the regular Events reservation API must not run.
|
|
870
|
+
const latestResponse = await queryAvailableTickets(s.id);
|
|
871
|
+
const latestDefinitions = latestResponse.definitions ?? [];
|
|
872
|
+
const fresh = loadedTiers(latestDefinitions);
|
|
873
|
+
const latestTickets = fresh.tickets;
|
|
874
|
+
const previousSelected = s.ticketTiers.filter((row) => (row.quantity ?? 0) > 0);
|
|
875
|
+
const previousRows = new Map(s.ticketTiers.map((row) => [row.id, row]));
|
|
876
|
+
const refreshedByDefinition = new Map<string, number>();
|
|
877
|
+
let refreshedCount = 0;
|
|
878
|
+
const refreshedRows = fresh.rows.map((row) => {
|
|
879
|
+
const previous = previousRows.get(row.id);
|
|
880
|
+
const definitionId = row.ticketDefinitionId ?? row.id;
|
|
881
|
+
const rowLimit = Math.min(row.rowLimit ?? 99, s.ticketLimitPerOrder);
|
|
882
|
+
const used = refreshedByDefinition.get(definitionId) ?? 0;
|
|
883
|
+
const quantity = row.available ? Math.max(0, Math.min(previous?.quantity ?? 0, rowLimit - used, s.ticketLimitPerOrder - refreshedCount)) : 0;
|
|
884
|
+
refreshedByDefinition.set(definitionId, used + quantity);
|
|
885
|
+
refreshedCount += quantity;
|
|
886
|
+
return { ...row, rowLimit,
|
|
887
|
+
quantity, guestPrice: previous?.guestPrice ?? "",
|
|
888
|
+
priceAmount: row.isGuestPrice ? Number(previous?.guestPrice || row.minPrice || 0) : row.priceAmount,
|
|
889
|
+
isSelected: row.id === s.selectedTierId, notSelected: row.id !== s.selectedTierId };
|
|
890
|
+
});
|
|
891
|
+
const termsChanged = previousSelected.some((previous) => {
|
|
892
|
+
const row = refreshedRows.find((next) => next.id === previous.id);
|
|
893
|
+
return !row || row.priceAmount !== previous.priceAmount || row.minPrice !== previous.minPrice
|
|
894
|
+
|| row.isGuestPrice !== previous.isGuestPrice || row.available !== previous.available
|
|
895
|
+
|| row.rowLimit !== previous.rowLimit || row.quantity !== previous.quantity
|
|
896
|
+
|| latestTickets.get(previous.ticketDefinitionId ?? previous.id)?.price?.currency !== paymentTickets.get(previous.ticketDefinitionId ?? previous.id)?.price?.currency;
|
|
897
|
+
});
|
|
898
|
+
const current = svc.getState();
|
|
899
|
+
s = { ...s, ...(current.status === "ready" && current.id === s.id ? current : {}), ticketTiers: refreshedRows,
|
|
900
|
+
ticketCurrency: latestTickets.values().next().value?.price?.currency || s.ticketCurrency };
|
|
901
|
+
const selectedRows = refreshedRows.filter((row) => (row.quantity ?? 0) > 0);
|
|
902
|
+
const latestSelected = selectedRows.map((row) => selectedPaymentTicket(row, latestTickets));
|
|
903
|
+
const routesAllowed = selectedRows.length === previousSelected.length
|
|
904
|
+
&& latestSelected.every((ticket) => !!ticket && tierAvailable(ticket))
|
|
905
|
+
&& (await Promise.all(latestSelected.map((ticket) => mayUseRegularTicketCheckout(paymentEvent, ticket)))).every(Boolean);
|
|
906
|
+
if (!routesAllowed) {
|
|
907
|
+
paymentTickets = latestTickets;
|
|
908
|
+
ticketCheckoutAllowed = false;
|
|
909
|
+
ticketCheckoutDenied = true;
|
|
910
|
+
if (selectedRows.length === 1 && selectedRows[0]!.quantity === 1) {
|
|
911
|
+
await priceTicket(paymentEvent, selectedRows[0]!.ticketDefinitionId ?? selectedRows[0]!.id, ticketSelectionVersion, latestSelected[0]);
|
|
912
|
+
}
|
|
913
|
+
const current = svc.getState();
|
|
914
|
+
const latest = current.status === "ready" && current.id === s.id ? { ...s, ...current } : s;
|
|
915
|
+
result = derive({ ...latest, ticketTiers: refreshedRows, ticketCurrency: s.ticketCurrency, snackbarMessage: copyParam("event.purchaseUnavailable", "Purchasing is temporarily unavailable.") });
|
|
916
|
+
ticketSelectionState = result;
|
|
917
|
+
if (result.status === "ready") lastReady = result;
|
|
918
|
+
} else {
|
|
919
|
+
paymentTickets = latestTickets;
|
|
920
|
+
ticketCheckoutAllowed = true;
|
|
921
|
+
ticketCheckoutDenied = false;
|
|
922
|
+
if (termsChanged) {
|
|
923
|
+
ticketCheckoutInFlight = false;
|
|
924
|
+
result = derive({ ...s, snackbarMessage: detailCopy("event.ticketsChanged", "Ticket details changed. Review your selection and try again.") });
|
|
925
|
+
ticketSelectionState = result;
|
|
926
|
+
lastReady = result;
|
|
927
|
+
} else if (isHostedWorker()) {
|
|
928
|
+
if (hostedOpenInFlight) result = derive(svc.getState());
|
|
929
|
+
else {
|
|
930
|
+
hostedOpenInFlight = true;
|
|
931
|
+
try {
|
|
932
|
+
const opened = await hostedSitePageOpener({ page: "event", eventId: s.id })(async () => {
|
|
933
|
+
try {
|
|
934
|
+
const fresh = await queryAvailableTickets(s.id);
|
|
935
|
+
const byId = new Map((fresh.definitions ?? []).filter((ticket) => ticket.id).map((ticket) => [ticket.id!, ticket]));
|
|
936
|
+
const freshSelected = selectedRows.map((row) => selectedPaymentTicket(row, byId));
|
|
937
|
+
const stillAllowed = freshSelected.every((ticket) => !!ticket && tierAvailable(ticket))
|
|
938
|
+
&& (await Promise.all(freshSelected.map((ticket) => mayUseRegularTicketCheckout(paymentEvent, ticket)))).every(Boolean);
|
|
939
|
+
if (stillAllowed) paymentTickets = byId;
|
|
940
|
+
return stillAllowed;
|
|
941
|
+
} catch { return false; }
|
|
942
|
+
});
|
|
943
|
+
const latestServiceState = svc.getState();
|
|
944
|
+
const latest = latestServiceState.status === "ready" && latestServiceState.id === s.id ? { ...s, ...latestServiceState } : s;
|
|
945
|
+
result = opened === true
|
|
946
|
+
? { ...latest, ticketSheetOpen: false, snackbarMessage: detailCopy("event.checkoutOpened", "Complete checkout in the browser to get your tickets.") }
|
|
947
|
+
: opened === "withdrawn" ? latest : { ...latest, snackbarMessage: detailCopy("event.registrationOpenFailed", "Could not open the registration page.") };
|
|
948
|
+
} finally { hostedOpenInFlight = false; }
|
|
949
|
+
}
|
|
950
|
+
} else {
|
|
951
|
+
const held = await createTicketReservation(s.id, quantities);
|
|
952
|
+
if (!held.id) throw new Error("Reservation did not return an id");
|
|
953
|
+
reservationId = held.id;
|
|
954
|
+
const placed = await checkoutReservation(s.id, held.id);
|
|
955
|
+
const snapshotId = placed.order?.snapshotId ?? "";
|
|
956
|
+
if (!snapshotId) result = { ...s, ticketSheetOpen: false, snackbarMessage: detailCopy("event.ticketIssued", "You're in — your ticket is confirmed.") };
|
|
957
|
+
else {
|
|
958
|
+
const msid = await wixPlatformSession.signedInstanceStatus().then((st) => st.msid ?? "").catch(() => "");
|
|
959
|
+
const pay = await payCashierOrder({ appId: WIX_EVENTS_APP_ID, snapshotId, msid, amount: placed.order?.totalPrice?.amount, currency: placed.order?.totalPrice?.currency, cashierUrl: async () => (await createRedirectSession({ eventsCheckout: { reservationId: held.id! } })).redirectSession?.fullUrl });
|
|
960
|
+
if (pay.kind === "paid") result = { ...s, ticketSheetOpen: false, snackbarMessage: detailCopy("event.ticketIssued", "You're in — your ticket is confirmed.") };
|
|
961
|
+
else if (pay.kind === "handoff") result = { ...s, ticketSheetOpen: false, snackbarMessage: detailCopy("event.checkoutOpened", "Complete checkout in the browser to get your tickets.") };
|
|
962
|
+
else if (pay.kind === "cancelled") result = { ...s, snackbarMessage: detailCopy("event.ticketCancelled", "Payment cancelled — no ticket was issued.") };
|
|
963
|
+
else if (isPaymentSetupFailure(pay)) result = { ...s, snackbarMessage: paymentSetupMessage("event") };
|
|
964
|
+
else throw new Error("Payment could not be completed");
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
} catch (error) {
|
|
969
|
+
if (isPaymentSetupFailure(error)) result = { ...s, snackbarMessage: paymentSetupMessage("event") };
|
|
970
|
+
try {
|
|
971
|
+
// A public event page is not pinned to this selection or price. Only
|
|
972
|
+
// continue in hosted checkout when a reservation already holds it.
|
|
973
|
+
const params = reservationId ? { reservationId } : undefined;
|
|
974
|
+
if (params && !result) {
|
|
975
|
+
const redirect = await createRedirectSession({ eventsCheckout: params });
|
|
976
|
+
const url = redirect.redirectSession?.fullUrl;
|
|
977
|
+
if (url) {
|
|
978
|
+
const opened = await open(url, "in_app_browser");
|
|
979
|
+
result = { ...s, ticketSheetOpen: false, snackbarMessage: opened.opened ? detailCopy("event.checkoutOpened", "Complete checkout in the browser to get your tickets.") : detailCopy("event.registrationOpenFailed", "Could not open the registration page.") };
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
} catch (error) {
|
|
983
|
+
if (isPaymentSetupFailure(error)) result = { ...s, snackbarMessage: paymentSetupMessage("event") };
|
|
984
|
+
}
|
|
985
|
+
if (!result) result = { ...s, snackbarMessage: detailCopy("event.purchaseUnavailable", "Purchasing is temporarily unavailable.") };
|
|
986
|
+
} finally { ticketCheckoutInFlight = false; }
|
|
987
|
+
return derive(result!);
|
|
988
|
+
},
|
|
989
|
+
iapPublish: (s) => {
|
|
990
|
+
// Prefer the live ready state so an asynchronous StoreKit publication
|
|
991
|
+
// cannot overwrite a newer selection or checkout snackbar with the
|
|
992
|
+
// original load snapshot.
|
|
993
|
+
const next = derive(s.status === "ready" ? s : lastReady ?? s);
|
|
994
|
+
if (next.status === "ready") lastReady = next;
|
|
995
|
+
return next;
|
|
996
|
+
},
|
|
997
|
+
iapRefresh: async (): Promise<S> => { await applePurchase.refresh(); return derive(svc.getState()); },
|
|
998
|
+
iapPoll: async (): Promise<S> => { await applePurchase.poll(); return derive(svc.getState()); },
|
|
999
|
+
setIapField: (s, arg) => { applePurchase.change(arg); return derive(s); },
|
|
1000
|
+
buyApple: async (s: S): Promise<S> => {
|
|
1001
|
+
const selected = s.ticketTiers.find((t) => t.id === s.selectedTierId);
|
|
1002
|
+
if (!selected || !selected.available || selected.quantity !== 1 || s.ticketTiers.some((t) => t.id !== s.selectedTierId && (t.quantity ?? 0) > 0)) return derive(s);
|
|
1003
|
+
await applePurchase.buy({ key: selected.ticketDefinitionId ?? selected.id, eventId: s.id });
|
|
1004
|
+
return derive(svc.getState());
|
|
1005
|
+
},
|
|
1006
|
+
load: async (s: S, arg?: unknown): Promise<S | undefined> => {
|
|
1007
|
+
const selectionVersion = ++ticketSelectionVersion;
|
|
1008
|
+
ticketCheckoutAllowed = false;
|
|
1009
|
+
ticketCheckoutDenied = false;
|
|
1010
|
+
ticketSelectionState = undefined;
|
|
1011
|
+
lastReady = undefined;
|
|
1012
|
+
s = { ...s, ticketSheetOpen: false, rsvpActionsOpen: false, cancelConfirmOpen: false, rsvpId: "", rsvpState: "none", rsvpLabel: "", openDisclosures: [] };
|
|
1013
|
+
applePurchase.invalidate();
|
|
1014
|
+
stashCopy(arg);
|
|
1015
|
+
let id = s.id || inputId();
|
|
1016
|
+
noFeaturedEvent = false;
|
|
1017
|
+
// A featured screen resolves its event on every load — each appear, and its Retry — since the
|
|
1018
|
+
// site's next event may have changed.
|
|
1019
|
+
if (featuredRequested(arg)) featuredMode = true;
|
|
1020
|
+
if (featuredMode && !inputId()) {
|
|
1021
|
+
const featured = await readFeaturedEvent(["DETAILS"]);
|
|
1022
|
+
if (selectionVersion !== ticketSelectionVersion) return undefined;
|
|
1023
|
+
// A failed read is a clean error: the last event's image, About, schedule and tiers must not
|
|
1024
|
+
// stay on screen under the Retry card (the loaded content hides only while loading).
|
|
1025
|
+
if (!featured.ok) return derive({ ...bootState(), id: "", status: "ready", errored: true, title: "" });
|
|
1026
|
+
if (!featured.event?.id) {
|
|
1027
|
+
noFeaturedEvent = true;
|
|
1028
|
+
return derive({ ...bootState(), id: "", status: "ready", errored: false, title: "" });
|
|
1029
|
+
}
|
|
1030
|
+
id = featured.event.id;
|
|
1031
|
+
// Another event than the one on screen starts clean: its offline fallback must not keep the
|
|
1032
|
+
// previous event's About, schedule or policies.
|
|
1033
|
+
s = s.id === id ? s : { ...bootState(), id };
|
|
1034
|
+
}
|
|
1035
|
+
if (!id) return derive({ ...s, status: "ready", errored: true });
|
|
1036
|
+
try {
|
|
1037
|
+
// TEXTS adds the Ricos `description` to the base fieldset (a bare read returns none);
|
|
1038
|
+
// REGISTRATION adds `registration` (the CTA's type, and an external event's own URL);
|
|
1039
|
+
// URLS adds `eventPageUrl` — the registration fallback and the share link. Without URLS a
|
|
1040
|
+
// ticket flow that cannot complete in-app had no page to send the buyer to.
|
|
1041
|
+
const res = await getEvent(id, { fields: EVENT_DETAIL_FIELDSETS });
|
|
1042
|
+
const e = ((res as unknown as { event?: WixEvent }).event ?? res) as WixEvent;
|
|
1043
|
+
// Ticketed events load their tiers with the event, so the price is on
|
|
1044
|
+
// screen BEFORE the CTA is tapped. Best-effort: a tier read that fails
|
|
1045
|
+
// leaves the picker collapsed and the CTA falls back to its own read.
|
|
1046
|
+
const kind = registrationKindOf(e);
|
|
1047
|
+
const loaded = kind === "tickets" ? await loadTiers(id) : { rows: [], tickets: new Map<string, WixAvailableTicket>() };
|
|
1048
|
+
const orderLimit = Number((e as unknown as { registration?: { tickets?: { ticketLimitPerOrder?: number } } }).registration?.tickets?.ticketLimitPerOrder ?? 99);
|
|
1049
|
+
const tiers = loaded.rows.map((row) => ({ ...row, rowLimit: Math.min(row.rowLimit ?? 99, orderLimit), maxQuantity: Math.min(row.maxQuantity ?? 99, orderLimit) }));
|
|
1050
|
+
const selectedTierId = tiers.find((t) => t.isSelected)?.id ?? tiers.find((t) => t.available)?.id ?? "";
|
|
1051
|
+
const selectedTicketId = tiers.find((row) => row.id === selectedTierId)?.ticketDefinitionId ?? selectedTierId;
|
|
1052
|
+
const regular = kind !== "tickets" || await mayUseRegularTicketCheckout(e, loaded.tickets.get(selectedTicketId));
|
|
1053
|
+
if (selectionVersion !== ticketSelectionVersion) return undefined;
|
|
1054
|
+
paymentEvent = e;
|
|
1055
|
+
paymentTickets = loaded.tickets;
|
|
1056
|
+
ticketCheckoutAllowed = regular;
|
|
1057
|
+
if (kind === "tickets" && !await priceTicket(e, selectedTicketId, selectionVersion)) return undefined;
|
|
1058
|
+
// Write-through: cache the fetched row (same EventRow shape as the list) so a
|
|
1059
|
+
// later offline open of this detail can fall back to it.
|
|
1060
|
+
await writeCachedRow(normalizeEvent(e));
|
|
1061
|
+
const image = eventImage(e);
|
|
1062
|
+
const title = e.title || "";
|
|
1063
|
+
const dates = detailDate(e);
|
|
1064
|
+
const place = detailPlace(e);
|
|
1065
|
+
const registration = registrationUi(e, Date.now());
|
|
1066
|
+
const rawEvent = e as unknown as { shortDescription?: string; agendaSettings?: { enabled?: boolean }; dateAndTimeSettings?: { recurrenceStatus?: string; recurringEvents?: { categoryId?: string } }; registration?: { allowedGuestTypes?: string; tickets?: { lowestPrice?: EventDetailMoney; highestPrice?: EventDetailMoney } } };
|
|
1067
|
+
const lowest = detailMoney(rawEvent.registration?.tickets?.lowestPrice);
|
|
1068
|
+
const highest = detailMoney(rawEvent.registration?.tickets?.highestPrice);
|
|
1069
|
+
const price = kind === "tickets" && lowest ? (highest && highest !== lowest ? detailCopy("event.priceFrom", "From {price}").replace("{price}", lowest) : lowest) : "";
|
|
1070
|
+
const memberProbeNeeded = kind === "rsvp" || rawEvent.registration?.allowedGuestTypes === "MEMBER";
|
|
1071
|
+
const isMember = memberProbeNeeded ? await signedInMember() : false;
|
|
1072
|
+
const [scheduleResponse, policyResponse, rsvpResponse] = await Promise.all([
|
|
1073
|
+
// `limit` is required: without it Wix answers the agenda's `total` with an EMPTY `items`.
|
|
1074
|
+
rawEvent.agendaSettings?.enabled ? bestEffort("GET", `/events/v1/schedule?eventId=${encodeURIComponent(id)}&limit=100`) : undefined,
|
|
1075
|
+
bestEffort("POST", "/events-policies/v2/policies/query", { query: { filter: { eventId: { $eq: id } }, paging: { limit: 100 } } }),
|
|
1076
|
+
kind === "rsvp" && isMember ? bestEffort("GET", `/events/v2/rsvps/current?eventId=${encodeURIComponent(id)}`) : undefined,
|
|
1077
|
+
]);
|
|
1078
|
+
let optionalReadFailed = [scheduleResponse, policyResponse, rsvpResponse].some((response) => response?.ok === false);
|
|
1079
|
+
const scheduleRaw = (scheduleResponse?.ok ? scheduleResponse.value : undefined) as { agenda?: Array<Record<string, unknown>>; schedule?: Array<Record<string, unknown>>; items?: Array<Record<string, unknown>>; agendaItems?: Array<Record<string, unknown>> } | undefined;
|
|
1080
|
+
// A hidden or canceled session is not on the agenda, and an item id is listed once (an owner's
|
|
1081
|
+
// read carries a draft and its published copy); sessions in start order.
|
|
1082
|
+
const seenItems = new Set<string>();
|
|
1083
|
+
const scheduleSource = (scheduleRaw?.agenda ?? scheduleRaw?.agendaItems ?? scheduleRaw?.schedule ?? scheduleRaw?.items ?? [])
|
|
1084
|
+
.filter((item) => item.hidden !== true && String(item.status ?? "").toUpperCase() !== "CANCELED")
|
|
1085
|
+
.filter((item) => { const key = String(item.id ?? ""); if (!key) return true; if (seenItems.has(key)) return false; seenItems.add(key); return true; })
|
|
1086
|
+
.map((item) => ({ item, at: Date.parse(String((item.timeSlot as { start?: string } | undefined)?.start ?? item.startTime ?? item.startDate ?? "")) }))
|
|
1087
|
+
.sort((a, b) => (Number.isNaN(a.at) ? Infinity : a.at) - (Number.isNaN(b.at) ? Infinity : b.at))
|
|
1088
|
+
.map(({ item }) => item);
|
|
1089
|
+
const fullSchedule = scheduleSource.map((item) => {
|
|
1090
|
+
const slot = item.timeSlot as { start?: string; end?: string; timeZoneId?: string } | undefined;
|
|
1091
|
+
const start = String(slot?.start ?? item.startTime ?? item.startDate ?? item.time ?? "");
|
|
1092
|
+
const date = start ? new Date(start) : undefined;
|
|
1093
|
+
return {
|
|
1094
|
+
time: date && !Number.isNaN(date.getTime()) ? formatWeekdayDateTime(date, "en-US", slot?.timeZoneId) : start,
|
|
1095
|
+
name: String(item.name ?? item.title ?? ""),
|
|
1096
|
+
detail: String(item.stageName ?? item.stage ?? item.host ?? ""),
|
|
1097
|
+
};
|
|
1098
|
+
});
|
|
1099
|
+
const scheduleItems = fullSchedule.slice(0, 3);
|
|
1100
|
+
const rawPolicies = (((policyResponse?.ok ? policyResponse.value : undefined) as { policies?: Array<Record<string, unknown>> } | undefined)?.policies ?? []);
|
|
1101
|
+
const policies = rawPolicies.map((policy) => ({ name: String(policy.name ?? ""), text: String(policy.body ?? "") })).filter((policy) => policy.name || policy.text);
|
|
1102
|
+
const rsvpPayload = (rsvpResponse?.ok ? rsvpResponse.value : undefined) as { rsvps?: Array<{ id?: string; status?: string }>; rsvp?: { id?: string; status?: string } } | undefined;
|
|
1103
|
+
const rsvps = rsvpPayload?.rsvps ?? (rsvpPayload?.rsvp ? [rsvpPayload.rsvp] : []);
|
|
1104
|
+
const heldRsvp = rsvps.find((r) => ["YES", "WAITLIST", "WAITING"].includes((r.status ?? "").toUpperCase()));
|
|
1105
|
+
const rsvpState = !heldRsvp ? "none" : /(WAITLIST|WAITING)/i.test(heldRsvp.status ?? "") ? "waitlist" : "going";
|
|
1106
|
+
const rsvpLabel = rsvpState === "waitlist" ? detailCopy("event.waitlisted", "You're on the waitlist") : rsvpState === "going" ? detailCopy("event.going", "You're going") : "";
|
|
1107
|
+
const memberOnly = rawEvent.registration?.allowedGuestTypes === "MEMBER" && !isMember && ["rsvp", "waitlist", "tickets", "scheduled"].includes(registration.state);
|
|
1108
|
+
const registrationRaw = rawEvent.registration as { status?: string; registrationPaused?: boolean; tickets?: { soldOut?: boolean } } | undefined;
|
|
1109
|
+
const registrationClosed = !!registrationRaw?.registrationPaused || ["CLOSED_AUTOMATICALLY", "CLOSED_MANUALLY"].includes(registrationRaw?.status ?? "");
|
|
1110
|
+
const soldOut = kind === "tickets" && !!registrationRaw?.tickets?.soldOut;
|
|
1111
|
+
const formMessages = (e as unknown as { form?: { messages?: { registrationClosed?: { exploreEventsActionLabel?: string }; ticketsUnavailable?: { exploreEventsActionLabel?: string } } } }).form?.messages;
|
|
1112
|
+
const exploreLabel = registrationClosed
|
|
1113
|
+
? formMessages?.registrationClosed?.exploreEventsActionLabel
|
|
1114
|
+
: soldOut ? formMessages?.ticketsUnavailable?.exploreEventsActionLabel : undefined;
|
|
1115
|
+
let moreDates: Array<{ id: string; date: string }> = [];
|
|
1116
|
+
const recurrence = rawEvent.dateAndTimeSettings?.recurringEvents;
|
|
1117
|
+
if (recurrence?.categoryId && rawEvent.dateAndTimeSettings?.recurrenceStatus !== "ONE_TIME") {
|
|
1118
|
+
try {
|
|
1119
|
+
const series: WixEvent[] = [];
|
|
1120
|
+
// The Events V3 category endpoint is the supported scoped series read.
|
|
1121
|
+
// Page in bounded batches, since a single 100-row response can omit later dates.
|
|
1122
|
+
for (let offset = 0; offset < 1000; offset += 100) {
|
|
1123
|
+
const page = await bestEffort("GET", `/events/v3/events/category/${encodeURIComponent(recurrence.categoryId)}?paging.limit=100&paging.offset=${offset}&fields=DETAILS&fields=TEXTS&fields=REGISTRATION`);
|
|
1124
|
+
if (!page.ok) { optionalReadFailed = true; break; }
|
|
1125
|
+
const pageEvents = (page.value.events ?? []) as WixEvent[];
|
|
1126
|
+
series.push(...pageEvents);
|
|
1127
|
+
if (pageEvents.length < 100) break;
|
|
1128
|
+
}
|
|
1129
|
+
const now = Date.now();
|
|
1130
|
+
moreDates = series.filter((item) => {
|
|
1131
|
+
const itemRaw = item as unknown as { status?: string; dateAndTimeSettings?: { recurringEvents?: { categoryId?: string } } };
|
|
1132
|
+
const start = eventStartMillis(item);
|
|
1133
|
+
return item.id !== id && itemRaw.dateAndTimeSettings?.recurringEvents?.categoryId === recurrence.categoryId && !["ENDED", "CANCELED", "DRAFT"].includes((itemRaw.status ?? "").toUpperCase()) && (start == null || start >= now);
|
|
1134
|
+
}).sort((a, b) => (eventStartMillis(a) ?? 0) - (eventStartMillis(b) ?? 0)).map((item) => ({ id: item.id ?? "", date: eventWhen(item) })).filter((item) => !!item.id);
|
|
1135
|
+
} catch { moreDates = []; optionalReadFailed = true; }
|
|
1136
|
+
}
|
|
1137
|
+
const body = eventBody(e);
|
|
1138
|
+
const shortDescription = descriptionBody(rawEvent.shortDescription).bodyText;
|
|
1139
|
+
const readyState = derive({
|
|
1140
|
+
...s,
|
|
1141
|
+
status: "ready",
|
|
1142
|
+
errored: false,
|
|
1143
|
+
id,
|
|
1144
|
+
ticketTiers: tiers,
|
|
1145
|
+
ticketCurrency: (e as unknown as { registration?: { tickets?: { currency?: string } } }).registration?.tickets?.currency || loaded.tickets.values().next().value?.price?.currency || "USD",
|
|
1146
|
+
ticketLimitPerOrder: orderLimit,
|
|
1147
|
+
// Default the pick to the cheapest AVAILABLE tier so the CTA is never
|
|
1148
|
+
// dead; the buyer's tap overrides it from there.
|
|
1149
|
+
selectedTierId,
|
|
1150
|
+
title,
|
|
1151
|
+
when: dates.line,
|
|
1152
|
+
location: eventLocation(e),
|
|
1153
|
+
place: place.value,
|
|
1154
|
+
placeIcon: place.icon,
|
|
1155
|
+
noPlace: !place.value,
|
|
1156
|
+
hidePlaceStatic: !place.value || !!place.mapUrl,
|
|
1157
|
+
price,
|
|
1158
|
+
zone: dates.zone,
|
|
1159
|
+
mapUrl: place.mapUrl,
|
|
1160
|
+
shortDescription,
|
|
1161
|
+
noShortDescription: !shortDescription || shortDescription === body.description,
|
|
1162
|
+
noDescription: !body.description && !body.descriptionJson,
|
|
1163
|
+
noDate: !dates.line,
|
|
1164
|
+
registrationState: registration.state,
|
|
1165
|
+
footerLabel: registration.label,
|
|
1166
|
+
footerAction: registration.action,
|
|
1167
|
+
footerCaption: memberOnly ? (kind === "tickets" ? detailCopy("event.membersOnlyTickets", "Only members can buy tickets.") : detailCopy("event.membersOnlyRsvp", "Only members can RSVP.")) : registration.caption,
|
|
1168
|
+
memberOnly,
|
|
1169
|
+
notice: registration.notice,
|
|
1170
|
+
exploreLabel: exploreLabel || detailCopy("event.exploreCta", "Explore Events"),
|
|
1171
|
+
rsvpLabel,
|
|
1172
|
+
rsvpId: heldRsvp?.id ?? "",
|
|
1173
|
+
rsvpState,
|
|
1174
|
+
schedule: scheduleItems,
|
|
1175
|
+
fullSchedule: fullSchedule.slice(3),
|
|
1176
|
+
noSchedule: scheduleItems.length === 0,
|
|
1177
|
+
policies,
|
|
1178
|
+
noPolicies: policies.length === 0,
|
|
1179
|
+
moreDates: moreDates.slice(0, 3),
|
|
1180
|
+
allDates: moreDates.slice(3),
|
|
1181
|
+
noMoreDates: moreDates.length === 0,
|
|
1182
|
+
// The Ricos description when the event has one (its own text is the plain copy); the legacy
|
|
1183
|
+
// string fields otherwise.
|
|
1184
|
+
...body,
|
|
1185
|
+
image,
|
|
1186
|
+
hasImage: !!image,
|
|
1187
|
+
noImage: !image,
|
|
1188
|
+
hideMapTap: place.hideMapTap,
|
|
1189
|
+
registrationKind: registrationKindOf(e),
|
|
1190
|
+
registrationUrl: registrationUrlOf(e),
|
|
1191
|
+
eventSlug: eventSlugOf(e),
|
|
1192
|
+
shareUrl: eventPageUrlOf(e),
|
|
1193
|
+
calendarStart: dates.start,
|
|
1194
|
+
calendarEnd: dates.end,
|
|
1195
|
+
snackbarMessage: optionalReadFailed ? detailCopy("event.detailsUnavailable", "Some event details couldn't load. Try again.") : "",
|
|
1196
|
+
});
|
|
1197
|
+
ticketSelectionState = readyState;
|
|
1198
|
+
lastReady = readyState;
|
|
1199
|
+
return readyState;
|
|
1200
|
+
} catch (error) {
|
|
1201
|
+
// Offline / fetch failure: fall back to the last-synced cached row before erroring.
|
|
1202
|
+
if (selectionVersion !== ticketSelectionVersion) return undefined;
|
|
1203
|
+
const cached = await readCachedRow(id);
|
|
1204
|
+
if (cached) {
|
|
1205
|
+
const title = cached.title || "Event";
|
|
1206
|
+
const cachedState = derive({
|
|
1207
|
+
...s,
|
|
1208
|
+
status: "ready",
|
|
1209
|
+
errored: false,
|
|
1210
|
+
id,
|
|
1211
|
+
title,
|
|
1212
|
+
when: cached.dateLine,
|
|
1213
|
+
location: cached.location,
|
|
1214
|
+
// The cached list row carries no description: an offline retry of THIS event keeps the pair it
|
|
1215
|
+
// already shows, and any other event's is cleared together, so neither half can linger alone.
|
|
1216
|
+
...(s.id === id ? {} : { description: "", descriptionJson: "" }),
|
|
1217
|
+
image: cached.image,
|
|
1218
|
+
hasImage: !!cached.image,
|
|
1219
|
+
noImage: !cached.image,
|
|
1220
|
+
});
|
|
1221
|
+
lastReady = cachedState;
|
|
1222
|
+
return cachedState;
|
|
1223
|
+
}
|
|
1224
|
+
const errorState = derive({ ...s, status: "ready", errored: true, title: "" });
|
|
1225
|
+
lastReady = errorState;
|
|
1226
|
+
return errorState;
|
|
1227
|
+
}
|
|
1228
|
+
},
|
|
1229
|
+
openMap: async (s) => {
|
|
1230
|
+
if (!s.mapUrl) return derive({ ...s, snackbarMessage: copyParam("event.noMapMessage", "This event does not have a mapped location yet.") });
|
|
1231
|
+
try {
|
|
1232
|
+
const result = await open(s.mapUrl, "external_app");
|
|
1233
|
+
return derive({ ...s, snackbarMessage: result.opened ? "" : copyParam("event.mapOpenFailed", "Could not open maps on this device.") });
|
|
1234
|
+
} catch {
|
|
1235
|
+
return derive({ ...s, snackbarMessage: copyParam("event.mapOpenFailed", "Could not open maps on this device.") });
|
|
1236
|
+
}
|
|
1237
|
+
},
|
|
1238
|
+
openRegistration: async (s): Promise<S> => {
|
|
1239
|
+
if (s.registrationKind !== "external" || !s.registrationUrl) return derive(s);
|
|
1240
|
+
try {
|
|
1241
|
+
const result = await open(s.registrationUrl, "in_app_browser");
|
|
1242
|
+
return derive({ ...s, snackbarMessage: result.opened ? "" : copyParam("event.registrationOpenFailed", "Could not open the registration page.") });
|
|
1243
|
+
} catch {
|
|
1244
|
+
return derive({ ...s, snackbarMessage: copyParam("event.registrationOpenFailed", "Could not open the registration page.") });
|
|
1245
|
+
}
|
|
1246
|
+
},
|
|
1247
|
+
share: async (s) => {
|
|
1248
|
+
if (!s.title) return s;
|
|
1249
|
+
const text = [s.title, s.when].filter(Boolean).join(" — ");
|
|
1250
|
+
try {
|
|
1251
|
+
await shareSheet({ subject: s.title, text, ...(s.shareUrl ? { url: s.shareUrl } : {}) });
|
|
1252
|
+
return s;
|
|
1253
|
+
} catch {
|
|
1254
|
+
return derive({ ...s, snackbarMessage: copyParam("event.shareUnavailable", "Sharing is not available on this device.") });
|
|
1255
|
+
}
|
|
1256
|
+
},
|
|
1257
|
+
addToCalendar: async (s) => {
|
|
1258
|
+
if (!s.calendarStart) return derive({ ...s, rsvpActionsOpen: false, snackbarMessage: copyParam("event.noDateMessage", "This event does not have a date yet.") });
|
|
1259
|
+
const end = s.calendarEnd > s.calendarStart ? s.calendarEnd : s.calendarStart + 60 * 60 * 1000;
|
|
1260
|
+
try {
|
|
1261
|
+
let permission = await getPermissionStatus();
|
|
1262
|
+
if (permission !== "granted" && permission !== "limited") {
|
|
1263
|
+
permission = await requestPermission("writeOnly");
|
|
1264
|
+
}
|
|
1265
|
+
if (permission !== "granted" && permission !== "limited") {
|
|
1266
|
+
const fallback = await open(calendarFallbackUrl(s, end), "in_app_browser");
|
|
1267
|
+
return derive({ ...s, rsvpActionsOpen: false, snackbarMessage: fallback.opened ? copyParam("event.calendarOpened", "Opened calendar.") : copyParam("event.calendarPermissionDenied", "Calendar permission was not granted.") });
|
|
1268
|
+
}
|
|
1269
|
+
const created = await createEvent({
|
|
1270
|
+
title: s.title || "Event",
|
|
1271
|
+
start: s.calendarStart,
|
|
1272
|
+
end,
|
|
1273
|
+
location: s.location,
|
|
1274
|
+
notes: s.description || s.when,
|
|
1275
|
+
});
|
|
1276
|
+
if (!created.id) {
|
|
1277
|
+
const fallback = await open(calendarFallbackUrl(s, end), "in_app_browser");
|
|
1278
|
+
return derive({ ...s, rsvpActionsOpen: false, snackbarMessage: fallback.opened ? copyParam("event.calendarOpened", "Opened calendar.") : copyParam("event.calendarAddFailed", "Could not add this event to calendar."), isAddingCalendar: false });
|
|
1279
|
+
}
|
|
1280
|
+
return derive({
|
|
1281
|
+
...s,
|
|
1282
|
+
rsvpActionsOpen: false,
|
|
1283
|
+
snackbarMessage: copyParam("event.calendarAdded", "Added to calendar."),
|
|
1284
|
+
isAddingCalendar: false,
|
|
1285
|
+
});
|
|
1286
|
+
} catch {
|
|
1287
|
+
return derive({ ...s, rsvpActionsOpen: false, snackbarMessage: copyParam("event.calendarAddFailed", "Could not add this event to calendar."), isAddingCalendar: false });
|
|
1288
|
+
}
|
|
1289
|
+
},
|
|
1290
|
+
// Only http(s), mailto and tel links reach open_url; a refused link, or one nothing opened, says so, and a
|
|
1291
|
+
// link that opens clears an earlier message.
|
|
1292
|
+
openLink: async (s, arg) => derive({
|
|
1293
|
+
...s,
|
|
1294
|
+
snackbarMessage: (await openRichLink(arg)) ? "" : copyParam("event.linkOpenFailed", "This link could not be opened."),
|
|
1295
|
+
}),
|
|
1296
|
+
},
|
|
1297
|
+
});
|
|
1298
|
+
resetUnhydratedKeysOnOlderRuntime(svc, { ...svc.getState(), ...ATTENDANCE_INITIAL, ticketPurchaseBlocked: true, ticketSheetOpen: false, rsvpActionsOpen: false, cancelConfirmOpen: false, rsvpId: "", rsvpState: "none", rsvpLabel: "" }, [...ATTENDANCE_NOT_HYDRATED, "ticketPurchaseBlocked", "ticketSheetOpen", "rsvpActionsOpen", "cancelConfirmOpen", "rsvpId", "rsvpState", "rsvpLabel"]);
|
|
1299
|
+
// The boot load needs an event id. Without one it could only answer "not found" — and on a
|
|
1300
|
+
// screen that finds its event itself (`featured`, a conference app's Tickets tab) that error
|
|
1301
|
+
// showed for the whole featured read, seconds on web, instead of the skeleton. The screen's
|
|
1302
|
+
// onAppear load decides an id-less open: the featured event, or the error.
|
|
1303
|
+
if (inputId()) svc.load();
|
|
1304
|
+
export { svc };
|