riverbankcms 0.31.2 → 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 { $n as headerStyleIdValues, A as footerPreferencesSchema, Cr as makeBoundaryId, Dt as resolveMediaIdentifier, Ir as createSiteCommandSiteRef, It as FILE_SIZE_LIMITS, Jn as asHeaderLayoutId, Kn as SUPPORTED_LOADER_ENDPOINTS, Lt as MAX_MANAGEMENT_MEDIA_UPLOAD_BYTES, Mt as getMimeType, Nn as RESOLVED_INTERNAL_LINK_ENTITY_TYPES, Or as createCommandRef, Ot as slugifyMediaIdentifier, Pt as normalizeAmbiguousStoragePathForSite, Qn as headerLayoutIdValues, R as footerModeSchema, Sn as eventBookingOfferIntentSchema, Sr as asSiteStyleId, St as mediaTypeDiscriminants, U as themeSchema, Un as ICON_PICKER_PRESETS, Xt as buttonStyleSelectionSchema, Yn as asHeaderStyleId, Zn as footerLookIdValues, _r as asDesignBoundaryId, b as getSiteCommandMetadata, bt as PUBLIC_FILE_FIELD_KINDS, fr as asAppearancePresetId, gr as asDesignBlockId, h as parseAndPlanCommandBatchForTypes, j as headerPreferencesSchema, jt as getExtensionForMimeType, kr as createContentEntryRef, 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, st as parseAspectRatioValue, ut as getDirectImageUrlForSiteScopedPath, v as evaluateSiteCommandBatchExposure, w as entryIdentifierForCommand, wr as bookingQuestionAttachmentSchema, wt as buildMediaIdentifierFromFilename, xn as require_dist, xr as asPageFlowPresetId, xt as isDisplayMediaKind, y as evaluateSiteCommandExposure, zr as slugPart } from "./sdk-event-upsert-BMYgDeSe.mjs";
3
- import { $t as businessCancellationRefusalCodes, C as isPublicReadEndpoint, Cn as unsafeAsNonNegativeCents, Dn as assertNever, En as parseCurrencyCode, Fn as parseMembershipId, G as parseFooterCompositionV1, Gt as isSettleableOrderInstalmentPlanStatus, Ht as validateBookingPaymentOptionKinds, It as resolveBookingTimeZoneId, Jt as getBookingInstalmentDepositRefundability, Kt as addIntervalPreservingMonthAnchor, Ln as unsafeAsPassId, M as exposeSecret, Mn as unsafeAsStaffMemberId, N as parseManagementKey, Nn as parseCustomerId, Nt as parseBookingLocalDate, Qt as splitAmountWithRemainderInFirst, Rn as parseDatedOfferingCapacityHoldAuditRef, S as getPublicReadCachePolicy, Sn as toNonNegativeCents, Ut as isLiveOrderInstalmentPlanStatus, W as parseMailingListProviderScope, Wt as isSettleableFlexibleBalanceContractStatus, Xt as getBookingInstalmentProtectedDepositAmountCents, Zt as omitZeroAmountFutureRows, _r as unsafeAsPricingOptionId, ar as parseApiKeyId, b as PUBLIC_AVAILABILITY_FRESHNESS_SECONDS, bn as parsePositiveCents, c as resolveEventCatalogue, d as canonicalizeConfiguredBookingVerticalConfig, dr as parseRetiredCourseId, en as scheduleBookingReasonCodes, et as assertAllowedPublicUrl, f as parseVerticalId, g as EVENT_PRESET_VALUES, gr as unsafeAsOccurrenceId, gt as formatDate, h as DEFAULT_EVENT_TYPE_PRESETS, hn as fromArray, hr as unsafeAsEventSeriesId, j as createSecret, jn as unsafeAsAppointmentResourceId, m as resolveSiteVerticalBookingConfig, mr as unsafeAsEventOfferingId, n as OFFLINE_PAYMENT_METHODS, nn as resolveFlexibleBalanceInitialPaymentCents, nr as parseEditorSessionGeneration, or as parseSiteId, ot as locationValueSchema, p as parseVerticalPresetId, pr as unsafeAsEventInstanceId, pt as trimmedStringOrNull, qt as clampConfiguredAmount, r as committedWriteProofSchema, rr as parsePageId, sr as parseUserId, tn as resolveFlexibleBalanceDueAt, tr as unsafeAsCheckoutLineId, u as areConfiguredBookingVerticalConfigsEqual, ur as parseEventSeriesId, ut as publicLocationSchema, v as SURFACE_EVENT_PRESET_VALUES, vn as isNonNegativeWholeCents$1, vr as err, w as publicReadFreshnessSeconds, wn as unsafeAsPositiveCents, x as PUBLIC_CONTENT_FRESHNESS_SECONDS, xn as toCents, yn as parseNonNegativeCents, yr as ok, zn as parseDatedOfferingCapacityHoldId } from "./src-BXMUcFYN.mjs";
4
- import { n as CliSdkPeerError, t as loadConfigFile } from "./load-config-CMeJVHDQ.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();
@@ -1926,7 +1928,6 @@ const arrangementDateResultSchema = z.intersection(z.object({ occurrenceDate: lo
1926
1928
  z.object({ code: z.enum([
1927
1929
  "package_shortfall",
1928
1930
  "not_available",
1929
- "needs_recorded_return",
1930
1931
  "client_not_found"
1931
1932
  ]) }),
1932
1933
  z.object({
@@ -2215,7 +2216,11 @@ const APPOINTMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
2215
2216
  method: "DELETE",
2216
2217
  auth: "user",
2217
2218
  responseKind: "json",
2218
- errors: ["resource:not_found", "server:internal_error"]
2219
+ errors: [
2220
+ "resource:not_found",
2221
+ "resource:conflict",
2222
+ "server:internal_error"
2223
+ ]
2219
2224
  },
2220
2225
  createTeamMemberProfile: {
2221
2226
  path: "/sites/{siteId}/bookings/resources/{resourceId}/profile",
@@ -2516,6 +2521,17 @@ const APPOINTMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
2516
2521
  "server:internal_error"
2517
2522
  ]
2518
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
+ },
2519
2535
  setServiceSpecificAvailability: {
2520
2536
  path: "/sites/{siteId}/bookings/resources/{resourceId}/service-availability",
2521
2537
  method: "PUT",
@@ -2855,6 +2871,54 @@ const EVENT_SERIES_REGISTRATION_ENDPOINT_DEFINITIONS = defineEndpointDefinitions
2855
2871
  "server:internal_error"
2856
2872
  ]
2857
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
+ },
2858
2922
  deleteEventOffering: {
2859
2923
  path: "/sites/{siteId}/bookings/event-offerings/{eventOfferingId}",
2860
2924
  method: "DELETE",
@@ -3889,6 +3953,11 @@ const eventCalendarListLayoutValues = [
3889
3953
  ];
3890
3954
  const eventCalendarListLayoutCompatibleDisplayModeValues = ["combined", "list"];
3891
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
+
3892
3961
  //#endregion
3893
3962
  //#region ../commerce/src/purchase/allocation.ts
3894
3963
  /**
@@ -3930,6 +3999,7 @@ const ORDER_STATUSES = [
3930
3999
  "failed",
3931
4000
  "cancelled"
3932
4001
  ];
4002
+ const orderStatusSchema = z.enum(ORDER_STATUSES);
3933
4003
  const orderStatusSet = new Set(ORDER_STATUSES);
3934
4004
  function isOrderStatus(value) {
3935
4005
  return orderStatusSet.has(value);
@@ -4109,6 +4179,320 @@ function getBookingLaterInstalments(schedule) {
4109
4179
  return schedule.filter((row) => row.stateAtBooking === "scheduled");
4110
4180
  }
4111
4181
 
4182
+ //#endregion
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}`);
4188
+ }
4189
+ return normalized;
4190
+ }
4191
+ function rebrandCents(amount) {
4192
+ return amount;
4193
+ }
4194
+ function toSubtotalCents(raw) {
4195
+ return rebrandCents(toNonNegativeCents(raw));
4196
+ }
4197
+ function toDiscountCents(raw) {
4198
+ return rebrandCents(toNonNegativeCents(raw));
4199
+ }
4200
+ function toCreditAppliedCents(raw) {
4201
+ return rebrandCents(toNonNegativeCents(raw));
4202
+ }
4203
+ function toStripeChargeCents(raw) {
4204
+ return rebrandCents(toNonNegativeCents(raw));
4205
+ }
4206
+ function toRefundedCents(raw) {
4207
+ return rebrandCents(toNonNegativeCents(raw));
4208
+ }
4209
+ function toRefundableTotalCents(raw) {
4210
+ return rebrandCents(toNonNegativeCents(raw));
4211
+ }
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) {
4221
+ return err({
4222
+ _tag: "invalid_line_money",
4223
+ lineId,
4224
+ field,
4225
+ message: `Line ${lineId} ${field} must be a non-negative whole number of cents`
4226
+ });
4227
+ }
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
+
4112
4496
  //#endregion
4113
4497
  //#region ../commerce/src/purchase/bookingPaymentSelection.ts
4114
4498
  function isBookingPlanOrContractSelection(selection) {
@@ -4145,17 +4529,15 @@ function resolveAvailableBookingCollectionOptions(input) {
4145
4529
  option,
4146
4530
  totalCents: input.totalCents,
4147
4531
  anchorAt: input.now,
4148
- bookingStartAt: input.bookingStartAt
4149
- })).filter((option) => option.kind !== "instalment_plan" || deadline !== null && canInstalmentPlanCompleteBefore({
4150
- now: input.now,
4151
- deadline,
4152
- schedule: option.schedule
4153
- }));
4532
+ bookingStartAt: input.bookingStartAt,
4533
+ timeZone: input.timeZone
4534
+ })).filter((option) => canOfferBookingCollectionOption(option, input.currency ?? "USD", deadline));
4154
4535
  const upfront = resolveBookingCollectionOptionFacts({
4155
4536
  option: { kind: "upfront" },
4156
4537
  totalCents: input.totalCents,
4157
4538
  anchorAt: input.now,
4158
- bookingStartAt: input.bookingStartAt
4539
+ bookingStartAt: input.bookingStartAt,
4540
+ timeZone: input.timeZone
4159
4541
  });
4160
4542
  const collapsed = available.map((option) => isBookingCollectionEquivalentToUpfront(option) ? upfront : option);
4161
4543
  const unique = collapsed.filter((option, index) => collapsed.findIndex((other) => other.kind === option.kind) === index);
@@ -4174,7 +4556,8 @@ function resolveBookingCollectionOptionFacts(input) {
4174
4556
  const money$1 = {
4175
4557
  totalCents: input.totalCents,
4176
4558
  anchorAt: input.anchorAt,
4177
- bookingStartAt: input.bookingStartAt
4559
+ bookingStartAt: input.bookingStartAt,
4560
+ timeZone: input.timeZone ?? "UTC"
4178
4561
  };
4179
4562
  switch (input.option.kind) {
4180
4563
  case "upfront": return {
@@ -4213,10 +4596,7 @@ function resolveBookingCollectionOptionFacts(input) {
4213
4596
  config: input.option.config,
4214
4597
  dueNowCents,
4215
4598
  remainingBalanceCents: Math.max(0, input.totalCents - dueNowCents),
4216
- balanceDueAt: resolveFlexibleBalanceDueAt({
4217
- bookingStartAt: input.bookingStartAt ?? input.anchorAt,
4218
- dueDateRule: input.option.config.dueDateRule
4219
- })
4599
+ balanceDueDay: flexibleBalanceDueDay(input.option.config, input.bookingStartAt ?? input.anchorAt, money$1.timeZone)
4220
4600
  };
4221
4601
  }
4222
4602
  default: return assertNever$3(input.option);
@@ -4224,30 +4604,64 @@ function resolveBookingCollectionOptionFacts(input) {
4224
4604
  }
4225
4605
  /** Discounts change preview money, never an already admitted collection identity. */
4226
4606
  function repriceBookingCollectionOptions(input) {
4227
- return input.options.map((option) => option.totalCents === input.totalCents ? option : resolveBookingCollectionOptionFacts({
4607
+ const repriced = input.options.map((option) => option.totalCents === input.totalCents ? option : resolveBookingCollectionOptionFacts({
4228
4608
  option,
4229
4609
  totalCents: input.totalCents,
4230
4610
  anchorAt: option.anchorAt,
4231
- bookingStartAt: option.bookingStartAt
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
4232
4643
  }));
4233
4644
  }
4234
-
4235
- //#endregion
4236
- //#region ../commerce/src/purchase/cancellationPolicy.ts
4237
- const CANCELLABLE_STATUSES = new Set([
4238
- "paid",
4239
- "partially_refunded",
4240
- "refunded",
4241
- "pending",
4242
- "failed"
4243
- ]);
4244
- /**
4245
- * Whether an order in the given status can be cancelled.
4246
- *
4247
- * `cancelled` orders cannot be cancelled again.
4248
- */
4249
- function isCancellableStatus(status) {
4250
- return CANCELLABLE_STATUSES.has(status);
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));
4251
4665
  }
4252
4666
 
4253
4667
  //#endregion
@@ -4425,13 +4839,14 @@ function formatUnexpectedValue(value) {
4425
4839
 
4426
4840
  //#endregion
4427
4841
  //#region ../commerce/src/purchase/checkoutDiscountContextPlanning.ts
4842
+ /** Group ticket lines within a date, keeping places per booking rather than adding dates. */
4428
4843
  function collectCheckoutDiscountContexts(items) {
4429
4844
  const contextsByIdentity = items.reduce((map, item) => {
4430
- const candidate = toCheckoutDiscountContextCandidate(item.validated);
4845
+ const candidate = toCheckoutDiscountContextCandidate(item);
4431
4846
  const existing = map.get(candidate.identityKey);
4432
4847
  const nextEntry = existing ? {
4433
4848
  identityKey: candidate.identityKey,
4434
- context: mergeCheckoutDiscountContexts(existing.context, candidate.context),
4849
+ context: mergeBookingDiscountContext(existing.context, candidate.context),
4435
4850
  subtotalCents: existing.subtotalCents + item.subtotalCents,
4436
4851
  lineIds: [...existing.lineIds, item.lineId]
4437
4852
  } : {
@@ -4454,7 +4869,7 @@ function collectCheckoutDiscountContexts(items) {
4454
4869
  function subtotalForCheckoutDiscountContexts(applicableContexts) {
4455
4870
  return applicableContexts.reduce((sum, entry) => sum + entry.subtotalCents, 0);
4456
4871
  }
4457
- function rankCheckoutAutoDiscountCandidates(candidates) {
4872
+ function rankCheckoutAutoDiscountCandidates(candidates, options = { includeZeroDiscounts: false }) {
4458
4873
  return candidates.map((candidate) => {
4459
4874
  const subtotalCents = subtotalForCheckoutDiscountContexts(candidate.applicableContexts);
4460
4875
  return {
@@ -4467,23 +4882,34 @@ function rankCheckoutAutoDiscountCandidates(candidates) {
4467
4882
  subtotalCents: toNonNegativeCents(subtotalCents)
4468
4883
  })
4469
4884
  };
4470
- }).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
+ }
4471
4889
  if (b.computedDiscountCents !== a.computedDiscountCents) {
4472
4890
  return b.computedDiscountCents - a.computedDiscountCents;
4473
4891
  }
4474
4892
  return a.code.id.localeCompare(b.code.id);
4475
4893
  });
4476
4894
  }
4477
- function toCheckoutDiscountContextCandidate(source) {
4478
- 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;
4479
4898
  return {
4480
- identityKey: checkoutDiscountContextIdentity(context),
4899
+ identityKey: checkoutDiscountContextIdentity(context, bookingId),
4481
4900
  context
4482
4901
  };
4483
4902
  }
4484
- 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) {
4485
4911
  switch (context.type) {
4486
- case "event": return `event:${context.eventSeriesId}`;
4912
+ case "event": return `event:${context.eventSeriesId}:${bookingId}`;
4487
4913
  case "whole_series": return `whole-series:${context.eventSeriesId}`;
4488
4914
  case "product": return `product:${context.productId}`;
4489
4915
  case "pass": return `pass:${context.passId}`;
@@ -4495,12 +4921,14 @@ function checkoutDiscountContext(source) {
4495
4921
  case "event_ticket": return {
4496
4922
  type: "event",
4497
4923
  eventSeriesId: source.eventSeries.id,
4924
+ eventOfferingId: source.eventSeries.eventOfferingId,
4498
4925
  eventCategoryId: source.eventSeries.eventCategoryId,
4499
4926
  ticketsCount: source.ticketCount
4500
4927
  };
4501
4928
  case "whole_series_enrollment": return {
4502
4929
  type: "whole_series",
4503
4930
  eventSeriesId: source.eventSeries.id,
4931
+ eventOfferingId: source.eventSeries.eventOfferingId,
4504
4932
  eventCategoryId: source.eventSeries.eventCategoryId,
4505
4933
  ticketsCount: source.participantCount
4506
4934
  };
@@ -4519,15 +4947,6 @@ function checkoutDiscountContext(source) {
4519
4947
  };
4520
4948
  }
4521
4949
  }
4522
- function mergeCheckoutDiscountContexts(existing, next) {
4523
- if (existing.type === "event" && next.type === "event" || existing.type === "whole_series" && next.type === "whole_series") {
4524
- return {
4525
- ...existing,
4526
- ticketsCount: (existing.ticketsCount ?? 0) + (next.ticketsCount ?? 0)
4527
- };
4528
- }
4529
- return existing;
4530
- }
4531
4950
  function computeCheckoutDiscountCents(options) {
4532
4951
  const subtotal = options.subtotalCents;
4533
4952
  if (subtotal === 0) return toNonNegativeCents(0);
@@ -4662,6 +5081,7 @@ function planCheckoutPaymentObligation(input) {
4662
5081
  };
4663
5082
  case "flexible_balance": return {
4664
5083
  kind: "flexible_balance",
5084
+ ...selection.timeZone === undefined ? {} : { timeZone: selection.timeZone },
4665
5085
  config: selection.config,
4666
5086
  configuredPaymentDueNowCents: resolveFlexibleBalanceInitialPaymentCents({
4667
5087
  totalAmountCents: input.totalAfterDiscountCents,
@@ -4751,261 +5171,6 @@ function unsafeAsPositiveCheckoutQuantity(quantity) {
4751
5171
  return quantity;
4752
5172
  }
4753
5173
 
4754
- //#endregion
4755
- //#region ../commerce/src/purchase/settlement.ts
4756
- function normalizeCurrencyCode(raw) {
4757
- const normalized = raw.trim().toUpperCase();
4758
- if (!/^[A-Z]{3}$/.test(normalized)) {
4759
- throw new Error(`Invalid currency code: ${raw}`);
4760
- }
4761
- return normalized;
4762
- }
4763
- function rebrandCents(amount) {
4764
- return amount;
4765
- }
4766
- function toSubtotalCents(raw) {
4767
- return rebrandCents(toNonNegativeCents(raw));
4768
- }
4769
- function toDiscountCents(raw) {
4770
- return rebrandCents(toNonNegativeCents(raw));
4771
- }
4772
- function toCreditAppliedCents(raw) {
4773
- return rebrandCents(toNonNegativeCents(raw));
4774
- }
4775
- function toStripeChargeCents(raw) {
4776
- return rebrandCents(toNonNegativeCents(raw));
4777
- }
4778
- function toRefundedCents(raw) {
4779
- return rebrandCents(toNonNegativeCents(raw));
4780
- }
4781
- function toRefundableTotalCents(raw) {
4782
- return rebrandCents(toNonNegativeCents(raw));
4783
- }
4784
- function money(amountCents, currency) {
4785
- return {
4786
- amountCents: toNonNegativeCents(amountCents),
4787
- currency
4788
- };
4789
- }
4790
- function parseLineSettlementCents(lineId, raw, field) {
4791
- const parsed = parseNonNegativeCents(raw);
4792
- if (!parsed.ok) {
4793
- return err({
4794
- _tag: "invalid_line_money",
4795
- lineId,
4796
- field,
4797
- message: `Line ${lineId} ${field} must be a non-negative whole number of cents`
4798
- });
4799
- }
4800
- return parsed;
4801
- }
4802
- function buildLineSettlementBreakdown(options) {
4803
- const subtotalResult = parseLineSettlementCents(options.lineId, options.subtotalCents, "subtotalCents");
4804
- if (!subtotalResult.ok) return subtotalResult;
4805
- const discountResult = parseLineSettlementCents(options.lineId, options.discountCents, "discountCents");
4806
- if (!discountResult.ok) return discountResult;
4807
- const creditAppliedResult = parseLineSettlementCents(options.lineId, options.creditAppliedCents, "creditAppliedCents");
4808
- if (!creditAppliedResult.ok) return creditAppliedResult;
4809
- const stripeChargeResult = parseLineSettlementCents(options.lineId, options.stripeChargeCents, "stripeChargeCents");
4810
- if (!stripeChargeResult.ok) return stripeChargeResult;
4811
- const subtotalCents = rebrandCents(subtotalResult.value);
4812
- const discountCents = rebrandCents(discountResult.value);
4813
- const creditAppliedCents = rebrandCents(creditAppliedResult.value);
4814
- const stripeChargeCents = rebrandCents(stripeChargeResult.value);
4815
- const expectedStripeCharge = subtotalCents - discountCents - creditAppliedCents;
4816
- if (expectedStripeCharge < 0) {
4817
- return err({
4818
- _tag: "inconsistent_line_totals",
4819
- lineId: options.lineId,
4820
- message: `Settlement invariant failed for line ${options.lineId}: reductions exceed subtotal`
4821
- });
4822
- }
4823
- if (stripeChargeCents !== expectedStripeCharge) {
4824
- return err({
4825
- _tag: "inconsistent_line_totals",
4826
- lineId: options.lineId,
4827
- message: `Settlement invariant failed for line ${options.lineId}: expected stripe charge ${expectedStripeCharge}, got ${stripeChargeCents}`
4828
- });
4829
- }
4830
- return ok({
4831
- subtotalCents,
4832
- discountCents,
4833
- creditAppliedCents,
4834
- stripeChargeCents
4835
- });
4836
- }
4837
- function buildRefundableLineSettlement(options) {
4838
- const line = buildLineSettlementBreakdown(options);
4839
- if (!line.ok) {
4840
- return line;
4841
- }
4842
- const alreadyRefundedResult = parseLineSettlementCents(options.lineId, options.alreadyRefundedCents, "alreadyRefundedCents");
4843
- if (!alreadyRefundedResult.ok) return alreadyRefundedResult;
4844
- const refundableTotalCents = toRefundableTotalCents(line.value.creditAppliedCents + line.value.stripeChargeCents);
4845
- const alreadyRefundedCents = rebrandCents(alreadyRefundedResult.value);
4846
- if (alreadyRefundedCents > refundableTotalCents) {
4847
- return err({
4848
- _tag: "refunded_exceeds_refundable_total",
4849
- lineId: options.lineId,
4850
- message: `Order item ${options.lineId} refunded amount exceeds refundable total`
4851
- });
4852
- }
4853
- return ok({
4854
- line: line.value,
4855
- refundableTotalCents,
4856
- alreadyRefundedCents
4857
- });
4858
- }
4859
- /**
4860
- * Cash actually collected against one order line, summed from its payment
4861
- * receipt allocations. Shared so every refundable-remainder caller measures
4862
- * funding the same way.
4863
- */
4864
- function orderItemCashFundedCents(allocations, orderItemId) {
4865
- let total = 0;
4866
- for (const allocation of allocations) {
4867
- if (allocation.orderItemId === orderItemId) {
4868
- total += allocation.amountCents;
4869
- }
4870
- }
4871
- return total;
4872
- }
4873
- /**
4874
- * The single authority on how much of an order line is still refundable.
4875
- *
4876
- * Every surface that shows or enforces a refundable remainder MUST go through
4877
- * this function. Computing it from the line's net total instead of its actual
4878
- * funding overstates the remainder on partially collected orders, which used to
4879
- * let the dashboard offer a refund the runtime then refused.
4880
- */
4881
- function orderItemRefundableRemainingCents(funding) {
4882
- return toNonNegativeCents(funding.cashFundedCents + funding.creditAppliedCents - funding.refundedCents);
4883
- }
4884
- function refundableRemainingCents(settlement) {
4885
- return orderItemRefundableRemainingCents({
4886
- cashFundedCents: settlement.refundableTotalCents,
4887
- creditAppliedCents: 0,
4888
- refundedCents: settlement.alreadyRefundedCents
4889
- });
4890
- }
4891
- function ensureSingleCurrency(lines) {
4892
- if (lines.length === 0) {
4893
- return {
4894
- ok: false,
4895
- reason: "empty_cart",
4896
- currencies: []
4897
- };
4898
- }
4899
- const uniqueCurrencies = Array.from(new Set(lines.map((line) => line.currency.trim().toUpperCase()))).sort();
4900
- if (uniqueCurrencies.length !== 1) {
4901
- return {
4902
- ok: false,
4903
- reason: "mixed_currency",
4904
- currencies: uniqueCurrencies
4905
- };
4906
- }
4907
- try {
4908
- return {
4909
- ok: true,
4910
- currency: normalizeCurrencyCode(uniqueCurrencies[0] ?? "")
4911
- };
4912
- } catch {
4913
- return {
4914
- ok: false,
4915
- reason: "invalid_currency",
4916
- currencies: uniqueCurrencies
4917
- };
4918
- }
4919
- }
4920
- function allocateReductionCents(inputs, requestedCents) {
4921
- const sanitizedInputs = inputs.map((input) => ({
4922
- lineId: input.lineId,
4923
- basisCents: toNonNegativeCents(input.basisCents),
4924
- maxReducibleCents: toNonNegativeCents(input.maxReducibleCents)
4925
- }));
4926
- const totalReducibleCents = sanitizedInputs.reduce((sum, input) => sum + input.maxReducibleCents, 0);
4927
- const targetCents = Math.max(0, Math.min(Math.trunc(requestedCents), totalReducibleCents));
4928
- const allocations = sanitizedInputs.map((input) => ({
4929
- lineId: input.lineId,
4930
- amountCents: toNonNegativeCents(0)
4931
- }));
4932
- if (targetCents === 0 || sanitizedInputs.length === 0) {
4933
- return {
4934
- requestedCents: toNonNegativeCents(requestedCents),
4935
- appliedCents: toNonNegativeCents(0),
4936
- allocations
4937
- };
4938
- }
4939
- const remainingCaps = sanitizedInputs.map((input) => input.maxReducibleCents);
4940
- let remainingCents = targetCents;
4941
- while (remainingCents > 0) {
4942
- const eligibleIndexes = sanitizedInputs.map((input, index) => ({
4943
- input,
4944
- index
4945
- })).filter(({ input, index }) => input.basisCents > 0 && (remainingCaps[index] ?? 0) > 0);
4946
- if (eligibleIndexes.length === 0) break;
4947
- const eligibleBasis = eligibleIndexes.reduce((sum, { input }) => sum + input.basisCents, 0);
4948
- if (eligibleBasis <= 0) break;
4949
- const roundCandidates = eligibleIndexes.map(({ input, index }) => {
4950
- const exactShare = input.basisCents / eligibleBasis * remainingCents;
4951
- const floorShare = Math.min(Math.floor(exactShare), remainingCaps[index] ?? 0);
4952
- const remainder = exactShare - floorShare;
4953
- return {
4954
- index,
4955
- floorShare,
4956
- remainder
4957
- };
4958
- });
4959
- let assignedThisRound = 0;
4960
- for (const candidate of roundCandidates) {
4961
- if (candidate.floorShare <= 0) continue;
4962
- const allocation = allocations[candidate.index];
4963
- if (!allocation) continue;
4964
- allocation.amountCents = toNonNegativeCents(allocation.amountCents + candidate.floorShare);
4965
- remainingCaps[candidate.index] = toNonNegativeCents((remainingCaps[candidate.index] ?? 0) - candidate.floorShare);
4966
- assignedThisRound += candidate.floorShare;
4967
- }
4968
- remainingCents -= assignedThisRound;
4969
- if (remainingCents <= 0) break;
4970
- const remainderCandidates = roundCandidates.filter((candidate) => (remainingCaps[candidate.index] ?? 0) > 0).sort((a, b) => {
4971
- if (b.remainder !== a.remainder) return b.remainder - a.remainder;
4972
- return a.index - b.index;
4973
- });
4974
- if (remainderCandidates.length === 0) break;
4975
- let remainderAssigned = 0;
4976
- for (const candidate of remainderCandidates) {
4977
- if (remainingCents <= 0) break;
4978
- if ((remainingCaps[candidate.index] ?? 0) <= 0) continue;
4979
- const allocation = allocations[candidate.index];
4980
- if (!allocation) continue;
4981
- allocation.amountCents = toNonNegativeCents(allocation.amountCents + 1);
4982
- remainingCaps[candidate.index] = toNonNegativeCents((remainingCaps[candidate.index] ?? 0) - 1);
4983
- remainingCents -= 1;
4984
- remainderAssigned += 1;
4985
- }
4986
- if (assignedThisRound === 0 && remainderAssigned === 0) {
4987
- break;
4988
- }
4989
- }
4990
- const appliedCents = allocations.reduce((sum, allocation) => sum + allocation.amountCents, 0);
4991
- return {
4992
- requestedCents: toNonNegativeCents(requestedCents),
4993
- appliedCents: toNonNegativeCents(appliedCents),
4994
- allocations
4995
- };
4996
- }
4997
- function assertSettledOrderLineInvariants(lines) {
4998
- for (const line of lines) {
4999
- if (line.discountCents < 0 || line.creditCents < 0 || line.netTotalCents < 0) {
5000
- throw new Error(`Negative settlement values are not allowed for line ${line.lineId}`);
5001
- }
5002
- const expectedNet = line.subtotalCents - line.discountCents - line.creditCents;
5003
- if (line.netTotalCents !== expectedNet) {
5004
- throw new Error(`Settlement invariant failed for line ${line.lineId}: expected ${expectedNet}, got ${line.netTotalCents}`);
5005
- }
5006
- }
5007
- }
5008
-
5009
5174
  //#endregion
5010
5175
  //#region ../commerce/src/purchase/result.ts
5011
5176
  function traverseResult(results) {
@@ -5155,7 +5320,7 @@ function planCheckoutStripeSessionMetadata(options) {
5155
5320
  metadata.discount_code_id = options.discount.discountCodeId;
5156
5321
  metadata.discount_code = options.discount.discountCode;
5157
5322
  metadata.discount_public_label = options.discount.discountPublicLabel;
5158
- metadata.discount_code_amount_cents = String(options.totals.discountCents);
5323
+ metadata.discount_code_amount_cents = String(options.discount.amountDiscountCents);
5159
5324
  }
5160
5325
  if (options.orderReferences.orderPaymentPlanId) {
5161
5326
  metadata.order_payment_plan_id = options.orderReferences.orderPaymentPlanId;
@@ -5351,7 +5516,31 @@ const SharedDatedOfferingOrderCheckoutSessionMetadataSchema = z.object({
5351
5516
  ...orderCheckoutSessionMetadataBaseShape,
5352
5517
  ...datedOfferingSharedEngineMetadataShape
5353
5518
  });
5354
- 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
+ ]);
5355
5544
 
5356
5545
  //#endregion
5357
5546
  //#region ../commerce/src/purchase/canonicalRefundPlanner.ts
@@ -5506,8 +5695,8 @@ const settledBalanceSchema = z.strictObject({ kind: z.literal("settled") });
5506
5695
  const dueBalanceSchema = z.strictObject({
5507
5696
  kind: z.literal("due"),
5508
5697
  amountCents: z.number().int().positive().transform((value, ctx) => {
5509
- const cents = parsePositiveCents(value);
5510
- if (cents.ok) return cents.value;
5698
+ const cents$2 = parsePositiveCents(value);
5699
+ if (cents$2.ok) return cents$2.value;
5511
5700
  ctx.addIssue({
5512
5701
  code: "custom",
5513
5702
  message: "Expected positive whole cents"
@@ -5645,7 +5834,6 @@ function fallbackOrderItemDisplayName(kind) {
5645
5834
 
5646
5835
  //#endregion
5647
5836
  //#region ../commerce/src/purchase/orderPaymentState.ts
5648
- const ZERO_CENTS = toNonNegativeCents(0);
5649
5837
  /** Amount arithmetic shared by strict payment evidence and tolerant email snapshots.
5650
5838
  * Snapshots historically clamp overcollection to zero; the strict decision below
5651
5839
  * checks collectability before using the same calculation.
@@ -5663,219 +5851,13 @@ function calculateOrderBalanceDueCents(input) {
5663
5851
  settledCents
5664
5852
  })));
5665
5853
  }
5666
- function derivePaymentTerms(input, outstandingCents) {
5667
- if (input.flexibleBalance && input.instalmentPlan) {
5668
- return err({ kind: "conflicting_payment_terms" });
5669
- }
5670
- const isNonMonetary = input.paymentMethod === "free" || input.paymentMethod === "waived" || input.paymentMethod === "pass_redemption" || input.paymentMethod === "membership_access";
5671
- if (isNonMonetary && (input.flexibleBalance || input.instalmentPlan)) {
5672
- return err({ kind: "managed_terms_for_non_monetary_order" });
5673
- }
5674
- if (input.flexibleBalance) {
5675
- if (input.flexibleBalance.remainingBalanceCents !== outstandingCents) {
5676
- return err({
5677
- kind: "projection_receipt_mismatch",
5678
- projection: "flexible_balance"
5679
- });
5680
- }
5681
- return ok({
5682
- kind: "flexible_balance",
5683
- contractId: input.flexibleBalance.contractId,
5684
- status: input.flexibleBalance.status,
5685
- dueAt: input.flexibleBalance.dueAt,
5686
- upfrontAmountCents: input.flexibleBalance.upfrontAmountCents
5687
- });
5688
- }
5689
- if (input.instalmentPlan) {
5690
- if (input.instalmentPlan.remainingBalanceCents !== outstandingCents) {
5691
- return err({
5692
- kind: "projection_receipt_mismatch",
5693
- projection: "instalment_plan"
5694
- });
5695
- }
5696
- return ok({
5697
- kind: "instalment_plan",
5698
- paymentPlanId: input.instalmentPlan.paymentPlanId,
5699
- status: input.instalmentPlan.status,
5700
- nextDueAt: input.instalmentPlan.nextDueAt,
5701
- nextDueAmountCents: input.instalmentPlan.nextDueAmountCents
5702
- });
5703
- }
5704
- return ok(input.paymentMethod === "manual" ? { kind: "manual" } : { kind: "immediate" });
5705
- }
5706
- function deriveOrderPaymentPosition(input) {
5707
- const balance = calculateOrderBalanceDueCents(input);
5708
- if (!balance.ok) return balance;
5709
- if (input.refundedCents > input.paidCents) {
5710
- return err({ kind: "refunded_exceeds_collected" });
5711
- }
5712
- const amounts = {
5713
- totalCents: input.grandTotalCents,
5714
- collectedCents: input.paidCents,
5715
- refundedCents: input.refundedCents,
5716
- outstandingCents: balance.value
5717
- };
5718
- const terms = derivePaymentTerms(input, balance.value);
5719
- if (!terms.ok) return terms;
5720
- if (input.status === "cancelled") {
5721
- return ok({
5722
- kind: "cancelled",
5723
- ...amounts,
5724
- outstandingCents: ZERO_CENTS,
5725
- terms: terms.value
5726
- });
5727
- }
5728
- if (input.status === "refunded") {
5729
- return ok({
5730
- kind: "refunded",
5731
- ...amounts,
5732
- outstandingCents: ZERO_CENTS,
5733
- terms: terms.value
5734
- });
5735
- }
5736
- if (input.waivedCents > 0) {
5737
- return ok({
5738
- kind: "waived",
5739
- ...amounts,
5740
- waivedCents: input.waivedCents,
5741
- outstandingCents: ZERO_CENTS,
5742
- terms: terms.value
5743
- });
5744
- }
5745
- switch (input.paymentMethod) {
5746
- case "free": return ok({
5747
- kind: "not_required",
5748
- reason: "free",
5749
- ...amounts,
5750
- outstandingCents: ZERO_CENTS
5751
- });
5752
- case "waived": return ok({
5753
- kind: "not_required",
5754
- reason: "waived",
5755
- ...amounts,
5756
- outstandingCents: ZERO_CENTS
5757
- });
5758
- case "pass_redemption": return ok({
5759
- kind: "not_required",
5760
- reason: "pass",
5761
- ...amounts,
5762
- outstandingCents: ZERO_CENTS
5763
- });
5764
- case "membership_access": return ok({
5765
- kind: "not_required",
5766
- reason: "membership",
5767
- ...amounts,
5768
- outstandingCents: ZERO_CENTS
5769
- });
5770
- case "stripe":
5771
- case "store_credit":
5772
- case "mixed":
5773
- case "manual": break;
5774
- default: return assertNever$3(input.paymentMethod);
5775
- }
5776
- if (input.status === "failed" || input.hasCollectionFailure) {
5777
- return ok({
5778
- kind: "collection_failed",
5779
- ...amounts,
5780
- terms: terms.value
5781
- });
5782
- }
5783
- if (balance.value === 0) {
5784
- return ok({
5785
- kind: "paid",
5786
- ...amounts,
5787
- outstandingCents: ZERO_CENTS,
5788
- settledVia: input.paymentMethod,
5789
- terms: terms.value
5790
- });
5791
- }
5792
- if (input.paidCents > 0) return ok({
5793
- kind: "partially_paid",
5794
- ...amounts,
5795
- terms: terms.value
5796
- });
5797
- return ok({
5798
- kind: "unpaid",
5799
- ...amounts,
5800
- terms: terms.value
5801
- });
5802
- }
5803
- function buildPaymentPresentation(position) {
5804
- const shared = {
5805
- collectedCents: position.collectedCents,
5806
- refundedCents: position.refundedCents,
5807
- outstandingCents: position.outstandingCents,
5808
- dueAt: "terms" in position && position.terms.kind === "flexible_balance" ? position.terms.dueAt : null,
5809
- nextDueAt: "terms" in position && position.terms.kind === "instalment_plan" ? position.terms.nextDueAt : null
5810
- };
5811
- switch (position.kind) {
5812
- case "not_required": return {
5813
- tone: "neutral",
5814
- label: "Not required",
5815
- ...shared
5816
- };
5817
- case "waived": return {
5818
- tone: "neutral",
5819
- label: "Waived",
5820
- ...shared
5821
- };
5822
- case "unpaid": return {
5823
- tone: "warning",
5824
- label: "Unpaid",
5825
- ...shared
5826
- };
5827
- case "partially_paid": return {
5828
- tone: "warning",
5829
- label: "Partially paid",
5830
- ...shared
5831
- };
5832
- case "paid": return {
5833
- tone: "positive",
5834
- label: "Paid",
5835
- ...shared
5836
- };
5837
- case "collection_failed": return {
5838
- tone: "critical",
5839
- label: "Payment failed",
5840
- ...shared
5841
- };
5842
- case "refunded": return {
5843
- tone: "neutral",
5844
- label: "Refunded",
5845
- ...shared
5846
- };
5847
- case "cancelled": return {
5848
- tone: "neutral",
5849
- label: "Cancelled",
5850
- ...shared
5851
- };
5852
- default: return assertNever$3(position);
5853
- }
5854
- }
5854
+ /** Online rails are presentation/effect choices; SQL has already admitted collection. */
5855
5855
  function hasOnlineOrderPaymentPath(input) {
5856
- if (input.position.kind !== "unpaid" && input.position.kind !== "partially_paid" && input.position.kind !== "collection_failed") return false;
5857
- if (input.position.outstandingCents === 0) return false;
5858
- switch (input.position.terms.kind) {
5859
- case "immediate": return input.paymentMethod === "stripe";
5860
- case "manual": return ["manual", "mixed"].includes(input.paymentMethod);
5861
- case "flexible_balance": return [
5862
- "manual",
5863
- "stripe",
5864
- "mixed"
5865
- ].includes(input.paymentMethod) && isSettleableFlexibleBalanceContractStatus(input.position.terms.status);
5866
- case "instalment_plan": return ["stripe", "mixed"].includes(input.paymentMethod) && isSettleableOrderInstalmentPlanStatus(input.position.terms.status);
5867
- default: return assertNever$3(input.position.terms);
5868
- }
5856
+ return input.position.admissions.paymentLinkPreparation.kind !== "refused";
5869
5857
  }
5870
- /** Executable outstanding card-payment path. Connection readiness is checked by the effect shell. */
5871
5858
  function resolveOnlineOrderCheckoutMode(order) {
5872
- if (order.status !== "pending" || order.commitState !== "committed" || order.balanceDueCents <= 0) return null;
5873
- if (!hasOnlineOrderPaymentPath({
5874
- position: order.paymentState,
5875
- paymentMethod: order.paymentMethod
5876
- })) return null;
5877
- if (!("terms" in order.paymentState)) return null;
5878
- switch (order.paymentState.terms.kind) {
5859
+ if (!hasOnlineOrderPaymentPath({ position: order.paymentPosition })) return null;
5860
+ switch (order.paymentPosition.terms.kind) {
5879
5861
  case "manual":
5880
5862
  case "immediate": return { kind: "immediate" };
5881
5863
  case "flexible_balance": return { kind: "flexible_balance" };
@@ -6058,94 +6040,102 @@ function buildTransferredAttendeeConfirmationEmailPaymentSummary(options) {
6058
6040
  //#endregion
6059
6041
  //#region ../commerce/src/purchase/discountApplication.ts
6060
6042
  const CHECKOUT_DISCOUNT_ALLOCATION_RULE_VERSION = "proportional-v1";
6043
+ /** Preserve combination allocations; allocate a code against the remaining line bases. */
6061
6044
  function planCheckoutDiscountApplication(input) {
6062
- 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) {
6063
6050
  return err({
6064
- _tag: "empty_cart",
6065
- message: "Cart is empty"
6051
+ _tag: "invalid_discount_amount",
6052
+ message: "A checkout accepts at most one discount code"
6066
6053
  });
6067
6054
  }
6068
- const lines = input.items.map((item) => ({
6069
- item,
6070
- subtotalCents: item.subtotalCents
6071
- }));
6072
- const subtotalCents = toNonNegativeCents(lines.reduce((sum, line) => sum + line.subtotalCents, 0));
6073
- if (!input.selectedDiscount) {
6074
- return ok(buildNoDiscountApplication({
6075
- currency: input.currency,
6076
- lines,
6077
- subtotalCents
6078
- }));
6079
- }
6080
- const selectedDiscount = input.selectedDiscount;
6081
- const discountAllocation = allocateReductionCents(lines.map((line) => ({
6082
- lineId: line.item.lineId,
6083
- basisCents: line.subtotalCents,
6084
- maxReducibleCents: selectedDiscount.eligibleLineIds.has(line.item.lineId) ? line.subtotalCents : toNonNegativeCents(0)
6085
- })), selectedDiscount.discount.amountDiscountCents);
6086
- const discountByLineId = new Map(discountAllocation.allocations.map((allocation) => [allocation.lineId, allocation.amountCents]));
6087
- const items = lines.map((line) => {
6088
- const discountCents = discountByLineId.get(line.item.lineId) ?? toNonNegativeCents(0);
6089
- return {
6090
- lineId: line.item.lineId,
6091
- subtotalCents: line.subtotalCents,
6092
- discountCents,
6093
- totalAfterDiscountCents: toNonNegativeCents(line.subtotalCents - discountCents),
6094
- payload: line.item.payload
6095
- };
6096
- });
6097
- return ok({
6055
+ const initial = {
6098
6056
  currency: input.currency,
6099
- items,
6100
- subtotalCents,
6101
- discountCents: discountAllocation.appliedCents,
6102
- totalAfterDiscountCents: toNonNegativeCents(subtotalCents - discountAllocation.appliedCents),
6103
- discount: selectedDiscount.discount,
6104
- discountApplication: buildDiscountApplicationSnapshot({
6105
- lines,
6106
- selectedDiscount,
6107
- discountByLineId,
6108
- appliedCents: discountAllocation.appliedCents,
6109
- currency: input.currency
6110
- })
6111
- });
6112
- }
6113
- function buildNoDiscountApplication(options) {
6114
- return {
6115
- currency: options.currency,
6116
- items: options.lines.map((line) => ({
6117
- lineId: line.item.lineId,
6118
- subtotalCents: line.subtotalCents,
6057
+ items: input.items.map((item) => ({
6058
+ ...item,
6119
6059
  discountCents: toNonNegativeCents(0),
6120
- totalAfterDiscountCents: line.subtotalCents,
6121
- payload: line.item.payload
6060
+ totalAfterDiscountCents: item.subtotalCents
6122
6061
  })),
6123
- subtotalCents: options.subtotalCents,
6062
+ subtotalCents: toNonNegativeCents(input.items.reduce((sum, item) => sum + item.subtotalCents, 0)),
6124
6063
  discountCents: toNonNegativeCents(0),
6125
- totalAfterDiscountCents: options.subtotalCents,
6064
+ totalAfterDiscountCents: toNonNegativeCents(input.items.reduce((sum, item) => sum + item.subtotalCents, 0)),
6126
6065
  discount: null,
6127
- 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"
6128
6087
  };
6129
6088
  }
6130
- 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);
6131
6105
  return {
6132
- discountCodeId: options.selectedDiscount.discount.discountCodeId,
6133
- discountRedemptionId: options.selectedDiscount.discount.redemptionId,
6134
- code: options.selectedDiscount.discount.discountCode,
6135
- displayLabel: options.selectedDiscount.discount.discountPublicLabel,
6136
- source: options.selectedDiscount.discount.autoApplied ? "auto" : "manual",
6137
- currency: options.currency,
6138
- 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,
6139
6117
  allocationRuleVersion: CHECKOUT_DISCOUNT_ALLOCATION_RULE_VERSION,
6140
- items: options.lines.map((line) => {
6141
- 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;
6142
6129
  return {
6143
- lineId: line.item.lineId,
6144
- eligible,
6145
- basisSubtotalCents: eligible ? line.subtotalCents : toNonNegativeCents(0),
6146
- discountCents: options.discountByLineId.get(line.item.lineId) ?? toNonNegativeCents(0)
6130
+ ...item,
6131
+ discountCents: toNonNegativeCents(item.discountCents + reduction),
6132
+ totalAfterDiscountCents: toNonNegativeCents(item.totalAfterDiscountCents - reduction)
6147
6133
  };
6148
- })
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]
6149
6139
  };
6150
6140
  }
6151
6141
 
@@ -6170,7 +6160,7 @@ function buildOneTimeCheckoutPlan(options) {
6170
6160
  totalAfterDiscount: money(options.settledCart.totalAfterDiscountCents, currency),
6171
6161
  totalAfterCredits: money(options.settledCart.totalAfterCreditsCents, currency),
6172
6162
  discount: options.settledCart.discount,
6173
- discountApplication: options.settledCart.discountApplication
6163
+ discountApplications: options.settledCart.discountApplications
6174
6164
  };
6175
6165
  const chargeMismatch = findInstalmentChargeMismatch(options.paymentPlan, settlement.totalAfterCredits.amountCents);
6176
6166
  if (chargeMismatch) return err(chargeMismatch);
@@ -6207,7 +6197,7 @@ function materializeSettledCart(plan) {
6207
6197
  totalAfterCreditsCents: plan.settlement.totalAfterCredits.amountCents,
6208
6198
  currency: plan.settlement.currency,
6209
6199
  discount: plan.settlement.discount,
6210
- discountApplication: plan.settlement.discountApplication
6200
+ discountApplications: plan.settlement.discountApplications
6211
6201
  };
6212
6202
  }
6213
6203
  function buildOrderDraftPlan(paymentPlan, settlement) {
@@ -6454,12 +6444,12 @@ function resolveOrderConfirmationPaymentMethodLabel(paymentMethod) {
6454
6444
  }
6455
6445
  return assertNever$3(paymentMethod);
6456
6446
  }
6457
- function resolveOrderConfirmationPaymentSummary(order, settlement, formatCurrencyAmount) {
6447
+ function resolveOrderConfirmationPaymentSummary(order, settlement, formatCurrencyAmount$1) {
6458
6448
  switch (order.paymentMethod) {
6459
- case "stripe": return settlement.collectedCents > 0 ? `${formatCurrencyAmount(settlement.collectedCents, order.currency)} charged to card` : null;
6460
- case "mixed": return `${formatCurrencyAmount(settlement.collectedCents, order.currency)} charged to card and ${formatCurrencyAmount(order.creditCents, order.currency)} applied from site credit`;
6461
- case "store_credit": return `${formatCurrencyAmount(order.creditCents, order.currency)} applied from site credit`;
6462
- 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`;
6463
6453
  case "pass_redemption": return "Covered by pass redemption";
6464
6454
  case "membership_access": return "Covered by membership access";
6465
6455
  case "waived": return "Payment was waived for this order";
@@ -6886,37 +6876,18 @@ function hasArchivedOrderHistorySource(record) {
6886
6876
 
6887
6877
  //#endregion
6888
6878
  //#region ../commerce/src/purchase/orderInstalmentAdminSettlement.ts
6889
- const MANUALLY_SETTLEABLE_PLAN_STATUSES = ["active", "payment_failed"];
6890
- const settleablePlanStatusSet = new Set(MANUALLY_SETTLEABLE_PLAN_STATUSES);
6891
6879
  const MANUALLY_SETTLEABLE_INSTALMENT_STATUSES = ["scheduled", "failed"];
6892
6880
  const settleableInstalmentStatusSet = new Set(MANUALLY_SETTLEABLE_INSTALMENT_STATUSES);
6893
- function isManuallySettleablePlanStatus(status) {
6894
- return settleablePlanStatusSet.has(status);
6895
- }
6896
6881
  function isManuallySettleableInstalmentStatus(status) {
6897
6882
  return settleableInstalmentStatusSet.has(status);
6898
6883
  }
6899
6884
  function listCollectibleRecurringInstalments(instalments) {
6900
6885
  return instalments.filter((instalment) => instalment.phaseKind === "scheduled" && isManuallySettleableInstalmentStatus(instalment.status)).sort((left, right) => left.sequence - right.sequence);
6901
6886
  }
6902
- function assertSupportedPlanStatus(paymentPlan) {
6903
- if (paymentPlan.remainingBalanceCents <= 0 || paymentPlan.status === "completed" || paymentPlan.status === "cancelled_as_paid_early") {
6904
- return;
6905
- }
6906
- if (!isManuallySettleablePlanStatus(paymentPlan.status)) {
6907
- throw new Error(`Cannot settle instalment plan in status '${paymentPlan.status}'`);
6908
- }
6909
- }
6910
6887
  function planOrderInstalmentManualPayment(input) {
6911
6888
  if (input.paymentPlan.remainingBalanceCents <= 0) {
6912
6889
  return { kind: "already_applied" };
6913
6890
  }
6914
- if (!isManuallySettleablePlanStatus(input.paymentPlan.status)) {
6915
- return {
6916
- kind: "refused",
6917
- message: `Cannot settle instalment plan in status '${input.paymentPlan.status}'`
6918
- };
6919
- }
6920
6891
  const collectibleInstalments = listCollectibleRecurringInstalments(input.instalments);
6921
6892
  if (collectibleInstalments.length === 0) {
6922
6893
  return {
@@ -6958,25 +6929,6 @@ function planOrderInstalmentManualPayment(input) {
6958
6929
  instalmentUpdates: allocation.updates
6959
6930
  };
6960
6931
  }
6961
- function planOrderInstalmentWaiver(input) {
6962
- if (input.paymentPlan.remainingBalanceCents <= 0) {
6963
- return { kind: "already_applied" };
6964
- }
6965
- assertSupportedPlanStatus(input.paymentPlan);
6966
- const instalmentUpdates = listCollectibleRecurringInstalments(input.instalments).map((instalment) => ({
6967
- instalmentId: instalment.id,
6968
- nextStatus: "waived"
6969
- }));
6970
- if (instalmentUpdates.length === 0) {
6971
- throw new Error("No recurring instalments are available to waive");
6972
- }
6973
- return {
6974
- kind: "apply",
6975
- nextPlanStatus: "completed",
6976
- nextRemainingBalanceCents: toNonNegativeCents(0),
6977
- instalmentUpdates
6978
- };
6979
- }
6980
6932
 
6981
6933
  //#endregion
6982
6934
  //#region ../commerce/src/purchase/orderInstalmentClosure.ts
@@ -7722,80 +7674,284 @@ function planUnappliedOrderPaymentReceiptAllocations(input) {
7722
7674
  return attributedCents === input.amountCents ? ok(allocations) : err({ kind: "allocation_invariant_failed" });
7723
7675
  }
7724
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
+
7725
7894
  //#endregion
7726
7895
  //#region ../commerce/src/purchase/orderPaymentLinkPlanning.ts
7727
7896
  function buildOrderPaymentAdminProjection(facts) {
7728
- const paymentPosition = deriveOrderPaymentPosition({
7729
- status: facts.status,
7730
- paymentMethod: facts.paymentMethod,
7731
- grandTotalCents: facts.grandTotalCents,
7732
- paidCents: facts.paidCents,
7733
- waivedCents: facts.waivedCents,
7734
- refundedCents: facts.refundedCents,
7735
- flexibleBalance: facts.flexibleBalance ? {
7736
- contractId: facts.flexibleBalance.contractId,
7737
- status: facts.flexibleBalance.status,
7738
- remainingBalanceCents: facts.flexibleBalance.remainingBalanceCents,
7739
- dueAt: facts.flexibleBalance.dueAt ?? null,
7740
- upfrontAmountCents: facts.flexibleBalance.upfrontAmountCents ?? facts.paidCents
7741
- } : null,
7742
- instalmentPlan: facts.instalmentPlan ? {
7743
- paymentPlanId: facts.instalmentPlan.paymentPlanId,
7744
- status: facts.instalmentPlan.status,
7745
- remainingBalanceCents: facts.instalmentPlan.remainingBalanceCents,
7746
- nextDueAt: facts.instalmentPlan.nextDueAt ?? null,
7747
- nextDueAmountCents: facts.instalmentPlan.nextDueAmountCents ?? null
7748
- } : null,
7749
- hasCollectionFailure: facts.instalmentPlan?.status === "payment_failed"
7750
- });
7751
- if (!paymentPosition.ok) return paymentPosition;
7752
- const paymentState = paymentPosition.value;
7753
- const balanceDueCents = paymentState.outstandingCents;
7754
- const paymentLinkAvailability = resolvePaymentLinkAvailabilityFromFacts({
7755
- ...facts,
7897
+ const paymentState = paymentPositionForDisplay(facts.paymentPosition);
7898
+ const balanceDueCents = facts.paymentPosition.amounts.remainderCents;
7899
+ const paymentLinkAvailability = resolvePaymentLinkAvailabilityFromFacts(facts);
7900
+ return {
7756
7901
  paymentState,
7757
- balanceDueCents
7758
- });
7759
- const paymentReminderAvailability = resolvePaymentReminderAvailabilityFromFacts({
7902
+ balanceDueCents,
7760
7903
  paymentLinkAvailability,
7761
- customerEmail: facts.customerEmail
7762
- });
7763
- return {
7764
- ok: true,
7765
- value: {
7766
- paymentState,
7767
- balanceDueCents,
7768
- paymentLinkAvailability,
7769
- paymentReminderAvailability
7770
- }
7904
+ paymentReminderAvailability: resolvePaymentReminderAvailabilityFromFacts({
7905
+ paymentLinkAvailability: resolvePaymentLinkAvailabilityFromFacts(facts, facts.paymentPosition.admissions.demand, false),
7906
+ customerEmail: facts.customerEmail
7907
+ })
7771
7908
  };
7772
7909
  }
7773
- function resolvePaymentLinkAvailabilityFromFacts(input) {
7774
- switch (input.historySource) {
7775
- case "ledger": return unavailable("archived_order", "Archived orders cannot generate customer payment links.", 422);
7776
- case "live": break;
7777
- default: return assertNever$3(input.historySource);
7778
- }
7779
- if (input.status !== "pending") {
7780
- return unavailable("order_not_pending", "Only pending orders can generate a customer payment link.", 422);
7781
- }
7782
- if (input.commitState !== "committed") {
7783
- return unavailable("order_not_committed", "This order cannot generate a customer payment link right now.", 422);
7784
- }
7785
- if (input.balanceDueCents <= 0) {
7786
- return unavailable("no_balance_due", "This order does not have a payable balance.", 422);
7787
- }
7788
- if (!resolveOnlineOrderCheckoutMode(input)) {
7789
- return unavailable("payment_path_unavailable", "This order cannot generate a customer payment link right now.", 422);
7790
- }
7910
+ function resolvePaymentLinkAvailabilityFromFacts(input, verdict = input.paymentPosition.admissions.paymentLinkPreparation, canCheckProvider = true) {
7911
+ const admission = operationAvailability(verdict, canCheckProvider);
7912
+ if (admission.kind === "unavailable") return admission;
7791
7913
  if (!input.stripeConnected) {
7792
7914
  return unavailable("stripe_not_connected", "Online payment is not available for this site.", 409);
7793
7915
  }
7794
- if (input.hasLiveCheckoutAttempt) {
7795
- return unavailable("checkout_in_progress", "An online payment checkout is already in progress for this order.", 409);
7796
- }
7797
7916
  return { kind: "available" };
7798
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
+ }
7799
7955
  function resolvePaymentReminderAvailabilityFromFacts(input) {
7800
7956
  if (input.paymentLinkAvailability.kind === "unavailable") {
7801
7957
  return input.paymentLinkAvailability;
@@ -7825,58 +7981,6 @@ function unavailable(reason, publicMessage, httpStatus) {
7825
7981
 
7826
7982
  //#endregion
7827
7983
  //#region ../commerce/src/purchase/orderRefundPlanning.ts
7828
- function planOrderRefund(options) {
7829
- const paidCents = options.paidCents;
7830
- const currentRefundedCents = options.currentRefundedCents;
7831
- if (currentRefundedCents > paidCents) {
7832
- return err("Current refunded amount exceeds paid amount");
7833
- }
7834
- const linesById = new Map();
7835
- for (const line of options.lines) {
7836
- if (linesById.has(line.orderItemId)) {
7837
- return err(`Duplicate refund line input: ${line.orderItemId}`);
7838
- }
7839
- linesById.set(line.orderItemId, line);
7840
- }
7841
- const plannedLines = [];
7842
- let requestedTotalCents = 0;
7843
- let appliedTotalCents = 0;
7844
- for (const requested of options.requestedLineRefunds) {
7845
- const line = linesById.get(requested.orderItemId);
7846
- if (!line) {
7847
- return err(`Unknown order item for refund planning: ${requested.orderItemId}`);
7848
- }
7849
- const netTotalCents = line.netTotalCents;
7850
- const alreadyRefundedCents = line.alreadyRefundedCents ?? toNonNegativeCents(0);
7851
- if (alreadyRefundedCents > netTotalCents) {
7852
- return err(`Refunded amount exceeds line total for ${line.orderItemId}`);
7853
- }
7854
- const refundableRemainingCents$1 = orderItemRefundableRemainingCents({
7855
- cashFundedCents: netTotalCents,
7856
- creditAppliedCents: 0,
7857
- refundedCents: alreadyRefundedCents
7858
- });
7859
- const requestedCents = requested.amountCents;
7860
- const appliedCents = toNonNegativeCents(Math.min(requestedCents, refundableRemainingCents$1));
7861
- requestedTotalCents += requestedCents;
7862
- appliedTotalCents += appliedCents;
7863
- plannedLines.push({
7864
- orderItemId: requested.orderItemId,
7865
- requestedCents,
7866
- refundableRemainingCents: refundableRemainingCents$1,
7867
- appliedCents
7868
- });
7869
- }
7870
- const nextRefundedCents = toNonNegativeCents(currentRefundedCents + appliedTotalCents);
7871
- const nextStatus = appliedTotalCents <= 0 ? null : nextRefundedCents >= paidCents ? "refunded" : "partially_refunded";
7872
- return ok({
7873
- lines: plannedLines,
7874
- requestedTotalCents: toNonNegativeCents(requestedTotalCents),
7875
- appliedTotalCents: toNonNegativeCents(appliedTotalCents),
7876
- nextRefundedCents,
7877
- nextStatus
7878
- });
7879
- }
7880
7984
  function planOrderRefundSummaryUpdate(options) {
7881
7985
  const paidCents = options.paidCents;
7882
7986
  const currentRefundedCents = options.currentRefundedCents;
@@ -7887,30 +7991,7 @@ function planOrderRefundSummaryUpdate(options) {
7887
7991
  if (nextRefundedCents < currentRefundedCents) {
7888
7992
  return err("Refunded amount cannot decrease");
7889
7993
  }
7890
- const nextStatus = nextRefundedCents <= 0 ? null : nextRefundedCents >= paidCents ? "refunded" : "partially_refunded";
7891
- return ok({
7892
- refundedCents: nextRefundedCents,
7893
- nextStatus
7894
- });
7895
- }
7896
- function settleOrderRefundPlan(options) {
7897
- const actualRefundedCents = options.actualRefundedCents;
7898
- if (actualRefundedCents > options.planned.appliedTotalCents) {
7899
- return err("Actual refunded amount exceeds planned refundable amount");
7900
- }
7901
- const allocation = allocateReductionCents(options.planned.lines.map((line) => ({
7902
- lineId: line.orderItemId,
7903
- basisCents: line.appliedCents,
7904
- maxReducibleCents: line.appliedCents
7905
- })), actualRefundedCents);
7906
- return ok({
7907
- lines: options.planned.lines.map((line) => ({
7908
- orderItemId: line.orderItemId,
7909
- requestedCents: line.requestedCents,
7910
- appliedCents: allocation.allocations.find((allocationLine) => allocationLine.lineId === line.orderItemId)?.amountCents ?? toNonNegativeCents(0)
7911
- })),
7912
- refundedTotalCents: allocation.appliedCents
7913
- });
7994
+ return ok({ refundedCents: nextRefundedCents });
7914
7995
  }
7915
7996
 
7916
7997
  //#endregion
@@ -8007,80 +8088,6 @@ function fallbackDisplayName(kind) {
8007
8088
 
8008
8089
  //#endregion
8009
8090
  //#region ../commerce/src/purchase/protectedDepositRefundPolicy.ts
8010
- function buildProtectedDepositPolicySubjectFromFlexibleBalance(input) {
8011
- return {
8012
- kind: "protected_deposit",
8013
- sourceKind: "flexible_balance",
8014
- protectedDepositAmountCents: input.upfrontAmountCents,
8015
- depositRefundability: input.depositRefundability
8016
- };
8017
- }
8018
- function buildProtectedDepositPolicySubjectFromInstalmentPlan(plan) {
8019
- const protectedDepositAmountCents = getBookingInstalmentProtectedDepositAmountCents(plan);
8020
- const depositRefundability = getBookingInstalmentDepositRefundability(plan);
8021
- if (protectedDepositAmountCents == null || depositRefundability == null) {
8022
- return { kind: "none" };
8023
- }
8024
- return {
8025
- kind: "protected_deposit",
8026
- sourceKind: "instalment_plan",
8027
- protectedDepositAmountCents: unsafeAsNonNegativeCents(protectedDepositAmountCents),
8028
- depositRefundability
8029
- };
8030
- }
8031
- function calculateProtectedDepositRefundExposure(input) {
8032
- const itemRemainingCents = toNonNegativeCents(input.itemTotalCents - input.itemRefundedCents);
8033
- const totalRemainingRefundableCents = toNonNegativeCents(Math.min(itemRemainingCents, input.collectedRemainingCents));
8034
- if (input.subject.kind === "none" || input.subject.depositRefundability === "refundable") {
8035
- return {
8036
- subject: input.subject,
8037
- totalRemainingRefundableCents,
8038
- policyRefundableCents: totalRemainingRefundableCents,
8039
- protectedDepositRemainingCents: toNonNegativeCents(0)
8040
- };
8041
- }
8042
- const protectedDepositOriginalCents = toNonNegativeCents(Math.min(input.subject.protectedDepositAmountCents, input.itemTotalCents));
8043
- const nonDepositOriginalCents = toNonNegativeCents(input.itemTotalCents - protectedDepositOriginalCents);
8044
- const refundedAgainstProtectedDepositCents = toNonNegativeCents(input.itemRefundedCents - nonDepositOriginalCents);
8045
- const protectedDepositRemainingByItemCents = toNonNegativeCents(protectedDepositOriginalCents - refundedAgainstProtectedDepositCents);
8046
- const nonDepositRemainingByItemCents = toNonNegativeCents(itemRemainingCents - protectedDepositRemainingByItemCents);
8047
- const policyRefundableCents = toNonNegativeCents(Math.min(totalRemainingRefundableCents, nonDepositRemainingByItemCents));
8048
- return {
8049
- subject: input.subject,
8050
- totalRemainingRefundableCents,
8051
- policyRefundableCents,
8052
- protectedDepositRemainingCents: toNonNegativeCents(totalRemainingRefundableCents - policyRefundableCents)
8053
- };
8054
- }
8055
- /**
8056
- * Calculates policy exposure for one receipt allocation.
8057
- *
8058
- * A protected deposit is collected by the initial-checkout receipt. Later
8059
- * paydowns and instalments therefore remain independently refundable even
8060
- * while the entity still has a non-refundable deposit balance.
8061
- */
8062
- function calculateReceiptProtectedDepositRefundExposure(input) {
8063
- const totalRemainingRefundableCents = toNonNegativeCents(input.allocatedCents - input.refundedCents);
8064
- if (input.subject.kind === "none" || input.subject.depositRefundability === "refundable" || input.receiptPurpose !== "initial_checkout") {
8065
- return {
8066
- subject: input.subject,
8067
- totalRemainingRefundableCents,
8068
- policyRefundableCents: totalRemainingRefundableCents,
8069
- protectedDepositRemainingCents: toNonNegativeCents(0)
8070
- };
8071
- }
8072
- const protectedDepositOriginalCents = toNonNegativeCents(Math.min(input.subject.protectedDepositAmountCents, input.allocatedCents));
8073
- const nonDepositOriginalCents = toNonNegativeCents(input.allocatedCents - protectedDepositOriginalCents);
8074
- const refundedAgainstProtectedDepositCents = toNonNegativeCents(input.refundedCents - nonDepositOriginalCents);
8075
- const protectedDepositRemainingCents = toNonNegativeCents(protectedDepositOriginalCents - refundedAgainstProtectedDepositCents);
8076
- const policyRefundableCents = toNonNegativeCents(totalRemainingRefundableCents - protectedDepositRemainingCents);
8077
- return {
8078
- subject: input.subject,
8079
- totalRemainingRefundableCents,
8080
- policyRefundableCents,
8081
- protectedDepositRemainingCents
8082
- };
8083
- }
8084
8091
  function planAdminProtectedDepositRefund(input) {
8085
8092
  const requestedAmountCents = resolveRequestedAmountCents(input.request, { fullRemainingCents: input.allowProtectedDepositOverride ? input.exposure.totalRemainingRefundableCents : input.exposure.policyRefundableCents });
8086
8093
  if (input.exposure.totalRemainingRefundableCents <= 0 || requestedAmountCents <= 0) {
@@ -8271,65 +8278,6 @@ function planShopRefund(order, shopItems) {
8271
8278
  };
8272
8279
  }
8273
8280
 
8274
- //#endregion
8275
- //#region ../commerce/src/purchase/stripeMinimumCharge.ts
8276
- const STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY = {
8277
- GBP: 30,
8278
- USD: 50,
8279
- EUR: 50,
8280
- AED: 200,
8281
- AUD: 50,
8282
- BGN: 100,
8283
- BRL: 50,
8284
- CAD: 50,
8285
- CHF: 50,
8286
- CZK: 1500,
8287
- DKK: 250,
8288
- HKD: 400,
8289
- HUF: 17500,
8290
- JPY: 50,
8291
- MXN: 1e3,
8292
- MYR: 200,
8293
- NOK: 300,
8294
- NZD: 50,
8295
- PLN: 200,
8296
- RON: 200,
8297
- SEK: 300,
8298
- SGD: 50,
8299
- THB: 1e3
8300
- };
8301
- function isStripeMinimumChargeCurrency(currency) {
8302
- return currency in STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY;
8303
- }
8304
- function getStripeMinimumChargeRequirement(rawCurrency) {
8305
- let currency;
8306
- try {
8307
- currency = normalizeCurrencyCode(rawCurrency);
8308
- } catch {
8309
- return null;
8310
- }
8311
- const currencyKey = currency;
8312
- if (!isStripeMinimumChargeCurrency(currencyKey)) {
8313
- return null;
8314
- }
8315
- return {
8316
- currency,
8317
- minimumAmountCents: STRIPE_MINIMUM_CHARGE_CENTS_BY_CURRENCY[currencyKey]
8318
- };
8319
- }
8320
- function isStripeChargeBelowMinimum(options) {
8321
- const requirement = getStripeMinimumChargeRequirement(options.currency);
8322
- return Boolean(requirement && options.amountCents > 0 && options.amountCents < requirement.minimumAmountCents);
8323
- }
8324
- /**
8325
- * The smallest deposit a plan that starts with one may ask for: the card
8326
- * minimum for the currency, or any positive amount for a currency Stripe has
8327
- * no minimum on record for.
8328
- */
8329
- function getInstalmentDepositMinimumCents(currency) {
8330
- return getStripeMinimumChargeRequirement(currency)?.minimumAmountCents ?? 1;
8331
- }
8332
-
8333
8281
  //#endregion
8334
8282
  //#region ../commerce/src/purchase/stripeCheckoutReturnUrl.ts
8335
8283
  const STRIPE_CHECKOUT_SESSION_ID_PLACEHOLDER = "{CHECKOUT_SESSION_ID}";
@@ -8368,39 +8316,6 @@ const checkoutCopy = {
8368
8316
 
8369
8317
  //#endregion
8370
8318
  //#region ../commerce/src/purchase/stateTransitions.ts
8371
- function advanceOrderStatus(from, event) {
8372
- switch (event) {
8373
- case "checkout_failed":
8374
- if (from === "pending") return ok("failed");
8375
- break;
8376
- case "stripe_payment_completed":
8377
- if (from === "pending") return ok("paid");
8378
- break;
8379
- case "cancel":
8380
- if (from === "pending" || from === "failed") return ok("cancelled");
8381
- if (from === "paid" || from === "partially_refunded" || from === "refunded") return ok("cancelled");
8382
- break;
8383
- case "partial_refund":
8384
- if (from === "paid" || from === "partially_refunded") return ok("partially_refunded");
8385
- break;
8386
- case "full_refund":
8387
- if (from === "paid" || from === "partially_refunded") return ok("refunded");
8388
- break;
8389
- }
8390
- return err(`Illegal order status transition: ${from} -> ${event}`);
8391
- }
8392
- function transitionOrderStatusTo(from, to) {
8393
- if (from === to) return ok(to);
8394
- switch (to) {
8395
- case "failed": return advanceOrderStatus(from, "checkout_failed");
8396
- case "paid": return advanceOrderStatus(from, "stripe_payment_completed");
8397
- case "cancelled": return advanceOrderStatus(from, "cancel");
8398
- case "partially_refunded": return advanceOrderStatus(from, "partial_refund");
8399
- case "refunded": return advanceOrderStatus(from, "full_refund");
8400
- case "pending": break;
8401
- }
8402
- return err(`Illegal order status transition: ${from} -> ${to}`);
8403
- }
8404
8319
  function classifyCheckoutCompensationDecision(input) {
8405
8320
  const sideEffects = checkoutCommitSideEffects(input.progress);
8406
8321
  if (input.paymentRail === "bypass") {
@@ -8594,6 +8509,10 @@ function eventRegistrationErrorEndsCommand(value) {
8594
8509
  //#region ../commerce/src/purchase/eventCheckoutRecoveryWindow.ts
8595
8510
  const EVENT_CHECKOUT_HOLD_DURATION_MS = 35 * 60 * 1e3;
8596
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
+ }
8597
8516
  function validInstant(value) {
8598
8517
  const instant = Date.parse(value);
8599
8518
  return Number.isFinite(instant) ? instant : null;
@@ -8639,6 +8558,942 @@ function checkBrowserStripeKey(publishableKey, livemode) {
8639
8558
  };
8640
8559
  }
8641
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
+
8642
9497
  //#endregion
8643
9498
  //#region ../site-contracts/src/siteData/eventCheckout.ts
8644
9499
  const uuid = z.string().uuid();
@@ -8688,7 +9543,13 @@ const eventBookingOutcomeSchema = z.discriminatedUnion("kind", [z.object({
8688
9543
  identity: confirmedBookingIdentitySchema,
8689
9544
  ...arrivalFields
8690
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();
8691
9551
  const eventEmbeddedCheckoutSchema = z.object({
9552
+ priceReductions: z.tuple([priceReductionSummarySchema]).rest(priceReductionSummarySchema).readonly().optional(),
8692
9553
  kind: z.literal("embedded"),
8693
9554
  sessionId: z.string().min(1),
8694
9555
  clientSecret: z.string().min(1),
@@ -8711,16 +9572,21 @@ const eventRegistrationSummarySchema = z.object({
8711
9572
  message: z.string(),
8712
9573
  passCreditsRemaining: z.number().int().nonnegative().optional()
8713
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");
8714
9578
  const eventRegisterResponseSchema = z.discriminatedUnion("kind", [
8715
9579
  z.object({
8716
9580
  kind: z.literal("bookingComplete"),
8717
9581
  outcome: eventBookingOutcomeSchema,
9582
+ outcomes: bookingOutcomesSchema.optional(),
8718
9583
  summary: eventRegistrationSummarySchema,
8719
9584
  ...decorations
8720
9585
  }).strict(),
8721
9586
  z.object({
8722
9587
  kind: z.literal("checkoutRequired"),
8723
9588
  reference: eventRegistrationStatusReferenceSchema,
9589
+ references: bookingReferencesSchema.optional(),
8724
9590
  checkout: eventEmbeddedCheckoutSchema,
8725
9591
  submissionId: uuid,
8726
9592
  ...decorations
@@ -8746,12 +9612,16 @@ const eventRegisterResponseSchema = z.discriminatedUnion("kind", [
8746
9612
  }).strict(),
8747
9613
  ...decorations
8748
9614
  }).strict()
8749
- ]);
9615
+ ]).superRefine((response, ctx) => {
9616
+ if (response.kind === "bookingComplete") validateOutcomeList(response, ctx);
9617
+ if (response.kind === "checkoutRequired") validateReferenceList(response, ctx);
9618
+ });
8750
9619
  const checkoutStatusArms = [
8751
9620
  z.object({
8752
9621
  kind: z.literal("resolved"),
8753
- outcome: eventBookingOutcomeSchema
8754
- }).strict(),
9622
+ outcome: eventBookingOutcomeSchema,
9623
+ outcomes: bookingOutcomesSchema.optional()
9624
+ }).strict().superRefine(validateOutcomeList),
8755
9625
  z.object({ kind: z.literal("abandoned") }).strict(),
8756
9626
  z.object({ kind: z.literal("reconciliationRequired") }).strict(),
8757
9627
  z.object({
@@ -8760,6 +9630,7 @@ const checkoutStatusArms = [
8760
9630
  }).strict(),
8761
9631
  z.object({
8762
9632
  kind: z.literal("paymentAvailable"),
9633
+ references: bookingReferencesSchema.optional(),
8763
9634
  checkout: eventEmbeddedCheckoutSchema,
8764
9635
  recoverableUntil: z.string().optional()
8765
9636
  }).strict(),
@@ -8783,8 +9654,7 @@ const eventCheckoutReturnResponseSchema = z.discriminatedUnion("kind", [
8783
9654
  z.object({ kind: z.literal("reconciliationRequired") }).strict()
8784
9655
  ]).superRefine((response, ctx) => {
8785
9656
  if (response.kind !== "checkout" || response.outcome.kind !== "resolved") return;
8786
- const identity = response.outcome.outcome.identity;
8787
- 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)) {
8788
9658
  ctx.addIssue({
8789
9659
  code: "custom",
8790
9660
  message: "Confirmed booking does not match checkout subject",
@@ -8804,6 +9674,7 @@ const eventCheckoutResponseSchema = z.union([
8804
9674
  kind: z.literal("completed"),
8805
9675
  scope: z.literal("wholeSeries"),
8806
9676
  outcome: eventBookingOutcomeSchema,
9677
+ outcomes: bookingOutcomesSchema.optional(),
8807
9678
  ...checkoutDecorations
8808
9679
  }).strict(),
8809
9680
  z.object({
@@ -8817,6 +9688,7 @@ const eventCheckoutResponseSchema = z.union([
8817
9688
  kind: z.literal("checkoutRequired"),
8818
9689
  scope: z.literal("wholeSeries"),
8819
9690
  registrationId: uuid,
9691
+ registrationIds: registrationIdsSchema.optional(),
8820
9692
  checkoutAttemptId: uuid,
8821
9693
  checkout: eventEmbeddedCheckoutSchema,
8822
9694
  recoverableUntil: z.string().optional(),
@@ -8838,16 +9710,65 @@ const eventCheckoutResponseSchema = z.union([
8838
9710
  ...checkoutDecorations
8839
9711
  }).strict()
8840
9712
  ]).superRefine((response, ctx) => {
8841
- 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({
8842
9742
  code: "custom",
8843
- message: "Confirmed booking scope mismatch",
8844
- path: [
8845
- "outcome",
8846
- "identity",
8847
- "scope"
8848
- ]
9743
+ message: "First booking outcome does not match the single-booking alias",
9744
+ path: ["outcomes", 0]
8849
9745
  });
8850
- });
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
+ }
8851
9772
 
8852
9773
  //#endregion
8853
9774
  //#region ../site-contracts/src/siteData/bookingQuestions.ts
@@ -8861,6 +9782,67 @@ const BEFORE_BOOKING_QUESTIONS_ROUTE = {
8861
9782
  method: "POST"
8862
9783
  };
8863
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
+
8864
9846
  //#endregion
8865
9847
  //#region ../api/src/publicEventEndpointDefinitions.ts
8866
9848
  const PUBLIC_EVENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
@@ -9191,6 +10173,13 @@ const EVENT_MANAGEMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
9191
10173
  "server:internal_error"
9192
10174
  ]
9193
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
+ },
9194
10183
  updateEventIdentity: {
9195
10184
  path: "/sites/{siteId}/bookings/events/{eventId}",
9196
10185
  method: "PATCH",
@@ -9787,6 +10776,30 @@ const PUBLIC_ONBOARDING_ATTEMPT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions
9787
10776
  //#endregion
9788
10777
  //#region ../api/src/billingEndpointDefinitions.ts
9789
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
+ },
9790
10803
  adminChangePlan: {
9791
10804
  path: "/admin/billing/plan",
9792
10805
  method: "POST",
@@ -10781,6 +11794,18 @@ const ENDPOINT_DEFINITIONS = {
10781
11794
  "server:internal_error"
10782
11795
  ]
10783
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
+ },
10784
11809
  sendTestEmail: {
10785
11810
  path: "/sites/{siteId}/settings/emails/test",
10786
11811
  method: "POST",
@@ -10863,6 +11888,30 @@ const ENDPOINT_DEFINITIONS = {
10863
11888
  responseKind: "json",
10864
11889
  errors: ["auth:forbidden", "server:internal_error"]
10865
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
+ },
10866
11915
  authLogin: {
10867
11916
  path: "/auth/login/submit",
10868
11917
  method: "POST",
@@ -10891,6 +11940,22 @@ const ENDPOINT_DEFINITIONS = {
10891
11940
  auth: "public",
10892
11941
  responseKind: "json"
10893
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
+ },
10894
11959
  authStatus: {
10895
11960
  path: "/auth/status",
10896
11961
  method: "GET",
@@ -10948,6 +12013,14 @@ const ENDPOINT_DEFINITIONS = {
10948
12013
  auth: "user",
10949
12014
  responseKind: "json"
10950
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
+ },
10951
12024
  revokeSiteInvitation: {
10952
12025
  path: "/sites/{siteId}/members/invitations/{invitationId}",
10953
12026
  method: "DELETE",
@@ -12060,6 +13133,22 @@ const ENDPOINT_DEFINITIONS = {
12060
13133
  auth: "user",
12061
13134
  responseKind: "json"
12062
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
+ },
12063
13152
  mfaBackupCodesGet: {
12064
13153
  path: "/auth/mfa/backup-codes",
12065
13154
  method: "GET",
@@ -12114,6 +13203,18 @@ const ENDPOINT_DEFINITIONS = {
12114
13203
  ],
12115
13204
  responseKind: "json"
12116
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
+ },
12117
13218
  accountRevokeSessions: {
12118
13219
  path: "/account/sessions/revoke",
12119
13220
  method: "POST",
@@ -12121,6 +13222,22 @@ const ENDPOINT_DEFINITIONS = {
12121
13222
  auth: "user",
12122
13223
  responseKind: "json"
12123
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
+ },
12124
13241
  adminListInvites: {
12125
13242
  path: "/admin/invites",
12126
13243
  method: "GET",
@@ -17729,6 +18846,13 @@ function resolveBookingSettingsEventCatalogue(settings) {
17729
18846
  eventTypePresets: settings.eventTypePresets ?? DEFAULT_EVENT_TYPE_PRESETS
17730
18847
  });
17731
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
+ }
17732
18856
 
17733
18857
  //#endregion
17734
18858
  //#region ../api/src/sdkManagementResponseSchemas.ts
@@ -19483,6 +20607,7 @@ const lookKnobBlocks = {
19483
20607
  showPhotos: cardListKnobBlocks,
19484
20608
  cardMarker: cardListFamilyBlocks,
19485
20609
  dates: "block.offerings-preview",
20610
+ grouping: "block.offerings-preview",
19486
20611
  columns: "block.feature-cards",
19487
20612
  listColumns: "block.event-calendar",
19488
20613
  blackAndWhite: "block.image-gallery",
@@ -21746,16 +22871,6 @@ async function confirmAction(message, options, isRemote) {
21746
22871
  });
21747
22872
  });
21748
22873
  }
21749
- /** Environment target/client helpers are backed by the execution boundary. */
21750
- /**
21751
- * Create a management client for a specific environment target.
21752
- *
21753
- * @param target - Environment target (local or remote)
21754
- * @returns Management client configured for that environment
21755
- */
21756
- function createClientForEnv(target) {
21757
- return createManagementClient(managementClientConfigFor(loadSdkEnvironment(target)));
21758
- }
21759
22874
  /**
21760
22875
  * Resolve the environment setting from global options.
21761
22876
  * Handles --env flag and deprecated --remote flag.
@@ -22003,95 +23118,6 @@ function withConfirmation(getMessage, action) {
22003
23118
  }
22004
23119
  };
22005
23120
  }
22006
- /**
22007
- * Capitalize the first letter of a string.
22008
- */
22009
- function capitalize(str) {
22010
- return str.charAt(0).toUpperCase() + str.slice(1);
22011
- }
22012
- /**
22013
- * Create a get command for a resource.
22014
- *
22015
- * @example
22016
- * const getCommand = createGetCommand({
22017
- * resourceName: 'entry',
22018
- * args: ['type', 'identifier'],
22019
- * get: (client, type, id) => client.entries.get(type, id),
22020
- * formatOutput: (entry) => ({
22021
- * id: entry.id,
22022
- * status: entry.status,
22023
- * }),
22024
- * });
22025
- */
22026
- function createGetCommand(config) {
22027
- const cmd = new Command("get").description(`Get a single ${config.resourceName}`);
22028
- for (const arg of config.args) {
22029
- cmd.argument(`<${arg}>`, `${capitalize(arg.replace("-", " "))}`);
22030
- }
22031
- return cmd.action(withErrorHandling(async (...actionArgs) => {
22032
- const args = actionArgs.slice(0, config.args.length);
22033
- const command = actionArgs[actionArgs.length - 1];
22034
- const { output, client, isJsonOutput } = createCommandContext(command);
22035
- const label = args.join("/");
22036
- const item = await config.get(client, ...args);
22037
- if (!item) {
22038
- return output.error(`${capitalize(config.resourceName)} not found: ${label}`, { suggestion: `Check that the ${config.args.join(" and ")} ${config.args.length > 1 ? "are" : "is"} correct` });
22039
- }
22040
- if (isJsonOutput) {
22041
- output.json(item);
22042
- } else {
22043
- output.success(`${capitalize(config.resourceName)}: ${label}`, config.formatOutput(item));
22044
- }
22045
- }));
22046
- }
22047
- /**
22048
- * Create a list command for a resource.
22049
- *
22050
- * @example
22051
- * const listCommand = createListCommand({
22052
- * resourceName: 'entry',
22053
- * resourceNamePlural: 'entries',
22054
- * args: ['type'],
22055
- * hasPagination: true,
22056
- * list: (client, [type], pagination) => client.entries.list(type, pagination),
22057
- * tableHeaders: ['Identifier', 'Status', 'Updated'],
22058
- * formatRow: (entry) => [entry.identifier, entry.status, entry.updatedAt],
22059
- * });
22060
- */
22061
- function createListCommand(config) {
22062
- const cmd = new Command("list").description(`List ${config.resourceNamePlural}`);
22063
- for (const arg of config.args) {
22064
- cmd.argument(`<${arg}>`, `${capitalize(arg.replace("-", " "))}`);
22065
- }
22066
- if (config.hasPagination) {
22067
- cmd.option("--limit <n>", "Number of items per page", "20");
22068
- cmd.option("--page <n>", "Page number", "1");
22069
- }
22070
- return cmd.action(withErrorHandling(async (...actionArgs) => {
22071
- const args = actionArgs.slice(0, config.args.length);
22072
- const options = actionArgs[config.args.length];
22073
- const command = actionArgs[actionArgs.length - 1];
22074
- const { output, client, isJsonOutput } = createCommandContext(command);
22075
- const pagination = config.hasPagination ? parsePaginationOptions(options) : undefined;
22076
- const result = await config.list(client, args, pagination);
22077
- if (isJsonOutput) {
22078
- output.json({
22079
- [config.resourceNamePlural]: result.items,
22080
- ...result.pagination && { pagination: result.pagination }
22081
- });
22082
- } else if (result.items.length === 0) {
22083
- const context = args.length > 0 ? ` for ${args.join("/")}` : "";
22084
- output.info(`No ${config.resourceNamePlural} found${context}`);
22085
- } else {
22086
- output.table(config.tableHeaders, result.items.map(config.formatRow));
22087
- if (result.pagination) {
22088
- output.info(`Showing ${result.items.length} of ${result.pagination.total} ${config.resourceNamePlural} (page ${result.pagination.page})`);
22089
- } else {
22090
- output.info(`${result.items.length} ${config.resourceNamePlural}`);
22091
- }
22092
- }
22093
- }));
22094
- }
22095
23121
 
22096
23122
  //#endregion
22097
23123
  //#region src/environment-outcome-json.ts
@@ -23576,7 +24602,7 @@ function buildPreviewSummary(sync) {
23576
24602
  }
23577
24603
 
23578
24604
  //#endregion
23579
- //#region src/push-config.ts
24605
+ //#region src/legacy/push-config.ts
23580
24606
  /**
23581
24607
  * push-config CLI command
23582
24608
  *
@@ -24737,7 +25763,7 @@ async function adminClearSitePublicCache(apiClient, siteId, options) {
24737
25763
  //#region ../api/src/accessAdmin.ts
24738
25764
  function getDefaultStaffCapabilities(surfaces) {
24739
25765
  if (surfaces.events && !surfaces.appointments) return ["event_ops"];
24740
- return ["appointments"];
25766
+ return surfaces.appointments ? ["appointments", "packages"] : ["appointments"];
24741
25767
  }
24742
25768
  const managedDomainAddOnPricingSnapshotSchema = z.object({
24743
25769
  formulaVersion: z.literal("managed-domain-overage-v2"),
@@ -24817,7 +25843,7 @@ async function linkCurrentUserPractitioner(apiClient, { siteId, body, options })
24817
25843
  options
24818
25844
  }));
24819
25845
  } catch (error) {
24820
- return normalizeApiError(error, "Failed to link practitioner profile");
25846
+ return normalizeApiError(error, "We couldn’t link that profile.");
24821
25847
  }
24822
25848
  }
24823
25849
  async function unlinkCurrentUserPractitioner(apiClient, { siteId, options }) {
@@ -24828,7 +25854,7 @@ async function unlinkCurrentUserPractitioner(apiClient, { siteId, options }) {
24828
25854
  options
24829
25855
  }));
24830
25856
  } catch (error) {
24831
- return normalizeApiError(error, "Failed to unlink practitioner profile");
25857
+ return normalizeApiError(error, "We couldn’t unlink that profile.");
24832
25858
  }
24833
25859
  }
24834
25860
  async function removeSiteMember(apiClient, { siteId, memberId, options }) {
@@ -25451,7 +26477,7 @@ const SETTINGS_SURFACE_POLICIES = {
25451
26477
  surfaceId: "settings.bookings",
25452
26478
  navVisibilityPolicy: administratorPolicy,
25453
26479
  pageAccessPolicy: administratorPolicy,
25454
- actionIds: []
26480
+ actionIds: ["bookings.updateSettings", "bookings.turnOnCourses"]
25455
26481
  },
25456
26482
  "settings.redirects": {
25457
26483
  surfaceId: "settings.redirects",
@@ -25538,6 +26564,8 @@ const SETTINGS_SURFACE_POLICIES = {
25538
26564
  };
25539
26565
  const SETTINGS_ACTION_POLICIES = {
25540
26566
  "privacy.update": administratorPolicy,
26567
+ "bookings.updateSettings": editorPolicy,
26568
+ "bookings.turnOnCourses": editorPolicy,
25541
26569
  "emails.read": editorPolicy,
25542
26570
  "emails.update": administratorPolicy,
25543
26571
  "emails.updateSendSetting": editorPolicy,
@@ -26284,13 +27312,13 @@ function createAccountApi(apiClient) {
26284
27312
  return response;
26285
27313
  },
26286
27314
  async listSites(input = {}) {
26287
- const search = input.query?.search?.trim();
27315
+ const search$1 = input.query?.search?.trim();
26288
27316
  const response = parseSuccessfulData("accountListSites", await apiClient({
26289
27317
  endpoint: "accountListSites",
26290
27318
  ...input.query ? { params: {
26291
27319
  ...input.query.cursor ? { cursor: input.query.cursor } : {},
26292
27320
  ...input.query.limit !== undefined ? { limit: String(input.query.limit) } : {},
26293
- ...search ? { search } : {}
27321
+ ...search$1 ? { search: search$1 } : {}
26294
27322
  } } : {},
26295
27323
  options: input.options
26296
27324
  }), listSitesResponseSchema);
@@ -27033,6 +28061,33 @@ async function reorderNavigationItems(apiClient, { siteId, menuId, items, option
27033
28061
  normalizeApiError(error, "Failed to reorder navigation items");
27034
28062
  }
27035
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
+ }
27036
28091
 
27037
28092
  //#endregion
27038
28093
  //#region src/sync/mapper.ts
@@ -33200,4 +34255,4 @@ function optionalTitle(data) {
33200
34255
  }
33201
34256
 
33202
34257
  //#endregion
33203
- 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 };