riverbankcms 0.31.1 → 0.32.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.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { $t as buttonStyleSelectionSchema, At as resolveMediaIdentifier, Bt as MAX_MANAGEMENT_MEDIA_UPLOAD_BYTES, C as entryIdentifierForCommand, Cn as ICON_PICKER_PRESETS, Ct as PUBLIC_FILE_FIELD_KINDS, Dn as asFooterLookId, Dt as buildMediaIdentifierFromFilename, En as SUPPORTED_LOADER_ENDPOINTS, Er as createContentEntryRef, Ft as getMimeType, Ir as slugPart, K as themeSchema, Kn as asAppearancePresetId, Ln as SYSTEM_BLOCK_KINDS, Lt as normalizeAmbiguousStoragePathForSite, Mn as headerLayoutIdValues, N as footerPreferencesSchema, Nn as headerStyleIdValues, Nr as createSiteCommandSiteRef, On as asHeaderLayoutId, P as headerPreferencesSchema, Pt as getExtensionForMimeType, Tr as createCommandRef, Tt as mediaTypeDiscriminants, V as footerModeSchema, Xn as asDesignBlockId, Zn as asDesignBoundaryId, _ as evaluateSiteCommandBatchExposure, br as require_dist, f as stableStringify, jn as footerLookIdValues, jt as slugifyMediaIdentifier, k as eventBookingOfferIntentSchema, kn as asHeaderStyleId, l as resolvePageUpsertSeo, lr as RESOLVED_INTERNAL_LINK_ENTITY_TYPES, m as parseAndPlanCommandBatchForTypes, n as sdkCourseBookingSettingsSchema, nr as asSiteStyleId, p as createDryRunReport, pt as getDirectImageUrlForSiteScopedPath, r as sdkEventOccurrenceInputSchema, rr as makeBoundaryId, s as eventVisibilitySchema, tr as asPageFlowPresetId, ut as parseAspectRatioValue, v as evaluateSiteCommandExposure, wt as isDisplayMediaKind, xr as bookingQuestionAttachmentSchema, y as getSiteCommandMetadata, zt as FILE_SIZE_LIMITS } from "./sdk-event-upsert-0U4hsDpo.mjs";
3
- import { $t as businessCancellationRefusalCodes, An as unsafeAsAppointmentResourceId, C as isPublicReadEndpoint, Cn as unsafeAsPositiveCents, En as assertNever, G as parseFooterCompositionV1, Gt as isSettleableOrderInstalmentPlanStatus, Ht as validateBookingPaymentOptionKinds, In as unsafeAsPassId, It as resolveBookingTimeZoneId, Jt as getBookingInstalmentDepositRefundability, Kt as addIntervalPreservingMonthAnchor, Ln as parseDatedOfferingCapacityHoldAuditRef, M as exposeSecret, Mn as parseCustomerId, N as parseManagementKey, Nt as parseBookingLocalDate, Pn as parseMembershipId, Qt as splitAmountWithRemainderInFirst, Rn as parseDatedOfferingCapacityHoldId, S as getPublicReadCachePolicy, Sn as unsafeAsNonNegativeCents, Tn as parseCurrencyCode, Ut as isLiveOrderInstalmentPlanStatus, W as parseMailingListProviderScope, Wt as isSettleableFlexibleBalanceContractStatus, Xt as getBookingInstalmentProtectedDepositAmountCents, Zt as omitZeroAmountFutureRows, _n as isNonNegativeWholeCents$1, _r as err, ar as parseSiteId, b as PUBLIC_AVAILABILITY_FRESHNESS_SECONDS, bn as toCents, d as canonicalizeConfiguredBookingVerticalConfig, en as scheduleBookingReasonCodes, er as unsafeAsCheckoutLineId, et as assertAllowedPublicUrl, f as parseVerticalId, fr as unsafeAsEventInstanceId, g as EVENT_PRESET_VALUES, gr as unsafeAsPricingOptionId, gt as formatDate, h as DEFAULT_EVENT_TYPE_PRESETS, hr as unsafeAsOccurrenceId, ir as parseApiKeyId, j as createSecret, jn as unsafeAsStaffMemberId, lr as parseEventSeriesId, m as resolveSiteVerticalBookingConfig, mn as fromArray, mr as unsafeAsEventSeriesId, n as committedWriteProofSchema, nn as resolveFlexibleBalanceInitialPaymentCents, nr as parsePageId, or as parseUserId, ot as locationValueSchema, p as parseVerticalPresetId, pr as unsafeAsEventOfferingId, pt as trimmedStringOrNull, qt as clampConfiguredAmount, s as resolveEventCatalogue, t as OFFLINE_PAYMENT_METHODS, tn as resolveFlexibleBalanceDueAt, tr as parseEditorSessionGeneration, u as areConfiguredBookingVerticalConfigsEqual, ur as parseRetiredCourseId, ut as publicLocationSchema, v as SURFACE_EVENT_PRESET_VALUES, vn as parseNonNegativeCents, vr as ok, w as publicReadFreshnessSeconds, x as PUBLIC_CONTENT_FRESHNESS_SECONDS, xn as toNonNegativeCents, yn as parsePositiveCents } from "./src-exrglXYU.mjs";
4
- import { n as CliSdkPeerError, t as loadConfigFile } from "./load-config-DIyqYeRP.mjs";
2
+ import { $n as headerStyleIdValues, At as getMimeType, Bt as footerPreferencesSchema, Cr as makeBoundaryId, Et as slugifyMediaIdentifier, Ft as MAX_MANAGEMENT_MEDIA_UPLOAD_BYTES, I as footerModeSchema, Ir as createSiteCommandSiteRef, Jn as asHeaderLayoutId, Kn as SUPPORTED_LOADER_ENDPOINTS, Mt as normalizeAmbiguousStoragePathForSite, Nn as RESOLVED_INTERNAL_LINK_ENTITY_TYPES, Or as createCommandRef, Pt as FILE_SIZE_LIMITS, Qn as headerLayoutIdValues, Sn as eventBookingOfferIntentSchema, Sr as asSiteStyleId, St as buildMediaIdentifierFromFilename, Tt as resolveMediaIdentifier, Un as ICON_PICKER_PRESETS, V as themeSchema, Xt as buttonStyleSelectionSchema, Yn as asHeaderStyleId, Zn as footerLookIdValues, _r as asDesignBoundaryId, at as parseAspectRatioValue, b as getSiteCommandMetadata, bt as mediaTypeDiscriminants, ct as getDirectImageUrlForSiteScopedPath, fr as asAppearancePresetId, gr as asDesignBlockId, h as parseAndPlanCommandBatchForTypes, k as headerPreferencesSchema, kr as createContentEntryRef, kt as getExtensionForMimeType, l as resolvePageUpsertSeo, m as createDryRunReport, n as sdkCourseBookingSettingsSchema, p as stableStringify, qn as asFooterLookId, r as sdkEventOccurrenceInputSchema, rr as SYSTEM_BLOCK_KINDS, s as eventVisibilitySchema, v as evaluateSiteCommandBatchExposure, vt as PUBLIC_FILE_FIELD_KINDS, w as entryIdentifierForCommand, wr as bookingQuestionAttachmentSchema, xn as require_dist, xr as asPageFlowPresetId, y as evaluateSiteCommandExposure, yt as isDisplayMediaKind, zr as slugPart } from "./sdk-event-upsert-SodZay6g.mjs";
3
+ import { $t as businessCancellationRefusalCodes, At as formatLocalScheduleDate, Bn as parseDatedOfferingCapacityHoldId, C as getPublicReadCachePolicy, Cn as toNonNegativeCents, Dn as parseCurrencyCode, En as formatCurrencyAmount, G as parseMailingListProviderScope, Gt as validateBookingPaymentOptionKinds, In as parseMembershipId, It as parseBookingLocalDate, Jt as clampConfiguredAmount, K as parseFooterCompositionV1, Kt as isLiveOrderInstalmentPlanStatus, M as createSecret, Mn as unsafeAsAppointmentResourceId, N as exposeSecret, Nn as unsafeAsStaffMemberId, Nt as getLocalScheduleDate, On as assertNever, Ot as addLocalScheduleDays, P as parseManagementKey, Pn as parseCustomerId, Qt as splitAmountWithRemainderInFirst, Rn as unsafeAsPassId, S as PUBLIC_CONTENT_FRESHNESS_SECONDS, Sn as toCents, Sr as ok, T as publicReadFreshnessSeconds, Tn as unsafeAsPositiveCents, Ut as toUtcIsoDateTimeString, Yt as getBookingInstalmentDepositRefundability, Zt as omitZeroAmountFutureRows, _ as EVENT_PRESET_VALUES, _r as unsafeAsEventOfferingId, ar as parseEditorSessionGeneration, bn as parseNonNegativeCents, br as unsafeAsPricingOptionId, c as planTurningOnCourses, cr as parseApiKeyId, ct as locationValueSchema, d as areConfiguredBookingVerticalConfigsEqual, en as scheduleBookingReasonCodes, f as canonicalizeConfiguredBookingVerticalConfig, ft as publicLocationSchema, g as DEFAULT_EVENT_TYPE_PRESETS, gn as fromArray, gr as unsafeAsEventInstanceId, h as resolveSiteVerticalBookingConfig, ht as trimmedStringOrNull, ir as unsafeAsOrderPaymentPlanId, l as resolveEventCatalogue, lr as parseSiteId, m as parseVerticalPresetId, mr as parseRetiredCourseId, n as OFFLINE_PAYMENT_METHODS, nn as resolveFlexibleBalanceInitialPaymentCents, nr as unsafeAsCheckoutLineId, nt as assertAllowedPublicUrl, or as parsePageId, ot as stableJsonStringify, p as parseVerticalId, pr as parseEventSeriesId, qt as addIntervalPreservingMonthAnchor, r as committedWriteProofSchema, rr as unsafeAsOrderFlexibleBalanceContractId, tn as resolveFlexibleBalanceDueAt, ur as parseUserId, vr as unsafeAsEventSeriesId, vt as formatDate, w as isPublicReadEndpoint, wn as unsafeAsNonNegativeCents, x as PUBLIC_AVAILABILITY_FRESHNESS_SECONDS, xn as parsePositiveCents, xr as err, y as SURFACE_EVENT_PRESET_VALUES, yn as isNonNegativeWholeCents$1, yr as unsafeAsOccurrenceId, zn as parseDatedOfferingCapacityHoldAuditRef, zt as resolveBookingTimeZoneId } from "./src-CVyy-M-N.mjs";
4
+ import { n as CliSdkPeerError, t as loadConfigFile } from "./load-config-CfL4ZWC8.mjs";
5
5
  import { Command } from "commander";
6
6
  import { safeParse, z } from "zod";
7
7
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -44,6 +44,7 @@ const API_ERROR_CODES = [
44
44
  "auth:token_invalid",
45
45
  "auth:forbidden",
46
46
  "auth:mfa_required",
47
+ "auth:mfa_setup_required",
47
48
  "auth:sudo_required",
48
49
  "auth:insufficient_permissions",
49
50
  "auth:impersonation_restricted",
@@ -1758,6 +1759,7 @@ const createClientArrangementSchema = z.object({
1758
1759
  /** The UI selects the next N dates from get.dates, then retains this body for retry. */
1759
1760
  const bookNextArrangementSchema = z.object({
1760
1761
  ...operation,
1762
+ confirmation: z.string().optional(),
1761
1763
  occurrenceDates: z.array(localDate).min(1).max(52).refine((values) => new Set(values).size === values.length, "Choose each date once."),
1762
1764
  bookShortfallAsOwed: z.boolean().default(false)
1763
1765
  }).strict();
@@ -1845,6 +1847,7 @@ const arrangementTimeOffSchema = z.object({
1845
1847
  startsAt: z.iso.datetime({ offset: true }),
1846
1848
  endsAt: z.iso.datetime({ offset: true }),
1847
1849
  reason: z.string().nullable(),
1850
+ deferredAppointmentIds: z.array(z.string().uuid()).max(200).optional(),
1848
1851
  selections: z.array(z.object({
1849
1852
  arrangementId: z.string().uuid(),
1850
1853
  appointmentId: z.string().uuid(),
@@ -1925,7 +1928,6 @@ const arrangementDateResultSchema = z.intersection(z.object({ occurrenceDate: lo
1925
1928
  z.object({ code: z.enum([
1926
1929
  "package_shortfall",
1927
1930
  "not_available",
1928
- "needs_recorded_return",
1929
1931
  "client_not_found"
1930
1932
  ]) }),
1931
1933
  z.object({
@@ -2214,7 +2216,11 @@ const APPOINTMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
2214
2216
  method: "DELETE",
2215
2217
  auth: "user",
2216
2218
  responseKind: "json",
2217
- errors: ["resource:not_found", "server:internal_error"]
2219
+ errors: [
2220
+ "resource:not_found",
2221
+ "resource:conflict",
2222
+ "server:internal_error"
2223
+ ]
2218
2224
  },
2219
2225
  createTeamMemberProfile: {
2220
2226
  path: "/sites/{siteId}/bookings/resources/{resourceId}/profile",
@@ -2228,6 +2234,39 @@ const APPOINTMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
2228
2234
  "server:internal_error"
2229
2235
  ]
2230
2236
  },
2237
+ resolveTeamMemberProfileEditorOwner: {
2238
+ path: "/sites/{siteId}/bookings/profile-editor/{entryId}/owner",
2239
+ method: "GET",
2240
+ auth: "user",
2241
+ responseKind: "json",
2242
+ errors: [
2243
+ "auth:forbidden",
2244
+ "resource:not_found",
2245
+ "server:internal_error"
2246
+ ]
2247
+ },
2248
+ getTeamMemberProfileContent: {
2249
+ path: "/sites/{siteId}/bookings/resources/{resourceId}/profile/{entryId}",
2250
+ method: "GET",
2251
+ auth: "user",
2252
+ responseKind: "json",
2253
+ errors: [
2254
+ "auth:forbidden",
2255
+ "resource:not_found",
2256
+ "server:internal_error"
2257
+ ]
2258
+ },
2259
+ listTeamMemberProfileContentSlots: {
2260
+ path: "/sites/{siteId}/bookings/resources/{resourceId}/profile/{entryId}/slots",
2261
+ method: "GET",
2262
+ auth: "user",
2263
+ responseKind: "json",
2264
+ errors: [
2265
+ "auth:forbidden",
2266
+ "resource:not_found",
2267
+ "server:internal_error"
2268
+ ]
2269
+ },
2231
2270
  updateTeamMemberProfilePolicy: {
2232
2271
  path: "/sites/{siteId}/bookings/resources/profile-policy",
2233
2272
  method: "PUT",
@@ -2482,6 +2521,17 @@ const APPOINTMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
2482
2521
  "server:internal_error"
2483
2522
  ]
2484
2523
  },
2524
+ previewWeeklyAvailabilityImpact: {
2525
+ path: "/sites/{siteId}/bookings/resources/{resourceId}/weekly-availability/impact",
2526
+ method: "POST",
2527
+ auth: "user",
2528
+ responseKind: "json",
2529
+ errors: [
2530
+ "validation:invalid_input",
2531
+ "resource:not_found",
2532
+ "server:internal_error"
2533
+ ]
2534
+ },
2485
2535
  setServiceSpecificAvailability: {
2486
2536
  path: "/sites/{siteId}/bookings/resources/{resourceId}/service-availability",
2487
2537
  method: "PUT",
@@ -2821,6 +2871,54 @@ const EVENT_SERIES_REGISTRATION_ENDPOINT_DEFINITIONS = defineEndpointDefinitions
2821
2871
  "server:internal_error"
2822
2872
  ]
2823
2873
  },
2874
+ listEventOfferingCombinationPrices: {
2875
+ path: "/sites/{siteId}/bookings/event-offerings/{eventOfferingId}/combination-prices",
2876
+ method: "GET",
2877
+ auth: "user",
2878
+ responseKind: "json",
2879
+ errors: [
2880
+ "validation:invalid_input",
2881
+ "auth:forbidden",
2882
+ "resource:not_found",
2883
+ "server:internal_error"
2884
+ ]
2885
+ },
2886
+ createEventOfferingCombinationPrice: {
2887
+ path: "/sites/{siteId}/bookings/event-offerings/{eventOfferingId}/combination-prices",
2888
+ method: "POST",
2889
+ auth: "user",
2890
+ responseKind: "json",
2891
+ errors: [
2892
+ "validation:invalid_input",
2893
+ "auth:forbidden",
2894
+ "resource:not_found",
2895
+ "server:internal_error"
2896
+ ]
2897
+ },
2898
+ updateEventOfferingCombinationPrice: {
2899
+ path: "/sites/{siteId}/bookings/event-offerings/{eventOfferingId}/combination-prices/{combinationPriceId}",
2900
+ method: "PUT",
2901
+ auth: "user",
2902
+ responseKind: "json",
2903
+ errors: [
2904
+ "validation:invalid_input",
2905
+ "auth:forbidden",
2906
+ "resource:not_found",
2907
+ "server:internal_error"
2908
+ ]
2909
+ },
2910
+ deleteEventOfferingCombinationPrice: {
2911
+ path: "/sites/{siteId}/bookings/event-offerings/{eventOfferingId}/combination-prices/{combinationPriceId}",
2912
+ method: "DELETE",
2913
+ auth: "user",
2914
+ responseKind: "json",
2915
+ errors: [
2916
+ "validation:invalid_input",
2917
+ "auth:forbidden",
2918
+ "resource:not_found",
2919
+ "server:internal_error"
2920
+ ]
2921
+ },
2824
2922
  deleteEventOffering: {
2825
2923
  path: "/sites/{siteId}/bookings/event-offerings/{eventOfferingId}",
2826
2924
  method: "DELETE",
@@ -3855,6 +3953,11 @@ const eventCalendarListLayoutValues = [
3855
3953
  ];
3856
3954
  const eventCalendarListLayoutCompatibleDisplayModeValues = ["combined", "list"];
3857
3955
 
3956
+ //#endregion
3957
+ //#region ../site-contracts/src/siteData/eventCheckoutTypes.ts
3958
+ /** The most dates or runs one booking request may name; the block stops ticking at the same number. */
3959
+ const MAX_EVENT_BOOKING_SELECTION_ITEMS = 20;
3960
+
3858
3961
  //#endregion
3859
3962
  //#region ../commerce/src/purchase/allocation.ts
3860
3963
  /**
@@ -3896,6 +3999,7 @@ const ORDER_STATUSES = [
3896
3999
  "failed",
3897
4000
  "cancelled"
3898
4001
  ];
4002
+ const orderStatusSchema = z.enum(ORDER_STATUSES);
3899
4003
  const orderStatusSet = new Set(ORDER_STATUSES);
3900
4004
  function isOrderStatus(value) {
3901
4005
  return orderStatusSet.has(value);
@@ -4076,173 +4180,517 @@ function getBookingLaterInstalments(schedule) {
4076
4180
  }
4077
4181
 
4078
4182
  //#endregion
4079
- //#region ../commerce/src/purchase/bookingPaymentSelection.ts
4080
- function isBookingPlanOrContractSelection(selection) {
4081
- switch (selection.kind) {
4082
- case "instalment_plan":
4083
- case "flexible_balance": return true;
4084
- case "not_required":
4085
- case "upfront":
4086
- case "deferred_manual": return false;
4087
- default: return assertNever$3(selection);
4183
+ //#region ../commerce/src/purchase/settlement.ts
4184
+ function normalizeCurrencyCode(raw) {
4185
+ const normalized = raw.trim().toUpperCase();
4186
+ if (!/^[A-Z]{3}$/.test(normalized)) {
4187
+ throw new Error(`Invalid currency code: ${raw}`);
4088
4188
  }
4189
+ return normalized;
4089
4190
  }
4090
- function isSameBookingPaymentReference(left, right) {
4091
- switch (left.kind) {
4092
- case "appointment": return right.kind === "appointment" && left.serviceId === right.serviceId && left.resourceId === right.resourceId && left.startAt === right.startAt;
4093
- case "event_ticket": return right.kind === "event_ticket" && left.occurrenceId === right.occurrenceId && isSameAttendee(left.attendee, right.attendee);
4094
- case "event_series_registration": return right.kind === "event_series_registration" && left.eventSeriesId === right.eventSeriesId && isSameAttendee(left.attendee, right.attendee);
4095
- default: return assertNever$3(left);
4096
- }
4191
+ function rebrandCents(amount) {
4192
+ return amount;
4097
4193
  }
4098
- function isSameAttendee(left, right) {
4099
- switch (left.kind) {
4100
- case "persisted": return right.kind === "persisted" && left.attendeeId === right.attendeeId;
4101
- case "checkout_command": return right.kind === "checkout_command" && left.checkoutLineId === right.checkoutLineId;
4102
- default: return assertNever$3(left);
4103
- }
4194
+ function toSubtotalCents(raw) {
4195
+ return rebrandCents(toNonNegativeCents(raw));
4104
4196
  }
4105
- /** Identity is decided against the authoritative quote, before display repricing. */
4106
- function resolveAvailableBookingCollectionOptions(input) {
4107
- const deadline = input.instalmentCollectionDeadlineAt === undefined ? input.bookingStartAt : input.instalmentCollectionDeadlineAt;
4108
- const configured = input.paymentTerms.allowedOptions;
4109
- if (!validateBookingPaymentOptionKinds(configured.map((option) => option.kind)).ok) return [];
4110
- const available = configured.filter((option) => option.kind !== "instalment_plan" || Number.isFinite(Date.parse(input.now))).map((option) => resolveBookingCollectionOptionFacts({
4111
- option,
4112
- totalCents: input.totalCents,
4113
- anchorAt: input.now,
4114
- bookingStartAt: input.bookingStartAt
4115
- })).filter((option) => option.kind !== "instalment_plan" || deadline !== null && canInstalmentPlanCompleteBefore({
4116
- now: input.now,
4117
- deadline,
4118
- schedule: option.schedule
4119
- }));
4120
- const upfront = resolveBookingCollectionOptionFacts({
4121
- option: { kind: "upfront" },
4122
- totalCents: input.totalCents,
4123
- anchorAt: input.now,
4124
- bookingStartAt: input.bookingStartAt
4125
- });
4126
- const collapsed = available.map((option) => isBookingCollectionEquivalentToUpfront(option) ? upfront : option);
4127
- const unique = collapsed.filter((option, index) => collapsed.findIndex((other) => other.kind === option.kind) === index);
4128
- return unique.length > 0 ? unique : [upfront];
4197
+ function toDiscountCents(raw) {
4198
+ return rebrandCents(toNonNegativeCents(raw));
4129
4199
  }
4130
- function isBookingCollectionEquivalentToUpfront(option) {
4131
- switch (option.kind) {
4132
- case "upfront": return true;
4133
- case "deferred_manual": return false;
4134
- case "flexible_balance": return option.config.depositRefundability === "refundable" && option.dueNowCents === option.totalCents;
4135
- case "instalment_plan": return option.depositRefundability !== "non_refundable" && option.schedule.length === 1;
4136
- default: return assertNever$3(option);
4137
- }
4200
+ function toCreditAppliedCents(raw) {
4201
+ return rebrandCents(toNonNegativeCents(raw));
4138
4202
  }
4139
- function resolveBookingCollectionOptionFacts(input) {
4140
- const money$1 = {
4141
- totalCents: input.totalCents,
4142
- anchorAt: input.anchorAt,
4143
- bookingStartAt: input.bookingStartAt
4144
- };
4145
- switch (input.option.kind) {
4146
- case "upfront": return {
4147
- ...money$1,
4148
- kind: "upfront",
4149
- dueNowCents: input.totalCents
4150
- };
4151
- case "deferred_manual": return {
4152
- ...money$1,
4153
- kind: "deferred_manual",
4154
- dueNowCents: 0
4155
- };
4156
- case "instalment_plan": {
4157
- const schedule = buildBookingInstalmentSchedule({
4158
- anchorAt: input.anchorAt,
4159
- totalAmountCents: input.totalCents,
4160
- plan: input.option.plan
4161
- });
4162
- return {
4163
- ...money$1,
4164
- kind: "instalment_plan",
4165
- plan: input.option.plan,
4166
- schedule,
4167
- dueNowCents: schedule[0]?.amountCents ?? 0,
4168
- depositRefundability: getBookingInstalmentDepositRefundability(input.option.plan)
4169
- };
4170
- }
4171
- case "flexible_balance": {
4172
- const dueNowCents = resolveFlexibleBalanceInitialPaymentCents({
4173
- totalAmountCents: input.totalCents,
4174
- config: input.option.config
4175
- });
4176
- return {
4177
- ...money$1,
4178
- kind: "flexible_balance",
4179
- config: input.option.config,
4180
- dueNowCents,
4181
- remainingBalanceCents: Math.max(0, input.totalCents - dueNowCents),
4182
- balanceDueAt: resolveFlexibleBalanceDueAt({
4183
- bookingStartAt: input.bookingStartAt ?? input.anchorAt,
4184
- dueDateRule: input.option.config.dueDateRule
4185
- })
4186
- };
4187
- }
4188
- default: return assertNever$3(input.option);
4189
- }
4203
+ function toStripeChargeCents(raw) {
4204
+ return rebrandCents(toNonNegativeCents(raw));
4190
4205
  }
4191
- /** Discounts change preview money, never an already admitted collection identity. */
4192
- function repriceBookingCollectionOptions(input) {
4193
- return input.options.map((option) => option.totalCents === input.totalCents ? option : resolveBookingCollectionOptionFacts({
4194
- option,
4195
- totalCents: input.totalCents,
4196
- anchorAt: option.anchorAt,
4197
- bookingStartAt: option.bookingStartAt
4198
- }));
4206
+ function toRefundedCents(raw) {
4207
+ return rebrandCents(toNonNegativeCents(raw));
4199
4208
  }
4200
-
4201
- //#endregion
4202
- //#region ../commerce/src/purchase/cancellationPolicy.ts
4203
- const CANCELLABLE_STATUSES = new Set([
4204
- "paid",
4205
- "partially_refunded",
4206
- "refunded",
4207
- "pending",
4208
- "failed"
4209
- ]);
4210
- /**
4211
- * Whether an order in the given status can be cancelled.
4212
- *
4213
- * `cancelled` orders cannot be cancelled again.
4214
- */
4215
- function isCancellableStatus(status) {
4216
- return CANCELLABLE_STATUSES.has(status);
4209
+ function toRefundableTotalCents(raw) {
4210
+ return rebrandCents(toNonNegativeCents(raw));
4217
4211
  }
4218
-
4219
- //#endregion
4220
- //#region ../commerce/src/purchase/checkoutCollectionPlan.ts
4221
- function buildCheckoutCollectionPlan(options) {
4222
- if (!cartRequiresShipping(options.settledCart)) {
4223
- return ok({
4224
- kind: "digital_only",
4225
- automaticTaxEnabled: options.automaticTaxEnabled,
4226
- billingAddressCollection: "auto"
4227
- });
4228
- }
4229
- const allowedShippingCountries = fromArray([...options.allowedShippingCountries]);
4230
- if (!allowedShippingCountries.ok) {
4212
+ function money(amountCents, currency) {
4213
+ return {
4214
+ amountCents: toNonNegativeCents(amountCents),
4215
+ currency
4216
+ };
4217
+ }
4218
+ function parseLineSettlementCents(lineId, raw, field) {
4219
+ const parsed = parseNonNegativeCents(raw);
4220
+ if (!parsed.ok) {
4231
4221
  return err({
4232
- _tag: "CheckoutCollectionPlanningError",
4233
- code: "shop_shipping_not_configured",
4234
- message: "SHOP_SHIPPING_NOT_CONFIGURED: Physical product checkout requires at least one allowed shipping country"
4222
+ _tag: "invalid_line_money",
4223
+ lineId,
4224
+ field,
4225
+ message: `Line ${lineId} ${field} must be a non-negative whole number of cents`
4235
4226
  });
4236
4227
  }
4237
- return ok({
4238
- kind: "requires_shipping",
4239
- automaticTaxEnabled: options.automaticTaxEnabled,
4240
- billingAddressCollection: "auto",
4241
- allowedShippingCountries: allowedShippingCountries.value
4242
- });
4243
- }
4244
- function cartRequiresShipping(settledCart) {
4245
- return settledCart.items.some((item) => item.validated.type === "product" && item.validated.product.requiresShipping);
4228
+ return parsed;
4229
+ }
4230
+ function buildLineSettlementBreakdown(options) {
4231
+ const subtotalResult = parseLineSettlementCents(options.lineId, options.subtotalCents, "subtotalCents");
4232
+ if (!subtotalResult.ok) return subtotalResult;
4233
+ const discountResult = parseLineSettlementCents(options.lineId, options.discountCents, "discountCents");
4234
+ if (!discountResult.ok) return discountResult;
4235
+ const creditAppliedResult = parseLineSettlementCents(options.lineId, options.creditAppliedCents, "creditAppliedCents");
4236
+ if (!creditAppliedResult.ok) return creditAppliedResult;
4237
+ const stripeChargeResult = parseLineSettlementCents(options.lineId, options.stripeChargeCents, "stripeChargeCents");
4238
+ if (!stripeChargeResult.ok) return stripeChargeResult;
4239
+ const subtotalCents = rebrandCents(subtotalResult.value);
4240
+ const discountCents = rebrandCents(discountResult.value);
4241
+ const creditAppliedCents = rebrandCents(creditAppliedResult.value);
4242
+ const stripeChargeCents = rebrandCents(stripeChargeResult.value);
4243
+ const expectedStripeCharge = subtotalCents - discountCents - creditAppliedCents;
4244
+ if (expectedStripeCharge < 0) {
4245
+ return err({
4246
+ _tag: "inconsistent_line_totals",
4247
+ lineId: options.lineId,
4248
+ message: `Settlement invariant failed for line ${options.lineId}: reductions exceed subtotal`
4249
+ });
4250
+ }
4251
+ if (stripeChargeCents !== expectedStripeCharge) {
4252
+ return err({
4253
+ _tag: "inconsistent_line_totals",
4254
+ lineId: options.lineId,
4255
+ message: `Settlement invariant failed for line ${options.lineId}: expected stripe charge ${expectedStripeCharge}, got ${stripeChargeCents}`
4256
+ });
4257
+ }
4258
+ return ok({
4259
+ subtotalCents,
4260
+ discountCents,
4261
+ creditAppliedCents,
4262
+ stripeChargeCents
4263
+ });
4264
+ }
4265
+ function buildRefundableLineSettlement(options) {
4266
+ const line = buildLineSettlementBreakdown(options);
4267
+ if (!line.ok) {
4268
+ return line;
4269
+ }
4270
+ const alreadyRefundedResult = parseLineSettlementCents(options.lineId, options.alreadyRefundedCents, "alreadyRefundedCents");
4271
+ if (!alreadyRefundedResult.ok) return alreadyRefundedResult;
4272
+ const refundableTotalCents = toRefundableTotalCents(line.value.creditAppliedCents + line.value.stripeChargeCents);
4273
+ const alreadyRefundedCents = rebrandCents(alreadyRefundedResult.value);
4274
+ if (alreadyRefundedCents > refundableTotalCents) {
4275
+ return err({
4276
+ _tag: "refunded_exceeds_refundable_total",
4277
+ lineId: options.lineId,
4278
+ message: `Order item ${options.lineId} refunded amount exceeds refundable total`
4279
+ });
4280
+ }
4281
+ return ok({
4282
+ line: line.value,
4283
+ refundableTotalCents,
4284
+ alreadyRefundedCents
4285
+ });
4286
+ }
4287
+ /**
4288
+ * Cash actually collected against one order line, summed from its payment
4289
+ * receipt allocations. Shared so every refundable-remainder caller measures
4290
+ * funding the same way.
4291
+ */
4292
+ function orderItemCashFundedCents(allocations, orderItemId) {
4293
+ let total = 0;
4294
+ for (const allocation of allocations) {
4295
+ if (allocation.orderItemId === orderItemId) {
4296
+ total += allocation.amountCents;
4297
+ }
4298
+ }
4299
+ return total;
4300
+ }
4301
+ /**
4302
+ * The single authority on how much of an order line is still refundable.
4303
+ *
4304
+ * Every surface that shows or enforces a refundable remainder MUST go through
4305
+ * this function. Computing it from the line's net total instead of its actual
4306
+ * funding overstates the remainder on partially collected orders, which used to
4307
+ * let the dashboard offer a refund the runtime then refused.
4308
+ */
4309
+ function orderItemRefundableRemainingCents(funding) {
4310
+ return toNonNegativeCents(funding.cashFundedCents + funding.creditAppliedCents - funding.refundedCents);
4311
+ }
4312
+ function refundableRemainingCents(settlement) {
4313
+ return orderItemRefundableRemainingCents({
4314
+ cashFundedCents: settlement.refundableTotalCents,
4315
+ creditAppliedCents: 0,
4316
+ refundedCents: settlement.alreadyRefundedCents
4317
+ });
4318
+ }
4319
+ function ensureSingleCurrency(lines) {
4320
+ if (lines.length === 0) {
4321
+ return {
4322
+ ok: false,
4323
+ reason: "empty_cart",
4324
+ currencies: []
4325
+ };
4326
+ }
4327
+ const uniqueCurrencies = Array.from(new Set(lines.map((line) => line.currency.trim().toUpperCase()))).sort();
4328
+ if (uniqueCurrencies.length !== 1) {
4329
+ return {
4330
+ ok: false,
4331
+ reason: "mixed_currency",
4332
+ currencies: uniqueCurrencies
4333
+ };
4334
+ }
4335
+ try {
4336
+ return {
4337
+ ok: true,
4338
+ currency: normalizeCurrencyCode(uniqueCurrencies[0] ?? "")
4339
+ };
4340
+ } catch {
4341
+ return {
4342
+ ok: false,
4343
+ reason: "invalid_currency",
4344
+ currencies: uniqueCurrencies
4345
+ };
4346
+ }
4347
+ }
4348
+ function allocateReductionCents(inputs, requestedCents) {
4349
+ const sanitizedInputs = inputs.map((input) => ({
4350
+ lineId: input.lineId,
4351
+ basisCents: toNonNegativeCents(input.basisCents),
4352
+ maxReducibleCents: toNonNegativeCents(input.maxReducibleCents)
4353
+ }));
4354
+ const totalReducibleCents = sanitizedInputs.reduce((sum, input) => sum + input.maxReducibleCents, 0);
4355
+ const targetCents = Math.max(0, Math.min(Math.trunc(requestedCents), totalReducibleCents));
4356
+ const allocations = sanitizedInputs.map((input) => ({
4357
+ lineId: input.lineId,
4358
+ amountCents: toNonNegativeCents(0)
4359
+ }));
4360
+ if (targetCents === 0 || sanitizedInputs.length === 0) {
4361
+ return {
4362
+ requestedCents: toNonNegativeCents(requestedCents),
4363
+ appliedCents: toNonNegativeCents(0),
4364
+ allocations
4365
+ };
4366
+ }
4367
+ const remainingCaps = sanitizedInputs.map((input) => input.maxReducibleCents);
4368
+ let remainingCents = targetCents;
4369
+ while (remainingCents > 0) {
4370
+ const eligibleIndexes = sanitizedInputs.map((input, index) => ({
4371
+ input,
4372
+ index
4373
+ })).filter(({ input, index }) => input.basisCents > 0 && (remainingCaps[index] ?? 0) > 0);
4374
+ if (eligibleIndexes.length === 0) break;
4375
+ const eligibleBasis = eligibleIndexes.reduce((sum, { input }) => sum + input.basisCents, 0);
4376
+ if (eligibleBasis <= 0) break;
4377
+ const roundCandidates = eligibleIndexes.map(({ input, index }) => {
4378
+ const exactShare = input.basisCents / eligibleBasis * remainingCents;
4379
+ const floorShare = Math.min(Math.floor(exactShare), remainingCaps[index] ?? 0);
4380
+ const remainder = exactShare - floorShare;
4381
+ return {
4382
+ index,
4383
+ floorShare,
4384
+ remainder
4385
+ };
4386
+ });
4387
+ let assignedThisRound = 0;
4388
+ for (const candidate of roundCandidates) {
4389
+ if (candidate.floorShare <= 0) continue;
4390
+ const allocation = allocations[candidate.index];
4391
+ if (!allocation) continue;
4392
+ allocation.amountCents = toNonNegativeCents(allocation.amountCents + candidate.floorShare);
4393
+ remainingCaps[candidate.index] = toNonNegativeCents((remainingCaps[candidate.index] ?? 0) - candidate.floorShare);
4394
+ assignedThisRound += candidate.floorShare;
4395
+ }
4396
+ remainingCents -= assignedThisRound;
4397
+ if (remainingCents <= 0) break;
4398
+ const remainderCandidates = roundCandidates.filter((candidate) => (remainingCaps[candidate.index] ?? 0) > 0).sort((a, b) => {
4399
+ if (b.remainder !== a.remainder) return b.remainder - a.remainder;
4400
+ return a.index - b.index;
4401
+ });
4402
+ if (remainderCandidates.length === 0) break;
4403
+ let remainderAssigned = 0;
4404
+ for (const candidate of remainderCandidates) {
4405
+ if (remainingCents <= 0) break;
4406
+ if ((remainingCaps[candidate.index] ?? 0) <= 0) continue;
4407
+ const allocation = allocations[candidate.index];
4408
+ if (!allocation) continue;
4409
+ allocation.amountCents = toNonNegativeCents(allocation.amountCents + 1);
4410
+ remainingCaps[candidate.index] = toNonNegativeCents((remainingCaps[candidate.index] ?? 0) - 1);
4411
+ remainingCents -= 1;
4412
+ remainderAssigned += 1;
4413
+ }
4414
+ if (assignedThisRound === 0 && remainderAssigned === 0) {
4415
+ break;
4416
+ }
4417
+ }
4418
+ const appliedCents = allocations.reduce((sum, allocation) => sum + allocation.amountCents, 0);
4419
+ return {
4420
+ requestedCents: toNonNegativeCents(requestedCents),
4421
+ appliedCents: toNonNegativeCents(appliedCents),
4422
+ allocations
4423
+ };
4424
+ }
4425
+ function assertSettledOrderLineInvariants(lines) {
4426
+ for (const line of lines) {
4427
+ if (line.discountCents < 0 || line.creditCents < 0 || line.netTotalCents < 0) {
4428
+ throw new Error(`Negative settlement values are not allowed for line ${line.lineId}`);
4429
+ }
4430
+ const expectedNet = line.subtotalCents - line.discountCents - line.creditCents;
4431
+ if (line.netTotalCents !== expectedNet) {
4432
+ throw new Error(`Settlement invariant failed for line ${line.lineId}: expected ${expectedNet}, got ${line.netTotalCents}`);
4433
+ }
4434
+ }
4435
+ }
4436
+
4437
+ //#endregion
4438
+ //#region ../commerce/src/purchase/stripeMinimumCharge.ts
4439
+ const STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY = {
4440
+ GBP: 30,
4441
+ USD: 50,
4442
+ EUR: 50,
4443
+ AED: 200,
4444
+ AUD: 50,
4445
+ BGN: 100,
4446
+ BRL: 50,
4447
+ CAD: 50,
4448
+ CHF: 50,
4449
+ CZK: 1500,
4450
+ DKK: 250,
4451
+ HKD: 400,
4452
+ HUF: 17500,
4453
+ JPY: 50,
4454
+ MXN: 1e3,
4455
+ MYR: 200,
4456
+ NOK: 300,
4457
+ NZD: 50,
4458
+ PLN: 200,
4459
+ RON: 200,
4460
+ SEK: 300,
4461
+ SGD: 50,
4462
+ THB: 1e3
4463
+ };
4464
+ function isStripeMinimumChargeCurrency(currency) {
4465
+ return currency in STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY;
4466
+ }
4467
+ function getStripeMinimumChargeRequirement(rawCurrency) {
4468
+ let currency;
4469
+ try {
4470
+ currency = normalizeCurrencyCode(rawCurrency);
4471
+ } catch {
4472
+ return null;
4473
+ }
4474
+ const currencyKey = currency;
4475
+ if (!isStripeMinimumChargeCurrency(currencyKey)) {
4476
+ return null;
4477
+ }
4478
+ return {
4479
+ currency,
4480
+ minimumAmountCents: STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY[currencyKey]
4481
+ };
4482
+ }
4483
+ function isStripeChargeBelowMinimum(options) {
4484
+ const requirement = getStripeMinimumChargeRequirement(options.currency);
4485
+ return Boolean(requirement && options.amountCents > 0 && options.amountCents < requirement.minimumAmountCents);
4486
+ }
4487
+ /**
4488
+ * The smallest deposit a plan that starts with one may ask for: the card
4489
+ * minimum for the currency, or any positive amount for a currency Stripe has
4490
+ * no minimum on record for.
4491
+ */
4492
+ function getInstalmentDepositMinimumCents(currency) {
4493
+ return getStripeMinimumChargeRequirement(currency)?.minimumAmountCents ?? 1;
4494
+ }
4495
+
4496
+ //#endregion
4497
+ //#region ../commerce/src/purchase/bookingPaymentSelection.ts
4498
+ function isBookingPlanOrContractSelection(selection) {
4499
+ switch (selection.kind) {
4500
+ case "instalment_plan":
4501
+ case "flexible_balance": return true;
4502
+ case "not_required":
4503
+ case "upfront":
4504
+ case "deferred_manual": return false;
4505
+ default: return assertNever$3(selection);
4506
+ }
4507
+ }
4508
+ function isSameBookingPaymentReference(left, right) {
4509
+ switch (left.kind) {
4510
+ case "appointment": return right.kind === "appointment" && left.serviceId === right.serviceId && left.resourceId === right.resourceId && left.startAt === right.startAt;
4511
+ case "event_ticket": return right.kind === "event_ticket" && left.occurrenceId === right.occurrenceId && isSameAttendee(left.attendee, right.attendee);
4512
+ case "event_series_registration": return right.kind === "event_series_registration" && left.eventSeriesId === right.eventSeriesId && isSameAttendee(left.attendee, right.attendee);
4513
+ default: return assertNever$3(left);
4514
+ }
4515
+ }
4516
+ function isSameAttendee(left, right) {
4517
+ switch (left.kind) {
4518
+ case "persisted": return right.kind === "persisted" && left.attendeeId === right.attendeeId;
4519
+ case "checkout_command": return right.kind === "checkout_command" && left.checkoutLineId === right.checkoutLineId;
4520
+ default: return assertNever$3(left);
4521
+ }
4522
+ }
4523
+ /** Identity is decided against the authoritative quote, before display repricing. */
4524
+ function resolveAvailableBookingCollectionOptions(input) {
4525
+ const deadline = input.instalmentCollectionDeadlineAt === undefined ? input.bookingStartAt : input.instalmentCollectionDeadlineAt;
4526
+ const configured = input.paymentTerms.allowedOptions;
4527
+ if (!validateBookingPaymentOptionKinds(configured.map((option) => option.kind)).ok) return [];
4528
+ const available = configured.filter((option) => option.kind !== "instalment_plan" || Number.isFinite(Date.parse(input.now))).map((option) => resolveBookingCollectionOptionFacts({
4529
+ option,
4530
+ totalCents: input.totalCents,
4531
+ anchorAt: input.now,
4532
+ bookingStartAt: input.bookingStartAt,
4533
+ timeZone: input.timeZone
4534
+ })).filter((option) => canOfferBookingCollectionOption(option, input.currency ?? "USD", deadline));
4535
+ const upfront = resolveBookingCollectionOptionFacts({
4536
+ option: { kind: "upfront" },
4537
+ totalCents: input.totalCents,
4538
+ anchorAt: input.now,
4539
+ bookingStartAt: input.bookingStartAt,
4540
+ timeZone: input.timeZone
4541
+ });
4542
+ const collapsed = available.map((option) => isBookingCollectionEquivalentToUpfront(option) ? upfront : option);
4543
+ const unique = collapsed.filter((option, index) => collapsed.findIndex((other) => other.kind === option.kind) === index);
4544
+ return unique.length > 0 ? unique : [upfront];
4545
+ }
4546
+ function isBookingCollectionEquivalentToUpfront(option) {
4547
+ switch (option.kind) {
4548
+ case "upfront": return true;
4549
+ case "deferred_manual": return false;
4550
+ case "flexible_balance": return option.config.depositRefundability === "refundable" && option.dueNowCents === option.totalCents;
4551
+ case "instalment_plan": return option.depositRefundability !== "non_refundable" && option.schedule.length === 1;
4552
+ default: return assertNever$3(option);
4553
+ }
4554
+ }
4555
+ function resolveBookingCollectionOptionFacts(input) {
4556
+ const money$1 = {
4557
+ totalCents: input.totalCents,
4558
+ anchorAt: input.anchorAt,
4559
+ bookingStartAt: input.bookingStartAt,
4560
+ timeZone: input.timeZone ?? "UTC"
4561
+ };
4562
+ switch (input.option.kind) {
4563
+ case "upfront": return {
4564
+ ...money$1,
4565
+ kind: "upfront",
4566
+ dueNowCents: input.totalCents
4567
+ };
4568
+ case "deferred_manual": return {
4569
+ ...money$1,
4570
+ kind: "deferred_manual",
4571
+ dueNowCents: 0
4572
+ };
4573
+ case "instalment_plan": {
4574
+ const schedule = buildBookingInstalmentSchedule({
4575
+ anchorAt: input.anchorAt,
4576
+ totalAmountCents: input.totalCents,
4577
+ plan: input.option.plan
4578
+ });
4579
+ return {
4580
+ ...money$1,
4581
+ kind: "instalment_plan",
4582
+ plan: input.option.plan,
4583
+ schedule,
4584
+ dueNowCents: schedule[0]?.amountCents ?? 0,
4585
+ depositRefundability: getBookingInstalmentDepositRefundability(input.option.plan)
4586
+ };
4587
+ }
4588
+ case "flexible_balance": {
4589
+ const dueNowCents = resolveFlexibleBalanceInitialPaymentCents({
4590
+ totalAmountCents: input.totalCents,
4591
+ config: input.option.config
4592
+ });
4593
+ return {
4594
+ ...money$1,
4595
+ kind: "flexible_balance",
4596
+ config: input.option.config,
4597
+ dueNowCents,
4598
+ remainingBalanceCents: Math.max(0, input.totalCents - dueNowCents),
4599
+ balanceDueDay: flexibleBalanceDueDay(input.option.config, input.bookingStartAt ?? input.anchorAt, money$1.timeZone)
4600
+ };
4601
+ }
4602
+ default: return assertNever$3(input.option);
4603
+ }
4604
+ }
4605
+ /** Discounts change preview money, never an already admitted collection identity. */
4606
+ function repriceBookingCollectionOptions(input) {
4607
+ const repriced = input.options.map((option) => option.totalCents === input.totalCents ? option : resolveBookingCollectionOptionFacts({
4608
+ option,
4609
+ totalCents: input.totalCents,
4610
+ anchorAt: option.anchorAt,
4611
+ bookingStartAt: option.bookingStartAt,
4612
+ timeZone: option.timeZone
4613
+ }));
4614
+ const available = repriced.filter((option) => canOfferBookingCollectionOption(option, input.currency, input.instalmentCollectionDeadlineAt));
4615
+ const first = repriced[0];
4616
+ return available.length > 0 || !first ? available : [resolveBookingCollectionOptionFacts({
4617
+ option: { kind: "upfront" },
4618
+ totalCents: input.totalCents,
4619
+ anchorAt: first.anchorAt,
4620
+ bookingStartAt: first.bookingStartAt,
4621
+ timeZone: first.timeZone
4622
+ })];
4623
+ }
4624
+ /** The same admission is used for the offer and the submitted selection. */
4625
+ function canOfferBookingCollectionOption(option, currency, deadline = option.bookingStartAt) {
4626
+ if (option.kind === "upfront" || option.kind === "deferred_manual") return true;
4627
+ const window$1 = bookingCollectionWindow(option);
4628
+ if (!window$1) return false;
4629
+ const { now, start } = window$1;
4630
+ if (option.kind === "flexible_balance") {
4631
+ return flexibleBalanceCanBeCollected(option, currency, now, start);
4632
+ }
4633
+ return deadline !== null && canInstalmentPlanCompleteBefore({
4634
+ now: option.anchorAt,
4635
+ deadline,
4636
+ schedule: option.schedule
4637
+ }) && laterInstalmentsCanBeCollected(option, currency, now);
4638
+ }
4639
+ function laterInstalmentsCanBeCollected(option, currency, now) {
4640
+ return option.schedule.filter((row) => row.stateAtBooking === "scheduled").every((row) => Date.parse(row.dueAt) > now && !isStripeChargeBelowMinimum({
4641
+ amountCents: row.amountCents,
4642
+ currency
4643
+ }));
4644
+ }
4645
+ function flexibleBalanceCanBeCollected(option, currency, now, start) {
4646
+ const today = formatLocalScheduleDate(getLocalScheduleDate(new Date(now), option.timeZone));
4647
+ const startDay = formatLocalScheduleDate(getLocalScheduleDate(new Date(start), option.timeZone));
4648
+ return option.balanceDueDay >= today && option.balanceDueDay < startDay && !isStripeChargeBelowMinimum({
4649
+ amountCents: option.remainingBalanceCents,
4650
+ currency
4651
+ });
4652
+ }
4653
+ function bookingCollectionWindow(option) {
4654
+ const now = Date.parse(option.anchorAt);
4655
+ const start = Date.parse(option.bookingStartAt ?? "");
4656
+ return Number.isFinite(now) && Number.isFinite(start) && start > now ? {
4657
+ now,
4658
+ start
4659
+ } : null;
4660
+ }
4661
+ /** Mirrors private.flexible_balance_due_day: fixed civil date, or local start minus calendar days. */
4662
+ function flexibleBalanceDueDay(config, bookingStartAt, timeZone) {
4663
+ const rule = config.dueDateRule;
4664
+ return formatLocalScheduleDate(rule.kind === "fixed_calendar_date" ? parseBookingLocalDate(rule.dueAt.slice(0, 10)) : addLocalScheduleDays(getLocalScheduleDate(new Date(bookingStartAt), timeZone), -rule.daysBeforeStart));
4665
+ }
4666
+
4667
+ //#endregion
4668
+ //#region ../commerce/src/purchase/checkoutCollectionPlan.ts
4669
+ function buildCheckoutCollectionPlan(options) {
4670
+ if (!cartRequiresShipping(options.settledCart)) {
4671
+ return ok({
4672
+ kind: "digital_only",
4673
+ automaticTaxEnabled: options.automaticTaxEnabled,
4674
+ billingAddressCollection: "auto"
4675
+ });
4676
+ }
4677
+ const allowedShippingCountries = fromArray([...options.allowedShippingCountries]);
4678
+ if (!allowedShippingCountries.ok) {
4679
+ return err({
4680
+ _tag: "CheckoutCollectionPlanningError",
4681
+ code: "shop_shipping_not_configured",
4682
+ message: "SHOP_SHIPPING_NOT_CONFIGURED: Physical product checkout requires at least one allowed shipping country"
4683
+ });
4684
+ }
4685
+ return ok({
4686
+ kind: "requires_shipping",
4687
+ automaticTaxEnabled: options.automaticTaxEnabled,
4688
+ billingAddressCollection: "auto",
4689
+ allowedShippingCountries: allowedShippingCountries.value
4690
+ });
4691
+ }
4692
+ function cartRequiresShipping(settledCart) {
4693
+ return settledCart.items.some((item) => item.validated.type === "product" && item.validated.product.requiresShipping);
4246
4694
  }
4247
4695
 
4248
4696
  //#endregion
@@ -4391,13 +4839,14 @@ function formatUnexpectedValue(value) {
4391
4839
 
4392
4840
  //#endregion
4393
4841
  //#region ../commerce/src/purchase/checkoutDiscountContextPlanning.ts
4842
+ /** Group ticket lines within a date, keeping places per booking rather than adding dates. */
4394
4843
  function collectCheckoutDiscountContexts(items) {
4395
4844
  const contextsByIdentity = items.reduce((map, item) => {
4396
- const candidate = toCheckoutDiscountContextCandidate(item.validated);
4845
+ const candidate = toCheckoutDiscountContextCandidate(item);
4397
4846
  const existing = map.get(candidate.identityKey);
4398
4847
  const nextEntry = existing ? {
4399
4848
  identityKey: candidate.identityKey,
4400
- context: mergeCheckoutDiscountContexts(existing.context, candidate.context),
4849
+ context: mergeBookingDiscountContext(existing.context, candidate.context),
4401
4850
  subtotalCents: existing.subtotalCents + item.subtotalCents,
4402
4851
  lineIds: [...existing.lineIds, item.lineId]
4403
4852
  } : {
@@ -4420,7 +4869,7 @@ function collectCheckoutDiscountContexts(items) {
4420
4869
  function subtotalForCheckoutDiscountContexts(applicableContexts) {
4421
4870
  return applicableContexts.reduce((sum, entry) => sum + entry.subtotalCents, 0);
4422
4871
  }
4423
- function rankCheckoutAutoDiscountCandidates(candidates) {
4872
+ function rankCheckoutAutoDiscountCandidates(candidates, options = { includeZeroDiscounts: false }) {
4424
4873
  return candidates.map((candidate) => {
4425
4874
  const subtotalCents = subtotalForCheckoutDiscountContexts(candidate.applicableContexts);
4426
4875
  return {
@@ -4433,23 +4882,34 @@ function rankCheckoutAutoDiscountCandidates(candidates) {
4433
4882
  subtotalCents: toNonNegativeCents(subtotalCents)
4434
4883
  })
4435
4884
  };
4436
- }).filter((candidate) => candidate.computedDiscountCents > 0).sort((a, b) => {
4885
+ }).filter((candidate) => options.includeZeroDiscounts || candidate.computedDiscountCents > 0).sort((a, b) => {
4886
+ if (options.pricedTotalCents) {
4887
+ return options.pricedTotalCents(a) - options.pricedTotalCents(b) || a.code.id.localeCompare(b.code.id);
4888
+ }
4437
4889
  if (b.computedDiscountCents !== a.computedDiscountCents) {
4438
4890
  return b.computedDiscountCents - a.computedDiscountCents;
4439
4891
  }
4440
4892
  return a.code.id.localeCompare(b.code.id);
4441
4893
  });
4442
4894
  }
4443
- function toCheckoutDiscountContextCandidate(source) {
4444
- const context = checkoutDiscountContext(source);
4895
+ function toCheckoutDiscountContextCandidate(item) {
4896
+ const context = checkoutDiscountContext(item.validated);
4897
+ const bookingId = item.validated.type === "event_ticket" ? item.validated.occurrenceId ?? item.lineId : item.lineId;
4445
4898
  return {
4446
- identityKey: checkoutDiscountContextIdentity(context),
4899
+ identityKey: checkoutDiscountContextIdentity(context, bookingId),
4447
4900
  context
4448
4901
  };
4449
4902
  }
4450
- function checkoutDiscountContextIdentity(context) {
4903
+ /** Price lines in the same booking (one date, or one run) add up their places; separate bookings never do. */
4904
+ function mergeBookingDiscountContext(existing, next) {
4905
+ return existing.type === "event" && next.type === "event" || existing.type === "whole_series" && next.type === "whole_series" ? {
4906
+ ...existing,
4907
+ ticketsCount: (existing.ticketsCount ?? 0) + (next.ticketsCount ?? 0)
4908
+ } : existing;
4909
+ }
4910
+ function checkoutDiscountContextIdentity(context, bookingId) {
4451
4911
  switch (context.type) {
4452
- case "event": return `event:${context.eventSeriesId}`;
4912
+ case "event": return `event:${context.eventSeriesId}:${bookingId}`;
4453
4913
  case "whole_series": return `whole-series:${context.eventSeriesId}`;
4454
4914
  case "product": return `product:${context.productId}`;
4455
4915
  case "pass": return `pass:${context.passId}`;
@@ -4461,12 +4921,14 @@ function checkoutDiscountContext(source) {
4461
4921
  case "event_ticket": return {
4462
4922
  type: "event",
4463
4923
  eventSeriesId: source.eventSeries.id,
4924
+ eventOfferingId: source.eventSeries.eventOfferingId,
4464
4925
  eventCategoryId: source.eventSeries.eventCategoryId,
4465
4926
  ticketsCount: source.ticketCount
4466
4927
  };
4467
4928
  case "whole_series_enrollment": return {
4468
4929
  type: "whole_series",
4469
4930
  eventSeriesId: source.eventSeries.id,
4931
+ eventOfferingId: source.eventSeries.eventOfferingId,
4470
4932
  eventCategoryId: source.eventSeries.eventCategoryId,
4471
4933
  ticketsCount: source.participantCount
4472
4934
  };
@@ -4485,491 +4947,228 @@ function checkoutDiscountContext(source) {
4485
4947
  };
4486
4948
  }
4487
4949
  }
4488
- function mergeCheckoutDiscountContexts(existing, next) {
4489
- if (existing.type === "event" && next.type === "event" || existing.type === "whole_series" && next.type === "whole_series") {
4490
- return {
4491
- ...existing,
4492
- ticketsCount: (existing.ticketsCount ?? 0) + (next.ticketsCount ?? 0)
4493
- };
4494
- }
4495
- return existing;
4496
- }
4497
4950
  function computeCheckoutDiscountCents(options) {
4498
4951
  const subtotal = options.subtotalCents;
4499
4952
  if (subtotal === 0) return toNonNegativeCents(0);
4500
4953
  if (options.discountType === "fixed") {
4501
- return toNonNegativeCents(Math.min(subtotal, options.discountAmountCents ?? 0));
4502
- }
4503
- const pct = Math.max(0, Math.min(100, options.discountPercent ?? 0));
4504
- return toNonNegativeCents(Math.min(subtotal, Math.floor(subtotal * pct / 100)));
4505
- }
4506
-
4507
- //#endregion
4508
- //#region ../commerce/src/purchase/checkoutOrderItemProjection.ts
4509
- function projectCheckoutOrderItemMoney(input) {
4510
- return {
4511
- lineKey: input.lineId,
4512
- unitPriceCents: input.unitPriceCents,
4513
- quantity: input.quantity,
4514
- subtotalCents: input.settlement.subtotalCents,
4515
- discountCents: input.settlement.discountCents,
4516
- creditCents: input.settlement.creditAppliedCents,
4517
- netTotalCents: input.settlement.stripeChargeCents,
4518
- totalCents: input.settlement.stripeChargeCents,
4519
- refundedCents: 0
4520
- };
4521
- }
4522
-
4523
- //#endregion
4524
- //#region ../commerce/src/purchase/checkoutPaymentFlow.ts
4525
- function planCheckoutPaymentFlow(options) {
4526
- const amountDueCents = toNonNegativeCents(options.amountDueCents);
4527
- const discountCents = toNonNegativeCents(options.discountCents);
4528
- const availableCreditCents = toNonNegativeCents(options.availableCreditCents);
4529
- const minimumStripeChargeCents = toNonNegativeCents(options.minimumStripeChargeCents ?? 0);
4530
- if (amountDueCents <= 0) {
4531
- return {
4532
- kind: "bypass",
4533
- bypassReason: discountCents > 0 ? "discount_free" : "free",
4534
- reserveCreditCents: 0
4535
- };
4536
- }
4537
- if (!options.creditCurrencyMatches || availableCreditCents <= 0) {
4538
- return {
4539
- kind: "stripe",
4540
- reserveCreditCents: toNonNegativeCents(0)
4541
- };
4542
- }
4543
- if (availableCreditCents >= amountDueCents) {
4544
- return {
4545
- kind: "store_credit_only",
4546
- reserveCreditCents: amountDueCents
4547
- };
4548
- }
4549
- const reserveCreditCents = planMixedPaymentCreditReservation({
4550
- amountDueCents,
4551
- availableCreditCents,
4552
- minimumStripeChargeCents
4553
- });
4554
- return {
4555
- kind: "stripe",
4556
- reserveCreditCents
4557
- };
4558
- }
4559
- function planMixedPaymentCreditReservation(input) {
4560
- const chargeAfterFullCredit = input.amountDueCents - input.availableCreditCents;
4561
- if (input.minimumStripeChargeCents <= 0 || chargeAfterFullCredit <= 0 || chargeAfterFullCredit >= input.minimumStripeChargeCents) {
4562
- return input.availableCreditCents;
4563
- }
4564
- if (input.amountDueCents < input.minimumStripeChargeCents) {
4565
- return toNonNegativeCents(0);
4566
- }
4567
- return toNonNegativeCents(input.amountDueCents - input.minimumStripeChargeCents);
4568
- }
4569
- /**
4570
- * Apply site credit to a flexible-balance booking before card payment.
4571
- *
4572
- * Credit first reduces the configured payment due now. Once that payment is
4573
- * covered, any remaining credit reduces the later balance. If a partial credit
4574
- * application would leave a positive card charge below Stripe's minimum, less
4575
- * credit is used so the configured payment can still be collected.
4576
- */
4577
- function planFlexibleBalanceCreditFirst(input) {
4578
- const totalCents = toNonNegativeCents(input.totalAfterDiscountCents);
4579
- const configuredDueNowCents = toNonNegativeCents(Math.min(input.configuredPaymentDueNowCents, totalCents));
4580
- const availableCreditCents = toNonNegativeCents(input.creditCurrencyMatches ? input.availableCreditCents : 0);
4581
- const minimumStripeChargeCents = toNonNegativeCents(input.minimumStripeChargeCents ?? 0);
4582
- if (availableCreditCents >= totalCents && totalCents > 0) {
4583
- return {
4584
- kind: "credit_only",
4585
- reserveCreditCents: totalCents,
4586
- cardDueNowCents: toNonNegativeCents(0),
4587
- laterBalanceCents: toNonNegativeCents(0)
4588
- };
4589
- }
4590
- let reserveCreditCents = toNonNegativeCents(Math.min(availableCreditCents, totalCents));
4591
- if (reserveCreditCents >= configuredDueNowCents) {
4592
- return {
4593
- kind: "flexible_balance",
4594
- reserveCreditCents,
4595
- cardDueNowCents: toNonNegativeCents(0),
4596
- laterBalanceCents: toNonNegativeCents(totalCents - reserveCreditCents)
4597
- };
4598
- }
4599
- const plannedCardDueNowCents = toNonNegativeCents(configuredDueNowCents - reserveCreditCents);
4600
- if (plannedCardDueNowCents > 0 && plannedCardDueNowCents < minimumStripeChargeCents) {
4601
- if (configuredDueNowCents < minimumStripeChargeCents) {
4602
- return {
4603
- kind: "card_below_minimum",
4604
- reserveCreditCents: toNonNegativeCents(0),
4605
- cardDueNowCents: configuredDueNowCents,
4606
- laterBalanceCents: toNonNegativeCents(totalCents - configuredDueNowCents)
4607
- };
4608
- }
4609
- reserveCreditCents = toNonNegativeCents(configuredDueNowCents - minimumStripeChargeCents);
4610
- }
4611
- const cardDueNowCents = toNonNegativeCents(configuredDueNowCents - reserveCreditCents);
4612
- return {
4613
- kind: "flexible_balance",
4614
- reserveCreditCents,
4615
- cardDueNowCents,
4616
- laterBalanceCents: toNonNegativeCents(totalCents - reserveCreditCents - cardDueNowCents)
4617
- };
4618
- }
4619
-
4620
- //#endregion
4621
- //#region ../commerce/src/purchase/checkoutPaymentPlanPlanning.ts
4622
- function planCheckoutPaymentObligation(input) {
4623
- const selection = input.paymentSelection;
4624
- switch (selection.kind) {
4625
- case "instalment_plan": return {
4626
- kind: "instalment_plan",
4627
- planDefinition: selection.plan
4628
- };
4629
- case "flexible_balance": return {
4630
- kind: "flexible_balance",
4631
- config: selection.config,
4632
- configuredPaymentDueNowCents: resolveFlexibleBalanceInitialPaymentCents({
4633
- totalAmountCents: input.totalAfterDiscountCents,
4634
- config: selection.config
4635
- }),
4636
- bookingStartAt: selection.bookingStartAt,
4637
- dueAt: resolveFlexibleBalanceDueAt({
4638
- bookingStartAt: selection.bookingStartAt,
4639
- dueDateRule: selection.config.dueDateRule
4640
- })
4641
- };
4642
- case "deferred_manual": return { kind: "deferred_manual" };
4643
- case "upfront":
4644
- case "not_required": return { kind: "stripe" };
4645
- default: return assertNever$3(selection);
4646
- }
4647
- }
4648
-
4649
- //#endregion
4650
- //#region ../commerce/src/purchase/checkoutPaymentTerms.ts
4651
- /**
4652
- * Resolves the one payment selection the whole checkout is paid with.
4653
- *
4654
- * A plan or contract only applies when the customer asked for it, and every
4655
- * line has to belong to the booking it collects for. Without a request the
4656
- * checkout pays whatever is due in full, even when a line's terms offered only
4657
- * a plan: that auto-selection stays on the line and isn't applied here.
4658
- */
4659
- function resolveCheckoutPaymentTerms(input) {
4660
- switch (input.requestedCollectionOptionKind) {
4661
- case "instalment_plan": return resolveInstalmentPlanSelection(input.items);
4662
- case "flexible_balance": return resolveFlexibleBalanceSelection(input.items);
4663
- case "upfront":
4664
- case "deferred_manual": return ok({ kind: input.requestedCollectionOptionKind });
4665
- case undefined: return ok(input.items.every(isNotRequiredBookingLine) ? { kind: "not_required" } : { kind: "upfront" });
4666
- }
4667
- }
4668
- /** Checks an already resolved selection without choosing the payment option again. */
4669
- function validateCheckoutPaymentSelection(selection, items) {
4670
- switch (selection.kind) {
4671
- case "instalment_plan": return items.length > 0 && items.every((item) => belongsToSelectionBooking(item, selection)) ? ok(selection) : err({ _tag: "instalment_plan_not_supported" });
4672
- case "flexible_balance":
4673
- if (items.length === 0) return err({ _tag: "flexible_balance_empty_cart" });
4674
- return items.every((item) => belongsToSelectionBooking(item, selection)) ? ok(selection) : err({ _tag: "flexible_balance_not_supported" });
4675
- case "upfront":
4676
- case "deferred_manual":
4677
- case "not_required": return ok(selection);
4678
- default: return assertNever$3(selection);
4679
- }
4680
- }
4681
- function resolveInstalmentPlanSelection(items) {
4682
- const selection = findSelectionCoveringEveryLine(items);
4683
- return selection?.kind === "instalment_plan" ? validateCheckoutPaymentSelection(selection, items) : err({ _tag: "instalment_plan_not_supported" });
4684
- }
4685
- function resolveFlexibleBalanceSelection(items) {
4686
- if (items.length === 0) return err({ _tag: "flexible_balance_empty_cart" });
4687
- const selection = findSelectionCoveringEveryLine(items);
4688
- return selection?.kind === "flexible_balance" ? validateCheckoutPaymentSelection(selection, items) : err({ _tag: "flexible_balance_not_supported" });
4689
- }
4690
- function findSelectionCoveringEveryLine(items) {
4691
- const [firstItem] = items;
4692
- if (firstItem?.kind !== "booking" || !isBookingPlanOrContractSelection(firstItem.selection)) {
4693
- return null;
4694
- }
4695
- const selection = firstItem.selection;
4696
- return items.every((item) => belongsToSelectionBooking(item, selection)) ? selection : null;
4697
- }
4698
- function belongsToSelectionBooking(item, selection) {
4699
- return item.kind === "booking" && isBookingPlanOrContractSelection(item.selection) && item.selection.kind === selection.kind && isSameBookingPaymentReference(item.selection.booking, selection.booking);
4700
- }
4701
- function isNotRequiredBookingLine(item) {
4702
- return item.kind === "booking" && item.selection.kind === "not_required";
4703
- }
4704
-
4705
- //#endregion
4706
- //#region ../commerce/src/purchase/checkoutQuantity.ts
4707
- function parsePositiveCheckoutQuantity(quantity) {
4708
- if (!Number.isInteger(quantity) || quantity <= 0) {
4709
- return err({
4710
- kind: "not_positive_whole_quantity",
4711
- quantity
4712
- });
4954
+ return toNonNegativeCents(Math.min(subtotal, options.discountAmountCents ?? 0));
4713
4955
  }
4714
- return ok(quantity);
4715
- }
4716
- function unsafeAsPositiveCheckoutQuantity(quantity) {
4717
- return quantity;
4956
+ const pct = Math.max(0, Math.min(100, options.discountPercent ?? 0));
4957
+ return toNonNegativeCents(Math.min(subtotal, Math.floor(subtotal * pct / 100)));
4718
4958
  }
4719
4959
 
4720
4960
  //#endregion
4721
- //#region ../commerce/src/purchase/settlement.ts
4722
- function normalizeCurrencyCode(raw) {
4723
- const normalized = raw.trim().toUpperCase();
4724
- if (!/^[A-Z]{3}$/.test(normalized)) {
4725
- throw new Error(`Invalid currency code: ${raw}`);
4726
- }
4727
- return normalized;
4728
- }
4729
- function rebrandCents(amount) {
4730
- return amount;
4731
- }
4732
- function toSubtotalCents(raw) {
4733
- return rebrandCents(toNonNegativeCents(raw));
4734
- }
4735
- function toDiscountCents(raw) {
4736
- return rebrandCents(toNonNegativeCents(raw));
4737
- }
4738
- function toCreditAppliedCents(raw) {
4739
- return rebrandCents(toNonNegativeCents(raw));
4740
- }
4741
- function toStripeChargeCents(raw) {
4742
- return rebrandCents(toNonNegativeCents(raw));
4743
- }
4744
- function toRefundedCents(raw) {
4745
- return rebrandCents(toNonNegativeCents(raw));
4746
- }
4747
- function toRefundableTotalCents(raw) {
4748
- return rebrandCents(toNonNegativeCents(raw));
4749
- }
4750
- function money(amountCents, currency) {
4961
+ //#region ../commerce/src/purchase/checkoutOrderItemProjection.ts
4962
+ function projectCheckoutOrderItemMoney(input) {
4751
4963
  return {
4752
- amountCents: toNonNegativeCents(amountCents),
4753
- currency
4964
+ lineKey: input.lineId,
4965
+ unitPriceCents: input.unitPriceCents,
4966
+ quantity: input.quantity,
4967
+ subtotalCents: input.settlement.subtotalCents,
4968
+ discountCents: input.settlement.discountCents,
4969
+ creditCents: input.settlement.creditAppliedCents,
4970
+ netTotalCents: input.settlement.stripeChargeCents,
4971
+ totalCents: input.settlement.stripeChargeCents,
4972
+ refundedCents: 0
4754
4973
  };
4755
4974
  }
4756
- function parseLineSettlementCents(lineId, raw, field) {
4757
- const parsed = parseNonNegativeCents(raw);
4758
- if (!parsed.ok) {
4759
- return err({
4760
- _tag: "invalid_line_money",
4761
- lineId,
4762
- field,
4763
- message: `Line ${lineId} ${field} must be a non-negative whole number of cents`
4764
- });
4975
+
4976
+ //#endregion
4977
+ //#region ../commerce/src/purchase/checkoutPaymentFlow.ts
4978
+ function planCheckoutPaymentFlow(options) {
4979
+ const amountDueCents = toNonNegativeCents(options.amountDueCents);
4980
+ const discountCents = toNonNegativeCents(options.discountCents);
4981
+ const availableCreditCents = toNonNegativeCents(options.availableCreditCents);
4982
+ const minimumStripeChargeCents = toNonNegativeCents(options.minimumStripeChargeCents ?? 0);
4983
+ if (amountDueCents <= 0) {
4984
+ return {
4985
+ kind: "bypass",
4986
+ bypassReason: discountCents > 0 ? "discount_free" : "free",
4987
+ reserveCreditCents: 0
4988
+ };
4765
4989
  }
4766
- return parsed;
4767
- }
4768
- function buildLineSettlementBreakdown(options) {
4769
- const subtotalResult = parseLineSettlementCents(options.lineId, options.subtotalCents, "subtotalCents");
4770
- if (!subtotalResult.ok) return subtotalResult;
4771
- const discountResult = parseLineSettlementCents(options.lineId, options.discountCents, "discountCents");
4772
- if (!discountResult.ok) return discountResult;
4773
- const creditAppliedResult = parseLineSettlementCents(options.lineId, options.creditAppliedCents, "creditAppliedCents");
4774
- if (!creditAppliedResult.ok) return creditAppliedResult;
4775
- const stripeChargeResult = parseLineSettlementCents(options.lineId, options.stripeChargeCents, "stripeChargeCents");
4776
- if (!stripeChargeResult.ok) return stripeChargeResult;
4777
- const subtotalCents = rebrandCents(subtotalResult.value);
4778
- const discountCents = rebrandCents(discountResult.value);
4779
- const creditAppliedCents = rebrandCents(creditAppliedResult.value);
4780
- const stripeChargeCents = rebrandCents(stripeChargeResult.value);
4781
- const expectedStripeCharge = subtotalCents - discountCents - creditAppliedCents;
4782
- if (expectedStripeCharge < 0) {
4783
- return err({
4784
- _tag: "inconsistent_line_totals",
4785
- lineId: options.lineId,
4786
- message: `Settlement invariant failed for line ${options.lineId}: reductions exceed subtotal`
4787
- });
4990
+ if (!options.creditCurrencyMatches || availableCreditCents <= 0) {
4991
+ return {
4992
+ kind: "stripe",
4993
+ reserveCreditCents: toNonNegativeCents(0)
4994
+ };
4788
4995
  }
4789
- if (stripeChargeCents !== expectedStripeCharge) {
4790
- return err({
4791
- _tag: "inconsistent_line_totals",
4792
- lineId: options.lineId,
4793
- message: `Settlement invariant failed for line ${options.lineId}: expected stripe charge ${expectedStripeCharge}, got ${stripeChargeCents}`
4794
- });
4996
+ if (availableCreditCents >= amountDueCents) {
4997
+ return {
4998
+ kind: "store_credit_only",
4999
+ reserveCreditCents: amountDueCents
5000
+ };
4795
5001
  }
4796
- return ok({
4797
- subtotalCents,
4798
- discountCents,
4799
- creditAppliedCents,
4800
- stripeChargeCents
5002
+ const reserveCreditCents = planMixedPaymentCreditReservation({
5003
+ amountDueCents,
5004
+ availableCreditCents,
5005
+ minimumStripeChargeCents
4801
5006
  });
5007
+ return {
5008
+ kind: "stripe",
5009
+ reserveCreditCents
5010
+ };
4802
5011
  }
4803
- function buildRefundableLineSettlement(options) {
4804
- const line = buildLineSettlementBreakdown(options);
4805
- if (!line.ok) {
4806
- return line;
4807
- }
4808
- const alreadyRefundedResult = parseLineSettlementCents(options.lineId, options.alreadyRefundedCents, "alreadyRefundedCents");
4809
- if (!alreadyRefundedResult.ok) return alreadyRefundedResult;
4810
- const refundableTotalCents = toRefundableTotalCents(line.value.creditAppliedCents + line.value.stripeChargeCents);
4811
- const alreadyRefundedCents = rebrandCents(alreadyRefundedResult.value);
4812
- if (alreadyRefundedCents > refundableTotalCents) {
4813
- return err({
4814
- _tag: "refunded_exceeds_refundable_total",
4815
- lineId: options.lineId,
4816
- message: `Order item ${options.lineId} refunded amount exceeds refundable total`
4817
- });
5012
+ function planMixedPaymentCreditReservation(input) {
5013
+ const chargeAfterFullCredit = input.amountDueCents - input.availableCreditCents;
5014
+ if (input.minimumStripeChargeCents <= 0 || chargeAfterFullCredit <= 0 || chargeAfterFullCredit >= input.minimumStripeChargeCents) {
5015
+ return input.availableCreditCents;
4818
5016
  }
4819
- return ok({
4820
- line: line.value,
4821
- refundableTotalCents,
4822
- alreadyRefundedCents
4823
- });
4824
- }
4825
- /**
4826
- * Cash actually collected against one order line, summed from its payment
4827
- * receipt allocations. Shared so every refundable-remainder caller measures
4828
- * funding the same way.
4829
- */
4830
- function orderItemCashFundedCents(allocations, orderItemId) {
4831
- let total = 0;
4832
- for (const allocation of allocations) {
4833
- if (allocation.orderItemId === orderItemId) {
4834
- total += allocation.amountCents;
4835
- }
5017
+ if (input.amountDueCents < input.minimumStripeChargeCents) {
5018
+ return toNonNegativeCents(0);
4836
5019
  }
4837
- return total;
5020
+ return toNonNegativeCents(input.amountDueCents - input.minimumStripeChargeCents);
4838
5021
  }
4839
5022
  /**
4840
- * The single authority on how much of an order line is still refundable.
5023
+ * Apply site credit to a flexible-balance booking before card payment.
4841
5024
  *
4842
- * Every surface that shows or enforces a refundable remainder MUST go through
4843
- * this function. Computing it from the line's net total instead of its actual
4844
- * funding overstates the remainder on partially collected orders, which used to
4845
- * let the dashboard offer a refund the runtime then refused.
5025
+ * Credit first reduces the configured payment due now. Once that payment is
5026
+ * covered, any remaining credit reduces the later balance. If a partial credit
5027
+ * application would leave a positive card charge below Stripe's minimum, less
5028
+ * credit is used so the configured payment can still be collected.
4846
5029
  */
4847
- function orderItemRefundableRemainingCents(funding) {
4848
- return toNonNegativeCents(funding.cashFundedCents + funding.creditAppliedCents - funding.refundedCents);
4849
- }
4850
- function refundableRemainingCents(settlement) {
4851
- return orderItemRefundableRemainingCents({
4852
- cashFundedCents: settlement.refundableTotalCents,
4853
- creditAppliedCents: 0,
4854
- refundedCents: settlement.alreadyRefundedCents
4855
- });
4856
- }
4857
- function ensureSingleCurrency(lines) {
4858
- if (lines.length === 0) {
4859
- return {
4860
- ok: false,
4861
- reason: "empty_cart",
4862
- currencies: []
4863
- };
4864
- }
4865
- const uniqueCurrencies = Array.from(new Set(lines.map((line) => line.currency.trim().toUpperCase()))).sort();
4866
- if (uniqueCurrencies.length !== 1) {
4867
- return {
4868
- ok: false,
4869
- reason: "mixed_currency",
4870
- currencies: uniqueCurrencies
4871
- };
4872
- }
4873
- try {
4874
- return {
4875
- ok: true,
4876
- currency: normalizeCurrencyCode(uniqueCurrencies[0] ?? "")
4877
- };
4878
- } catch {
5030
+ function planFlexibleBalanceCreditFirst(input) {
5031
+ const totalCents = toNonNegativeCents(input.totalAfterDiscountCents);
5032
+ const configuredDueNowCents = toNonNegativeCents(Math.min(input.configuredPaymentDueNowCents, totalCents));
5033
+ const availableCreditCents = toNonNegativeCents(input.creditCurrencyMatches ? input.availableCreditCents : 0);
5034
+ const minimumStripeChargeCents = toNonNegativeCents(input.minimumStripeChargeCents ?? 0);
5035
+ if (availableCreditCents >= totalCents && totalCents > 0) {
4879
5036
  return {
4880
- ok: false,
4881
- reason: "invalid_currency",
4882
- currencies: uniqueCurrencies
5037
+ kind: "credit_only",
5038
+ reserveCreditCents: totalCents,
5039
+ cardDueNowCents: toNonNegativeCents(0),
5040
+ laterBalanceCents: toNonNegativeCents(0)
4883
5041
  };
4884
5042
  }
4885
- }
4886
- function allocateReductionCents(inputs, requestedCents) {
4887
- const sanitizedInputs = inputs.map((input) => ({
4888
- lineId: input.lineId,
4889
- basisCents: toNonNegativeCents(input.basisCents),
4890
- maxReducibleCents: toNonNegativeCents(input.maxReducibleCents)
4891
- }));
4892
- const totalReducibleCents = sanitizedInputs.reduce((sum, input) => sum + input.maxReducibleCents, 0);
4893
- const targetCents = Math.max(0, Math.min(Math.trunc(requestedCents), totalReducibleCents));
4894
- const allocations = sanitizedInputs.map((input) => ({
4895
- lineId: input.lineId,
4896
- amountCents: toNonNegativeCents(0)
4897
- }));
4898
- if (targetCents === 0 || sanitizedInputs.length === 0) {
5043
+ let reserveCreditCents = toNonNegativeCents(Math.min(availableCreditCents, totalCents));
5044
+ if (reserveCreditCents >= configuredDueNowCents) {
4899
5045
  return {
4900
- requestedCents: toNonNegativeCents(requestedCents),
4901
- appliedCents: toNonNegativeCents(0),
4902
- allocations
5046
+ kind: "flexible_balance",
5047
+ reserveCreditCents,
5048
+ cardDueNowCents: toNonNegativeCents(0),
5049
+ laterBalanceCents: toNonNegativeCents(totalCents - reserveCreditCents)
4903
5050
  };
4904
5051
  }
4905
- const remainingCaps = sanitizedInputs.map((input) => input.maxReducibleCents);
4906
- let remainingCents = targetCents;
4907
- while (remainingCents > 0) {
4908
- const eligibleIndexes = sanitizedInputs.map((input, index) => ({
4909
- input,
4910
- index
4911
- })).filter(({ input, index }) => input.basisCents > 0 && (remainingCaps[index] ?? 0) > 0);
4912
- if (eligibleIndexes.length === 0) break;
4913
- const eligibleBasis = eligibleIndexes.reduce((sum, { input }) => sum + input.basisCents, 0);
4914
- if (eligibleBasis <= 0) break;
4915
- const roundCandidates = eligibleIndexes.map(({ input, index }) => {
4916
- const exactShare = input.basisCents / eligibleBasis * remainingCents;
4917
- const floorShare = Math.min(Math.floor(exactShare), remainingCaps[index] ?? 0);
4918
- const remainder = exactShare - floorShare;
5052
+ const plannedCardDueNowCents = toNonNegativeCents(configuredDueNowCents - reserveCreditCents);
5053
+ if (plannedCardDueNowCents > 0 && plannedCardDueNowCents < minimumStripeChargeCents) {
5054
+ if (configuredDueNowCents < minimumStripeChargeCents) {
4919
5055
  return {
4920
- index,
4921
- floorShare,
4922
- remainder
5056
+ kind: "card_below_minimum",
5057
+ reserveCreditCents: toNonNegativeCents(0),
5058
+ cardDueNowCents: configuredDueNowCents,
5059
+ laterBalanceCents: toNonNegativeCents(totalCents - configuredDueNowCents)
4923
5060
  };
4924
- });
4925
- let assignedThisRound = 0;
4926
- for (const candidate of roundCandidates) {
4927
- if (candidate.floorShare <= 0) continue;
4928
- const allocation = allocations[candidate.index];
4929
- if (!allocation) continue;
4930
- allocation.amountCents = toNonNegativeCents(allocation.amountCents + candidate.floorShare);
4931
- remainingCaps[candidate.index] = toNonNegativeCents((remainingCaps[candidate.index] ?? 0) - candidate.floorShare);
4932
- assignedThisRound += candidate.floorShare;
4933
- }
4934
- remainingCents -= assignedThisRound;
4935
- if (remainingCents <= 0) break;
4936
- const remainderCandidates = roundCandidates.filter((candidate) => (remainingCaps[candidate.index] ?? 0) > 0).sort((a, b) => {
4937
- if (b.remainder !== a.remainder) return b.remainder - a.remainder;
4938
- return a.index - b.index;
4939
- });
4940
- if (remainderCandidates.length === 0) break;
4941
- let remainderAssigned = 0;
4942
- for (const candidate of remainderCandidates) {
4943
- if (remainingCents <= 0) break;
4944
- if ((remainingCaps[candidate.index] ?? 0) <= 0) continue;
4945
- const allocation = allocations[candidate.index];
4946
- if (!allocation) continue;
4947
- allocation.amountCents = toNonNegativeCents(allocation.amountCents + 1);
4948
- remainingCaps[candidate.index] = toNonNegativeCents((remainingCaps[candidate.index] ?? 0) - 1);
4949
- remainingCents -= 1;
4950
- remainderAssigned += 1;
4951
- }
4952
- if (assignedThisRound === 0 && remainderAssigned === 0) {
4953
- break;
4954
5061
  }
5062
+ reserveCreditCents = toNonNegativeCents(configuredDueNowCents - minimumStripeChargeCents);
4955
5063
  }
4956
- const appliedCents = allocations.reduce((sum, allocation) => sum + allocation.amountCents, 0);
5064
+ const cardDueNowCents = toNonNegativeCents(configuredDueNowCents - reserveCreditCents);
4957
5065
  return {
4958
- requestedCents: toNonNegativeCents(requestedCents),
4959
- appliedCents: toNonNegativeCents(appliedCents),
4960
- allocations
5066
+ kind: "flexible_balance",
5067
+ reserveCreditCents,
5068
+ cardDueNowCents,
5069
+ laterBalanceCents: toNonNegativeCents(totalCents - reserveCreditCents - cardDueNowCents)
4961
5070
  };
4962
5071
  }
4963
- function assertSettledOrderLineInvariants(lines) {
4964
- for (const line of lines) {
4965
- if (line.discountCents < 0 || line.creditCents < 0 || line.netTotalCents < 0) {
4966
- throw new Error(`Negative settlement values are not allowed for line ${line.lineId}`);
4967
- }
4968
- const expectedNet = line.subtotalCents - line.discountCents - line.creditCents;
4969
- if (line.netTotalCents !== expectedNet) {
4970
- throw new Error(`Settlement invariant failed for line ${line.lineId}: expected ${expectedNet}, got ${line.netTotalCents}`);
4971
- }
5072
+
5073
+ //#endregion
5074
+ //#region ../commerce/src/purchase/checkoutPaymentPlanPlanning.ts
5075
+ function planCheckoutPaymentObligation(input) {
5076
+ const selection = input.paymentSelection;
5077
+ switch (selection.kind) {
5078
+ case "instalment_plan": return {
5079
+ kind: "instalment_plan",
5080
+ planDefinition: selection.plan
5081
+ };
5082
+ case "flexible_balance": return {
5083
+ kind: "flexible_balance",
5084
+ ...selection.timeZone === undefined ? {} : { timeZone: selection.timeZone },
5085
+ config: selection.config,
5086
+ configuredPaymentDueNowCents: resolveFlexibleBalanceInitialPaymentCents({
5087
+ totalAmountCents: input.totalAfterDiscountCents,
5088
+ config: selection.config
5089
+ }),
5090
+ bookingStartAt: selection.bookingStartAt,
5091
+ dueAt: resolveFlexibleBalanceDueAt({
5092
+ bookingStartAt: selection.bookingStartAt,
5093
+ dueDateRule: selection.config.dueDateRule
5094
+ })
5095
+ };
5096
+ case "deferred_manual": return { kind: "deferred_manual" };
5097
+ case "upfront":
5098
+ case "not_required": return { kind: "stripe" };
5099
+ default: return assertNever$3(selection);
5100
+ }
5101
+ }
5102
+
5103
+ //#endregion
5104
+ //#region ../commerce/src/purchase/checkoutPaymentTerms.ts
5105
+ /**
5106
+ * Resolves the one payment selection the whole checkout is paid with.
5107
+ *
5108
+ * A plan or contract only applies when the customer asked for it, and every
5109
+ * line has to belong to the booking it collects for. Without a request the
5110
+ * checkout pays whatever is due in full, even when a line's terms offered only
5111
+ * a plan: that auto-selection stays on the line and isn't applied here.
5112
+ */
5113
+ function resolveCheckoutPaymentTerms(input) {
5114
+ switch (input.requestedCollectionOptionKind) {
5115
+ case "instalment_plan": return resolveInstalmentPlanSelection(input.items);
5116
+ case "flexible_balance": return resolveFlexibleBalanceSelection(input.items);
5117
+ case "upfront":
5118
+ case "deferred_manual": return ok({ kind: input.requestedCollectionOptionKind });
5119
+ case undefined: return ok(input.items.every(isNotRequiredBookingLine) ? { kind: "not_required" } : { kind: "upfront" });
5120
+ }
5121
+ }
5122
+ /** Checks an already resolved selection without choosing the payment option again. */
5123
+ function validateCheckoutPaymentSelection(selection, items) {
5124
+ switch (selection.kind) {
5125
+ case "instalment_plan": return items.length > 0 && items.every((item) => belongsToSelectionBooking(item, selection)) ? ok(selection) : err({ _tag: "instalment_plan_not_supported" });
5126
+ case "flexible_balance":
5127
+ if (items.length === 0) return err({ _tag: "flexible_balance_empty_cart" });
5128
+ return items.every((item) => belongsToSelectionBooking(item, selection)) ? ok(selection) : err({ _tag: "flexible_balance_not_supported" });
5129
+ case "upfront":
5130
+ case "deferred_manual":
5131
+ case "not_required": return ok(selection);
5132
+ default: return assertNever$3(selection);
5133
+ }
5134
+ }
5135
+ function resolveInstalmentPlanSelection(items) {
5136
+ const selection = findSelectionCoveringEveryLine(items);
5137
+ return selection?.kind === "instalment_plan" ? validateCheckoutPaymentSelection(selection, items) : err({ _tag: "instalment_plan_not_supported" });
5138
+ }
5139
+ function resolveFlexibleBalanceSelection(items) {
5140
+ if (items.length === 0) return err({ _tag: "flexible_balance_empty_cart" });
5141
+ const selection = findSelectionCoveringEveryLine(items);
5142
+ return selection?.kind === "flexible_balance" ? validateCheckoutPaymentSelection(selection, items) : err({ _tag: "flexible_balance_not_supported" });
5143
+ }
5144
+ function findSelectionCoveringEveryLine(items) {
5145
+ const [firstItem] = items;
5146
+ if (firstItem?.kind !== "booking" || !isBookingPlanOrContractSelection(firstItem.selection)) {
5147
+ return null;
5148
+ }
5149
+ const selection = firstItem.selection;
5150
+ return items.every((item) => belongsToSelectionBooking(item, selection)) ? selection : null;
5151
+ }
5152
+ function belongsToSelectionBooking(item, selection) {
5153
+ return item.kind === "booking" && isBookingPlanOrContractSelection(item.selection) && item.selection.kind === selection.kind && isSameBookingPaymentReference(item.selection.booking, selection.booking);
5154
+ }
5155
+ function isNotRequiredBookingLine(item) {
5156
+ return item.kind === "booking" && item.selection.kind === "not_required";
5157
+ }
5158
+
5159
+ //#endregion
5160
+ //#region ../commerce/src/purchase/checkoutQuantity.ts
5161
+ function parsePositiveCheckoutQuantity(quantity) {
5162
+ if (!Number.isInteger(quantity) || quantity <= 0) {
5163
+ return err({
5164
+ kind: "not_positive_whole_quantity",
5165
+ quantity
5166
+ });
4972
5167
  }
5168
+ return ok(quantity);
5169
+ }
5170
+ function unsafeAsPositiveCheckoutQuantity(quantity) {
5171
+ return quantity;
4973
5172
  }
4974
5173
 
4975
5174
  //#endregion
@@ -5121,7 +5320,7 @@ function planCheckoutStripeSessionMetadata(options) {
5121
5320
  metadata.discount_code_id = options.discount.discountCodeId;
5122
5321
  metadata.discount_code = options.discount.discountCode;
5123
5322
  metadata.discount_public_label = options.discount.discountPublicLabel;
5124
- metadata.discount_code_amount_cents = String(options.totals.discountCents);
5323
+ metadata.discount_code_amount_cents = String(options.discount.amountDiscountCents);
5125
5324
  }
5126
5325
  if (options.orderReferences.orderPaymentPlanId) {
5127
5326
  metadata.order_payment_plan_id = options.orderReferences.orderPaymentPlanId;
@@ -5317,7 +5516,31 @@ const SharedDatedOfferingOrderCheckoutSessionMetadataSchema = z.object({
5317
5516
  ...orderCheckoutSessionMetadataBaseShape,
5318
5517
  ...datedOfferingSharedEngineMetadataShape
5319
5518
  });
5320
- const OrderCheckoutSessionMetadataSchema = z.union([SharedDatedOfferingOrderCheckoutSessionMetadataSchema, LegacyOrderCheckoutSessionMetadataSchema]);
5519
+ /** Several whole-series bookings are owned by one attempt, never a representative hold. */
5520
+ const WholeSeriesSelectionOrderCheckoutSessionMetadataSchema = z.object({
5521
+ ...orderCheckoutSessionMetadataBaseShape,
5522
+ order_id: z.string().uuid(),
5523
+ datedOfferingEngineContractVersion: z.literal("shared_v1"),
5524
+ datedOfferingEngineRouteKind: z.literal("shared_whole_series_registration"),
5525
+ customerId: z.string().uuid(),
5526
+ checkout_attempt_id: z.string().uuid(),
5527
+ datedOfferingCapacityHoldId: z.never().optional(),
5528
+ datedOfferingCapacityHoldAuditRef: z.never().optional(),
5529
+ eventSeriesId: z.never().optional()
5530
+ });
5531
+ const OrderCheckoutSessionMetadataSchema = z.union([
5532
+ z.object({
5533
+ ...orderCheckoutSessionMetadataBaseShape,
5534
+ ...absentDatedOfferingSharedEngineMetadataShape,
5535
+ order_id: z.string().uuid(),
5536
+ checkout_attempt_id: z.string().uuid(),
5537
+ attendee_id: z.never().optional(),
5538
+ occurrence_id: z.never().optional()
5539
+ }),
5540
+ WholeSeriesSelectionOrderCheckoutSessionMetadataSchema,
5541
+ SharedDatedOfferingOrderCheckoutSessionMetadataSchema,
5542
+ LegacyOrderCheckoutSessionMetadataSchema
5543
+ ]);
5321
5544
 
5322
5545
  //#endregion
5323
5546
  //#region ../commerce/src/purchase/canonicalRefundPlanner.ts
@@ -5472,8 +5695,8 @@ const settledBalanceSchema = z.strictObject({ kind: z.literal("settled") });
5472
5695
  const dueBalanceSchema = z.strictObject({
5473
5696
  kind: z.literal("due"),
5474
5697
  amountCents: z.number().int().positive().transform((value, ctx) => {
5475
- const cents = parsePositiveCents(value);
5476
- if (cents.ok) return cents.value;
5698
+ const cents$2 = parsePositiveCents(value);
5699
+ if (cents$2.ok) return cents$2.value;
5477
5700
  ctx.addIssue({
5478
5701
  code: "custom",
5479
5702
  message: "Expected positive whole cents"
@@ -5611,7 +5834,6 @@ function fallbackOrderItemDisplayName(kind) {
5611
5834
 
5612
5835
  //#endregion
5613
5836
  //#region ../commerce/src/purchase/orderPaymentState.ts
5614
- const ZERO_CENTS = toNonNegativeCents(0);
5615
5837
  /** Amount arithmetic shared by strict payment evidence and tolerant email snapshots.
5616
5838
  * Snapshots historically clamp overcollection to zero; the strict decision below
5617
5839
  * checks collectability before using the same calculation.
@@ -5622,226 +5844,20 @@ function calculateOutstandingOrderAmountCents(input) {
5622
5844
  function calculateOrderBalanceDueCents(input) {
5623
5845
  const settledCents = input.paidCents + (input.waivedCents ?? 0);
5624
5846
  if (settledCents > input.grandTotalCents) {
5625
- return err({ kind: "paid_exceeds_collectable" });
5626
- }
5627
- return ok(toNonNegativeCents(calculateOutstandingOrderAmountCents({
5628
- totalCents: input.grandTotalCents,
5629
- settledCents
5630
- })));
5631
- }
5632
- function derivePaymentTerms(input, outstandingCents) {
5633
- if (input.flexibleBalance && input.instalmentPlan) {
5634
- return err({ kind: "conflicting_payment_terms" });
5635
- }
5636
- const isNonMonetary = input.paymentMethod === "free" || input.paymentMethod === "waived" || input.paymentMethod === "pass_redemption" || input.paymentMethod === "membership_access";
5637
- if (isNonMonetary && (input.flexibleBalance || input.instalmentPlan)) {
5638
- return err({ kind: "managed_terms_for_non_monetary_order" });
5639
- }
5640
- if (input.flexibleBalance) {
5641
- if (input.flexibleBalance.remainingBalanceCents !== outstandingCents) {
5642
- return err({
5643
- kind: "projection_receipt_mismatch",
5644
- projection: "flexible_balance"
5645
- });
5646
- }
5647
- return ok({
5648
- kind: "flexible_balance",
5649
- contractId: input.flexibleBalance.contractId,
5650
- status: input.flexibleBalance.status,
5651
- dueAt: input.flexibleBalance.dueAt,
5652
- upfrontAmountCents: input.flexibleBalance.upfrontAmountCents
5653
- });
5654
- }
5655
- if (input.instalmentPlan) {
5656
- if (input.instalmentPlan.remainingBalanceCents !== outstandingCents) {
5657
- return err({
5658
- kind: "projection_receipt_mismatch",
5659
- projection: "instalment_plan"
5660
- });
5661
- }
5662
- return ok({
5663
- kind: "instalment_plan",
5664
- paymentPlanId: input.instalmentPlan.paymentPlanId,
5665
- status: input.instalmentPlan.status,
5666
- nextDueAt: input.instalmentPlan.nextDueAt,
5667
- nextDueAmountCents: input.instalmentPlan.nextDueAmountCents
5668
- });
5669
- }
5670
- return ok(input.paymentMethod === "manual" ? { kind: "manual" } : { kind: "immediate" });
5671
- }
5672
- function deriveOrderPaymentPosition(input) {
5673
- const balance = calculateOrderBalanceDueCents(input);
5674
- if (!balance.ok) return balance;
5675
- if (input.refundedCents > input.paidCents) {
5676
- return err({ kind: "refunded_exceeds_collected" });
5677
- }
5678
- const amounts = {
5679
- totalCents: input.grandTotalCents,
5680
- collectedCents: input.paidCents,
5681
- refundedCents: input.refundedCents,
5682
- outstandingCents: balance.value
5683
- };
5684
- const terms = derivePaymentTerms(input, balance.value);
5685
- if (!terms.ok) return terms;
5686
- if (input.status === "cancelled") {
5687
- return ok({
5688
- kind: "cancelled",
5689
- ...amounts,
5690
- outstandingCents: ZERO_CENTS,
5691
- terms: terms.value
5692
- });
5693
- }
5694
- if (input.status === "refunded") {
5695
- return ok({
5696
- kind: "refunded",
5697
- ...amounts,
5698
- outstandingCents: ZERO_CENTS,
5699
- terms: terms.value
5700
- });
5701
- }
5702
- if (input.waivedCents > 0) {
5703
- return ok({
5704
- kind: "waived",
5705
- ...amounts,
5706
- waivedCents: input.waivedCents,
5707
- outstandingCents: ZERO_CENTS,
5708
- terms: terms.value
5709
- });
5710
- }
5711
- switch (input.paymentMethod) {
5712
- case "free": return ok({
5713
- kind: "not_required",
5714
- reason: "free",
5715
- ...amounts,
5716
- outstandingCents: ZERO_CENTS
5717
- });
5718
- case "waived": return ok({
5719
- kind: "not_required",
5720
- reason: "waived",
5721
- ...amounts,
5722
- outstandingCents: ZERO_CENTS
5723
- });
5724
- case "pass_redemption": return ok({
5725
- kind: "not_required",
5726
- reason: "pass",
5727
- ...amounts,
5728
- outstandingCents: ZERO_CENTS
5729
- });
5730
- case "membership_access": return ok({
5731
- kind: "not_required",
5732
- reason: "membership",
5733
- ...amounts,
5734
- outstandingCents: ZERO_CENTS
5735
- });
5736
- case "stripe":
5737
- case "store_credit":
5738
- case "mixed":
5739
- case "manual": break;
5740
- default: return assertNever$3(input.paymentMethod);
5741
- }
5742
- if (input.status === "failed" || input.hasCollectionFailure) {
5743
- return ok({
5744
- kind: "collection_failed",
5745
- ...amounts,
5746
- terms: terms.value
5747
- });
5748
- }
5749
- if (balance.value === 0) {
5750
- return ok({
5751
- kind: "paid",
5752
- ...amounts,
5753
- outstandingCents: ZERO_CENTS,
5754
- settledVia: input.paymentMethod,
5755
- terms: terms.value
5756
- });
5757
- }
5758
- if (input.paidCents > 0) return ok({
5759
- kind: "partially_paid",
5760
- ...amounts,
5761
- terms: terms.value
5762
- });
5763
- return ok({
5764
- kind: "unpaid",
5765
- ...amounts,
5766
- terms: terms.value
5767
- });
5768
- }
5769
- function buildPaymentPresentation(position) {
5770
- const shared = {
5771
- collectedCents: position.collectedCents,
5772
- refundedCents: position.refundedCents,
5773
- outstandingCents: position.outstandingCents,
5774
- dueAt: "terms" in position && position.terms.kind === "flexible_balance" ? position.terms.dueAt : null,
5775
- nextDueAt: "terms" in position && position.terms.kind === "instalment_plan" ? position.terms.nextDueAt : null
5776
- };
5777
- switch (position.kind) {
5778
- case "not_required": return {
5779
- tone: "neutral",
5780
- label: "Not required",
5781
- ...shared
5782
- };
5783
- case "waived": return {
5784
- tone: "neutral",
5785
- label: "Waived",
5786
- ...shared
5787
- };
5788
- case "unpaid": return {
5789
- tone: "warning",
5790
- label: "Unpaid",
5791
- ...shared
5792
- };
5793
- case "partially_paid": return {
5794
- tone: "warning",
5795
- label: "Partially paid",
5796
- ...shared
5797
- };
5798
- case "paid": return {
5799
- tone: "positive",
5800
- label: "Paid",
5801
- ...shared
5802
- };
5803
- case "collection_failed": return {
5804
- tone: "critical",
5805
- label: "Payment failed",
5806
- ...shared
5807
- };
5808
- case "refunded": return {
5809
- tone: "neutral",
5810
- label: "Refunded",
5811
- ...shared
5812
- };
5813
- case "cancelled": return {
5814
- tone: "neutral",
5815
- label: "Cancelled",
5816
- ...shared
5817
- };
5818
- default: return assertNever$3(position);
5847
+ return err({ kind: "paid_exceeds_collectable" });
5819
5848
  }
5849
+ return ok(toNonNegativeCents(calculateOutstandingOrderAmountCents({
5850
+ totalCents: input.grandTotalCents,
5851
+ settledCents
5852
+ })));
5820
5853
  }
5854
+ /** Online rails are presentation/effect choices; SQL has already admitted collection. */
5821
5855
  function hasOnlineOrderPaymentPath(input) {
5822
- if (input.position.kind !== "unpaid" && input.position.kind !== "partially_paid" && input.position.kind !== "collection_failed") return false;
5823
- if (input.position.outstandingCents === 0) return false;
5824
- switch (input.position.terms.kind) {
5825
- case "immediate": return input.paymentMethod === "stripe";
5826
- case "manual": return ["manual", "mixed"].includes(input.paymentMethod);
5827
- case "flexible_balance": return [
5828
- "manual",
5829
- "stripe",
5830
- "mixed"
5831
- ].includes(input.paymentMethod) && isSettleableFlexibleBalanceContractStatus(input.position.terms.status);
5832
- case "instalment_plan": return ["stripe", "mixed"].includes(input.paymentMethod) && isSettleableOrderInstalmentPlanStatus(input.position.terms.status);
5833
- default: return assertNever$3(input.position.terms);
5834
- }
5856
+ return input.position.admissions.paymentLinkPreparation.kind !== "refused";
5835
5857
  }
5836
- /** Executable outstanding card-payment path. Connection readiness is checked by the effect shell. */
5837
5858
  function resolveOnlineOrderCheckoutMode(order) {
5838
- if (order.status !== "pending" || order.commitState !== "committed" || order.balanceDueCents <= 0) return null;
5839
- if (!hasOnlineOrderPaymentPath({
5840
- position: order.paymentState,
5841
- paymentMethod: order.paymentMethod
5842
- })) return null;
5843
- if (!("terms" in order.paymentState)) return null;
5844
- switch (order.paymentState.terms.kind) {
5859
+ if (!hasOnlineOrderPaymentPath({ position: order.paymentPosition })) return null;
5860
+ switch (order.paymentPosition.terms.kind) {
5845
5861
  case "manual":
5846
5862
  case "immediate": return { kind: "immediate" };
5847
5863
  case "flexible_balance": return { kind: "flexible_balance" };
@@ -6024,94 +6040,102 @@ function buildTransferredAttendeeConfirmationEmailPaymentSummary(options) {
6024
6040
  //#endregion
6025
6041
  //#region ../commerce/src/purchase/discountApplication.ts
6026
6042
  const CHECKOUT_DISCOUNT_ALLOCATION_RULE_VERSION = "proportional-v1";
6043
+ /** Preserve combination allocations; allocate a code against the remaining line bases. */
6027
6044
  function planCheckoutDiscountApplication(input) {
6028
- if (input.items.length === 0) {
6045
+ if (input.items.length === 0) return err({
6046
+ _tag: "empty_cart",
6047
+ message: "Cart is empty"
6048
+ });
6049
+ if (input.applications.filter((app) => app.kind === "discount_code").length > 1) {
6029
6050
  return err({
6030
- _tag: "empty_cart",
6031
- message: "Cart is empty"
6051
+ _tag: "invalid_discount_amount",
6052
+ message: "A checkout accepts at most one discount code"
6032
6053
  });
6033
6054
  }
6034
- const lines = input.items.map((item) => ({
6035
- item,
6036
- subtotalCents: item.subtotalCents
6037
- }));
6038
- const subtotalCents = toNonNegativeCents(lines.reduce((sum, line) => sum + line.subtotalCents, 0));
6039
- if (!input.selectedDiscount) {
6040
- return ok(buildNoDiscountApplication({
6041
- currency: input.currency,
6042
- lines,
6043
- subtotalCents
6044
- }));
6045
- }
6046
- const selectedDiscount = input.selectedDiscount;
6047
- const discountAllocation = allocateReductionCents(lines.map((line) => ({
6048
- lineId: line.item.lineId,
6049
- basisCents: line.subtotalCents,
6050
- maxReducibleCents: selectedDiscount.eligibleLineIds.has(line.item.lineId) ? line.subtotalCents : toNonNegativeCents(0)
6051
- })), selectedDiscount.discount.amountDiscountCents);
6052
- const discountByLineId = new Map(discountAllocation.allocations.map((allocation) => [allocation.lineId, allocation.amountCents]));
6053
- const items = lines.map((line) => {
6054
- const discountCents = discountByLineId.get(line.item.lineId) ?? toNonNegativeCents(0);
6055
- return {
6056
- lineId: line.item.lineId,
6057
- subtotalCents: line.subtotalCents,
6058
- discountCents,
6059
- totalAfterDiscountCents: toNonNegativeCents(line.subtotalCents - discountCents),
6060
- payload: line.item.payload
6061
- };
6062
- });
6063
- return ok({
6055
+ const initial = {
6064
6056
  currency: input.currency,
6065
- items,
6066
- subtotalCents,
6067
- discountCents: discountAllocation.appliedCents,
6068
- totalAfterDiscountCents: toNonNegativeCents(subtotalCents - discountAllocation.appliedCents),
6069
- discount: selectedDiscount.discount,
6070
- discountApplication: buildDiscountApplicationSnapshot({
6071
- lines,
6072
- selectedDiscount,
6073
- discountByLineId,
6074
- appliedCents: discountAllocation.appliedCents,
6075
- currency: input.currency
6076
- })
6077
- });
6078
- }
6079
- function buildNoDiscountApplication(options) {
6080
- return {
6081
- currency: options.currency,
6082
- items: options.lines.map((line) => ({
6083
- lineId: line.item.lineId,
6084
- subtotalCents: line.subtotalCents,
6057
+ items: input.items.map((item) => ({
6058
+ ...item,
6085
6059
  discountCents: toNonNegativeCents(0),
6086
- totalAfterDiscountCents: line.subtotalCents,
6087
- payload: line.item.payload
6060
+ totalAfterDiscountCents: item.subtotalCents
6088
6061
  })),
6089
- subtotalCents: options.subtotalCents,
6062
+ subtotalCents: toNonNegativeCents(input.items.reduce((sum, item) => sum + item.subtotalCents, 0)),
6090
6063
  discountCents: toNonNegativeCents(0),
6091
- totalAfterDiscountCents: options.subtotalCents,
6064
+ totalAfterDiscountCents: toNonNegativeCents(input.items.reduce((sum, item) => sum + item.subtotalCents, 0)),
6092
6065
  discount: null,
6093
- discountApplication: null
6066
+ discountApplications: []
6067
+ };
6068
+ return ok(input.applications.reduce(applyReduction, initial));
6069
+ }
6070
+ function reductionIdentity(selected) {
6071
+ return selected.kind === "combination_price" ? {
6072
+ kind: selected.kind,
6073
+ combinationPriceId: selected.combinationPriceId,
6074
+ displayLabel: selected.displayLabel,
6075
+ discountCodeId: null,
6076
+ discountRedemptionId: null,
6077
+ code: null,
6078
+ source: "auto"
6079
+ } : {
6080
+ kind: selected.kind,
6081
+ combinationPriceId: null,
6082
+ discountCodeId: selected.discount.discountCodeId,
6083
+ discountRedemptionId: selected.discount.redemptionId,
6084
+ code: selected.discount.discountCode,
6085
+ displayLabel: selected.discount.discountPublicLabel,
6086
+ source: selected.discount.autoApplied ? "auto" : "manual"
6094
6087
  };
6095
6088
  }
6096
- function buildDiscountApplicationSnapshot(options) {
6089
+ function reductionAllocation(cart, selected) {
6090
+ if (selected.kind === "combination_price") {
6091
+ return {
6092
+ allocations: selected.allocations,
6093
+ appliedCents: toNonNegativeCents(selected.allocations.reduce((sum, row) => sum + row.amountCents, 0)),
6094
+ eligibleLineIds: new Set(selected.allocations.map((row) => row.lineId))
6095
+ };
6096
+ }
6097
+ const lineIds = selected.allocationLineIds ?? cart.items.map((item) => item.lineId);
6098
+ const order = new Map(lineIds.map((id, index) => [id, index]));
6099
+ const ordered = [...cart.items].sort((a, b) => (order.get(a.lineId) ?? Infinity) - (order.get(b.lineId) ?? Infinity));
6100
+ const allocation = allocateReductionCents(ordered.map((item) => ({
6101
+ lineId: item.lineId,
6102
+ basisCents: item.totalAfterDiscountCents,
6103
+ maxReducibleCents: selected.eligibleLineIds.has(item.lineId) ? item.totalAfterDiscountCents : toNonNegativeCents(0)
6104
+ })), selected.discount.amountDiscountCents);
6097
6105
  return {
6098
- discountCodeId: options.selectedDiscount.discount.discountCodeId,
6099
- discountRedemptionId: options.selectedDiscount.discount.redemptionId,
6100
- code: options.selectedDiscount.discount.discountCode,
6101
- displayLabel: options.selectedDiscount.discount.discountPublicLabel,
6102
- source: options.selectedDiscount.discount.autoApplied ? "auto" : "manual",
6103
- currency: options.currency,
6104
- totalDiscountCents: options.appliedCents,
6106
+ ...allocation,
6107
+ eligibleLineIds: selected.eligibleLineIds
6108
+ };
6109
+ }
6110
+ function applyReduction(cart, selected) {
6111
+ const allocation = reductionAllocation(cart, selected);
6112
+ const amounts = new Map(allocation.allocations.map((row) => [row.lineId, row.amountCents]));
6113
+ const snapshot = {
6114
+ ...reductionIdentity(selected),
6115
+ currency: cart.currency,
6116
+ totalDiscountCents: allocation.appliedCents,
6105
6117
  allocationRuleVersion: CHECKOUT_DISCOUNT_ALLOCATION_RULE_VERSION,
6106
- items: options.lines.map((line) => {
6107
- const eligible = options.selectedDiscount.eligibleLineIds.has(line.item.lineId);
6118
+ items: cart.items.map((item) => ({
6119
+ lineId: item.lineId,
6120
+ eligible: allocation.eligibleLineIds.has(item.lineId),
6121
+ basisSubtotalCents: allocation.eligibleLineIds.has(item.lineId) ? item.totalAfterDiscountCents : toNonNegativeCents(0),
6122
+ discountCents: amounts.get(item.lineId) ?? toNonNegativeCents(0)
6123
+ }))
6124
+ };
6125
+ return {
6126
+ ...cart,
6127
+ items: cart.items.map((item) => {
6128
+ const reduction = amounts.get(item.lineId) ?? 0;
6108
6129
  return {
6109
- lineId: line.item.lineId,
6110
- eligible,
6111
- basisSubtotalCents: eligible ? line.subtotalCents : toNonNegativeCents(0),
6112
- discountCents: options.discountByLineId.get(line.item.lineId) ?? toNonNegativeCents(0)
6130
+ ...item,
6131
+ discountCents: toNonNegativeCents(item.discountCents + reduction),
6132
+ totalAfterDiscountCents: toNonNegativeCents(item.totalAfterDiscountCents - reduction)
6113
6133
  };
6114
- })
6134
+ }),
6135
+ discountCents: toNonNegativeCents(cart.discountCents + allocation.appliedCents),
6136
+ totalAfterDiscountCents: toNonNegativeCents(cart.totalAfterDiscountCents - allocation.appliedCents),
6137
+ discount: selected.kind === "discount_code" ? selected.discount : cart.discount,
6138
+ discountApplications: [...cart.discountApplications, snapshot]
6115
6139
  };
6116
6140
  }
6117
6141
 
@@ -6136,7 +6160,7 @@ function buildOneTimeCheckoutPlan(options) {
6136
6160
  totalAfterDiscount: money(options.settledCart.totalAfterDiscountCents, currency),
6137
6161
  totalAfterCredits: money(options.settledCart.totalAfterCreditsCents, currency),
6138
6162
  discount: options.settledCart.discount,
6139
- discountApplication: options.settledCart.discountApplication
6163
+ discountApplications: options.settledCart.discountApplications
6140
6164
  };
6141
6165
  const chargeMismatch = findInstalmentChargeMismatch(options.paymentPlan, settlement.totalAfterCredits.amountCents);
6142
6166
  if (chargeMismatch) return err(chargeMismatch);
@@ -6173,7 +6197,7 @@ function materializeSettledCart(plan) {
6173
6197
  totalAfterCreditsCents: plan.settlement.totalAfterCredits.amountCents,
6174
6198
  currency: plan.settlement.currency,
6175
6199
  discount: plan.settlement.discount,
6176
- discountApplication: plan.settlement.discountApplication
6200
+ discountApplications: plan.settlement.discountApplications
6177
6201
  };
6178
6202
  }
6179
6203
  function buildOrderDraftPlan(paymentPlan, settlement) {
@@ -6420,12 +6444,12 @@ function resolveOrderConfirmationPaymentMethodLabel(paymentMethod) {
6420
6444
  }
6421
6445
  return assertNever$3(paymentMethod);
6422
6446
  }
6423
- function resolveOrderConfirmationPaymentSummary(order, settlement, formatCurrencyAmount) {
6447
+ function resolveOrderConfirmationPaymentSummary(order, settlement, formatCurrencyAmount$1) {
6424
6448
  switch (order.paymentMethod) {
6425
- case "stripe": return settlement.collectedCents > 0 ? `${formatCurrencyAmount(settlement.collectedCents, order.currency)} charged to card` : null;
6426
- case "mixed": return `${formatCurrencyAmount(settlement.collectedCents, order.currency)} charged to card and ${formatCurrencyAmount(order.creditCents, order.currency)} applied from site credit`;
6427
- case "store_credit": return `${formatCurrencyAmount(order.creditCents, order.currency)} applied from site credit`;
6428
- case "manual": return settlement.collectedCents > 0 ? "Marked paid manually" : `Payment of ${formatCurrencyAmount(computeOrderReceiptTotalCents(brandOrderReceiptTotalSource(order)), order.currency)} is still due`;
6449
+ case "stripe": return settlement.collectedCents > 0 ? `${formatCurrencyAmount$1(settlement.collectedCents, order.currency)} charged to card` : null;
6450
+ case "mixed": return `${formatCurrencyAmount$1(settlement.collectedCents, order.currency)} charged to card and ${formatCurrencyAmount$1(order.creditCents, order.currency)} applied from site credit`;
6451
+ case "store_credit": return `${formatCurrencyAmount$1(order.creditCents, order.currency)} applied from site credit`;
6452
+ case "manual": return settlement.collectedCents > 0 ? "Marked paid manually" : `Payment of ${formatCurrencyAmount$1(computeOrderReceiptTotalCents(brandOrderReceiptTotalSource(order)), order.currency)} is still due`;
6429
6453
  case "pass_redemption": return "Covered by pass redemption";
6430
6454
  case "membership_access": return "Covered by membership access";
6431
6455
  case "waived": return "Payment was waived for this order";
@@ -6852,37 +6876,18 @@ function hasArchivedOrderHistorySource(record) {
6852
6876
 
6853
6877
  //#endregion
6854
6878
  //#region ../commerce/src/purchase/orderInstalmentAdminSettlement.ts
6855
- const MANUALLY_SETTLEABLE_PLAN_STATUSES = ["active", "payment_failed"];
6856
- const settleablePlanStatusSet = new Set(MANUALLY_SETTLEABLE_PLAN_STATUSES);
6857
6879
  const MANUALLY_SETTLEABLE_INSTALMENT_STATUSES = ["scheduled", "failed"];
6858
6880
  const settleableInstalmentStatusSet = new Set(MANUALLY_SETTLEABLE_INSTALMENT_STATUSES);
6859
- function isManuallySettleablePlanStatus(status) {
6860
- return settleablePlanStatusSet.has(status);
6861
- }
6862
6881
  function isManuallySettleableInstalmentStatus(status) {
6863
6882
  return settleableInstalmentStatusSet.has(status);
6864
6883
  }
6865
6884
  function listCollectibleRecurringInstalments(instalments) {
6866
6885
  return instalments.filter((instalment) => instalment.phaseKind === "scheduled" && isManuallySettleableInstalmentStatus(instalment.status)).sort((left, right) => left.sequence - right.sequence);
6867
6886
  }
6868
- function assertSupportedPlanStatus(paymentPlan) {
6869
- if (paymentPlan.remainingBalanceCents <= 0 || paymentPlan.status === "completed" || paymentPlan.status === "cancelled_as_paid_early") {
6870
- return;
6871
- }
6872
- if (!isManuallySettleablePlanStatus(paymentPlan.status)) {
6873
- throw new Error(`Cannot settle instalment plan in status '${paymentPlan.status}'`);
6874
- }
6875
- }
6876
6887
  function planOrderInstalmentManualPayment(input) {
6877
6888
  if (input.paymentPlan.remainingBalanceCents <= 0) {
6878
6889
  return { kind: "already_applied" };
6879
6890
  }
6880
- if (!isManuallySettleablePlanStatus(input.paymentPlan.status)) {
6881
- return {
6882
- kind: "refused",
6883
- message: `Cannot settle instalment plan in status '${input.paymentPlan.status}'`
6884
- };
6885
- }
6886
6891
  const collectibleInstalments = listCollectibleRecurringInstalments(input.instalments);
6887
6892
  if (collectibleInstalments.length === 0) {
6888
6893
  return {
@@ -6924,25 +6929,6 @@ function planOrderInstalmentManualPayment(input) {
6924
6929
  instalmentUpdates: allocation.updates
6925
6930
  };
6926
6931
  }
6927
- function planOrderInstalmentWaiver(input) {
6928
- if (input.paymentPlan.remainingBalanceCents <= 0) {
6929
- return { kind: "already_applied" };
6930
- }
6931
- assertSupportedPlanStatus(input.paymentPlan);
6932
- const instalmentUpdates = listCollectibleRecurringInstalments(input.instalments).map((instalment) => ({
6933
- instalmentId: instalment.id,
6934
- nextStatus: "waived"
6935
- }));
6936
- if (instalmentUpdates.length === 0) {
6937
- throw new Error("No recurring instalments are available to waive");
6938
- }
6939
- return {
6940
- kind: "apply",
6941
- nextPlanStatus: "completed",
6942
- nextRemainingBalanceCents: toNonNegativeCents(0),
6943
- instalmentUpdates
6944
- };
6945
- }
6946
6932
 
6947
6933
  //#endregion
6948
6934
  //#region ../commerce/src/purchase/orderInstalmentClosure.ts
@@ -7688,80 +7674,284 @@ function planUnappliedOrderPaymentReceiptAllocations(input) {
7688
7674
  return attributedCents === input.amountCents ? ok(allocations) : err({ kind: "allocation_invariant_failed" });
7689
7675
  }
7690
7676
 
7677
+ //#endregion
7678
+ //#region ../commerce/src/purchase/orderPaymentPositionDisplay.ts
7679
+ function settlementFlags(position) {
7680
+ const { collectedCents, refundedCents, waivedCents, remainderCents } = position.amounts;
7681
+ return {
7682
+ refunded: collectedCents > 0 && refundedCents === collectedCents,
7683
+ waived: waivedCents > 0 && remainderCents === 0
7684
+ };
7685
+ }
7686
+ /** Legacy customer display/wire mapping. No behavioural admission may consume its labels. */
7687
+ function paymentPositionContractStatus(position) {
7688
+ if (position.lifecycle.kind === "cancelled_non_payment") return "cancelled_due_to_non_payment";
7689
+ if (position.lifecycle.kind === "retired" && position.lifecycle.reason === "staff") return "closed_order_failed";
7690
+ if (settlementFlags(position).refunded) return "refunded";
7691
+ if (position.lifecycle.kind === "retired") return "closed_order_failed";
7692
+ if (settlementFlags(position).waived) return "waived";
7693
+ return contractCollectionStatus(position);
7694
+ }
7695
+ function contractCollectionStatus(position) {
7696
+ if (position.collection.kind === "closed" && position.collection.reason === "settled") return "completed";
7697
+ if (position.collection.kind === "in_progress") return "payment_pending";
7698
+ if (position.collection.kind === "closed" && position.collection.reason === "disputed") return position.deadline.kind === "overdue" ? "overdue" : "active";
7699
+ if (position.collection.kind === "closed" || position.collection.kind === "unresolved") return "closed_order_failed";
7700
+ return position.deadline.kind === "overdue" ? "overdue" : "active";
7701
+ }
7702
+ function paymentPositionDisplayTerms(position) {
7703
+ const terms = position.terms;
7704
+ switch (terms.kind) {
7705
+ case "immediate":
7706
+ case "manual": return terms;
7707
+ case "flexible_balance": return {
7708
+ ...terms,
7709
+ dueAt: position.deadline.kind === "none" ? null : position.deadline.dueAt,
7710
+ status: paymentPositionContractStatus(position)
7711
+ };
7712
+ case "instalment_plan": return {
7713
+ kind: "instalment_plan",
7714
+ paymentPlanId: terms.paymentPlanId,
7715
+ status: terms.state.kind,
7716
+ nextDueAt: position.deadline.kind === "none" ? null : position.deadline.dueAt,
7717
+ nextDueAmountCents: terms.nextDueAmountCents
7718
+ };
7719
+ }
7720
+ }
7721
+ /** The old union survives only at presentation and wire boundaries for the stable customer wire. */
7722
+ function paymentPositionForDisplay(position) {
7723
+ const { totalCents, collectedCents, refundedCents, waivedCents, remainderCents } = position.amounts;
7724
+ const amounts = {
7725
+ totalCents,
7726
+ collectedCents,
7727
+ refundedCents,
7728
+ outstandingCents: remainderCents
7729
+ };
7730
+ const terms = paymentPositionDisplayTerms(position);
7731
+ const zero = toNonNegativeCents(0);
7732
+ if (settlementFlags(position).refunded) return {
7733
+ kind: "refunded",
7734
+ ...amounts,
7735
+ outstandingCents: zero,
7736
+ terms
7737
+ };
7738
+ const retiredKind = retiredPaymentDisplayKind(position.lifecycle);
7739
+ if (retiredKind) return {
7740
+ kind: retiredKind,
7741
+ ...amounts,
7742
+ outstandingCents: zero,
7743
+ terms
7744
+ };
7745
+ if (settlementFlags(position).waived) return {
7746
+ kind: "waived",
7747
+ ...amounts,
7748
+ waivedCents,
7749
+ outstandingCents: zero,
7750
+ terms
7751
+ };
7752
+ switch (position.paymentMethod) {
7753
+ case "free": return {
7754
+ kind: "not_required",
7755
+ reason: "free",
7756
+ ...amounts,
7757
+ outstandingCents: zero
7758
+ };
7759
+ case "waived": return {
7760
+ kind: "not_required",
7761
+ reason: "waived",
7762
+ ...amounts,
7763
+ outstandingCents: zero
7764
+ };
7765
+ case "pass_redemption": return {
7766
+ kind: "not_required",
7767
+ reason: "pass",
7768
+ ...amounts,
7769
+ outstandingCents: zero
7770
+ };
7771
+ case "membership_access": return {
7772
+ kind: "not_required",
7773
+ reason: "membership",
7774
+ ...amounts,
7775
+ outstandingCents: zero
7776
+ };
7777
+ case "manual":
7778
+ case "mixed":
7779
+ case "store_credit":
7780
+ case "stripe": break;
7781
+ }
7782
+ if (hasFailedDisplayCollection(position)) return {
7783
+ kind: "collection_failed",
7784
+ ...amounts,
7785
+ terms
7786
+ };
7787
+ if (remainderCents === 0) return {
7788
+ kind: "paid",
7789
+ ...amounts,
7790
+ outstandingCents: zero,
7791
+ settledVia: position.paymentMethod,
7792
+ terms
7793
+ };
7794
+ return {
7795
+ kind: collectedCents > 0 ? "partially_paid" : "unpaid",
7796
+ ...amounts,
7797
+ terms
7798
+ };
7799
+ }
7800
+ const RETIRED_PAYMENT_KINDS = {
7801
+ checkout_failed: "collection_failed",
7802
+ abandoned_failed: "collection_failed",
7803
+ dispute_lost: "collection_failed",
7804
+ staff: "cancelled",
7805
+ booking_cancelled: "cancelled",
7806
+ abandoned_cancelled: "cancelled"
7807
+ };
7808
+ function retiredPaymentDisplayKind(lifecycle) {
7809
+ switch (lifecycle.kind) {
7810
+ case "open": return null;
7811
+ case "cancelled_non_payment": return "cancelled";
7812
+ case "retired": return RETIRED_PAYMENT_KINDS[lifecycle.reason];
7813
+ default: return assertNever(lifecycle);
7814
+ }
7815
+ }
7816
+ function hasFailedDisplayCollection(position) {
7817
+ return position.collection.kind === "unresolved" || position.openDispute || position.terms.kind === "instalment_plan" && position.terms.state.kind === "payment_failed" || position.collection.kind === "closed" && position.collection.reason === "checkout_failed";
7818
+ }
7819
+ /** Wire adapter only: amount selection and admission have already been decided in SQL. */
7820
+ function paymentPositionFlexibleEligibility(position) {
7821
+ const verdict = position.admissions.paymentLink;
7822
+ if (verdict.kind === "refused") {
7823
+ switch (verdict.reason) {
7824
+ case "below_card_minimum": return {
7825
+ kind: "unavailable",
7826
+ reason: "below_card_minimum"
7827
+ };
7828
+ case "in_progress": return {
7829
+ kind: "unavailable",
7830
+ reason: "payment_pending"
7831
+ };
7832
+ case "identity":
7833
+ case "amounts":
7834
+ case "conflicting_terms":
7835
+ case "provider_reconciliation":
7836
+ case "missing_instalments": return {
7837
+ kind: "unavailable",
7838
+ reason: "unresolved"
7839
+ };
7840
+ case "refunded": return {
7841
+ kind: "unavailable",
7842
+ reason: "refunded"
7843
+ };
7844
+ case "settled":
7845
+ case "nothing_owed": return {
7846
+ kind: "unavailable",
7847
+ reason: position.amounts.waivedCents > 0 ? "waived" : "already_settled"
7848
+ };
7849
+ case "cancelled_non_payment": return {
7850
+ kind: "unavailable",
7851
+ reason: "cancelled_due_to_non_payment"
7852
+ };
7853
+ case "cancelled":
7854
+ case "disputed":
7855
+ case "not_committed":
7856
+ case "unsupported_payment_method":
7857
+ case "live_terms":
7858
+ case "not_applicable":
7859
+ case "terms_closed":
7860
+ case "partly_cancelled":
7861
+ case "retired":
7862
+ case "retirement_pending":
7863
+ case "recurring_collection_active":
7864
+ case "non_monetary":
7865
+ case "checkout_failed":
7866
+ case "archived": return {
7867
+ kind: "unavailable",
7868
+ reason: "booking_cancelled"
7869
+ };
7870
+ default: return assertNever(verdict.reason);
7871
+ }
7872
+ }
7873
+ if (verdict.kind === "requires_provider_check") return {
7874
+ kind: "unavailable",
7875
+ reason: "payment_pending"
7876
+ };
7877
+ const selection = position.paymentSelection;
7878
+ return selection.kind === "full" ? {
7879
+ kind: "full_balance_only",
7880
+ remainingBalanceCents: selection.maximumCents,
7881
+ reason: selection.reason
7882
+ } : {
7883
+ kind: "eligible",
7884
+ minimumAmountCents: selection.minimumCents,
7885
+ maximumCustomAmountCents: selection.maximumCustomCents,
7886
+ suggestedPayFullAmountCents: selection.maximumCents
7887
+ };
7888
+ }
7889
+ /** The SQL position owns the order filter/badge value; customer wire mappings above retain their separate contract. */
7890
+ function paymentPositionOrderStatus(position) {
7891
+ return position.orderStatus;
7892
+ }
7893
+
7691
7894
  //#endregion
7692
7895
  //#region ../commerce/src/purchase/orderPaymentLinkPlanning.ts
7693
7896
  function buildOrderPaymentAdminProjection(facts) {
7694
- const paymentPosition = deriveOrderPaymentPosition({
7695
- status: facts.status,
7696
- paymentMethod: facts.paymentMethod,
7697
- grandTotalCents: facts.grandTotalCents,
7698
- paidCents: facts.paidCents,
7699
- waivedCents: facts.waivedCents,
7700
- refundedCents: facts.refundedCents,
7701
- flexibleBalance: facts.flexibleBalance ? {
7702
- contractId: facts.flexibleBalance.contractId,
7703
- status: facts.flexibleBalance.status,
7704
- remainingBalanceCents: facts.flexibleBalance.remainingBalanceCents,
7705
- dueAt: facts.flexibleBalance.dueAt ?? null,
7706
- upfrontAmountCents: facts.flexibleBalance.upfrontAmountCents ?? facts.paidCents
7707
- } : null,
7708
- instalmentPlan: facts.instalmentPlan ? {
7709
- paymentPlanId: facts.instalmentPlan.paymentPlanId,
7710
- status: facts.instalmentPlan.status,
7711
- remainingBalanceCents: facts.instalmentPlan.remainingBalanceCents,
7712
- nextDueAt: facts.instalmentPlan.nextDueAt ?? null,
7713
- nextDueAmountCents: facts.instalmentPlan.nextDueAmountCents ?? null
7714
- } : null,
7715
- hasCollectionFailure: facts.instalmentPlan?.status === "payment_failed"
7716
- });
7717
- if (!paymentPosition.ok) return paymentPosition;
7718
- const paymentState = paymentPosition.value;
7719
- const balanceDueCents = paymentState.outstandingCents;
7720
- const paymentLinkAvailability = resolvePaymentLinkAvailabilityFromFacts({
7721
- ...facts,
7897
+ const paymentState = paymentPositionForDisplay(facts.paymentPosition);
7898
+ const balanceDueCents = facts.paymentPosition.amounts.remainderCents;
7899
+ const paymentLinkAvailability = resolvePaymentLinkAvailabilityFromFacts(facts);
7900
+ return {
7722
7901
  paymentState,
7723
- balanceDueCents
7724
- });
7725
- const paymentReminderAvailability = resolvePaymentReminderAvailabilityFromFacts({
7902
+ balanceDueCents,
7726
7903
  paymentLinkAvailability,
7727
- customerEmail: facts.customerEmail
7728
- });
7729
- return {
7730
- ok: true,
7731
- value: {
7732
- paymentState,
7733
- balanceDueCents,
7734
- paymentLinkAvailability,
7735
- paymentReminderAvailability
7736
- }
7904
+ paymentReminderAvailability: resolvePaymentReminderAvailabilityFromFacts({
7905
+ paymentLinkAvailability: resolvePaymentLinkAvailabilityFromFacts(facts, facts.paymentPosition.admissions.demand, false),
7906
+ customerEmail: facts.customerEmail
7907
+ })
7737
7908
  };
7738
7909
  }
7739
- function resolvePaymentLinkAvailabilityFromFacts(input) {
7740
- switch (input.historySource) {
7741
- case "ledger": return unavailable("archived_order", "Archived orders cannot generate customer payment links.", 422);
7742
- case "live": break;
7743
- default: return assertNever$3(input.historySource);
7744
- }
7745
- if (input.status !== "pending") {
7746
- return unavailable("order_not_pending", "Only pending orders can generate a customer payment link.", 422);
7747
- }
7748
- if (input.commitState !== "committed") {
7749
- return unavailable("order_not_committed", "This order cannot generate a customer payment link right now.", 422);
7750
- }
7751
- if (input.balanceDueCents <= 0) {
7752
- return unavailable("no_balance_due", "This order does not have a payable balance.", 422);
7753
- }
7754
- if (!resolveOnlineOrderCheckoutMode(input)) {
7755
- return unavailable("payment_path_unavailable", "This order cannot generate a customer payment link right now.", 422);
7756
- }
7910
+ function resolvePaymentLinkAvailabilityFromFacts(input, verdict = input.paymentPosition.admissions.paymentLinkPreparation, canCheckProvider = true) {
7911
+ const admission = operationAvailability(verdict, canCheckProvider);
7912
+ if (admission.kind === "unavailable") return admission;
7757
7913
  if (!input.stripeConnected) {
7758
7914
  return unavailable("stripe_not_connected", "Online payment is not available for this site.", 409);
7759
7915
  }
7760
- if (input.hasLiveCheckoutAttempt) {
7761
- return unavailable("checkout_in_progress", "An online payment checkout is already in progress for this order.", 409);
7762
- }
7763
7916
  return { kind: "available" };
7764
7917
  }
7918
+ function operationAvailability(verdict, canCheckProvider) {
7919
+ switch (verdict.kind) {
7920
+ case "admitted": return { kind: "available" };
7921
+ case "requires_provider_check": return canCheckProvider ? { kind: "available" } : unavailable("checkout_in_progress", "A scheduled payment needs to be checked before requesting another payment.", 409);
7922
+ case "refused": {
7923
+ switch (verdict.reason) {
7924
+ case "in_progress": return unavailable("checkout_in_progress", "An online payment checkout is already in progress for this order.", 409);
7925
+ case "refunded":
7926
+ case "nothing_owed":
7927
+ case "settled": return unavailable("no_balance_due", "This order does not have a payable balance.", 422);
7928
+ case "archived": return unavailable("archived_order", "Archived orders cannot generate customer payment links.", 422);
7929
+ case "below_card_minimum": return unavailable("payment_path_unavailable", "What's left is below the smallest card payment Stripe accepts, so it can't be paid by link. You can record it as paid or waive it.", 422);
7930
+ case "amounts":
7931
+ case "cancelled":
7932
+ case "cancelled_non_payment":
7933
+ case "checkout_failed":
7934
+ case "conflicting_terms":
7935
+ case "disputed":
7936
+ case "identity":
7937
+ case "live_terms":
7938
+ case "missing_instalments":
7939
+ case "non_monetary":
7940
+ case "not_applicable":
7941
+ case "not_committed":
7942
+ case "partly_cancelled":
7943
+ case "provider_reconciliation":
7944
+ case "retired":
7945
+ case "retirement_pending":
7946
+ case "terms_closed":
7947
+ case "unsupported_payment_method":
7948
+ case "recurring_collection_active": return unavailable("payment_path_unavailable", "This order cannot generate a customer payment link right now.", 422);
7949
+ default: return assertNever$3(verdict.reason);
7950
+ }
7951
+ }
7952
+ default: return assertNever$3(verdict);
7953
+ }
7954
+ }
7765
7955
  function resolvePaymentReminderAvailabilityFromFacts(input) {
7766
7956
  if (input.paymentLinkAvailability.kind === "unavailable") {
7767
7957
  return input.paymentLinkAvailability;
@@ -7791,58 +7981,6 @@ function unavailable(reason, publicMessage, httpStatus) {
7791
7981
 
7792
7982
  //#endregion
7793
7983
  //#region ../commerce/src/purchase/orderRefundPlanning.ts
7794
- function planOrderRefund(options) {
7795
- const paidCents = options.paidCents;
7796
- const currentRefundedCents = options.currentRefundedCents;
7797
- if (currentRefundedCents > paidCents) {
7798
- return err("Current refunded amount exceeds paid amount");
7799
- }
7800
- const linesById = new Map();
7801
- for (const line of options.lines) {
7802
- if (linesById.has(line.orderItemId)) {
7803
- return err(`Duplicate refund line input: ${line.orderItemId}`);
7804
- }
7805
- linesById.set(line.orderItemId, line);
7806
- }
7807
- const plannedLines = [];
7808
- let requestedTotalCents = 0;
7809
- let appliedTotalCents = 0;
7810
- for (const requested of options.requestedLineRefunds) {
7811
- const line = linesById.get(requested.orderItemId);
7812
- if (!line) {
7813
- return err(`Unknown order item for refund planning: ${requested.orderItemId}`);
7814
- }
7815
- const netTotalCents = line.netTotalCents;
7816
- const alreadyRefundedCents = line.alreadyRefundedCents ?? toNonNegativeCents(0);
7817
- if (alreadyRefundedCents > netTotalCents) {
7818
- return err(`Refunded amount exceeds line total for ${line.orderItemId}`);
7819
- }
7820
- const refundableRemainingCents$1 = orderItemRefundableRemainingCents({
7821
- cashFundedCents: netTotalCents,
7822
- creditAppliedCents: 0,
7823
- refundedCents: alreadyRefundedCents
7824
- });
7825
- const requestedCents = requested.amountCents;
7826
- const appliedCents = toNonNegativeCents(Math.min(requestedCents, refundableRemainingCents$1));
7827
- requestedTotalCents += requestedCents;
7828
- appliedTotalCents += appliedCents;
7829
- plannedLines.push({
7830
- orderItemId: requested.orderItemId,
7831
- requestedCents,
7832
- refundableRemainingCents: refundableRemainingCents$1,
7833
- appliedCents
7834
- });
7835
- }
7836
- const nextRefundedCents = toNonNegativeCents(currentRefundedCents + appliedTotalCents);
7837
- const nextStatus = appliedTotalCents <= 0 ? null : nextRefundedCents >= paidCents ? "refunded" : "partially_refunded";
7838
- return ok({
7839
- lines: plannedLines,
7840
- requestedTotalCents: toNonNegativeCents(requestedTotalCents),
7841
- appliedTotalCents: toNonNegativeCents(appliedTotalCents),
7842
- nextRefundedCents,
7843
- nextStatus
7844
- });
7845
- }
7846
7984
  function planOrderRefundSummaryUpdate(options) {
7847
7985
  const paidCents = options.paidCents;
7848
7986
  const currentRefundedCents = options.currentRefundedCents;
@@ -7853,30 +7991,7 @@ function planOrderRefundSummaryUpdate(options) {
7853
7991
  if (nextRefundedCents < currentRefundedCents) {
7854
7992
  return err("Refunded amount cannot decrease");
7855
7993
  }
7856
- const nextStatus = nextRefundedCents <= 0 ? null : nextRefundedCents >= paidCents ? "refunded" : "partially_refunded";
7857
- return ok({
7858
- refundedCents: nextRefundedCents,
7859
- nextStatus
7860
- });
7861
- }
7862
- function settleOrderRefundPlan(options) {
7863
- const actualRefundedCents = options.actualRefundedCents;
7864
- if (actualRefundedCents > options.planned.appliedTotalCents) {
7865
- return err("Actual refunded amount exceeds planned refundable amount");
7866
- }
7867
- const allocation = allocateReductionCents(options.planned.lines.map((line) => ({
7868
- lineId: line.orderItemId,
7869
- basisCents: line.appliedCents,
7870
- maxReducibleCents: line.appliedCents
7871
- })), actualRefundedCents);
7872
- return ok({
7873
- lines: options.planned.lines.map((line) => ({
7874
- orderItemId: line.orderItemId,
7875
- requestedCents: line.requestedCents,
7876
- appliedCents: allocation.allocations.find((allocationLine) => allocationLine.lineId === line.orderItemId)?.amountCents ?? toNonNegativeCents(0)
7877
- })),
7878
- refundedTotalCents: allocation.appliedCents
7879
- });
7994
+ return ok({ refundedCents: nextRefundedCents });
7880
7995
  }
7881
7996
 
7882
7997
  //#endregion
@@ -7973,80 +8088,6 @@ function fallbackDisplayName(kind) {
7973
8088
 
7974
8089
  //#endregion
7975
8090
  //#region ../commerce/src/purchase/protectedDepositRefundPolicy.ts
7976
- function buildProtectedDepositPolicySubjectFromFlexibleBalance(input) {
7977
- return {
7978
- kind: "protected_deposit",
7979
- sourceKind: "flexible_balance",
7980
- protectedDepositAmountCents: input.upfrontAmountCents,
7981
- depositRefundability: input.depositRefundability
7982
- };
7983
- }
7984
- function buildProtectedDepositPolicySubjectFromInstalmentPlan(plan) {
7985
- const protectedDepositAmountCents = getBookingInstalmentProtectedDepositAmountCents(plan);
7986
- const depositRefundability = getBookingInstalmentDepositRefundability(plan);
7987
- if (protectedDepositAmountCents == null || depositRefundability == null) {
7988
- return { kind: "none" };
7989
- }
7990
- return {
7991
- kind: "protected_deposit",
7992
- sourceKind: "instalment_plan",
7993
- protectedDepositAmountCents: unsafeAsNonNegativeCents(protectedDepositAmountCents),
7994
- depositRefundability
7995
- };
7996
- }
7997
- function calculateProtectedDepositRefundExposure(input) {
7998
- const itemRemainingCents = toNonNegativeCents(input.itemTotalCents - input.itemRefundedCents);
7999
- const totalRemainingRefundableCents = toNonNegativeCents(Math.min(itemRemainingCents, input.collectedRemainingCents));
8000
- if (input.subject.kind === "none" || input.subject.depositRefundability === "refundable") {
8001
- return {
8002
- subject: input.subject,
8003
- totalRemainingRefundableCents,
8004
- policyRefundableCents: totalRemainingRefundableCents,
8005
- protectedDepositRemainingCents: toNonNegativeCents(0)
8006
- };
8007
- }
8008
- const protectedDepositOriginalCents = toNonNegativeCents(Math.min(input.subject.protectedDepositAmountCents, input.itemTotalCents));
8009
- const nonDepositOriginalCents = toNonNegativeCents(input.itemTotalCents - protectedDepositOriginalCents);
8010
- const refundedAgainstProtectedDepositCents = toNonNegativeCents(input.itemRefundedCents - nonDepositOriginalCents);
8011
- const protectedDepositRemainingByItemCents = toNonNegativeCents(protectedDepositOriginalCents - refundedAgainstProtectedDepositCents);
8012
- const nonDepositRemainingByItemCents = toNonNegativeCents(itemRemainingCents - protectedDepositRemainingByItemCents);
8013
- const policyRefundableCents = toNonNegativeCents(Math.min(totalRemainingRefundableCents, nonDepositRemainingByItemCents));
8014
- return {
8015
- subject: input.subject,
8016
- totalRemainingRefundableCents,
8017
- policyRefundableCents,
8018
- protectedDepositRemainingCents: toNonNegativeCents(totalRemainingRefundableCents - policyRefundableCents)
8019
- };
8020
- }
8021
- /**
8022
- * Calculates policy exposure for one receipt allocation.
8023
- *
8024
- * A protected deposit is collected by the initial-checkout receipt. Later
8025
- * paydowns and instalments therefore remain independently refundable even
8026
- * while the entity still has a non-refundable deposit balance.
8027
- */
8028
- function calculateReceiptProtectedDepositRefundExposure(input) {
8029
- const totalRemainingRefundableCents = toNonNegativeCents(input.allocatedCents - input.refundedCents);
8030
- if (input.subject.kind === "none" || input.subject.depositRefundability === "refundable" || input.receiptPurpose !== "initial_checkout") {
8031
- return {
8032
- subject: input.subject,
8033
- totalRemainingRefundableCents,
8034
- policyRefundableCents: totalRemainingRefundableCents,
8035
- protectedDepositRemainingCents: toNonNegativeCents(0)
8036
- };
8037
- }
8038
- const protectedDepositOriginalCents = toNonNegativeCents(Math.min(input.subject.protectedDepositAmountCents, input.allocatedCents));
8039
- const nonDepositOriginalCents = toNonNegativeCents(input.allocatedCents - protectedDepositOriginalCents);
8040
- const refundedAgainstProtectedDepositCents = toNonNegativeCents(input.refundedCents - nonDepositOriginalCents);
8041
- const protectedDepositRemainingCents = toNonNegativeCents(protectedDepositOriginalCents - refundedAgainstProtectedDepositCents);
8042
- const policyRefundableCents = toNonNegativeCents(totalRemainingRefundableCents - protectedDepositRemainingCents);
8043
- return {
8044
- subject: input.subject,
8045
- totalRemainingRefundableCents,
8046
- policyRefundableCents,
8047
- protectedDepositRemainingCents
8048
- };
8049
- }
8050
8091
  function planAdminProtectedDepositRefund(input) {
8051
8092
  const requestedAmountCents = resolveRequestedAmountCents(input.request, { fullRemainingCents: input.allowProtectedDepositOverride ? input.exposure.totalRemainingRefundableCents : input.exposure.policyRefundableCents });
8052
8093
  if (input.exposure.totalRemainingRefundableCents <= 0 || requestedAmountCents <= 0) {
@@ -8218,83 +8259,24 @@ function planShopRefund(order, shopItems) {
8218
8259
  ok: false,
8219
8260
  error: {
8220
8261
  tag: "NO_REFUNDABLE_ITEMS",
8221
- message: `Order ${order.orderNumber} has no refundable Shop items`
8222
- }
8223
- };
8224
- }
8225
- const refundableItems = shopItems.map((item) => ({
8226
- item,
8227
- displayName: getOrderItemDisplayName(item),
8228
- refundMode: "refund_and_revoke",
8229
- sourceType: item.kind === "pass" ? "pass_order_refund" : "product_order_refund"
8230
- }));
8231
- return {
8232
- ok: true,
8233
- value: {
8234
- order: refundableOrder,
8235
- items: refundableItems
8236
- }
8237
- };
8238
- }
8239
-
8240
- //#endregion
8241
- //#region ../commerce/src/purchase/stripeMinimumCharge.ts
8242
- const STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY = {
8243
- GBP: 30,
8244
- USD: 50,
8245
- EUR: 50,
8246
- AED: 200,
8247
- AUD: 50,
8248
- BGN: 100,
8249
- BRL: 50,
8250
- CAD: 50,
8251
- CHF: 50,
8252
- CZK: 1500,
8253
- DKK: 250,
8254
- HKD: 400,
8255
- HUF: 17500,
8256
- JPY: 50,
8257
- MXN: 1e3,
8258
- MYR: 200,
8259
- NOK: 300,
8260
- NZD: 50,
8261
- PLN: 200,
8262
- RON: 200,
8263
- SEK: 300,
8264
- SGD: 50,
8265
- THB: 1e3
8266
- };
8267
- function isStripeMinimumChargeCurrency(currency) {
8268
- return currency in STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY;
8269
- }
8270
- function getStripeMinimumChargeRequirement(rawCurrency) {
8271
- let currency;
8272
- try {
8273
- currency = normalizeCurrencyCode(rawCurrency);
8274
- } catch {
8275
- return null;
8276
- }
8277
- const currencyKey = currency;
8278
- if (!isStripeMinimumChargeCurrency(currencyKey)) {
8279
- return null;
8262
+ message: `Order ${order.orderNumber} has no refundable Shop items`
8263
+ }
8264
+ };
8280
8265
  }
8266
+ const refundableItems = shopItems.map((item) => ({
8267
+ item,
8268
+ displayName: getOrderItemDisplayName(item),
8269
+ refundMode: "refund_and_revoke",
8270
+ sourceType: item.kind === "pass" ? "pass_order_refund" : "product_order_refund"
8271
+ }));
8281
8272
  return {
8282
- currency,
8283
- minimumAmountCents: STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY[currencyKey]
8273
+ ok: true,
8274
+ value: {
8275
+ order: refundableOrder,
8276
+ items: refundableItems
8277
+ }
8284
8278
  };
8285
8279
  }
8286
- function isStripeChargeBelowMinimum(options) {
8287
- const requirement = getStripeMinimumChargeRequirement(options.currency);
8288
- return Boolean(requirement && options.amountCents > 0 && options.amountCents < requirement.minimumAmountCents);
8289
- }
8290
- /**
8291
- * The smallest deposit a plan that starts with one may ask for: the card
8292
- * minimum for the currency, or any positive amount for a currency Stripe has
8293
- * no minimum on record for.
8294
- */
8295
- function getInstalmentDepositMinimumCents(currency) {
8296
- return getStripeMinimumChargeRequirement(currency)?.minimumAmountCents ?? 1;
8297
- }
8298
8280
 
8299
8281
  //#endregion
8300
8282
  //#region ../commerce/src/purchase/stripeCheckoutReturnUrl.ts
@@ -8334,39 +8316,6 @@ const checkoutCopy = {
8334
8316
 
8335
8317
  //#endregion
8336
8318
  //#region ../commerce/src/purchase/stateTransitions.ts
8337
- function advanceOrderStatus(from, event) {
8338
- switch (event) {
8339
- case "checkout_failed":
8340
- if (from === "pending") return ok("failed");
8341
- break;
8342
- case "stripe_payment_completed":
8343
- if (from === "pending") return ok("paid");
8344
- break;
8345
- case "cancel":
8346
- if (from === "pending" || from === "failed") return ok("cancelled");
8347
- if (from === "paid" || from === "partially_refunded" || from === "refunded") return ok("cancelled");
8348
- break;
8349
- case "partial_refund":
8350
- if (from === "paid" || from === "partially_refunded") return ok("partially_refunded");
8351
- break;
8352
- case "full_refund":
8353
- if (from === "paid" || from === "partially_refunded") return ok("refunded");
8354
- break;
8355
- }
8356
- return err(`Illegal order status transition: ${from} -> ${event}`);
8357
- }
8358
- function transitionOrderStatusTo(from, to) {
8359
- if (from === to) return ok(to);
8360
- switch (to) {
8361
- case "failed": return advanceOrderStatus(from, "checkout_failed");
8362
- case "paid": return advanceOrderStatus(from, "stripe_payment_completed");
8363
- case "cancelled": return advanceOrderStatus(from, "cancel");
8364
- case "partially_refunded": return advanceOrderStatus(from, "partial_refund");
8365
- case "refunded": return advanceOrderStatus(from, "full_refund");
8366
- case "pending": break;
8367
- }
8368
- return err(`Illegal order status transition: ${from} -> ${to}`);
8369
- }
8370
8319
  function classifyCheckoutCompensationDecision(input) {
8371
8320
  const sideEffects = checkoutCommitSideEffects(input.progress);
8372
8321
  if (input.paymentRail === "bypass") {
@@ -8560,6 +8509,10 @@ function eventRegistrationErrorEndsCommand(value) {
8560
8509
  //#region ../commerce/src/purchase/eventCheckoutRecoveryWindow.ts
8561
8510
  const EVENT_CHECKOUT_HOLD_DURATION_MS = 35 * 60 * 1e3;
8562
8511
  const EVENT_CHECKOUT_RECOVERY_GRACE_MS = 24 * 60 * 60 * 1e3;
8512
+ /** Admission deadlines close new bookings; an admitted payment gets the full hold window. */
8513
+ function eventCheckoutPaymentDeadlineEpoch(deadlineEpoch, nowMs) {
8514
+ return Math.max(deadlineEpoch, Math.floor((nowMs + EVENT_CHECKOUT_HOLD_DURATION_MS) / 1e3));
8515
+ }
8563
8516
  function validInstant(value) {
8564
8517
  const instant = Date.parse(value);
8565
8518
  return Number.isFinite(instant) ? instant : null;
@@ -8605,6 +8558,942 @@ function checkBrowserStripeKey(publishableKey, livemode) {
8605
8558
  };
8606
8559
  }
8607
8560
 
8561
+ //#endregion
8562
+ //#region ../commerce/src/purchase/discountCodeApplicability.ts
8563
+ const DISCOUNT_EVENT_SCOPE_MODES = [
8564
+ "all_categories",
8565
+ "categories",
8566
+ "event_offerings"
8567
+ ];
8568
+ function discountMinimumTickets(code) {
8569
+ if (!code.eventMinTicketsEnabled) return 1;
8570
+ const minimum = code.eventMinTickets ?? 0;
8571
+ return minimum >= 2 ? minimum : "misconfigured";
8572
+ }
8573
+ function meetsDiscountMinimumTickets(code, ticketsCount) {
8574
+ const minimum = discountMinimumTickets(code);
8575
+ return minimum !== "misconfigured" && ticketsCount >= minimum;
8576
+ }
8577
+ function matchesSelectedScope(mode, ids, id) {
8578
+ switch (mode) {
8579
+ case "all": return true;
8580
+ case "selected": return ids.includes(id);
8581
+ }
8582
+ }
8583
+ function matchesEventScope(mode, scopes, context) {
8584
+ switch (mode) {
8585
+ case "all_categories": return true;
8586
+ case "categories": return context.eventCategoryId !== null && scopes.eventCategoryIds.includes(context.eventCategoryId);
8587
+ case "event_offerings": return scopes.eventOfferingIds.includes(context.eventOfferingId);
8588
+ }
8589
+ }
8590
+ function matchesProductScope(mode, scopes, context) {
8591
+ switch (mode) {
8592
+ case "all": return true;
8593
+ case "categories": return context.productCategoryId !== null && scopes.productCategoryIds.includes(context.productCategoryId);
8594
+ case "selected": return scopes.productIds.includes(context.productId);
8595
+ }
8596
+ }
8597
+ /** All applicability rules, evaluated against loaded facts and an explicit clock. */
8598
+ function discountCodeAppliesTo(code, scopes, context, now) {
8599
+ const enabled = {
8600
+ event: code.appliesToEvents,
8601
+ whole_series: code.appliesToEvents,
8602
+ appointment: code.appliesToAppointments,
8603
+ pass: code.appliesToPasses,
8604
+ membership: code.appliesToMemberships,
8605
+ product: code.appliesToProducts
8606
+ }[context.type];
8607
+ return enabled && code.isActive && isWithinDiscountWindow(code, now) && matchesDiscountContext(code, scopes, context);
8608
+ }
8609
+ function isWithinDiscountWindow(code, now) {
8610
+ return !(code.startsAt !== null && code.startsAt > now) && !(code.endsAt !== null && code.endsAt < now);
8611
+ }
8612
+ function matchesDiscountContext(code, scopes, context) {
8613
+ switch (context.type) {
8614
+ case "event":
8615
+ case "whole_series": return meetsDiscountMinimumTickets(code, context.ticketsCount ?? 1) && matchesEventScope(code.eventsScopeMode, scopes, context);
8616
+ case "appointment": return matchesSelectedScope(code.appointmentsScopeMode, scopes.appointmentServiceIds, context.serviceId);
8617
+ case "pass": return matchesSelectedScope(code.passesScopeMode, scopes.passIds, context.passId);
8618
+ case "membership": return matchesSelectedScope(code.membershipsScopeMode, scopes.membershipIds, context.membershipId);
8619
+ case "product": return matchesProductScope(code.productsScopeMode, scopes, context);
8620
+ }
8621
+ }
8622
+
8623
+ //#endregion
8624
+ //#region ../commerce/src/purchase/combinationPricing.ts
8625
+ const cents$1 = toNonNegativeCents;
8626
+ const compareText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
8627
+ const compareLine = (a, b) => compareText(a.date, b.date) || compareText(a.lineId, b.lineId);
8628
+ const compareOffer = (a, b) => a.sortOrder - b.sortOrder || compareText(a.id, b.id);
8629
+ const sumPrices = (lines) => lines.reduce((sum, line) => sum + line.unitPriceCents, 0);
8630
+ function application(offer, lines, places) {
8631
+ const ordered = [...lines].sort(compareLine);
8632
+ const savingCents = cents$1((sumPrices(lines) - offer.priceCents) * places);
8633
+ const allocation = allocateReductionCents(ordered.map((line) => ({
8634
+ lineId: line.lineId,
8635
+ basisCents: cents$1(line.unitPriceCents * places),
8636
+ maxReducibleCents: cents$1(line.unitPriceCents * places)
8637
+ })), savingCents);
8638
+ return {
8639
+ offer,
8640
+ lines: ordered,
8641
+ totalCents: cents$1(offer.priceCents * places),
8642
+ savingCents,
8643
+ allocations: allocation.allocations.map((row, index) => ({
8644
+ lineId: row.lineId,
8645
+ reductionCents: row.amountCents,
8646
+ totalCents: cents$1((ordered[index]?.unitPriceCents ?? 0) * places - row.amountCents)
8647
+ }))
8648
+ };
8649
+ }
8650
+ const compareApplication = (a, b) => compareOffer(a.offer, b.offer) || compareText(JSON.stringify(a.lines.map((line) => [line.date, line.lineId])), JSON.stringify(b.lines.map((line) => [line.date, line.lineId])));
8651
+ const saving = (apps) => apps.reduce((sum, app) => sum + app.savingCents, 0);
8652
+ function prefer(a, b) {
8653
+ const money$1 = saving(b) - saving(a);
8654
+ if (money$1 !== 0) return money$1 < 0 ? a : b;
8655
+ if (a.length !== b.length) return a.length < b.length ? a : b;
8656
+ const left = [...a].sort(compareApplication);
8657
+ const right = [...b].sort(compareApplication);
8658
+ const offerDifference = left.map((app, index) => right[index] ? compareOffer(app.offer, right[index].offer) : 0).find((value) => value !== 0) ?? 0;
8659
+ if (offerDifference !== 0) return offerDifference < 0 ? left : right;
8660
+ const difference = left.map((app, index) => right[index] ? compareApplication(app, right[index]) : 0).find((value) => value !== 0) ?? 0;
8661
+ return difference <= 0 ? left : right;
8662
+ }
8663
+ function cheaperSelection(a, b) {
8664
+ if (!a) return b;
8665
+ if (a.priceCents !== b.priceCents) return a.priceCents < b.priceCents ? a : b;
8666
+ if (a.offers.length !== b.offers.length) return a.offers.length < b.offers.length ? a : b;
8667
+ const difference = a.offers.map((offer, index) => b.offers[index] ? compareOffer(offer, b.offers[index]) : 0).find((value) => value !== 0) ?? 0;
8668
+ return difference <= 0 ? a : b;
8669
+ }
8670
+ /** Cheapest exact cover of each count, independent of which dates fill it. */
8671
+ function anySelections(count, offers) {
8672
+ const memo = new Map([[0, {
8673
+ offers: [],
8674
+ priceCents: 0
8675
+ }]]);
8676
+ const visit = (size) => {
8677
+ if (memo.has(size)) return memo.get(size) ?? null;
8678
+ const best = offers.reduce((best$1, offer) => {
8679
+ if (offer.itemCount > size) return best$1;
8680
+ const previous = visit(size - offer.itemCount);
8681
+ return previous ? cheaperSelection(best$1, {
8682
+ offers: [...previous.offers, offer].sort(compareOffer),
8683
+ priceCents: previous.priceCents + offer.priceCents
8684
+ }) : best$1;
8685
+ }, null);
8686
+ memo.set(size, best);
8687
+ return best;
8688
+ };
8689
+ return Array.from({ length: count + 1 }, (_, size) => visit(size));
8690
+ }
8691
+ /**
8692
+ * Covering k items always uses the k highest list prices (earliest dates on ties).
8693
+ * Once offer counts are fixed, grouping cannot change the total. A globally best
8694
+ * candidate cannot contain a non-saving group: dropping it would improve the
8695
+ * total or the application-count tie. So canonical date grouping is sufficient.
8696
+ */
8697
+ function planAny(lines, offers, places) {
8698
+ const ranked = [...lines].sort((a, b) => b.unitPriceCents - a.unitPriceCents || compareLine(a, b));
8699
+ return anySelections(lines.length, offers.filter((offer) => offer.kind === "any")).reduce((best, selected, count) => {
8700
+ if (!selected) return best;
8701
+ const chosen = ranked.slice(0, count).sort(compareLine);
8702
+ const grouped = selected.offers.reduce((state, offer) => {
8703
+ const size = offer.itemCount;
8704
+ const group = chosen.slice(state.offset, state.offset + size);
8705
+ return {
8706
+ offset: state.offset + size,
8707
+ apps: [...state.apps, application(offer, group, places)]
8708
+ };
8709
+ }, {
8710
+ offset: 0,
8711
+ apps: []
8712
+ });
8713
+ return grouped.apps.every((app) => app.savingCents > 0) ? prefer(best, grouped.apps) : best;
8714
+ }, []);
8715
+ }
8716
+ /** Search particular-set subsets; memoised masks collapse different application orders. */
8717
+ function search(input) {
8718
+ const memo = new Map();
8719
+ const visit = (mask) => {
8720
+ const cached = memo.get(mask);
8721
+ if (cached) return cached;
8722
+ const remaining = input.lines.filter((_, index) => (mask & 1 << index) !== 0);
8723
+ const best = input.offers.reduce((best$1, offer) => {
8724
+ if (offer.kind !== "particular") return best$1;
8725
+ const group = remaining.filter((line) => offer.lineIds.includes(line.lineId));
8726
+ if (group.length !== offer.lineIds.length || sumPrices(group) <= offer.priceCents) return best$1;
8727
+ const used = input.lines.reduce((bits, line, index) => group.includes(line) ? bits | 1 << index : bits, 0);
8728
+ return prefer(best$1, [application(offer, group, input.places), ...visit(mask ^ used)]);
8729
+ }, planAny(remaining, input.offers, input.places));
8730
+ memo.set(mask, best);
8731
+ return best;
8732
+ };
8733
+ return visit((1 << input.lines.length) - 1);
8734
+ }
8735
+ function validate(input) {
8736
+ if (input.lines.length > 20 || new Set(input.lines.map((line) => line.lineId)).size !== input.lines.length) throw new Error("Combination pricing requires at most 20 distinct lines");
8737
+ if (input.offers.some((offer) => offer.kind === "any" ? offer.itemCount < 2 : offer.lineIds.length < 2 || new Set(offer.lineIds).size !== offer.lineIds.length)) throw new Error("Combination offers require at least two distinct items");
8738
+ }
8739
+ function planCombinationPrices(input) {
8740
+ validate(input);
8741
+ const applications = [...search(input)].sort(compareApplication);
8742
+ const lines = [...input.lines].sort(compareLine).map((line) => {
8743
+ const allocated = applications.flatMap((app) => app.allocations).find((row) => row.lineId === line.lineId);
8744
+ const listCents = cents$1(line.unitPriceCents * input.places);
8745
+ return {
8746
+ line,
8747
+ listCents,
8748
+ totalCents: allocated?.totalCents ?? listCents,
8749
+ combined: allocated !== undefined
8750
+ };
8751
+ });
8752
+ return {
8753
+ places: input.places,
8754
+ applications,
8755
+ lines,
8756
+ totalCents: cents$1(lines.reduce((sum, line) => sum + line.totalCents, 0)),
8757
+ listTotalCents: cents$1(sumPrices(input.lines) * input.places)
8758
+ };
8759
+ }
8760
+ /**
8761
+ * The offers a selection can use, with particular offers mapped from the item
8762
+ * ids they name to this basket's line ids. A particular offer applies only
8763
+ * when every item it names is selected. Which items an offer may cover at all
8764
+ * (fixed-price ones) is decided when offers are stored and published, so the
8765
+ * offers arriving here already exclude ticket types and sliding scales.
8766
+ */
8767
+ function combinationOffersForSelection(offers, items) {
8768
+ const lineIds = new Map(items.map((item) => [item.itemId, item.lineId]));
8769
+ return offers.flatMap((offer) => {
8770
+ if (offer.kind === "any") return [offer];
8771
+ const selected = offer.lineIds.map((id) => lineIds.get(id));
8772
+ return selected.every((id) => id !== undefined) ? [{
8773
+ ...offer,
8774
+ lineIds: selected
8775
+ }] : [];
8776
+ });
8777
+ }
8778
+ /**
8779
+ * Checkout and the booking block price a selection here (issue 1725). Every
8780
+ * item enters at its resolved price, so an item no offer covers (a run with
8781
+ * ticket types next to "Part 1 and Part 2 for £120") stays at the price
8782
+ * chosen for it and still counts in the total.
8783
+ */
8784
+ function planSelectionCombinationPrices(input) {
8785
+ const plan = planCombinationPrices({
8786
+ lines: input.items.map(({ lineId, date, label, unitPriceCents }) => ({
8787
+ lineId,
8788
+ date,
8789
+ label,
8790
+ unitPriceCents
8791
+ })),
8792
+ offers: combinationOffersForSelection(input.offers, input.items),
8793
+ places: input.places
8794
+ });
8795
+ const uncovered = (input.uncovered ?? []).map(({ line, subtotalCents }) => ({
8796
+ line,
8797
+ listCents: subtotalCents,
8798
+ totalCents: subtotalCents,
8799
+ combined: false
8800
+ }));
8801
+ const extra = uncovered.reduce((sum, row) => sum + row.totalCents, 0);
8802
+ return {
8803
+ ...plan,
8804
+ lines: [...plan.lines, ...uncovered],
8805
+ totalCents: cents$1(plan.totalCents + extra),
8806
+ listTotalCents: cents$1(plan.listTotalCents + extra)
8807
+ };
8808
+ }
8809
+ /** One completion per offer, never arbitrary subsets of the available items. */
8810
+ function missingOfferLines(input, offer) {
8811
+ const selected = new Set(input.lines.map((line) => line.lineId));
8812
+ if (offer.kind === "particular") {
8813
+ const missing = offer.lineIds.filter((id) => !selected.has(id));
8814
+ const added = missing.flatMap((id) => input.addable.filter((line) => line.lineId === id));
8815
+ return added.length === missing.length ? added.sort(compareLine) : null;
8816
+ }
8817
+ const count = Math.max(0, offer.itemCount - input.lines.length);
8818
+ return [...input.addable].sort((a, b) => a.unitPriceCents - b.unitPriceCents || compareLine(a, b)).slice(0, count);
8819
+ }
8820
+ function nextCombinationHint(input) {
8821
+ const current = planCombinationPrices(input);
8822
+ const used = new Set(current.applications.map((app) => app.offer.id));
8823
+ const candidates = input.offers.filter((offer) => !used.has(offer.id)).flatMap((offer) => {
8824
+ const added = missingOfferLines(input, offer);
8825
+ if (!added?.length || input.lines.length + added.length > 20) return [];
8826
+ const plan = planCombinationPrices({
8827
+ ...input,
8828
+ lines: [...input.lines, ...added]
8829
+ });
8830
+ const fresh = plan.applications.find((app) => !used.has(app.offer.id) && app.lines.some((line) => added.some((item) => item.lineId === line.lineId)));
8831
+ return fresh ? [{
8832
+ added,
8833
+ offer: fresh.offer,
8834
+ plan,
8835
+ savingCents: cents$1(plan.listTotalCents - plan.totalCents)
8836
+ }] : [];
8837
+ });
8838
+ return candidates.sort((a, b) => a.added.length - b.added.length || a.plan.totalCents - b.plan.totalCents || compareOffer(a.offer, b.offer))[0] ?? null;
8839
+ }
8840
+ function codeCandidate(plan, code, kind) {
8841
+ const bases = plan.lines.map((row) => ({
8842
+ lineId: row.line.lineId,
8843
+ basisCents: kind === "code_only" ? row.listCents : row.totalCents,
8844
+ eligible: code.eligibleLineIds.includes(row.line.lineId) && (kind === "code_only" || code.combinesWithCombinationPrices || !row.combined)
8845
+ }));
8846
+ const reductions = code.reductions(bases);
8847
+ if (new Set(reductions.map((row) => row.lineId)).size !== reductions.length || reductions.some((row) => !bases.some((base) => base.lineId === row.lineId && (base.eligible || row.reductionCents === 0) && row.reductionCents <= base.basisCents))) throw new Error("Invalid discount code allocation");
8848
+ const lines = bases.map((base, index) => {
8849
+ const codeReductionCents = reductions.find((row) => row.lineId === base.lineId)?.reductionCents ?? cents$1(0);
8850
+ return {
8851
+ lineId: base.lineId,
8852
+ combinationReductionCents: cents$1((plan.lines[index]?.listCents ?? 0) - base.basisCents),
8853
+ codeReductionCents,
8854
+ totalCents: cents$1(base.basisCents - codeReductionCents)
8855
+ };
8856
+ });
8857
+ return {
8858
+ kind,
8859
+ applications: kind === "code_only" ? [] : plan.applications,
8860
+ lines,
8861
+ totalCents: cents$1(lines.reduce((sum, row) => sum + row.totalCents, 0)),
8862
+ listTotalCents: plan.listTotalCents
8863
+ };
8864
+ }
8865
+ /** Deliberately compares two candidates; this is not a joint combinations/code optimiser. */
8866
+ function compareCombinationPriceCode(plan, code) {
8867
+ const combined = codeCandidate(plan, code, "combinations_and_code");
8868
+ const alone = codeCandidate(plan, code, "code_only");
8869
+ return alone.totalCents < combined.totalCents ? alone : combined;
8870
+ }
8871
+
8872
+ //#endregion
8873
+ //#region ../commerce/src/purchase/flexibleBalanceCollection.ts
8874
+ function flexibleBalanceCollectionIsAvailable(collection) {
8875
+ return collection?.kind === "available";
8876
+ }
8877
+ const flexibleBalanceUnavailableCopy = "You can’t pay this balance online at the moment. Please contact us to arrange payment.";
8878
+ const flexibleBalanceProcessingCopy = "A payment for this booking is already being processed. Please check back in a few minutes.";
8879
+
8880
+ //#endregion
8881
+ //#region ../commerce/src/purchase/orderPaymentPosition.ts
8882
+ const cents = z.number().int().nonnegative().transform(toNonNegativeCents);
8883
+ const orderPaymentAdmissionSchema = z.discriminatedUnion("kind", [
8884
+ z.object({ kind: z.literal("admitted") }),
8885
+ z.object({ kind: z.literal("requires_provider_check") }),
8886
+ z.object({
8887
+ kind: z.literal("refused"),
8888
+ reason: z.enum([
8889
+ "in_progress",
8890
+ "cancelled",
8891
+ "disputed",
8892
+ "identity",
8893
+ "amounts",
8894
+ "conflicting_terms",
8895
+ "provider_reconciliation",
8896
+ "missing_instalments",
8897
+ "nothing_owed",
8898
+ "not_committed",
8899
+ "unsupported_payment_method",
8900
+ "live_terms",
8901
+ "not_applicable",
8902
+ "terms_closed",
8903
+ "refunded",
8904
+ "partly_cancelled",
8905
+ "retired",
8906
+ "retirement_pending",
8907
+ "cancelled_non_payment",
8908
+ "non_monetary",
8909
+ "settled",
8910
+ "checkout_failed",
8911
+ "archived",
8912
+ "recurring_collection_active",
8913
+ "below_card_minimum"
8914
+ ])
8915
+ })
8916
+ ]).readonly();
8917
+ const orderPaymentOperationKeys = [
8918
+ "manualReceipt",
8919
+ "waiver",
8920
+ "paymentLink",
8921
+ "demand",
8922
+ "partialRefund",
8923
+ "closeBalance",
8924
+ "instalmentSetup",
8925
+ "cashlessCompletion",
8926
+ "initialCheckout",
8927
+ "checkoutResume",
8928
+ "providerReceipt",
8929
+ "recovery",
8930
+ "closePlan",
8931
+ "partialManualReceipt",
8932
+ "expiryRelease",
8933
+ "manualReceiptPreparation",
8934
+ "waiverPreparation",
8935
+ "paymentLinkPreparation",
8936
+ "bookingRestore",
8937
+ "staffCancellation"
8938
+ ];
8939
+ const retirementScope = z.discriminatedUnion("kind", [
8940
+ z.object({ kind: z.literal("pending") }),
8941
+ z.object({ kind: z.literal("whole_order") }),
8942
+ z.object({ kind: z.literal("terms_only") }),
8943
+ z.object({
8944
+ kind: z.literal("items"),
8945
+ itemIds: z.array(z.string().uuid()).readonly()
8946
+ })
8947
+ ]).readonly();
8948
+ const orderRefundProtectionSchema = z.object({
8949
+ subject: z.discriminatedUnion("kind", [z.object({ kind: z.literal("none") }), z.object({
8950
+ kind: z.literal("protected_deposit"),
8951
+ sourceKind: z.enum(["flexible_balance", "instalment_plan"]),
8952
+ protectedDepositAmountCents: cents,
8953
+ depositRefundability: z.enum(["refundable", "non_refundable"])
8954
+ })]).readonly(),
8955
+ funding: z.array(z.object({
8956
+ orderItemId: z.string().uuid(),
8957
+ paymentReceiptId: z.string().uuid().nullable(),
8958
+ originalCents: cents,
8959
+ totalRemainingRefundableCents: cents,
8960
+ policyRefundableCents: cents,
8961
+ protectedDepositRemainingCents: cents
8962
+ }).readonly()).readonly()
8963
+ }).readonly();
8964
+ /** SQL owns the decision. This schema only parses its closed result. */
8965
+ const orderPaymentPositionSchema = z.object({
8966
+ orderStatus: z.enum([
8967
+ "pending",
8968
+ "paid",
8969
+ "partially_refunded",
8970
+ "refunded",
8971
+ "cancelled",
8972
+ "failed"
8973
+ ]),
8974
+ refundProtection: orderRefundProtectionSchema,
8975
+ amounts: z.object({
8976
+ totalCents: cents,
8977
+ collectedCents: cents,
8978
+ refundedCents: cents,
8979
+ waivedCents: cents,
8980
+ remainderCents: cents
8981
+ }).readonly(),
8982
+ lifecycle: z.discriminatedUnion("kind", [
8983
+ z.object({ kind: z.literal("open") }),
8984
+ z.object({
8985
+ kind: z.literal("retired"),
8986
+ scope: retirementScope,
8987
+ reason: z.enum([
8988
+ "staff",
8989
+ "checkout_failed",
8990
+ "abandoned_failed",
8991
+ "abandoned_cancelled",
8992
+ "dispute_lost",
8993
+ "booking_cancelled"
8994
+ ])
8995
+ }),
8996
+ z.object({ kind: z.literal("cancelled_non_payment") })
8997
+ ]).readonly(),
8998
+ openDispute: z.boolean(),
8999
+ termsLive: z.boolean(),
9000
+ admissions: z.object({
9001
+ bookingRestore: orderPaymentAdmissionSchema,
9002
+ staffCancellation: orderPaymentAdmissionSchema,
9003
+ manualReceipt: orderPaymentAdmissionSchema,
9004
+ waiver: orderPaymentAdmissionSchema,
9005
+ paymentLink: orderPaymentAdmissionSchema,
9006
+ demand: orderPaymentAdmissionSchema,
9007
+ partialRefund: orderPaymentAdmissionSchema,
9008
+ closeBalance: orderPaymentAdmissionSchema,
9009
+ instalmentSetup: orderPaymentAdmissionSchema,
9010
+ cashlessCompletion: orderPaymentAdmissionSchema,
9011
+ initialCheckout: orderPaymentAdmissionSchema,
9012
+ checkoutResume: orderPaymentAdmissionSchema,
9013
+ providerReceipt: orderPaymentAdmissionSchema,
9014
+ recovery: orderPaymentAdmissionSchema,
9015
+ closePlan: orderPaymentAdmissionSchema,
9016
+ partialManualReceipt: orderPaymentAdmissionSchema,
9017
+ expiryRelease: orderPaymentAdmissionSchema,
9018
+ manualReceiptPreparation: orderPaymentAdmissionSchema,
9019
+ waiverPreparation: orderPaymentAdmissionSchema,
9020
+ paymentLinkPreparation: orderPaymentAdmissionSchema
9021
+ }).readonly(),
9022
+ paymentSelection: z.object({
9023
+ kind: z.enum(["full", "custom"]),
9024
+ minimumCents: cents,
9025
+ maximumCents: cents,
9026
+ maximumCustomCents: cents,
9027
+ reason: z.enum(["overdue", "dust_balance"])
9028
+ }).readonly(),
9029
+ collection: z.discriminatedUnion("kind", [
9030
+ z.object({ kind: z.literal("available") }),
9031
+ z.object({ kind: z.literal("in_progress") }),
9032
+ z.object({
9033
+ kind: z.literal("closed"),
9034
+ reason: z.enum([
9035
+ "archived",
9036
+ "partly_cancelled",
9037
+ "retired",
9038
+ "retirement_pending",
9039
+ "cancelled_non_payment",
9040
+ "disputed",
9041
+ "non_monetary",
9042
+ "settled",
9043
+ "terms_closed",
9044
+ "refunded",
9045
+ "not_committed",
9046
+ "checkout_failed"
9047
+ ])
9048
+ }),
9049
+ z.object({
9050
+ kind: z.literal("unresolved"),
9051
+ reason: z.enum([
9052
+ "identity",
9053
+ "amounts",
9054
+ "conflicting_terms",
9055
+ "provider_reconciliation",
9056
+ "missing_instalments"
9057
+ ])
9058
+ })
9059
+ ]).readonly(),
9060
+ deadline: z.discriminatedUnion("kind", [
9061
+ z.object({ kind: z.literal("none") }),
9062
+ z.object({
9063
+ kind: z.literal("not_yet_due"),
9064
+ dueAt: z.string().datetime({ offset: true }),
9065
+ dueDay: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
9066
+ timezone: z.string().optional()
9067
+ }),
9068
+ z.object({
9069
+ kind: z.literal("overdue"),
9070
+ dueAt: z.string().datetime({ offset: true }),
9071
+ dueDay: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
9072
+ timezone: z.string().optional()
9073
+ })
9074
+ ]).readonly(),
9075
+ terms: z.discriminatedUnion("kind", [
9076
+ z.object({ kind: z.literal("immediate") }),
9077
+ z.object({ kind: z.literal("manual") }),
9078
+ z.object({
9079
+ kind: z.literal("flexible_balance"),
9080
+ contractId: z.string().uuid().transform(unsafeAsOrderFlexibleBalanceContractId),
9081
+ upfrontAmountCents: cents
9082
+ }),
9083
+ z.object({
9084
+ kind: z.literal("instalment_plan"),
9085
+ paymentPlanId: z.string().uuid().transform(unsafeAsOrderPaymentPlanId),
9086
+ nextDueAmountCents: cents.nullable(),
9087
+ collectionStopped: z.boolean(),
9088
+ state: z.object({ kind: z.enum([
9089
+ "active",
9090
+ "payment_failed",
9091
+ "pending_initial_payment",
9092
+ "reconciliation_required",
9093
+ "cancelled",
9094
+ "refunded",
9095
+ "completed"
9096
+ ]) }).readonly()
9097
+ })
9098
+ ]).readonly(),
9099
+ paymentMethod: z.enum([
9100
+ "free",
9101
+ "waived",
9102
+ "pass_redemption",
9103
+ "membership_access",
9104
+ "stripe",
9105
+ "store_credit",
9106
+ "mixed",
9107
+ "manual"
9108
+ ]),
9109
+ currency: z.string().transform((value, ctx) => {
9110
+ const currency = parseCurrencyCode(value);
9111
+ if (currency) return currency;
9112
+ ctx.addIssue({
9113
+ code: "custom",
9114
+ message: "Invalid currency code"
9115
+ });
9116
+ return z.NEVER;
9117
+ })
9118
+ }).superRefine((position, ctx) => {
9119
+ const { totalCents, collectedCents, waivedCents, refundedCents, remainderCents } = position.amounts;
9120
+ if (remainderCents !== Math.max(0, totalCents - collectedCents - waivedCents)) ctx.addIssue({
9121
+ code: "custom",
9122
+ path: ["amounts", "remainderCents"],
9123
+ message: "Payment remainder does not match its facts"
9124
+ });
9125
+ if (refundedCents > collectedCents) ctx.addIssue({
9126
+ code: "custom",
9127
+ path: ["amounts", "refundedCents"],
9128
+ message: "Refund exceeds collection"
9129
+ });
9130
+ if (position.collection.kind === "available" && (position.lifecycle.kind !== "open" || position.openDispute)) ctx.addIssue({
9131
+ code: "custom",
9132
+ path: ["collection"],
9133
+ message: "Available collection requires an open undisputed order"
9134
+ });
9135
+ if (position.deadline.kind !== "none" && position.terms.kind !== "flexible_balance" && position.terms.kind !== "instalment_plan") ctx.addIssue({
9136
+ code: "custom",
9137
+ path: ["deadline"],
9138
+ message: "A deadline requires agreed payment terms"
9139
+ });
9140
+ }).readonly();
9141
+ const parseOrderPaymentPosition = (value) => orderPaymentPositionSchema.parse(value);
9142
+ /** History snapshots have totals, not live collection evidence. Never reopen them. */
9143
+ function parseArchivedOrderPaymentPosition(snapshot) {
9144
+ return parseOrderPaymentPosition({
9145
+ orderStatus: snapshot.status,
9146
+ amounts: {
9147
+ ...snapshot,
9148
+ remainderCents: calculateOutstandingOrderAmountCents({
9149
+ totalCents: snapshot.totalCents,
9150
+ settledCents: snapshot.collectedCents + snapshot.waivedCents
9151
+ })
9152
+ },
9153
+ lifecycle: snapshot.status === "cancelled" ? {
9154
+ kind: "retired",
9155
+ scope: { kind: "whole_order" },
9156
+ reason: "booking_cancelled"
9157
+ } : snapshot.status === "failed" ? {
9158
+ kind: "retired",
9159
+ scope: { kind: "terms_only" },
9160
+ reason: "checkout_failed"
9161
+ } : { kind: "open" },
9162
+ termsLive: false,
9163
+ admissions: Object.fromEntries(orderPaymentOperationKeys.map((key) => [key, {
9164
+ kind: "refused",
9165
+ reason: "archived"
9166
+ }])),
9167
+ refundProtection: {
9168
+ subject: { kind: "none" },
9169
+ funding: []
9170
+ },
9171
+ paymentSelection: {
9172
+ kind: "full",
9173
+ minimumCents: 0,
9174
+ maximumCents: 0,
9175
+ maximumCustomCents: 0,
9176
+ reason: "dust_balance"
9177
+ },
9178
+ openDispute: false,
9179
+ collection: {
9180
+ kind: "closed",
9181
+ reason: "archived"
9182
+ },
9183
+ deadline: { kind: "none" },
9184
+ terms: { kind: snapshot.paymentMethod === "manual" ? "manual" : "immediate" },
9185
+ paymentMethod: snapshot.paymentMethod,
9186
+ currency: snapshot.currency
9187
+ });
9188
+ }
9189
+ /** Retain per-item SQL caps alongside their source totals; allocators never rebuild them. */
9190
+ function projectOrderRefundExposure(protection, paymentReceiptId, orderItemIds) {
9191
+ const funding = protection.funding.filter((line) => line.paymentReceiptId === paymentReceiptId && orderItemIds.includes(line.orderItemId));
9192
+ return {
9193
+ subject: protection.subject,
9194
+ policyLineRemaining: funding.map((line) => ({
9195
+ orderItemId: line.orderItemId,
9196
+ remainingCents: line.policyRefundableCents
9197
+ })),
9198
+ unrestrictedLineRemaining: funding.map((line) => ({
9199
+ orderItemId: line.orderItemId,
9200
+ remainingCents: line.totalRemainingRefundableCents
9201
+ })),
9202
+ totalRemainingRefundableCents: toNonNegativeCents(funding.reduce((sum, line) => sum + line.totalRemainingRefundableCents, 0)),
9203
+ policyRefundableCents: toNonNegativeCents(funding.reduce((sum, line) => sum + line.policyRefundableCents, 0)),
9204
+ protectedDepositRemainingCents: toNonNegativeCents(funding.reduce((sum, line) => sum + line.protectedDepositRemainingCents, 0))
9205
+ };
9206
+ }
9207
+
9208
+ //#endregion
9209
+ //#region ../commerce/src/purchase/orderPaymentLabels.ts
9210
+ const NEEDS_CHECKING_OWNER_HINT = "We couldn't work out what's still owed on this booking, so we've paused payment requests. Contact us and we'll sort it out.";
9211
+ function orderPaymentLabelFormatters(currency, context) {
9212
+ return {
9213
+ money: (cents$2) => formatCurrencyAmount(cents$2, currency, { decimals: "auto" }),
9214
+ day: (day) => formatDate(day, context, {
9215
+ date: "short",
9216
+ year: "omit"
9217
+ })
9218
+ };
9219
+ }
9220
+ function effectiveDueDay(deadline) {
9221
+ return deadline.dueDay ? {
9222
+ kind: "civil",
9223
+ value: parseBookingLocalDate(deadline.dueDay)
9224
+ } : {
9225
+ kind: "instant",
9226
+ value: toUtcIsoDateTimeString(new Date(deadline.dueAt).toISOString())
9227
+ };
9228
+ }
9229
+ function decideBookingOutcome({ lifecycle, collection }) {
9230
+ switch (lifecycle.kind) {
9231
+ case "open": return collection.kind === "closed" && (collection.reason === "checkout_failed" || collection.reason === "not_committed") ? "checkout_not_finished" : "booked";
9232
+ case "cancelled_non_payment": return "cancelled_non_payment";
9233
+ case "retired":
9234
+ if (lifecycle.scope.kind === "whole_order") return "cancelled";
9235
+ switch (lifecycle.reason) {
9236
+ case "checkout_failed":
9237
+ case "abandoned_failed":
9238
+ case "abandoned_cancelled": return "checkout_not_finished";
9239
+ case "dispute_lost": return "dispute_lost";
9240
+ case "staff":
9241
+ case "booking_cancelled": return collection.kind === "closed" && collection.reason === "partly_cancelled" ? "partly_cancelled" : "cancelled";
9242
+ default: return assertNever(lifecycle.reason);
9243
+ }
9244
+ default: return assertNever(lifecycle);
9245
+ }
9246
+ }
9247
+ function decideStillToPay({ amounts, collection, deadline }) {
9248
+ if (collection.kind !== "available" || amounts.remainderCents === 0) return { kind: "nothing" };
9249
+ const cents$2 = amounts.remainderCents;
9250
+ return deadline.kind === "none" ? {
9251
+ kind: "no_deadline",
9252
+ cents: cents$2
9253
+ } : {
9254
+ kind: deadline.kind,
9255
+ cents: cents$2,
9256
+ day: effectiveDueDay(deadline)
9257
+ };
9258
+ }
9259
+ function decidePaidInFull(position, outcome) {
9260
+ const { collectedCents, refundedCents, waivedCents, remainderCents } = position.amounts;
9261
+ if (outcome !== "booked" || remainderCents > 0 || refundedCents > 0 || waivedCents > 0) return null;
9262
+ switch (position.paymentMethod) {
9263
+ case "store_credit": return {
9264
+ kind: "paid_in_full",
9265
+ via: "credit"
9266
+ };
9267
+ case "manual": return collectedCents > 0 ? {
9268
+ kind: "paid_in_full",
9269
+ via: "offline"
9270
+ } : null;
9271
+ case "stripe":
9272
+ case "mixed": return collectedCents > 0 ? {
9273
+ kind: "paid_in_full",
9274
+ via: "online"
9275
+ } : null;
9276
+ case "waived":
9277
+ case "free":
9278
+ case "pass_redemption":
9279
+ case "membership_access": return null;
9280
+ default: return assertNever(position.paymentMethod);
9281
+ }
9282
+ }
9283
+ function decideInstalmentStanding(position) {
9284
+ const { terms, deadline, collection, amounts } = position;
9285
+ if (terms.kind !== "instalment_plan" || collection.kind !== "available") return null;
9286
+ switch (terms.state.kind) {
9287
+ case "payment_failed": return {
9288
+ kind: "instalment_failed",
9289
+ canPayNow: position.admissions.paymentLink.kind === "admitted"
9290
+ };
9291
+ case "active":
9292
+ if (amounts.collectedCents === 0 || deadline.kind === "overdue") return null;
9293
+ return {
9294
+ kind: "instalments_running",
9295
+ next: deadline.kind === "not_yet_due" && terms.nextDueAmountCents !== null ? {
9296
+ cents: terms.nextDueAmountCents,
9297
+ day: effectiveDueDay(deadline)
9298
+ } : null
9299
+ };
9300
+ case "pending_initial_payment":
9301
+ case "reconciliation_required":
9302
+ case "cancelled":
9303
+ case "refunded":
9304
+ case "completed": return null;
9305
+ default: return assertNever(terms.state.kind);
9306
+ }
9307
+ }
9308
+ function decideMoneyStanding(position, outcome) {
9309
+ const { terms, collection } = position;
9310
+ const planState = terms.kind === "instalment_plan" ? terms.state.kind : null;
9311
+ if (collection.kind === "unresolved" || planState === "reconciliation_required") return { kind: "needs_checking" };
9312
+ switch (position.paymentMethod) {
9313
+ case "free": return {
9314
+ kind: "covered",
9315
+ by: "free"
9316
+ };
9317
+ case "pass_redemption": return {
9318
+ kind: "covered",
9319
+ by: "pass"
9320
+ };
9321
+ case "membership_access": return {
9322
+ kind: "covered",
9323
+ by: "membership"
9324
+ };
9325
+ case "waived":
9326
+ case "stripe":
9327
+ case "store_credit":
9328
+ case "mixed":
9329
+ case "manual": break;
9330
+ default: return assertNever(position.paymentMethod);
9331
+ }
9332
+ if (planState === "pending_initial_payment" && collection.kind !== "closed") return { kind: "first_instalment_pending" };
9333
+ if (collection.kind === "in_progress") return { kind: "in_progress" };
9334
+ return decideInstalmentStanding(position) ?? decidePaidInFull(position, outcome) ?? {
9335
+ kind: "amounts",
9336
+ stillToPay: decideStillToPay(position)
9337
+ };
9338
+ }
9339
+ const OWNER_COPY = {
9340
+ noPaymentDue: "No payment due",
9341
+ nothingPaid: "Nothing paid",
9342
+ credit: "Paid with credit",
9343
+ pass: "Covered by pass or package",
9344
+ membership: "Covered by membership",
9345
+ paidOnline: "Paid",
9346
+ paidOffline: "Paid offline",
9347
+ inProgress: "Payment in progress",
9348
+ firstInstalmentPending: "Waiting for the first payment",
9349
+ instalmentFailed: "A payment didn't go through",
9350
+ waived: (amount) => `${amount} waived`,
9351
+ dueNoDeadline: (amount) => `${amount} due`,
9352
+ due: (amount, day) => `${amount} due by ${day}`,
9353
+ overdue: (amount, day) => `${amount} overdue (due ${day})`,
9354
+ instalments: ({ paid, refunded, next }) => [
9355
+ paid,
9356
+ refunded,
9357
+ next && `next ${next.amount} on ${next.day}`
9358
+ ].filter((part) => part !== null).join(" · ")
9359
+ };
9360
+ const CUSTOMER_COPY = {
9361
+ noPaymentDue: "No payment due",
9362
+ nothingPaid: "Nothing paid",
9363
+ credit: "Paid with credit",
9364
+ pass: "Covered by pass or package",
9365
+ membership: "Covered by membership",
9366
+ paidOnline: "Paid",
9367
+ paidOffline: "Paid",
9368
+ inProgress: "Your payment is being processed",
9369
+ firstInstalmentPending: "Your first payment is being processed",
9370
+ instalmentFailed: "A payment didn't go through.",
9371
+ waived: () => null,
9372
+ dueNoDeadline: (amount) => `${amount} to pay`,
9373
+ due: (amount, day) => `${amount} to pay by ${day}`,
9374
+ overdue: (amount, day) => `${amount} to pay. It was due on ${day}.`,
9375
+ instalments: ({ paid, refunded, next }) => [
9376
+ paid,
9377
+ refunded,
9378
+ next && `Next payment of ${next.amount} on ${next.day}`
9379
+ ].filter((part) => part !== null).join(". ") + (next || refunded ? "." : "")
9380
+ };
9381
+ function moneySegments(position, outcome, copy, format, stillToPay) {
9382
+ const { collectedCents, refundedCents, waivedCents } = position.amounts;
9383
+ const keptCents = collectedCents - refundedCents;
9384
+ const cancelled = outcome === "cancelled" || outcome === "cancelled_non_payment";
9385
+ const paid = collectedCents === 0 ? null : cancelled && refundedCents === 0 ? `${format.money(collectedCents)} paid, not refunded` : `${format.money(collectedCents)} paid`;
9386
+ return [
9387
+ paid,
9388
+ refundedCents > 0 ? `${format.money(refundedCents)} refunded` : null,
9389
+ cancelled && refundedCents > 0 && keptCents > 0 ? `${format.money(keptCents)} not refunded` : null,
9390
+ waivedCents > 0 ? copy.waived(format.money(waivedCents)) : null,
9391
+ stillToPaySegment(stillToPay, copy, format)
9392
+ ].filter((segment) => segment !== null);
9393
+ }
9394
+ function stillToPaySegment(stillToPay, copy, format) {
9395
+ switch (stillToPay.kind) {
9396
+ case "nothing": return null;
9397
+ case "no_deadline": return copy.dueNoDeadline(format.money(stillToPay.cents));
9398
+ case "not_yet_due": return copy.due(format.money(stillToPay.cents), format.day(stillToPay.day));
9399
+ case "overdue": return copy.overdue(format.money(stillToPay.cents), format.day(stillToPay.day));
9400
+ default: return assertNever(stillToPay);
9401
+ }
9402
+ }
9403
+ function needsCheckingMoneyLine(position, outcome, audience, copy, format) {
9404
+ if (audience.audience === "owner") return "Needs checking";
9405
+ const checking = `We're checking what's left to pay. ${audience.siteName} will be in touch.`;
9406
+ const segments = moneySegments(position, outcome, copy, format, { kind: "nothing" });
9407
+ return segments.length > 0 ? `${segments.join(" · ")}. ${checking}` : checking;
9408
+ }
9409
+ function moneyLine(standing, position, outcome, audience, format) {
9410
+ const copy = audience.audience === "owner" ? OWNER_COPY : CUSTOMER_COPY;
9411
+ switch (standing.kind) {
9412
+ case "covered": return {
9413
+ free: copy.noPaymentDue,
9414
+ pass: copy.pass,
9415
+ membership: copy.membership
9416
+ }[standing.by];
9417
+ case "needs_checking": return needsCheckingMoneyLine(position, outcome, audience, copy, format);
9418
+ case "first_instalment_pending": return copy.firstInstalmentPending;
9419
+ case "in_progress": return copy.inProgress;
9420
+ case "instalment_failed": return audience.audience === "customer" && standing.canPayNow ? `${copy.instalmentFailed} You can pay the rest now.` : copy.instalmentFailed;
9421
+ case "instalments_running": {
9422
+ const { collectedCents, refundedCents, totalCents } = position.amounts;
9423
+ return copy.instalments({
9424
+ paid: `${format.money(collectedCents)} of ${format.money(totalCents)} paid`,
9425
+ refunded: refundedCents > 0 ? `${format.money(refundedCents)} refunded` : null,
9426
+ next: standing.next && {
9427
+ amount: format.money(standing.next.cents),
9428
+ day: format.day(standing.next.day)
9429
+ }
9430
+ });
9431
+ }
9432
+ case "paid_in_full": return {
9433
+ online: copy.paidOnline,
9434
+ credit: copy.credit,
9435
+ offline: copy.paidOffline
9436
+ }[standing.via];
9437
+ case "amounts": {
9438
+ const segments = moneySegments(position, outcome, copy, format, standing.stillToPay);
9439
+ if (segments.length > 0) return segments.join(" · ");
9440
+ return position.amounts.remainderCents === 0 ? copy.noPaymentDue : copy.nothingPaid;
9441
+ }
9442
+ default: return assertNever(standing);
9443
+ }
9444
+ }
9445
+ function moneyTone(standing, position, outcome) {
9446
+ switch (standing.kind) {
9447
+ case "needs_checking":
9448
+ case "instalment_failed": return "problem";
9449
+ case "paid_in_full": return "success";
9450
+ case "instalments_running": return "attention";
9451
+ case "covered":
9452
+ case "first_instalment_pending":
9453
+ case "in_progress": return "neutral";
9454
+ case "amounts": switch (standing.stillToPay.kind) {
9455
+ case "overdue": return "problem";
9456
+ case "not_yet_due":
9457
+ case "no_deadline": return "attention";
9458
+ case "nothing": return outcome === "booked" && position.amounts.remainderCents === 0 && position.amounts.collectedCents > position.amounts.refundedCents ? "success" : "neutral";
9459
+ default: return assertNever(standing.stillToPay);
9460
+ }
9461
+ default: return assertNever(standing);
9462
+ }
9463
+ }
9464
+ function bookingOutcomeLabel(outcome, audience) {
9465
+ switch (outcome) {
9466
+ case "booked": return null;
9467
+ case "cancelled": return "Cancelled";
9468
+ case "cancelled_non_payment": return audience === "owner" ? "Cancelled for non-payment" : "Cancelled";
9469
+ case "partly_cancelled": return "Partly cancelled";
9470
+ case "checkout_not_finished": return "Checkout not finished";
9471
+ case "dispute_lost": return audience === "owner" ? "Dispute lost" : null;
9472
+ default: return assertNever(outcome);
9473
+ }
9474
+ }
9475
+ function bookingLine(position, outcome, audience) {
9476
+ const archived = position.collection.kind === "closed" && position.collection.reason === "archived";
9477
+ const parts = [
9478
+ bookingOutcomeLabel(outcome, audience),
9479
+ audience === "owner" && position.openDispute ? "Payment disputed" : null,
9480
+ audience === "owner" && archived ? "Archived" : null
9481
+ ].filter((part) => part !== null);
9482
+ return parts.length > 0 ? parts.join(" · ") : null;
9483
+ }
9484
+ /** The one owner of how a payment position reads, for site owners and their customers. */
9485
+ function describeOrderPayment(position, audience, format) {
9486
+ const outcome = decideBookingOutcome(position);
9487
+ const standing = decideMoneyStanding(position, outcome);
9488
+ const disputeShown = audience.audience === "owner" && (position.openDispute || outcome === "dispute_lost");
9489
+ return {
9490
+ booking: bookingLine(position, outcome, audience.audience),
9491
+ money: moneyLine(standing, position, outcome, audience, format),
9492
+ tone: disputeShown ? "problem" : moneyTone(standing, position, outcome),
9493
+ ownerHint: audience.audience === "owner" && standing.kind === "needs_checking" ? NEEDS_CHECKING_OWNER_HINT : null
9494
+ };
9495
+ }
9496
+
8608
9497
  //#endregion
8609
9498
  //#region ../site-contracts/src/siteData/eventCheckout.ts
8610
9499
  const uuid = z.string().uuid();
@@ -8654,7 +9543,13 @@ const eventBookingOutcomeSchema = z.discriminatedUnion("kind", [z.object({
8654
9543
  identity: confirmedBookingIdentitySchema,
8655
9544
  ...arrivalFields
8656
9545
  }).strict()]);
9546
+ const priceReductionSummarySchema = z.object({
9547
+ kind: z.enum(["discount_code", "combination_price"]),
9548
+ label: z.string(),
9549
+ amountCents: z.number().int().nonnegative()
9550
+ }).strict();
8657
9551
  const eventEmbeddedCheckoutSchema = z.object({
9552
+ priceReductions: z.tuple([priceReductionSummarySchema]).rest(priceReductionSummarySchema).readonly().optional(),
8658
9553
  kind: z.literal("embedded"),
8659
9554
  sessionId: z.string().min(1),
8660
9555
  clientSecret: z.string().min(1),
@@ -8677,16 +9572,21 @@ const eventRegistrationSummarySchema = z.object({
8677
9572
  message: z.string(),
8678
9573
  passCreditsRemaining: z.number().int().nonnegative().optional()
8679
9574
  }).strict();
9575
+ const bookingOutcomesSchema = z.tuple([eventBookingOutcomeSchema]).rest(eventBookingOutcomeSchema).readonly().refine((outcomes) => outcomes.length <= MAX_EVENT_BOOKING_SELECTION_ITEMS, "Too many booking outcomes");
9576
+ const bookingReferencesSchema = z.tuple([eventRegistrationStatusReferenceSchema]).rest(eventRegistrationStatusReferenceSchema).readonly().refine((references) => references.length <= MAX_EVENT_BOOKING_SELECTION_ITEMS, "Too many booking references");
9577
+ const registrationIdsSchema = z.tuple([uuid]).rest(uuid).readonly().refine((ids) => ids.length <= MAX_EVENT_BOOKING_SELECTION_ITEMS, "Too many registrations");
8680
9578
  const eventRegisterResponseSchema = z.discriminatedUnion("kind", [
8681
9579
  z.object({
8682
9580
  kind: z.literal("bookingComplete"),
8683
9581
  outcome: eventBookingOutcomeSchema,
9582
+ outcomes: bookingOutcomesSchema.optional(),
8684
9583
  summary: eventRegistrationSummarySchema,
8685
9584
  ...decorations
8686
9585
  }).strict(),
8687
9586
  z.object({
8688
9587
  kind: z.literal("checkoutRequired"),
8689
9588
  reference: eventRegistrationStatusReferenceSchema,
9589
+ references: bookingReferencesSchema.optional(),
8690
9590
  checkout: eventEmbeddedCheckoutSchema,
8691
9591
  submissionId: uuid,
8692
9592
  ...decorations
@@ -8712,12 +9612,16 @@ const eventRegisterResponseSchema = z.discriminatedUnion("kind", [
8712
9612
  }).strict(),
8713
9613
  ...decorations
8714
9614
  }).strict()
8715
- ]);
9615
+ ]).superRefine((response, ctx) => {
9616
+ if (response.kind === "bookingComplete") validateOutcomeList(response, ctx);
9617
+ if (response.kind === "checkoutRequired") validateReferenceList(response, ctx);
9618
+ });
8716
9619
  const checkoutStatusArms = [
8717
9620
  z.object({
8718
9621
  kind: z.literal("resolved"),
8719
- outcome: eventBookingOutcomeSchema
8720
- }).strict(),
9622
+ outcome: eventBookingOutcomeSchema,
9623
+ outcomes: bookingOutcomesSchema.optional()
9624
+ }).strict().superRefine(validateOutcomeList),
8721
9625
  z.object({ kind: z.literal("abandoned") }).strict(),
8722
9626
  z.object({ kind: z.literal("reconciliationRequired") }).strict(),
8723
9627
  z.object({
@@ -8726,6 +9630,7 @@ const checkoutStatusArms = [
8726
9630
  }).strict(),
8727
9631
  z.object({
8728
9632
  kind: z.literal("paymentAvailable"),
9633
+ references: bookingReferencesSchema.optional(),
8729
9634
  checkout: eventEmbeddedCheckoutSchema,
8730
9635
  recoverableUntil: z.string().optional()
8731
9636
  }).strict(),
@@ -8749,8 +9654,7 @@ const eventCheckoutReturnResponseSchema = z.discriminatedUnion("kind", [
8749
9654
  z.object({ kind: z.literal("reconciliationRequired") }).strict()
8750
9655
  ]).superRefine((response, ctx) => {
8751
9656
  if (response.kind !== "checkout" || response.outcome.kind !== "resolved") return;
8752
- const identity = response.outcome.outcome.identity;
8753
- if (identity.scope !== response.subject.scope || identity.submissionId !== response.subject.submissionId || identity.scope === "occurrence" && response.subject.scope === "occurrence" && identity.attendeeId !== response.subject.attendeeId) {
9657
+ if (!identityMatchesSubject(response.outcome.outcome.identity, response.subject)) {
8754
9658
  ctx.addIssue({
8755
9659
  code: "custom",
8756
9660
  message: "Confirmed booking does not match checkout subject",
@@ -8770,6 +9674,7 @@ const eventCheckoutResponseSchema = z.union([
8770
9674
  kind: z.literal("completed"),
8771
9675
  scope: z.literal("wholeSeries"),
8772
9676
  outcome: eventBookingOutcomeSchema,
9677
+ outcomes: bookingOutcomesSchema.optional(),
8773
9678
  ...checkoutDecorations
8774
9679
  }).strict(),
8775
9680
  z.object({
@@ -8783,6 +9688,7 @@ const eventCheckoutResponseSchema = z.union([
8783
9688
  kind: z.literal("checkoutRequired"),
8784
9689
  scope: z.literal("wholeSeries"),
8785
9690
  registrationId: uuid,
9691
+ registrationIds: registrationIdsSchema.optional(),
8786
9692
  checkoutAttemptId: uuid,
8787
9693
  checkout: eventEmbeddedCheckoutSchema,
8788
9694
  recoverableUntil: z.string().optional(),
@@ -8804,16 +9710,65 @@ const eventCheckoutResponseSchema = z.union([
8804
9710
  ...checkoutDecorations
8805
9711
  }).strict()
8806
9712
  ]).superRefine((response, ctx) => {
8807
- if ("kind" in response && response.kind === "completed" && response.scope !== response.outcome.identity.scope) ctx.addIssue({
9713
+ if (!("kind" in response)) return;
9714
+ if (response.kind === "completed") {
9715
+ if (response.scope !== response.outcome.identity.scope) ctx.addIssue({
9716
+ code: "custom",
9717
+ message: "Confirmed booking scope mismatch",
9718
+ path: [
9719
+ "outcome",
9720
+ "identity",
9721
+ "scope"
9722
+ ]
9723
+ });
9724
+ validateOutcomeList(response, ctx);
9725
+ }
9726
+ if (response.kind === "checkoutRequired" && response.scope === "wholeSeries" && response.registrationIds) {
9727
+ if (response.registrationIds[0] !== response.registrationId || new Set(response.registrationIds).size !== response.registrationIds.length) ctx.addIssue({
9728
+ code: "custom",
9729
+ message: "Registration list does not match its first reference or repeats a booking",
9730
+ path: ["registrationIds"]
9731
+ });
9732
+ }
9733
+ });
9734
+ function bookingReferenceKey(reference) {
9735
+ return reference.scope === "wholeSeries" ? `run:${reference.registrationId}` : `date:${reference.attendeeId}`;
9736
+ }
9737
+ /** Singular fields are aliases of the first member; every member belongs to one submission. */
9738
+ function validateOutcomeList(response, ctx) {
9739
+ const outcomes = response.outcomes;
9740
+ if (!outcomes) return;
9741
+ if (stableJsonStringify(outcomes[0]) !== stableJsonStringify(response.outcome)) ctx.addIssue({
8808
9742
  code: "custom",
8809
- message: "Confirmed booking scope mismatch",
8810
- path: [
8811
- "outcome",
8812
- "identity",
8813
- "scope"
8814
- ]
9743
+ message: "First booking outcome does not match the single-booking alias",
9744
+ path: ["outcomes", 0]
8815
9745
  });
8816
- });
9746
+ const identity = response.outcome.identity;
9747
+ if (outcomes.some((outcome) => outcome.identity.scope !== identity.scope || outcome.identity.submissionId !== identity.submissionId)) ctx.addIssue({
9748
+ code: "custom",
9749
+ message: "Booking outcomes must belong to the same submission and scope",
9750
+ path: ["outcomes"]
9751
+ });
9752
+ const keys = outcomes.map((outcome) => bookingReferenceKey(outcome.identity));
9753
+ if (new Set(keys).size !== keys.length) ctx.addIssue({
9754
+ code: "custom",
9755
+ message: "Booking outcomes repeat a booking",
9756
+ path: ["outcomes"]
9757
+ });
9758
+ }
9759
+ function validateReferenceList(response, ctx) {
9760
+ const references = response.references;
9761
+ if (!references) return;
9762
+ const keys = references.map(bookingReferenceKey);
9763
+ if (keys[0] !== bookingReferenceKey(response.reference) || new Set(keys).size !== keys.length || references.some((reference) => reference.scope !== response.reference.scope)) ctx.addIssue({
9764
+ code: "custom",
9765
+ message: "Booking references must be distinct, share a scope and match the first reference",
9766
+ path: ["references"]
9767
+ });
9768
+ }
9769
+ function identityMatchesSubject(identity, subject) {
9770
+ return identity.scope === subject.scope && identity.submissionId === subject.submissionId && (identity.scope !== "occurrence" || subject.scope !== "occurrence" || identity.attendeeId === subject.attendeeId);
9771
+ }
8817
9772
 
8818
9773
  //#endregion
8819
9774
  //#region ../site-contracts/src/siteData/bookingQuestions.ts
@@ -8827,6 +9782,67 @@ const BEFORE_BOOKING_QUESTIONS_ROUTE = {
8827
9782
  method: "POST"
8828
9783
  };
8829
9784
 
9785
+ //#endregion
9786
+ //#region ../site-contracts/src/siteData/eventSelection.ts
9787
+ function isHybrid(item) {
9788
+ return item.deliveryMode === "hybrid";
9789
+ }
9790
+ function offeredModes(item) {
9791
+ const delivery = item.deliveryMode ?? "in_person";
9792
+ return delivery === "hybrid" ? (item.attendanceModes ?? []).map((row) => row.mode) : [delivery];
9793
+ }
9794
+ function decideSelectionAttendance(items) {
9795
+ const [first, ...rest] = items;
9796
+ if (!first) return { kind: "none" };
9797
+ const common = rest.reduce((modes, item) => modes.filter((mode) => offeredModes(item).includes(mode)), offeredModes(first));
9798
+ const [only, ...others] = common;
9799
+ if (!items.every(isHybrid)) return only && others.length === 0 ? {
9800
+ kind: "fixed",
9801
+ mode: only
9802
+ } : { kind: "incompatible" };
9803
+ return rest.length > 0 && common.length === 0 ? { kind: "incompatible" } : {
9804
+ kind: "choose",
9805
+ modes: common
9806
+ };
9807
+ }
9808
+ /** The way of attending the booking uses: the fixed one, or the visitor's choice while it's still offered. */
9809
+ function resolveSelectionAttendanceMode(attendance, selected) {
9810
+ switch (attendance.kind) {
9811
+ case "none":
9812
+ case "incompatible": return null;
9813
+ case "fixed": return attendance.mode;
9814
+ case "choose": return selected !== null && attendance.modes.includes(selected) ? selected : null;
9815
+ }
9816
+ }
9817
+ const INCOMPATIBLE_ATTENDANCE_MESSAGE = "These runs can’t be booked together, because they don’t share a way to attend. Book them one at a time.";
9818
+
9819
+ //#endregion
9820
+ //#region ../site-contracts/src/siteData/eventSelectionRequirements.ts
9821
+ /** The consent text is its version: attachment IDs alone do not change when copy is edited. */
9822
+ function eventBookingConsentContentKey(consent) {
9823
+ return stableJsonStringify({
9824
+ title: consent.title,
9825
+ agreement: consent.agreement,
9826
+ checkboxLabel: consent.checkboxLabel
9827
+ });
9828
+ }
9829
+ /** Unavailable or older question payloads cannot prove that sharing is safe. */
9830
+ function areEventBookingRequirementsIdentical(requirements) {
9831
+ const keys = requirements.map(requirementsKey);
9832
+ const first = keys[0];
9833
+ return first !== undefined && first !== null && keys.every((key) => key === first);
9834
+ }
9835
+ function requirementsKey(view) {
9836
+ const questions = view.bookingQuestions;
9837
+ if (questions.kind === "unavailable") return null;
9838
+ const questionKey = questions.kind === "none" ? null : questions.set.sharingKey;
9839
+ if (questionKey === undefined) return null;
9840
+ return stableJsonStringify({
9841
+ consent: view.consent ? eventBookingConsentContentKey(view.consent) : null,
9842
+ questions: questionKey
9843
+ });
9844
+ }
9845
+
8830
9846
  //#endregion
8831
9847
  //#region ../api/src/publicEventEndpointDefinitions.ts
8832
9848
  const PUBLIC_EVENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
@@ -9157,6 +10173,13 @@ const EVENT_MANAGEMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
9157
10173
  "server:internal_error"
9158
10174
  ]
9159
10175
  },
10176
+ getEventGoLivePage: {
10177
+ path: "/sites/{siteId}/bookings/events/{eventId}/go-live-page",
10178
+ method: "GET",
10179
+ auth: "user",
10180
+ responseKind: "json",
10181
+ errors: ["validation:invalid_input", "server:internal_error"]
10182
+ },
9160
10183
  updateEventIdentity: {
9161
10184
  path: "/sites/{siteId}/bookings/events/{eventId}",
9162
10185
  method: "PATCH",
@@ -9226,6 +10249,18 @@ const EVENT_MANAGEMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
9226
10249
  "server:internal_error"
9227
10250
  ]
9228
10251
  },
10252
+ previewWholeSeriesRunCancellation: {
10253
+ path: "/sites/{siteId}/bookings/events/{eventId}/runs/{runId}/cancellation",
10254
+ method: "GET",
10255
+ tags: ["site-{siteId}", "event-series-{siteId}"],
10256
+ auth: "user",
10257
+ responseKind: "json",
10258
+ errors: [
10259
+ "auth:forbidden",
10260
+ "resource:not_found",
10261
+ "server:internal_error"
10262
+ ]
10263
+ },
9229
10264
  cancelWholeSeriesRun: {
9230
10265
  path: "/sites/{siteId}/bookings/events/{eventId}/runs/{runId}/cancellation",
9231
10266
  method: "POST",
@@ -9741,6 +10776,30 @@ const PUBLIC_ONBOARDING_ATTEMPT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions
9741
10776
  //#endregion
9742
10777
  //#region ../api/src/billingEndpointDefinitions.ts
9743
10778
  const BILLING_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
10779
+ adminSendSiteHandover: {
10780
+ path: "/admin/sites/{siteId}/handover",
10781
+ method: "POST",
10782
+ tags: ["admin"],
10783
+ auth: "admin",
10784
+ responseKind: "json",
10785
+ errors: []
10786
+ },
10787
+ adminResendSiteHandover: {
10788
+ path: "/admin/sites/{siteId}/handover/resend",
10789
+ method: "POST",
10790
+ tags: ["admin"],
10791
+ auth: "admin",
10792
+ responseKind: "json",
10793
+ errors: []
10794
+ },
10795
+ adminWithdrawSiteHandover: {
10796
+ path: "/admin/sites/{siteId}/handover/withdraw",
10797
+ method: "POST",
10798
+ tags: ["admin"],
10799
+ auth: "admin",
10800
+ responseKind: "json",
10801
+ errors: []
10802
+ },
9744
10803
  adminChangePlan: {
9745
10804
  path: "/admin/billing/plan",
9746
10805
  method: "POST",
@@ -9756,6 +10815,20 @@ const BILLING_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
9756
10815
  responseKind: "json",
9757
10816
  errors: []
9758
10817
  },
10818
+ previewPlanChange: {
10819
+ path: "/billing/plan/preview",
10820
+ method: "POST",
10821
+ tags: ["billing"],
10822
+ auth: "user",
10823
+ responseKind: "json",
10824
+ errors: [
10825
+ "validation:invalid_input",
10826
+ "auth:unauthenticated",
10827
+ "resource:conflict",
10828
+ "server:internal_error",
10829
+ "external:service_error"
10830
+ ]
10831
+ },
9759
10832
  changePlan: {
9760
10833
  path: "/billing/plan/change",
9761
10834
  method: "POST",
@@ -10721,6 +11794,18 @@ const ENDPOINT_DEFINITIONS = {
10721
11794
  "server:internal_error"
10722
11795
  ]
10723
11796
  },
11797
+ turnOnCourses: {
11798
+ path: "/sites/{siteId}/bookings/settings/courses",
11799
+ method: "POST",
11800
+ tags: [TAG_TEMPLATES.site, TAG_TEMPLATES.siteBookingSettings],
11801
+ auth: "user",
11802
+ responseKind: "json",
11803
+ errors: [
11804
+ "auth:forbidden",
11805
+ "resource:conflict",
11806
+ "server:internal_error"
11807
+ ]
11808
+ },
10724
11809
  sendTestEmail: {
10725
11810
  path: "/sites/{siteId}/settings/emails/test",
10726
11811
  method: "POST",
@@ -10803,6 +11888,30 @@ const ENDPOINT_DEFINITIONS = {
10803
11888
  responseKind: "json",
10804
11889
  errors: ["auth:forbidden", "server:internal_error"]
10805
11890
  },
11891
+ authEmailCodeSend: {
11892
+ path: "/auth/email-code/send",
11893
+ method: "POST",
11894
+ tags: ["auth"],
11895
+ auth: "public",
11896
+ responseKind: "json",
11897
+ errors: []
11898
+ },
11899
+ authEmailCodeVerify: {
11900
+ path: "/auth/email-code/verify",
11901
+ method: "POST",
11902
+ tags: ["auth"],
11903
+ auth: "public",
11904
+ responseKind: "json",
11905
+ errors: []
11906
+ },
11907
+ authForgetEmail: {
11908
+ path: "/auth/remembered-email/clear",
11909
+ method: "POST",
11910
+ tags: ["auth"],
11911
+ auth: "public",
11912
+ responseKind: "json",
11913
+ errors: []
11914
+ },
10806
11915
  authLogin: {
10807
11916
  path: "/auth/login/submit",
10808
11917
  method: "POST",
@@ -10831,6 +11940,22 @@ const ENDPOINT_DEFINITIONS = {
10831
11940
  auth: "public",
10832
11941
  responseKind: "json"
10833
11942
  },
11943
+ authReauthEmailCodeSend: {
11944
+ path: "/auth/reauth/email-code",
11945
+ method: "POST",
11946
+ tags: ["auth"],
11947
+ auth: "user",
11948
+ errors: [],
11949
+ responseKind: "json"
11950
+ },
11951
+ authReauthEmailCodeVerify: {
11952
+ path: "/auth/reauth/email-code/verify",
11953
+ method: "POST",
11954
+ tags: ["auth"],
11955
+ auth: "user",
11956
+ errors: [],
11957
+ responseKind: "json"
11958
+ },
10834
11959
  authStatus: {
10835
11960
  path: "/auth/status",
10836
11961
  method: "GET",
@@ -10888,6 +12013,14 @@ const ENDPOINT_DEFINITIONS = {
10888
12013
  auth: "user",
10889
12014
  responseKind: "json"
10890
12015
  },
12016
+ dismissSiteInviteWelcome: {
12017
+ path: "/sites/{siteId}/members/invite-welcome/dismiss",
12018
+ method: "POST",
12019
+ auth: "user",
12020
+ responseKind: "json",
12021
+ errors: ["auth:forbidden", "server:internal_error"],
12022
+ tags: ["site-{siteId}"]
12023
+ },
10891
12024
  revokeSiteInvitation: {
10892
12025
  path: "/sites/{siteId}/members/invitations/{invitationId}",
10893
12026
  method: "DELETE",
@@ -12000,6 +13133,22 @@ const ENDPOINT_DEFINITIONS = {
12000
13133
  auth: "user",
12001
13134
  responseKind: "json"
12002
13135
  },
13136
+ mfaRenameFactor: {
13137
+ path: "/auth/mfa/factors/{factorId}",
13138
+ method: "PATCH",
13139
+ tags: ["mfa"],
13140
+ auth: "user",
13141
+ errors: [],
13142
+ responseKind: "json"
13143
+ },
13144
+ mfaTurnOff: {
13145
+ path: "/auth/mfa/turn-off",
13146
+ method: "POST",
13147
+ tags: ["mfa"],
13148
+ auth: "user",
13149
+ errors: [],
13150
+ responseKind: "json"
13151
+ },
12003
13152
  mfaBackupCodesGet: {
12004
13153
  path: "/auth/mfa/backup-codes",
12005
13154
  method: "GET",
@@ -12054,6 +13203,18 @@ const ENDPOINT_DEFINITIONS = {
12054
13203
  ],
12055
13204
  responseKind: "json"
12056
13205
  },
13206
+ accountDismissTwoStepPrompt: {
13207
+ path: "/account/two-step-prompt/dismiss",
13208
+ method: "POST",
13209
+ tags: ["account"],
13210
+ auth: "user",
13211
+ errors: [
13212
+ "auth:unauthenticated",
13213
+ "validation:invalid_input",
13214
+ "server:internal_error"
13215
+ ],
13216
+ responseKind: "json"
13217
+ },
12057
13218
  accountRevokeSessions: {
12058
13219
  path: "/account/sessions/revoke",
12059
13220
  method: "POST",
@@ -12061,6 +13222,22 @@ const ENDPOINT_DEFINITIONS = {
12061
13222
  auth: "user",
12062
13223
  responseKind: "json"
12063
13224
  },
13225
+ accountRevokeSession: {
13226
+ path: "/account/sessions/{sessionId}",
13227
+ method: "DELETE",
13228
+ tags: ["account"],
13229
+ auth: "user",
13230
+ errors: [],
13231
+ responseKind: "json"
13232
+ },
13233
+ accountUnlinkGoogle: {
13234
+ path: "/account/identities/google",
13235
+ method: "DELETE",
13236
+ tags: ["account"],
13237
+ auth: "user",
13238
+ errors: [],
13239
+ responseKind: "json"
13240
+ },
12064
13241
  adminListInvites: {
12065
13242
  path: "/admin/invites",
12066
13243
  method: "GET",
@@ -14202,6 +15379,70 @@ const ENDPOINT_DEFINITIONS = {
14202
15379
  "server:internal_error"
14203
15380
  ]
14204
15381
  },
15382
+ endCustomerMembershipNow: {
15383
+ path: "/sites/{siteId}/bookings/customer-memberships/{customerMembershipId}/end",
15384
+ method: "POST",
15385
+ tags: [
15386
+ "site-{siteId}",
15387
+ "bookings",
15388
+ "customer-membership-{customerMembershipId}"
15389
+ ],
15390
+ auth: "user",
15391
+ responseKind: "json",
15392
+ errors: [
15393
+ "validation:invalid_input",
15394
+ "resource:not_found",
15395
+ "server:internal_error"
15396
+ ]
15397
+ },
15398
+ resumeCustomerMembership: {
15399
+ path: "/sites/{siteId}/bookings/customer-memberships/{customerMembershipId}/resume",
15400
+ method: "POST",
15401
+ tags: [
15402
+ "site-{siteId}",
15403
+ "bookings",
15404
+ "customer-membership-{customerMembershipId}"
15405
+ ],
15406
+ auth: "user",
15407
+ responseKind: "json",
15408
+ errors: [
15409
+ "validation:invalid_input",
15410
+ "resource:not_found",
15411
+ "server:internal_error"
15412
+ ]
15413
+ },
15414
+ finishCustomerMembershipChange: {
15415
+ path: "/sites/{siteId}/bookings/customer-memberships/{customerMembershipId}/finish",
15416
+ method: "POST",
15417
+ tags: [
15418
+ "site-{siteId}",
15419
+ "bookings",
15420
+ "customer-membership-{customerMembershipId}"
15421
+ ],
15422
+ auth: "user",
15423
+ responseKind: "json",
15424
+ errors: [
15425
+ "validation:invalid_input",
15426
+ "resource:not_found",
15427
+ "server:internal_error"
15428
+ ]
15429
+ },
15430
+ correctCustomerMembershipDates: {
15431
+ path: "/sites/{siteId}/bookings/customer-memberships/{customerMembershipId}",
15432
+ method: "PATCH",
15433
+ tags: [
15434
+ "site-{siteId}",
15435
+ "bookings",
15436
+ "customer-membership-{customerMembershipId}"
15437
+ ],
15438
+ auth: "user",
15439
+ responseKind: "json",
15440
+ errors: [
15441
+ "validation:invalid_input",
15442
+ "resource:not_found",
15443
+ "server:internal_error"
15444
+ ]
15445
+ },
14205
15446
  refundCustomerMembershipPayment: {
14206
15447
  path: "/sites/{siteId}/bookings/customer-memberships/{customerMembershipId}/refund",
14207
15448
  method: "POST",
@@ -15621,6 +16862,13 @@ const ENDPOINT_DEFINITIONS = {
15621
16862
  auth: "public",
15622
16863
  responseKind: "json"
15623
16864
  },
16865
+ portalResumeMembership: {
16866
+ path: "/portal/memberships/{customerMembershipId}/resume",
16867
+ method: "POST",
16868
+ auth: "public",
16869
+ responseKind: "json",
16870
+ errors: []
16871
+ },
15624
16872
  portalSendMagicLink: {
15625
16873
  path: "/portal/auth/send-magic-link",
15626
16874
  method: "POST",
@@ -15809,6 +17057,69 @@ function commandHeaders(endpoint, headers, operationId) {
15809
17057
  return result;
15810
17058
  }
15811
17059
 
17060
+ //#endregion
17061
+ //#region ../api/src/common/billingPlanChange.ts
17062
+ const accessBlockedSchema = z.object({
17063
+ kind: z.literal("access_blocked"),
17064
+ sites: z.array(z.object({
17065
+ siteId: z.string().uuid(),
17066
+ siteName: z.string(),
17067
+ reasons: z.array(z.enum([
17068
+ "website_collaboration_exceeds_target",
17069
+ "operational_access_not_supported",
17070
+ "multiple_active_staff"
17071
+ ]))
17072
+ }))
17073
+ });
17074
+ /** Why a plan change was refused: team access to remove first, or a preview too old to charge from. */
17075
+ const billingPlanChangeFailureSchema = z.discriminatedUnion("kind", [accessBlockedSchema, z.object({ kind: z.literal("preview_expired") })]);
17076
+ /**
17077
+ * The figures a plan change was confirmed from: the preview's proration date
17078
+ * and the monthly price it showed. The server refuses the change as
17079
+ * `preview_expired` when the date is too old or the price it works out now is
17080
+ * different, so an owner is never charged from figures they didn't see.
17081
+ */
17082
+ const planChangeQuoteSchema = z.object({
17083
+ prorationDate: z.number().int().positive(),
17084
+ monthlyPricePence: z.number().int().nonnegative()
17085
+ });
17086
+
17087
+ //#endregion
17088
+ //#region ../api/src/common/billingReturn.ts
17089
+ /**
17090
+ * Where an owner came from when a dashboard prompt sent them to Billing, so the
17091
+ * page can lead with the plan they came for and, after checkout, offer the way
17092
+ * back. It's a closed set rather than a URL, so a link can't be turned into an
17093
+ * open redirect. Launch keeps its own checkout continuation; this is only the
17094
+ * "Back to…" convenience.
17095
+ */
17096
+ const BILLING_RETURN_PAGES = [
17097
+ "site_team",
17098
+ "site_domains",
17099
+ "site_media",
17100
+ "site_home",
17101
+ "launch"
17102
+ ];
17103
+ const billingReturnSchema = z.object({
17104
+ page: z.enum(BILLING_RETURN_PAGES),
17105
+ siteId: z.string().uuid()
17106
+ });
17107
+ /** `site_team:<site uuid>`, the form a `from` query parameter carries. */
17108
+ function serializeBillingReturn(value) {
17109
+ return `${value.page}:${value.siteId}`;
17110
+ }
17111
+ /** Anything that isn't exactly one known page and a uuid is ignored. */
17112
+ function parseBillingReturn(raw) {
17113
+ if (!raw) return null;
17114
+ const separator = raw.indexOf(":");
17115
+ if (separator < 0) return null;
17116
+ const parsed = billingReturnSchema.safeParse({
17117
+ page: raw.slice(0, separator),
17118
+ siteId: raw.slice(separator + 1)
17119
+ });
17120
+ return parsed.success ? parsed.data : null;
17121
+ }
17122
+
15812
17123
  //#endregion
15813
17124
  //#region ../api/src/bookingVerticals.ts
15814
17125
  /**
@@ -16196,6 +17507,15 @@ const pageDesignBoundaryTreatmentSchema = z.discriminatedUnion("kind", [
16196
17507
  ]),
16197
17508
  echo: z.literal(true).optional()
16198
17509
  }).strict(),
17510
+ z.object({
17511
+ kind: z.literal("arc-edge"),
17512
+ height: z.enum([
17513
+ "compact",
17514
+ "medium",
17515
+ "large"
17516
+ ]),
17517
+ echo: z.literal(true).optional()
17518
+ }).strict(),
16199
17519
  z.object({
16200
17520
  kind: z.literal("angle-edge"),
16201
17521
  height: z.enum([
@@ -17526,6 +18846,13 @@ function resolveBookingSettingsEventCatalogue(settings) {
17526
18846
  eventTypePresets: settings.eventTypePresets ?? DEFAULT_EVENT_TYPE_PRESETS
17527
18847
  });
17528
18848
  }
18849
+ /** Normalizes the same wire default as the catalogue before planning the change. */
18850
+ function planBookingSettingsCoursesTurnOn(settings) {
18851
+ return planTurningOnCourses({
18852
+ verticalConfig: settings.verticalConfig,
18853
+ eventTypePresets: settings.eventTypePresets ?? DEFAULT_EVENT_TYPE_PRESETS
18854
+ });
18855
+ }
17529
18856
 
17530
18857
  //#endregion
17531
18858
  //#region ../api/src/sdkManagementResponseSchemas.ts
@@ -19280,6 +20607,7 @@ const lookKnobBlocks = {
19280
20607
  showPhotos: cardListKnobBlocks,
19281
20608
  cardMarker: cardListFamilyBlocks,
19282
20609
  dates: "block.offerings-preview",
20610
+ grouping: "block.offerings-preview",
19283
20611
  columns: "block.feature-cards",
19284
20612
  listColumns: "block.event-calendar",
19285
20613
  blackAndWhite: "block.image-gallery",
@@ -21543,16 +22871,6 @@ async function confirmAction(message, options, isRemote) {
21543
22871
  });
21544
22872
  });
21545
22873
  }
21546
- /** Environment target/client helpers are backed by the execution boundary. */
21547
- /**
21548
- * Create a management client for a specific environment target.
21549
- *
21550
- * @param target - Environment target (local or remote)
21551
- * @returns Management client configured for that environment
21552
- */
21553
- function createClientForEnv(target) {
21554
- return createManagementClient(managementClientConfigFor(loadSdkEnvironment(target)));
21555
- }
21556
22874
  /**
21557
22875
  * Resolve the environment setting from global options.
21558
22876
  * Handles --env flag and deprecated --remote flag.
@@ -21800,95 +23118,6 @@ function withConfirmation(getMessage, action) {
21800
23118
  }
21801
23119
  };
21802
23120
  }
21803
- /**
21804
- * Capitalize the first letter of a string.
21805
- */
21806
- function capitalize(str) {
21807
- return str.charAt(0).toUpperCase() + str.slice(1);
21808
- }
21809
- /**
21810
- * Create a get command for a resource.
21811
- *
21812
- * @example
21813
- * const getCommand = createGetCommand({
21814
- * resourceName: 'entry',
21815
- * args: ['type', 'identifier'],
21816
- * get: (client, type, id) => client.entries.get(type, id),
21817
- * formatOutput: (entry) => ({
21818
- * id: entry.id,
21819
- * status: entry.status,
21820
- * }),
21821
- * });
21822
- */
21823
- function createGetCommand(config) {
21824
- const cmd = new Command("get").description(`Get a single ${config.resourceName}`);
21825
- for (const arg of config.args) {
21826
- cmd.argument(`<${arg}>`, `${capitalize(arg.replace("-", " "))}`);
21827
- }
21828
- return cmd.action(withErrorHandling(async (...actionArgs) => {
21829
- const args = actionArgs.slice(0, config.args.length);
21830
- const command = actionArgs[actionArgs.length - 1];
21831
- const { output, client, isJsonOutput } = createCommandContext(command);
21832
- const label = args.join("/");
21833
- const item = await config.get(client, ...args);
21834
- if (!item) {
21835
- return output.error(`${capitalize(config.resourceName)} not found: ${label}`, { suggestion: `Check that the ${config.args.join(" and ")} ${config.args.length > 1 ? "are" : "is"} correct` });
21836
- }
21837
- if (isJsonOutput) {
21838
- output.json(item);
21839
- } else {
21840
- output.success(`${capitalize(config.resourceName)}: ${label}`, config.formatOutput(item));
21841
- }
21842
- }));
21843
- }
21844
- /**
21845
- * Create a list command for a resource.
21846
- *
21847
- * @example
21848
- * const listCommand = createListCommand({
21849
- * resourceName: 'entry',
21850
- * resourceNamePlural: 'entries',
21851
- * args: ['type'],
21852
- * hasPagination: true,
21853
- * list: (client, [type], pagination) => client.entries.list(type, pagination),
21854
- * tableHeaders: ['Identifier', 'Status', 'Updated'],
21855
- * formatRow: (entry) => [entry.identifier, entry.status, entry.updatedAt],
21856
- * });
21857
- */
21858
- function createListCommand(config) {
21859
- const cmd = new Command("list").description(`List ${config.resourceNamePlural}`);
21860
- for (const arg of config.args) {
21861
- cmd.argument(`<${arg}>`, `${capitalize(arg.replace("-", " "))}`);
21862
- }
21863
- if (config.hasPagination) {
21864
- cmd.option("--limit <n>", "Number of items per page", "20");
21865
- cmd.option("--page <n>", "Page number", "1");
21866
- }
21867
- return cmd.action(withErrorHandling(async (...actionArgs) => {
21868
- const args = actionArgs.slice(0, config.args.length);
21869
- const options = actionArgs[config.args.length];
21870
- const command = actionArgs[actionArgs.length - 1];
21871
- const { output, client, isJsonOutput } = createCommandContext(command);
21872
- const pagination = config.hasPagination ? parsePaginationOptions(options) : undefined;
21873
- const result = await config.list(client, args, pagination);
21874
- if (isJsonOutput) {
21875
- output.json({
21876
- [config.resourceNamePlural]: result.items,
21877
- ...result.pagination && { pagination: result.pagination }
21878
- });
21879
- } else if (result.items.length === 0) {
21880
- const context = args.length > 0 ? ` for ${args.join("/")}` : "";
21881
- output.info(`No ${config.resourceNamePlural} found${context}`);
21882
- } else {
21883
- output.table(config.tableHeaders, result.items.map(config.formatRow));
21884
- if (result.pagination) {
21885
- output.info(`Showing ${result.items.length} of ${result.pagination.total} ${config.resourceNamePlural} (page ${result.pagination.page})`);
21886
- } else {
21887
- output.info(`${result.items.length} ${config.resourceNamePlural}`);
21888
- }
21889
- }
21890
- }));
21891
- }
21892
23121
 
21893
23122
  //#endregion
21894
23123
  //#region src/environment-outcome-json.ts
@@ -23075,6 +24304,13 @@ const BOOKING_QUESTION_ANSWER_EXPORT_SCOPE_VALUES = [
23075
24304
  BOOKING_QUESTION_ANSWER_EXPORT_SCOPES.appointments,
23076
24305
  BOOKING_QUESTION_ANSWER_EXPORT_SCOPES.eventSeries
23077
24306
  ];
24307
+ /** Periods shared by appointment list, export and dashboard URL contracts. */
24308
+ const APPOINTMENT_LIST_PERIODS = [
24309
+ "upcoming",
24310
+ "past",
24311
+ "all",
24312
+ "no_shows"
24313
+ ];
23078
24314
 
23079
24315
  //#endregion
23080
24316
  //#region ../api/src/bookingPeople.ts
@@ -23366,7 +24602,7 @@ function buildPreviewSummary(sync) {
23366
24602
  }
23367
24603
 
23368
24604
  //#endregion
23369
- //#region src/push-config.ts
24605
+ //#region src/legacy/push-config.ts
23370
24606
  /**
23371
24607
  * push-config CLI command
23372
24608
  *
@@ -24527,7 +25763,7 @@ async function adminClearSitePublicCache(apiClient, siteId, options) {
24527
25763
  //#region ../api/src/accessAdmin.ts
24528
25764
  function getDefaultStaffCapabilities(surfaces) {
24529
25765
  if (surfaces.events && !surfaces.appointments) return ["event_ops"];
24530
- return ["appointments"];
25766
+ return surfaces.appointments ? ["appointments", "packages"] : ["appointments"];
24531
25767
  }
24532
25768
  const managedDomainAddOnPricingSnapshotSchema = z.object({
24533
25769
  formulaVersion: z.literal("managed-domain-overage-v2"),
@@ -24607,7 +25843,7 @@ async function linkCurrentUserPractitioner(apiClient, { siteId, body, options })
24607
25843
  options
24608
25844
  }));
24609
25845
  } catch (error) {
24610
- return normalizeApiError(error, "Failed to link practitioner profile");
25846
+ return normalizeApiError(error, "We couldn’t link that profile.");
24611
25847
  }
24612
25848
  }
24613
25849
  async function unlinkCurrentUserPractitioner(apiClient, { siteId, options }) {
@@ -24618,7 +25854,7 @@ async function unlinkCurrentUserPractitioner(apiClient, { siteId, options }) {
24618
25854
  options
24619
25855
  }));
24620
25856
  } catch (error) {
24621
- return normalizeApiError(error, "Failed to unlink practitioner profile");
25857
+ return normalizeApiError(error, "We couldn’t unlink that profile.");
24622
25858
  }
24623
25859
  }
24624
25860
  async function removeSiteMember(apiClient, { siteId, memberId, options }) {
@@ -25241,7 +26477,7 @@ const SETTINGS_SURFACE_POLICIES = {
25241
26477
  surfaceId: "settings.bookings",
25242
26478
  navVisibilityPolicy: administratorPolicy,
25243
26479
  pageAccessPolicy: administratorPolicy,
25244
- actionIds: []
26480
+ actionIds: ["bookings.updateSettings", "bookings.turnOnCourses"]
25245
26481
  },
25246
26482
  "settings.redirects": {
25247
26483
  surfaceId: "settings.redirects",
@@ -25328,6 +26564,8 @@ const SETTINGS_SURFACE_POLICIES = {
25328
26564
  };
25329
26565
  const SETTINGS_ACTION_POLICIES = {
25330
26566
  "privacy.update": administratorPolicy,
26567
+ "bookings.updateSettings": editorPolicy,
26568
+ "bookings.turnOnCourses": editorPolicy,
25331
26569
  "emails.read": editorPolicy,
25332
26570
  "emails.update": administratorPolicy,
25333
26571
  "emails.updateSendSetting": editorPolicy,
@@ -25695,10 +26933,9 @@ function buildDashboardSettingsNavPlan(ctx) {
25695
26933
  function buildDashboardTeamMemberNavPlan(ctx) {
25696
26934
  const ownResourceId = getOwnAppointmentResourceId(ctx.staffScope);
25697
26935
  return [
25698
- ...hasAppointmentStaffAccess(ctx.staffScope) ? buildAppointmentStaffNavPlan(ownResourceId) : [],
25699
- ...ownResourceId ? [{
25700
- id: "team.calendarSync",
25701
- label: "My Calendar Sync",
26936
+ ...hasAppointmentStaffAccess(ctx.staffScope) ? buildAppointmentStaffNavPlan(ownResourceId) : ownResourceId ? [{
26937
+ id: "team.availability",
26938
+ label: "My Hours and Calendars",
25702
26939
  destination: {
25703
26940
  kind: "appointment_resource_calendar",
25704
26941
  resourceId: ownResourceId
@@ -25729,7 +26966,7 @@ function buildAppointmentStaffNavPlan(resourceId) {
25729
26966
  destination: { kind: "appointments_calendar" }
25730
26967
  }, {
25731
26968
  id: "team.availability",
25732
- label: "My Availability",
26969
+ label: "My Hours and Calendars",
25733
26970
  destination: resourceId ? {
25734
26971
  kind: "appointment_resource_availability",
25735
26972
  resourceId
@@ -26075,13 +27312,13 @@ function createAccountApi(apiClient) {
26075
27312
  return response;
26076
27313
  },
26077
27314
  async listSites(input = {}) {
26078
- const search = input.query?.search?.trim();
27315
+ const search$1 = input.query?.search?.trim();
26079
27316
  const response = parseSuccessfulData("accountListSites", await apiClient({
26080
27317
  endpoint: "accountListSites",
26081
27318
  ...input.query ? { params: {
26082
27319
  ...input.query.cursor ? { cursor: input.query.cursor } : {},
26083
27320
  ...input.query.limit !== undefined ? { limit: String(input.query.limit) } : {},
26084
- ...search ? { search } : {}
27321
+ ...search$1 ? { search: search$1 } : {}
26085
27322
  } } : {},
26086
27323
  options: input.options
26087
27324
  }), listSitesResponseSchema);
@@ -26475,7 +27712,7 @@ function buildStaffAppointmentsNavGroup(ownResourceId) {
26475
27712
  }];
26476
27713
  if (ownResourceId) {
26477
27714
  appointmentItems.push({
26478
- label: "My Availability",
27715
+ label: "My Hours and Calendars",
26479
27716
  destination: {
26480
27717
  kind: "appointment_resource_availability",
26481
27718
  resourceId: ownResourceId
@@ -26484,15 +27721,7 @@ function buildStaffAppointmentsNavGroup(ownResourceId) {
26484
27721
  "availability",
26485
27722
  "schedule",
26486
27723
  "hours",
26487
- "time slots"
26488
- ]
26489
- }, {
26490
- label: "My Calendars",
26491
- destination: {
26492
- kind: "appointment_resource_calendar",
26493
- resourceId: ownResourceId
26494
- },
26495
- keywords: [
27724
+ "time slots",
26496
27725
  "calendar sync",
26497
27726
  "google calendar",
26498
27727
  "external calendar",
@@ -26832,6 +28061,33 @@ async function reorderNavigationItems(apiClient, { siteId, menuId, items, option
26832
28061
  normalizeApiError(error, "Failed to reorder navigation items");
26833
28062
  }
26834
28063
  }
28064
+ /** Resolved partitions own the navigation facts used by footer layout planning. */
28065
+ function footerNavigationFacts(menu) {
28066
+ return {
28067
+ hasFooterNavigation: menu.groups.length > 0 || menu.links.length > 0,
28068
+ navigationGroups: [...menu.groups, ...menu.links.length ? [{ label: null }] : []]
28069
+ };
28070
+ }
28071
+ /**
28072
+ * The one owner of the navigation facts a footer plans its layout with, read from the
28073
+ * stored menus' shape: a root item with children is a labelled group, any other root
28074
+ * link joins the unlabelled set. Route resolution plays no part, so the served site,
28075
+ * the SDK and the editor preview (which has no route map) all decide alike, and a link
28076
+ * that needs a route can't drop the whole links module.
28077
+ */
28078
+ function footerMenuNavigationFacts(menus) {
28079
+ const items = menus.find((menu) => menu.location === "footer")?.items ?? [];
28080
+ const roots = items.filter((item) => !item.parentId);
28081
+ const groups = roots.filter((item) => items.some((child) => child.parentId === item.id));
28082
+ const links = roots.filter((item) => item.urlType !== "dropdown" && !groups.includes(item));
28083
+ return {
28084
+ ...footerNavigationFacts({
28085
+ groups,
28086
+ links
28087
+ }),
28088
+ hasLegalPolicyNavigation: menus.some((menu) => menu.location === "legal" && menu.items.length > 0)
28089
+ };
28090
+ }
26835
28091
 
26836
28092
  //#endregion
26837
28093
  //#region src/sync/mapper.ts
@@ -32999,4 +34255,4 @@ function optionalTitle(data) {
32999
34255
  }
33000
34256
 
33001
34257
  //#endregion
33002
- export { normalizeMediaValueToIdentifierOnly as $, parseRepeaterGridInteger as $n, bindRequestTimeout as $t, formatDiffDetail as A, transportSuggestion as An, eventCalendarListLayoutValues as Ar, navigationIdentity as At, buildFieldChanges as B, cardListFamilyBlocks as Bn, calendarSourceCursorSchema as Br, ACCOUNT_SITE_LIST_LIMIT_MIN as Bt, reportFromOutcomes as C, parseEnvironmentSelection as Cn, repriceBookingCollectionOptions as Cr, fileExists$1 as Ct, normalizeRemoteHomepageReference as D, withRiverbankEnv as Dn, eventCalendarDefaultViewValues as Dr, writeJsonFileAtomic as Dt, createEmptySyncResult as E, requireEnvironmentWriteAuthorization as En, getBookingLaterInstalments as Er, writeJsonFile$1 as Et, calculatePullDiff as F, isLocalConfigured as Fn, purchasablePublicMembershipProductSchema as Fr, AccountApiMalformedResponseError as Ft, syncLocalMediaForPull as G, bindingSchema as Gn, normalizeCalendarFilterId as Gr, applyPushConfigPlan as Gt, formatFieldPath as H, lookKnobBlocks as Hn, eventSurfacePresetValues as Hr, ACCOUNT_SITE_TITLE_MAX_LENGTH as Ht, buildJsonDiff as I, isRemoteConfigured as In, purchasablePublicPassProductSchema as Ir, createBearerAccountApi as It, admitBinaryWriteDestination as J, blockContentSourceSchema as Jn, unwrapResponse as Jr, preparePushConfigTarget as Jt, applyLocalMediaPush as K, DEFAULT_MEDIA_FIELD_KINDS as Kn, publicEventLoaderQuerySchemaShape as Kr, createPushConfigCommand as Kt, hasPageOperations as L, loadSdkEnvironment as Ln, CALENDAR_SSR_PAGE_SIZE as Lr, ACCOUNT_SITE_CURSOR_MAX_LENGTH as Lt, hasPendingChanges as M, createOutput as Mn, publicMembershipProductSchema as Mr, convertPulledFooterToLocal as Mt, findChangedFieldsWithValues as N, getEnvPrefix as Nn, publicPassProductSchema as Nr, convertPulledNavigationToLocal as Nt, calculateDiff as O, ErrorCodes as On, eventCalendarDisplayModeValues as Or, isMediaValue as Ot, formatHumanDiff as P, getEnvironmentDebugInfo as Pn, publicProductSchema as Pr, convertPulledPagesToLocal as Pt, normalizeMediaIdentifierInput as Q, isAcceptedRepeaterGridSpan as Qn, mapEnvironmentExecutionOutcomesJson as Qt, pageMetadataForUpsert as R, createManagementClient as Rn, calendarMonthDate as Rr, ACCOUNT_SITE_LIST_LIMIT_DEFAULT as Rt, planCliCommandBatchForBindings as S, executeEnvironmentPlan as Sn, isBookingCollectionEquivalentToUpfront as Sr, ensureDir$1 as St, executeResidualSettingsSyncPlan as T, planEnvironmentWriteAuthorization as Tn, resolveBookingCollectionOptionFacts as Tr, readJsonFile as Tt, revalidateLocalMediaPushPlan as U, NodeSchema as Un, eventSurfaceScopeValues as Ur, navigationCommandItemToManagementInput as Ut, formatFieldChange as V, cardListKnobBlocks as Vn, eventScheduleScopeValues as Vr, ACCOUNT_SITE_SEARCH_MAX_LENGTH as Vt, syncLocalMediaForPush as W, NodeTreeSchema as Wn, monthNumber as Wr, normalizeNavigationConfigItemForCommand as Wt, writeBinaryFileAtomic as X, fieldSchema as Xn, createBearerAPIClient as Xt, readStableBinaryFile as Y, blockRequiredFeatureSchema as Yn, revalidatePushConfigPlan as Yt, sha256 as Z, MAX_REPEATER_GRID_COLUMNS as Zn, deriveCmsApiUrlFromDashboardUrl as Zt, commandExecutionToReport as _, runWithInvocation as _n, checkoutStatusArms as _r, metadataFilePath as _t, executeEntryCommandPlanAsReport as a, createOutputForCommand as an, extractApiErrorMessage as ar, readEntries as at, executeCompiledCliCommandPlanAsReport as b, withErrorHandling as bn, planCheckoutPaymentFlow as br, writeMetadataFile as bt, titleFromEntryData as c, getOutputContext as cn, ApiRequestError as cr, readEventsMeta as ct, unsafeAsCliEntryIdentifier as d, managementClientConfigFor as dn, linkPayloadSchema as dr, readNavigationMeta as dt, confirmAction as en, resolveRepeaterGridColumnFieldId as er, walkLocalContentMedia as et, unsafeAsCliFormSlug as f, mapEntryForOutput as fn, portablePageDesignSchema as fr, readPagesMeta as ft, commandCompileFailureToReport as g, resolveCommandPath as gn, API_ENDPOINTS as gr, ensureMetadataDir as gt, mutationCounterForEffect as h, parsePaginationOptions as hn, sdkConfiguredBookingVerticalConfigSchema as hr, writeMediaManifest as ht, entrySiteCommandTypes as i, createListCommand as in, ManagementApiError as ir, findLegacyEntryFiles as it, formatDiffSummary as j, CliExit as jn, publicVenueMapLocationSchema as jr, navigationIdentityMap as jt, calculateFooterDiff as k, formatError as kn, eventCalendarListLayoutCompatibleDisplayModeValues as kr, duplicateNavigationIdentityMessage as kt, unsafeAsCliBlockIdentifier as l, getOutputOnlyContext as ln, sdkEventScheduleSchema as lr, readFooterMeta as lt, commandReportToSyncResult as m, parseJsonData as mn, pageDesignIntentSchemaVersion as mr, readVenuesMeta as mt, entryCommandCompileErrorToReport as n, createCommandContext as nn, resolveRepeaterGridSpanFieldId as nr, downloadMedia as nt, executeEntryCommandPlanAsSyncResult as o, currentInvocationEnvelope as on, normalizeApiError as or, readAllMeta as ot, unsafeAsCliPageIdentifier as p, parseJsonArray as pn, pageDesignDecisionsV2Schema as pr, readSettingsMeta as pt, prepareLocalMediaForPush as q, blockCategoryEnum as qn, ApiEnvelopeError as qr, loadPushConfigTarget as qt, entryCommandReportToSyncResult as r, createGetCommand as rn, visibilityLevels as rr, extractMediaIdentifiers as rt, syncResultForEntryCommandCompileError as s, formatDateShort as sn, isRecord$5 as sr, readEventCategoriesMeta as st, compileEntryPushCommands as t, createClientForEnv as tn, resolveRepeaterGridRowFieldId as tr, buildStorageUrl as tt, unsafeAsCliContentTypeKey as u, handleCommandError as un, sdkSettingsUpdateSchema as ur, readFormsMeta as ut, commandReportHasFailures as v, withCommandContext as vn, checkoutCopy as vr, metadataTargetFromEnvironment as vt, mergeManySyncResults as w, planEnvironmentExecution as wn, resolveAvailableBookingCollectionOptions as wr, listFiles as wt, formatManagementError as x, withOutputOnlyErrorHandling as xn, planFlexibleBalanceCreditFirst as xr, writeMetadataRecordMap as xt, executeCliCommandPlan as y, withConfirmation as yn, getStripeMinimumChargeRequirement as yr, readMetadataFile as yt, calculateEntryDiffs as z, cardListBlockParts as zn, calendarMonthWindowSchema as zr, ACCOUNT_SITE_LIST_LIMIT_MAX as zt };
34258
+ export { normalizeMediaValueToIdentifierOnly as $, resolveRepeaterGridSpanFieldId as $n, ApiEnvelopeError as $r, bindRequestTimeout as $t, formatDiffDetail as A, getEnvPrefix as An, getStripeMinimumChargeRequirement as Ar, navigationIdentity as At, buildFieldChanges as B, NodeSchema as Bn, publicProductSchema as Br, ACCOUNT_SITE_LIST_LIMIT_MIN as Bt, reportFromOutcomes as C, requireEnvironmentWriteAuthorization as Cn, unsafeAsPositiveCheckoutQuantity as Cr, fileExists$1 as Ct, normalizeRemoteHomepageReference as D, transportSuggestion as Dn, repriceBookingCollectionOptions as Dr, writeJsonFileAtomic as Dt, createEmptySyncResult as E, formatError as En, isBookingCollectionEquivalentToUpfront as Er, writeJsonFile$1 as Et, calculatePullDiff as F, createManagementClient as Fn, eventCalendarListLayoutCompatibleDisplayModeValues as Fr, AccountApiMalformedResponseError as Ft, syncLocalMediaForPull as G, blockContentSourceSchema as Gn, calendarMonthWindowSchema as Gr, applyPushConfigPlan as Gt, formatFieldPath as H, bindingSchema as Hn, purchasablePublicPassProductSchema as Hr, ACCOUNT_SITE_TITLE_MAX_LENGTH as Ht, buildJsonDiff as I, cardListBlockParts as In, eventCalendarListLayoutValues as Ir, createBearerAccountApi as It, admitBinaryWriteDestination as J, MAX_REPEATER_GRID_COLUMNS as Jn, eventSurfacePresetValues as Jr, preparePushConfigTarget as Jt, applyLocalMediaPush as K, blockRequiredFeatureSchema as Kn, calendarSourceCursorSchema as Kr, createPushConfigCommand as Kt, hasPageOperations as L, cardListFamilyBlocks as Ln, publicVenueMapLocationSchema as Lr, ACCOUNT_SITE_CURSOR_MAX_LENGTH as Lt, hasPendingChanges as M, isLocalConfigured as Mn, MAX_EVENT_BOOKING_SELECTION_ITEMS as Mr, convertPulledFooterToLocal as Mt, findChangedFieldsWithValues as N, isRemoteConfigured as Nn, eventCalendarDefaultViewValues as Nr, convertPulledNavigationToLocal as Nt, calculateDiff as O, CliExit as On, resolveAvailableBookingCollectionOptions as Or, isMediaValue as Ot, formatHumanDiff as P, loadSdkEnvironment as Pn, eventCalendarDisplayModeValues as Pr, convertPulledPagesToLocal as Pt, normalizeMediaIdentifierInput as Q, resolveRepeaterGridRowFieldId as Qn, publicEventLoaderQuerySchemaShape as Qr, mapEnvironmentExecutionOutcomesJson as Qt, pageMetadataForUpsert as R, cardListKnobBlocks as Rn, publicMembershipProductSchema as Rr, ACCOUNT_SITE_LIST_LIMIT_DEFAULT as Rt, planCliCommandBatchForBindings as S, planEnvironmentWriteAuthorization as Sn, checkoutCopy as Sr, ensureDir$1 as St, executeResidualSettingsSyncPlan as T, ErrorCodes as Tn, planFlexibleBalanceCreditFirst as Tr, readJsonFile as Tt, revalidateLocalMediaPushPlan as U, DEFAULT_MEDIA_FIELD_KINDS as Un, CALENDAR_SSR_PAGE_SIZE as Ur, navigationCommandItemToManagementInput as Ut, formatFieldChange as V, NodeTreeSchema as Vn, purchasablePublicMembershipProductSchema as Vr, ACCOUNT_SITE_SEARCH_MAX_LENGTH as Vt, syncLocalMediaForPush as W, blockCategoryEnum as Wn, calendarMonthDate as Wr, normalizeNavigationConfigItemForCommand as Wt, writeBinaryFileAtomic as X, parseRepeaterGridInteger as Xn, monthNumber as Xr, createBearerAPIClient as Xt, readStableBinaryFile as Y, isAcceptedRepeaterGridSpan as Yn, eventSurfaceScopeValues as Yr, revalidatePushConfigPlan as Yt, sha256 as Z, resolveRepeaterGridColumnFieldId as Zn, normalizeCalendarFilterId as Zr, deriveCmsApiUrlFromDashboardUrl as Zt, commandExecutionToReport as _, withErrorHandling as _n, decideSelectionAttendance as _r, metadataFilePath as _t, executeEntryCommandPlanAsReport as a, getOutputContext as an, ApiRequestError as ar, readEntries as at, executeCompiledCliCommandPlanAsReport as b, parseEnvironmentSelection as bn, nextCombinationHint as br, writeMetadataFile as bt, titleFromEntryData as c, managementClientConfigFor as cn, linkPayloadSchema as cr, readEventsMeta as ct, unsafeAsCliEntryIdentifier as d, parseJsonData as dn, pageDesignIntentSchemaVersion as dr, readNavigationMeta as dt, unwrapResponse as ei, confirmAction as en, visibilityLevels as er, walkLocalContentMedia as et, unsafeAsCliFormSlug as f, parsePaginationOptions as fn, sdkConfiguredBookingVerticalConfigSchema as fr, readPagesMeta as ft, commandCompileFailureToReport as g, withConfirmation as gn, INCOMPATIBLE_ATTENDANCE_MESSAGE as gr, ensureMetadataDir as gt, mutationCounterForEffect as h, withCommandContext as hn, eventBookingConsentContentKey as hr, writeMediaManifest as ht, entrySiteCommandTypes as i, formatDateShort as in, isRecord$5 as ir, findLegacyEntryFiles as it, formatDiffSummary as j, getEnvironmentDebugInfo as jn, getBookingLaterInstalments as jr, navigationIdentityMap as jt, calculateFooterDiff as k, createOutput as kn, resolveBookingCollectionOptionFacts as kr, duplicateNavigationIdentityMessage as kt, unsafeAsCliBlockIdentifier as l, mapEntryForOutput as ln, portablePageDesignSchema as lr, readFooterMeta as lt, commandReportToSyncResult as m, runWithInvocation as mn, areEventBookingRequirementsIdentical as mr, readVenuesMeta as mt, entryCommandCompileErrorToReport as n, createOutputForCommand as nn, extractApiErrorMessage as nr, downloadMedia as nt, executeEntryCommandPlanAsSyncResult as o, getOutputOnlyContext as on, sdkEventScheduleSchema as or, readAllMeta as ot, unsafeAsCliPageIdentifier as p, resolveCommandPath as pn, API_ENDPOINTS as pr, readSettingsMeta as pt, prepareLocalMediaForPush as q, fieldSchema as qn, eventScheduleScopeValues as qr, loadPushConfigTarget as qt, entryCommandReportToSyncResult as r, currentInvocationEnvelope as rn, normalizeApiError as rr, extractMediaIdentifiers as rt, syncResultForEntryCommandCompileError as s, handleCommandError as sn, sdkSettingsUpdateSchema as sr, readEventCategoriesMeta as st, compileEntryPushCommands as t, createCommandContext as tn, ManagementApiError as tr, buildStorageUrl as tt, unsafeAsCliContentTypeKey as u, parseJsonArray as un, pageDesignDecisionsV2Schema as ur, readFormsMeta as ut, commandReportHasFailures as v, withOutputOnlyErrorHandling as vn, resolveSelectionAttendanceMode as vr, metadataTargetFromEnvironment as vt, mergeManySyncResults as w, withRiverbankEnv as wn, planCheckoutPaymentFlow as wr, listFiles as wt, formatManagementError as x, planEnvironmentExecution as xn, planSelectionCombinationPrices as xr, writeMetadataRecordMap as xt, executeCliCommandPlan as y, executeEnvironmentPlan as yn, checkoutStatusArms as yr, readMetadataFile as yt, calculateEntryDiffs as z, lookKnobBlocks as zn, publicPassProductSchema as zr, ACCOUNT_SITE_LIST_LIMIT_MAX as zt };