riverbankcms 0.36.0 → 0.37.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, Ar as createContentEntryRef, At as getMimeType, Br as slugPart, Bt as footerPreferencesSchema, Cr as makeBoundaryId, Et as slugifyMediaIdentifier, Ft as MAX_MANAGEMENT_MEDIA_UPLOAD_BYTES, I as footerModeSchema, Jn as asHeaderLayoutId, Kn as SUPPORTED_LOADER_ENDPOINTS, Lr as createSiteCommandSiteRef, Mt as normalizeAmbiguousStoragePathForSite, Nn as RESOLVED_INTERNAL_LINK_ENTITY_TYPES, Pt as FILE_SIZE_LIMITS, Qn as headerLayoutIdValues, Sn as eventBookingOfferIntentSchema, Sr as asSiteStyleId, St as buildMediaIdentifierFromFilename, Tr as bookingQuestionAttachmentSchema, 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 createCommandRef, 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 compareEntrySlug, xn as require_dist, xr as asPageFlowPresetId, y as evaluateSiteCommandExposure, yt as isDisplayMediaKind } from "./sdk-event-upsert-n4in1E4v.mjs";
3
- import { $n as parseDatedOfferingCapacityHoldId, A as publicReadBatchFreshnessSeconds, Ar as unsafeAsEventSeriesId, At as clampConfiguredAmount, B as parseManagementKey, Bn as parseCurrencyCode, D as PUBLIC_CONTENT_FRESHNESS_SECONDS, Dt as validateBookingPaymentOptionKinds, E as PUBLIC_AVAILABILITY_FRESHNESS_SECONDS, Er as parseRetiredCourseId, Fn as toCents, Ft as splitAmountWithRemainderInFirst, Gn as unsafeAsAppointmentResourceId, In as toNonNegativeCents, It as businessCancellationRefusalCodes, Kn as unsafeAsStaffMemberId, Kt as formatDate, Ln as unsafeAsNonNegativeCents, Lt as scheduleBookingReasonCodes, Mn as isNonNegativeWholeCents$1, Mr as unsafeAsPricingOptionId, Nn as parseNonNegativeCents, Nr as err, O as getPublicReadCachePolicy, Or as unsafeAsEventInstanceId, Ot as isLiveOrderInstalmentPlanStatus, Pn as parsePositiveCents, Pr as ok, Pt as omitZeroAmountFutureRows, Q as parseFooterCompositionV1, Qn as parseDatedOfferingCapacityHoldAuditRef, R as createSecret, Rn as unsafeAsPositiveCents, Rt as resolveFlexibleBalanceDueAt, S as EVENT_PRESET_VALUES, Sr as parseUserId, St as trimmedStringOrNull, Tr as parseEventSeriesId, Vn as assertNever, Yn as parseMembershipId, Z as parseMailingListProviderScope, Zn as unsafeAsPassId, _ as canonicalizeConfiguredBookingVerticalConfig, _r as unsafeAsOrderPaymentPlanId, b as resolveSiteVerticalBookingConfig, br as parseApiKeyId, c as STAFF_OPERATIONAL_CAPABILITIES, ct as assertAllowedPublicUrl, f as planTurningOnCourses, fn as toUtcIsoDateTimeString, ft as stableJsonStringify, g as areConfiguredBookingVerticalConfigsEqual, gr as unsafeAsOrderFlexibleBalanceContractId, hr as unsafeAsCheckoutLineId, ht as locationValueSchema, j as publicReadFreshnessSeconds, jr as unsafeAsOccurrenceId, jt as getBookingInstalmentDepositRefundability, k as isPublicReadEndpoint, kn as fromArray, kr as unsafeAsEventOfferingId, kt as addIntervalPreservingMonthAnchor, ln as parseBookingLocalDate, m as withBookingModulesForSelectionChange, mn as resolveBookingTimeZoneId, n as OFFLINE_PAYMENT_METHODS, on as getLocalScheduleDate, p as resolveEventCatalogue, qn as parseCustomerId, r as committedWriteProofSchema, rn as formatLocalScheduleDate, tn as addLocalScheduleDays, v as parseVerticalId, vr as parseEditorSessionGeneration, w as SURFACE_EVENT_PRESET_VALUES, x as DEFAULT_EVENT_TYPE_PRESETS, xr as parseSiteId, y as parseVerticalPresetId, yt as publicLocationSchema, z as exposeSecret, zn as formatCurrencyAmount, zt as resolveFlexibleBalanceInitialPaymentCents } from "./src-DHIn60_q.mjs";
4
- import { n as CliSdkPeerError, t as loadConfigFile } from "./load-config-k3XF8V97.mjs";
2
+ import { $n as headerStyleIdValues, Ar as createContentEntryRef, At as getMimeType, Br as slugPart, Bt as footerPreferencesSchema, Cr as makeBoundaryId, Et as slugifyMediaIdentifier, Ft as MAX_MANAGEMENT_MEDIA_UPLOAD_BYTES, I as footerModeSchema, Jn as asHeaderLayoutId, Kn as SUPPORTED_LOADER_ENDPOINTS, Lr as createSiteCommandSiteRef, Mt as normalizeAmbiguousStoragePathForSite, Nn as RESOLVED_INTERNAL_LINK_ENTITY_TYPES, Pt as FILE_SIZE_LIMITS, Qn as headerLayoutIdValues, Sn as eventBookingOfferIntentSchema, Sr as asSiteStyleId, St as buildMediaIdentifierFromFilename, Tr as bookingQuestionAttachmentSchema, 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 createCommandRef, 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 compareEntrySlug, xn as require_dist, xr as asPageFlowPresetId, y as evaluateSiteCommandExposure, yt as isDisplayMediaKind } from "./sdk-event-upsert-BL6uAz53.mjs";
3
+ import { $ as parseFooterCompositionV1, $n as unsafeAsPassId, A as publicReadBatchFreshnessSeconds, An as fromArray, Ar as parseRetiredCourseId, At as addIntervalPreservingMonthAnchor, B as exposeSecret, Bn as formatCurrencyAmount, Bt as resolveFlexibleBalanceInitialPaymentCents, Ct as trimmedStringOrNull, D as PUBLIC_CONTENT_FRESHNESS_SECONDS, E as PUBLIC_AVAILABILITY_FRESHNESS_SECONDS, Er as parseUserId, Fn as parsePositiveCents, Fr as unsafeAsPricingOptionId, Ft as omitZeroAmountFutureRows, Hn as assertNever, In as toCents, Ir as err, It as splitAmountWithRemainderInFirst, Jn as unsafeAsStaffMemberId, Ln as toNonNegativeCents, Lr as ok, Lt as businessCancellationRefusalCodes, Mr as unsafeAsEventOfferingId, Mt as getBookingInstalmentDepositRefundability, Nn as isNonNegativeWholeCents$1, Nr as unsafeAsEventSeriesId, O as getPublicReadCachePolicy, Ot as validateBookingPaymentOptionKinds, Pn as parseNonNegativeCents, Pr as unsafeAsOccurrenceId, Q as parseMailingListProviderScope, Rn as unsafeAsNonNegativeCents, Rt as scheduleBookingReasonCodes, S as EVENT_PRESET_VALUES, Tr as parseSiteId, V as parseManagementKey, Vn as parseCurrencyCode, Yn as parseCustomerId, Zn as parseMembershipId, _ as canonicalizeConfiguredBookingVerticalConfig, _r as unsafeAsCheckoutLineId, b as resolveSiteVerticalBookingConfig, br as unsafeAsOrderPaymentReceiptId, bt as publicLocationSchema, c as STAFF_OPERATIONAL_CAPABILITIES, er as parseDatedOfferingCapacityHoldAuditRef, f as planTurningOnCourses, g as areConfiguredBookingVerticalConfigsEqual, gt as locationValueSchema, hn as resolveBookingTimeZoneId, in as formatLocalScheduleDate, j as publicReadFreshnessSeconds, jt as clampConfiguredAmount, k as isPublicReadEndpoint, kr as parseEventSeriesId, kt as isLiveOrderInstalmentPlanStatus, lt as assertAllowedPublicUrl, m as withBookingModulesForSelectionChange, n as OFFLINE_PAYMENT_METHODS, nn as addLocalScheduleDays, p as resolveEventCatalogue, pn as toUtcIsoDateTimeString, pt as stableJsonStringify, qn as unsafeAsAppointmentResourceId, qt as formatDate, r as committedWriteProofSchema, sn as getLocalScheduleDate, tr as parseDatedOfferingCapacityHoldId, un as parseBookingLocalDate, v as parseVerticalId, vr as unsafeAsOrderFlexibleBalanceContractId, w as SURFACE_EVENT_PRESET_VALUES, wr as parseApiKeyId, x as DEFAULT_EVENT_TYPE_PRESETS, xr as parseEditorSessionGeneration, y as parseVerticalPresetId, yr as unsafeAsOrderPaymentPlanId, z as createSecret, zn as unsafeAsPositiveCents, zt as resolveFlexibleBalanceDueAt } from "./src-ClX_VLD6.mjs";
4
+ import { n as CliSdkPeerError, t as loadConfigFile } from "./load-config-Bhh-kYhx.mjs";
5
5
  import { safeParse, z } from "zod";
6
6
  import { Argument, Command, Option } from "commander";
7
7
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -1489,8 +1489,8 @@ function optionalLookupTag(value, build) {
1489
1489
  }
1490
1490
  function buildSiteReadTags(params) {
1491
1491
  return normalizeRevalidateTags([
1492
- ...optionalLookupTag(params.siteId, (id) => tags.site(normalizeSiteCacheId(id))),
1493
- ...optionalLookupTag(params.id, (id) => tags.siteById(normalizeSiteCacheId(id))),
1492
+ ...optionalLookupTag(params.siteId, (id$1) => tags.site(normalizeSiteCacheId(id$1))),
1493
+ ...optionalLookupTag(params.id, (id$1) => tags.siteById(normalizeSiteCacheId(id$1))),
1494
1494
  ...optionalLookupTag(params.slug, tags.siteBySlug),
1495
1495
  ...optionalLookupTag(params.domain, (domain) => tags.siteByDomain(normalizeSiteCacheDomain(domain)))
1496
1496
  ]);
@@ -1515,7 +1515,7 @@ function buildCacheReadTags(templates, input = {}) {
1515
1515
  TAG_TEMPLATES.siteById,
1516
1516
  TAG_TEMPLATES.siteBySlug,
1517
1517
  TAG_TEMPLATES.siteByDomain
1518
- ].some((lookup) => lookup === template)) return [];
1518
+ ].some((lookup$1) => lookup$1 === template)) return [];
1519
1519
  const tag = template.replace(/\{([^}]+)\}/gu, (placeholder, key) => {
1520
1520
  const value = params[key];
1521
1521
  return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : placeholder;
@@ -1571,9 +1571,9 @@ function siteIdentifierTagParams(params) {
1571
1571
  slug: params.site
1572
1572
  };
1573
1573
  }
1574
- function normalizeSiteCacheId(id) {
1575
- const parsed = parseSiteId(id);
1576
- return parsed.ok ? parsed.value : id;
1574
+ function normalizeSiteCacheId(id$1) {
1575
+ const parsed = parseSiteId(id$1);
1576
+ return parsed.ok ? parsed.value : id$1;
1577
1577
  }
1578
1578
  const PUBLIC_READ_TAG_TEMPLATES = {
1579
1579
  published_content: TAG_TEMPLATES.siteRoutableContent,
@@ -1620,6 +1620,13 @@ function buildPublicReadFetchPolicy(siteId, reads) {
1620
1620
  function buildPublicReadBatchFetchPolicy(siteId, reads) {
1621
1621
  return buildFetchPolicy(siteId, reads, publicReadBatchFreshnessSeconds);
1622
1622
  }
1623
+ /** A page read failure says which policy its absence depends on, so the miss is registered with the right tags. */
1624
+ const PAGE_READ_DEPENDENCIES_HEADER = "x-riverbank-page-dependencies";
1625
+ /**
1626
+ * A page read sent with this header set to `no-store` was built with parts missing (a support read
1627
+ * fell back to an empty value), so no cache may keep it: the next read should get the complete page.
1628
+ */
1629
+ const PAGE_READ_STORAGE_HEADER = "x-riverbank-page-storage";
1623
1630
  /** A page may depend on admission even when an ordinary CMS page won precedence. */
1624
1631
  function buildPageReadCachePolicy(siteId, dependencies) {
1625
1632
  return dependencies === "availability" ? {
@@ -2335,6 +2342,17 @@ const APPOINTMENT_ENDPOINT_DEFINITIONS = defineEndpointDefinitions({
2335
2342
  "server:internal_error"
2336
2343
  ]
2337
2344
  },
2345
+ getTeamMemberTemplatePreview: {
2346
+ path: "/sites/{siteId}/bookings/profile-editor/{entryId}/template-preview",
2347
+ method: "GET",
2348
+ auth: "user",
2349
+ responseKind: "json",
2350
+ errors: [
2351
+ "auth:forbidden",
2352
+ "resource:not_found",
2353
+ "server:internal_error"
2354
+ ]
2355
+ },
2338
2356
  updateTeamMemberProfilePolicy: {
2339
2357
  path: "/sites/{siteId}/bookings/resources/profile-policy",
2340
2358
  method: "PUT",
@@ -3843,8 +3861,8 @@ const eventScheduleScopeValues = [
3843
3861
  ];
3844
3862
  /** Runtime picker sentinels and bound loader IDs must describe the same query. */
3845
3863
  function normalizeCalendarFilterId(value) {
3846
- const id = value?.trim();
3847
- return !id || id === "all" ? undefined : id;
3864
+ const id$1 = value?.trim();
3865
+ return !id$1 || id$1 === "all" ? undefined : id$1;
3848
3866
  }
3849
3867
  const CALENDAR_SSR_PAGE_SIZE = 100;
3850
3868
  const CALENDAR_CLIENT_PAGE_SIZE = 200;
@@ -4087,6 +4105,103 @@ const eventCalendarListLayoutCompatibleDisplayModeValues = ["combined", "list"];
4087
4105
  /** The most dates or runs one booking request may name; the block stops ticking at the same number. */
4088
4106
  const MAX_EVENT_BOOKING_SELECTION_ITEMS = 20;
4089
4107
 
4108
+ //#endregion
4109
+ //#region ../site-contracts/src/siteData/eventSelectionFunding.ts
4110
+ /**
4111
+ * How a date booking can be paid: money alone, or one pass or membership covering the dates it can,
4112
+ * with money for the rest. The server plans it (`planSelectionFunding` in @riverbankcms/bookings) and
4113
+ * the block renders what it's sent. One date is the one-date case.
4114
+ */
4115
+ const id = z.string().min(1);
4116
+ const ids = z.tuple([id]).rest(id).readonly();
4117
+ const eventFundingSourceSchema = z.discriminatedUnion("kind", [
4118
+ z.object({
4119
+ kind: z.literal("ownedPass"),
4120
+ passId: id
4121
+ }),
4122
+ z.object({
4123
+ kind: z.literal("ownedMembership"),
4124
+ membershipId: id
4125
+ }),
4126
+ z.object({
4127
+ kind: z.literal("buyPass"),
4128
+ productId: id
4129
+ }),
4130
+ z.object({
4131
+ kind: z.literal("buyMembership"),
4132
+ productId: id
4133
+ })
4134
+ ]);
4135
+ const eventSelectionFundingPickSchema = z.discriminatedUnion("kind", [z.object({ kind: z.literal("money") }), z.object({
4136
+ kind: z.literal("entitlement"),
4137
+ source: eventFundingSourceSchema
4138
+ })]);
4139
+ const uncoveredReason = z.enum([
4140
+ "not_started",
4141
+ "ends_before",
4142
+ "membership_ended",
4143
+ "already_used_on_date",
4144
+ "no_credits_left"
4145
+ ]);
4146
+ const cents$2 = z.number().int().nonnegative();
4147
+ const credits = z.object({
4148
+ used: z.number().int().nonnegative(),
4149
+ leftAfter: z.number().int().nonnegative()
4150
+ });
4151
+ const entitlementSchema = z.discriminatedUnion("kind", [
4152
+ z.object({
4153
+ kind: z.literal("ownedPass"),
4154
+ passId: id,
4155
+ name: z.string(),
4156
+ credits,
4157
+ expiresAt: z.string().nullable()
4158
+ }),
4159
+ z.object({
4160
+ kind: z.literal("ownedMembership"),
4161
+ membershipId: id,
4162
+ name: z.string(),
4163
+ endsAt: z.string().nullable()
4164
+ }),
4165
+ z.object({
4166
+ kind: z.literal("buyPass"),
4167
+ productId: id,
4168
+ name: z.string(),
4169
+ priceCents: cents$2,
4170
+ credits: credits.extend({ total: z.number().int().positive() }),
4171
+ expiresAt: z.string().nullable()
4172
+ }),
4173
+ z.object({
4174
+ kind: z.literal("buyMembership"),
4175
+ productId: id,
4176
+ name: z.string(),
4177
+ priceCents: cents$2,
4178
+ interval: z.enum(["month", "year"])
4179
+ })
4180
+ ]);
4181
+ const moneySchema = z.object({
4182
+ totalCents: cents$2,
4183
+ currency: z.string().min(1)
4184
+ });
4185
+ const optionSchema = z.discriminatedUnion("kind", [z.object({
4186
+ kind: z.literal("money"),
4187
+ moneyDates: ids,
4188
+ money: moneySchema
4189
+ }), z.object({
4190
+ kind: z.literal("entitlement"),
4191
+ entitlement: entitlementSchema,
4192
+ covered: ids,
4193
+ uncovered: z.array(z.object({
4194
+ occurrenceId: id,
4195
+ reason: uncoveredReason
4196
+ })).readonly(),
4197
+ money: moneySchema
4198
+ })]);
4199
+ const eventSelectionFundingSchema = z.object({
4200
+ options: z.tuple([optionSchema]).rest(optionSchema).readonly(),
4201
+ selected: eventSelectionFundingPickSchema,
4202
+ entitlementNote: z.enum(["none", "severalPlaces"])
4203
+ });
4204
+
4090
4205
  //#endregion
4091
4206
  //#region ../commerce/src/purchase/allocation.ts
4092
4207
  /**
@@ -4332,12 +4447,6 @@ function toCreditAppliedCents(raw) {
4332
4447
  function toStripeChargeCents(raw) {
4333
4448
  return rebrandCents(toNonNegativeCents(raw));
4334
4449
  }
4335
- function toRefundedCents(raw) {
4336
- return rebrandCents(toNonNegativeCents(raw));
4337
- }
4338
- function toRefundableTotalCents(raw) {
4339
- return rebrandCents(toNonNegativeCents(raw));
4340
- }
4341
4450
  function money(amountCents, currency) {
4342
4451
  return {
4343
4452
  amountCents: toNonNegativeCents(amountCents),
@@ -4391,60 +4500,6 @@ function buildLineSettlementBreakdown(options) {
4391
4500
  stripeChargeCents
4392
4501
  });
4393
4502
  }
4394
- function buildRefundableLineSettlement(options) {
4395
- const line = buildLineSettlementBreakdown(options);
4396
- if (!line.ok) {
4397
- return line;
4398
- }
4399
- const alreadyRefundedResult = parseLineSettlementCents(options.lineId, options.alreadyRefundedCents, "alreadyRefundedCents");
4400
- if (!alreadyRefundedResult.ok) return alreadyRefundedResult;
4401
- const refundableTotalCents = toRefundableTotalCents(line.value.creditAppliedCents + line.value.stripeChargeCents);
4402
- const alreadyRefundedCents = rebrandCents(alreadyRefundedResult.value);
4403
- if (alreadyRefundedCents > refundableTotalCents) {
4404
- return err({
4405
- _tag: "refunded_exceeds_refundable_total",
4406
- lineId: options.lineId,
4407
- message: `Order item ${options.lineId} refunded amount exceeds refundable total`
4408
- });
4409
- }
4410
- return ok({
4411
- line: line.value,
4412
- refundableTotalCents,
4413
- alreadyRefundedCents
4414
- });
4415
- }
4416
- /**
4417
- * Cash actually collected against one order line, summed from its payment
4418
- * receipt allocations. Shared so every refundable-remainder caller measures
4419
- * funding the same way.
4420
- */
4421
- function orderItemCashFundedCents(allocations, orderItemId) {
4422
- let total = 0;
4423
- for (const allocation of allocations) {
4424
- if (allocation.orderItemId === orderItemId) {
4425
- total += allocation.amountCents;
4426
- }
4427
- }
4428
- return total;
4429
- }
4430
- /**
4431
- * The single authority on how much of an order line is still refundable.
4432
- *
4433
- * Every surface that shows or enforces a refundable remainder MUST go through
4434
- * this function. Computing it from the line's net total instead of its actual
4435
- * funding overstates the remainder on partially collected orders, which used to
4436
- * let the dashboard offer a refund the runtime then refused.
4437
- */
4438
- function orderItemRefundableRemainingCents(funding) {
4439
- return toNonNegativeCents(funding.cashFundedCents + funding.creditAppliedCents - funding.refundedCents);
4440
- }
4441
- function refundableRemainingCents(settlement) {
4442
- return orderItemRefundableRemainingCents({
4443
- cashFundedCents: settlement.refundableTotalCents,
4444
- creditAppliedCents: 0,
4445
- refundedCents: settlement.alreadyRefundedCents
4446
- });
4447
- }
4448
4503
  function ensureSingleCurrency(lines) {
4449
4504
  if (lines.length === 0) {
4450
4505
  return {
@@ -4670,7 +4725,13 @@ function resolveAvailableBookingCollectionOptions(input) {
4670
4725
  });
4671
4726
  const collapsed = available.map((option) => isBookingCollectionEquivalentToUpfront(option) ? upfront : option);
4672
4727
  const unique = collapsed.filter((option, index) => collapsed.findIndex((other) => other.kind === option.kind) === index);
4673
- return unique.length > 0 ? unique : [upfront];
4728
+ return unique.length > 0 ? unique.map((option) => permitted(option, "configured")) : [permitted(upfront, "lateFallback")];
4729
+ }
4730
+ function permitted(option, permission) {
4731
+ return {
4732
+ ...option,
4733
+ permission
4734
+ };
4674
4735
  }
4675
4736
  function isBookingCollectionEquivalentToUpfront(option) {
4676
4737
  switch (option.kind) {
@@ -4733,22 +4794,22 @@ function resolveBookingCollectionOptionFacts(input) {
4733
4794
  }
4734
4795
  /** Discounts change preview money, never an already admitted collection identity. */
4735
4796
  function repriceBookingCollectionOptions(input) {
4736
- const repriced = input.options.map((option) => option.totalCents === input.totalCents ? option : resolveBookingCollectionOptionFacts({
4797
+ const repriced = input.options.map((option) => option.totalCents === input.totalCents ? option : permitted(resolveBookingCollectionOptionFacts({
4737
4798
  option,
4738
4799
  totalCents: input.totalCents,
4739
4800
  anchorAt: option.anchorAt,
4740
4801
  bookingStartAt: option.bookingStartAt,
4741
4802
  timeZone: option.timeZone
4742
- }));
4803
+ }), option.permission));
4743
4804
  const available = repriced.filter((option) => canOfferBookingCollectionOption(option, input.currency, input.instalmentCollectionDeadlineAt));
4744
4805
  const first = repriced[0];
4745
- return available.length > 0 || !first ? available : [resolveBookingCollectionOptionFacts({
4806
+ return available.length > 0 || !first ? available : [permitted(resolveBookingCollectionOptionFacts({
4746
4807
  option: { kind: "upfront" },
4747
4808
  totalCents: input.totalCents,
4748
4809
  anchorAt: first.anchorAt,
4749
4810
  bookingStartAt: first.bookingStartAt,
4750
4811
  timeZone: first.timeZone
4751
- })];
4812
+ }), "lateFallback")];
4752
4813
  }
4753
4814
  /** The same admission is used for the offer and the submitted selection. */
4754
4815
  function canOfferBookingCollectionOption(option, currency, deadline = option.bookingStartAt) {
@@ -4787,6 +4848,45 @@ function bookingCollectionWindow(option) {
4787
4848
  start
4788
4849
  } : null;
4789
4850
  }
4851
+ /** Instalment due dates don't depend on the amount; this total keeps every row (zero rows are dropped). */
4852
+ const SCHEDULE_DATES_TOTAL_CENTS = 1e9;
4853
+ /**
4854
+ * The date half of `canOfferBookingCollectionOption`, for a configured option
4855
+ * before any total is known: whether its dates still allow it to be offered.
4856
+ * Amount rules (Stripe minimums, a deposit below the total) are left out, so a
4857
+ * `true` here is an offer the total may still refuse. Upfront and pay-directly
4858
+ * options have no dates to miss.
4859
+ */
4860
+ function bookingCollectionDatesOpen(option, dates) {
4861
+ if (option.kind === "upfront" || option.kind === "deferred_manual") return true;
4862
+ const window$1 = bookingCollectionWindow({
4863
+ anchorAt: dates.nowIso,
4864
+ bookingStartAt: dates.bookingStartAt
4865
+ });
4866
+ if (!window$1 || dates.bookingStartAt === null) return false;
4867
+ switch (option.kind) {
4868
+ case "flexible_balance": {
4869
+ const due = flexibleBalanceDueDay(option.config, dates.bookingStartAt, dates.timeZone);
4870
+ const localDay = (at) => formatLocalScheduleDate(getLocalScheduleDate(new Date(at), dates.timeZone));
4871
+ return due >= localDay(window$1.now) && due < localDay(window$1.start);
4872
+ }
4873
+ case "instalment_plan": {
4874
+ const deadline = dates.instalmentCollectionDeadlineAt === undefined ? dates.bookingStartAt : dates.instalmentCollectionDeadlineAt;
4875
+ if (deadline === null) return false;
4876
+ const schedule = buildBookingInstalmentSchedule({
4877
+ anchorAt: dates.nowIso,
4878
+ totalAmountCents: SCHEDULE_DATES_TOTAL_CENTS,
4879
+ plan: option.plan
4880
+ });
4881
+ return canInstalmentPlanCompleteBefore({
4882
+ now: dates.nowIso,
4883
+ deadline,
4884
+ schedule
4885
+ }) && schedule.every((row) => row.stateAtBooking !== "scheduled" || Date.parse(row.dueAt) > window$1.now);
4886
+ }
4887
+ default: return assertNever$3(option);
4888
+ }
4889
+ }
4790
4890
  /** Mirrors private.flexible_balance_due_day: fixed civil date, or local start minus calendar days. */
4791
4891
  function flexibleBalanceDueDay(config, bookingStartAt, timeZone) {
4792
4892
  const rule = config.dueDateRule;
@@ -5095,10 +5195,9 @@ function projectCheckoutOrderItemMoney(input) {
5095
5195
  quantity: input.quantity,
5096
5196
  subtotalCents: input.settlement.subtotalCents,
5097
5197
  discountCents: input.settlement.discountCents,
5198
+ purchaseCents: input.settlement.stripeChargeCents + input.settlement.creditAppliedCents,
5098
5199
  creditCents: input.settlement.creditAppliedCents,
5099
- netTotalCents: input.settlement.stripeChargeCents,
5100
- totalCents: input.settlement.stripeChargeCents,
5101
- refundedCents: 0
5200
+ receiptRefundedCents: 0
5102
5201
  };
5103
5202
  }
5104
5203
 
@@ -5757,23 +5856,22 @@ function pendingIdempotentRefundOutcome(input, refund) {
5757
5856
  };
5758
5857
  }
5759
5858
  function pendingRefundOutcome(input) {
5760
- if (input.latestPending) {
5761
- if (!input.latestPending.isStale) {
5762
- return failedDecision({
5763
- input,
5764
- errorCode: "refund_in_progress",
5765
- errorMessage: "A refund is already being processed for this purchase",
5766
- refund: input.latestPending,
5767
- amountCents: input.latestPending.amountCents
5768
- });
5769
- }
5770
- return {
5771
- kind: "resume_pending",
5772
- refund: input.latestPending,
5773
- requestedAmountCents: input.latestPending.amountCents
5774
- };
5859
+ const inProgress = input.pendingOnScope.find((refund) => !refund.isStale);
5860
+ if (inProgress) {
5861
+ return failedDecision({
5862
+ input,
5863
+ errorCode: "refund_in_progress",
5864
+ errorMessage: "A refund is already being processed for this purchase",
5865
+ refund: inProgress,
5866
+ amountCents: inProgress.amountCents
5867
+ });
5775
5868
  }
5776
- return null;
5869
+ const stale = input.pendingOnScope[0];
5870
+ return stale ? {
5871
+ kind: "resume_pending",
5872
+ refund: stale,
5873
+ requestedAmountCents: stale.amountCents
5874
+ } : null;
5777
5875
  }
5778
5876
  function heldRefundConflict(input, requestedAmountCents) {
5779
5877
  if (input.heldCents > 0 && (input.requestedAmountCents === undefined || requestedAmountCents > input.remainingRefundableCents || input.requireFullRemainingRefund)) {
@@ -5818,14 +5916,63 @@ function refundAmountOutcome(input, requestedAmountCents) {
5818
5916
  };
5819
5917
  }
5820
5918
 
5919
+ //#endregion
5920
+ //#region ../commerce/src/purchase/confirmationEmailPayment.ts
5921
+ /** Email copy projection; this function never decides settlement. */
5922
+ function toConfirmationEmailPaymentSummary(payment) {
5923
+ return {
5924
+ ...projectConfirmationEmailPaymentSummary(payment),
5925
+ ...payment.discount ? { discount: payment.discount } : {}
5926
+ };
5927
+ }
5928
+ function projectConfirmationEmailPaymentSummary(payment) {
5929
+ switch (payment.kind) {
5930
+ case "free": return { kind: "free" };
5931
+ case "waived": return { kind: "waived" };
5932
+ case "pass": return {
5933
+ kind: "pass",
5934
+ passName: payment.passName ?? undefined,
5935
+ passCreditsUsed: payment.passCreditsUsed ?? undefined,
5936
+ ...payment.passCreditsRemaining !== undefined ? { passCreditsRemaining: payment.passCreditsRemaining } : {}
5937
+ };
5938
+ case "membership": return {
5939
+ kind: "membership",
5940
+ membershipName: payment.membershipName ?? undefined
5941
+ };
5942
+ case "manual_due": return {
5943
+ kind: "manual_due",
5944
+ amountDueCents: payment.balance.amountCents,
5945
+ currency: payment.currency
5946
+ };
5947
+ case "managed_balance_due": return {
5948
+ kind: "managed_balance_due",
5949
+ amountPaidCents: payment.amountPaidCents,
5950
+ amountOutstandingCents: payment.balance.amountCents,
5951
+ currency: payment.currency,
5952
+ dueAt: payment.balance.dueAt
5953
+ };
5954
+ case "monetary": return {
5955
+ kind: "monetary",
5956
+ amountPaidCents: payment.amountPaidCents,
5957
+ ...payment.balance.kind === "due" ? {
5958
+ amountOutstandingCents: payment.balance.amountCents,
5959
+ dueAt: payment.balance.dueAt
5960
+ } : {},
5961
+ currency: payment.currency,
5962
+ paymentMethod: payment.paymentMethod
5963
+ };
5964
+ default: return assertNever$3(payment);
5965
+ }
5966
+ }
5967
+
5821
5968
  //#endregion
5822
5969
  //#region ../commerce/src/purchase/confirmationPaymentSchema.ts
5823
5970
  const settledBalanceSchema = z.object({ kind: z.literal("settled") });
5824
5971
  const dueBalanceSchema = z.object({
5825
5972
  kind: z.literal("due"),
5826
5973
  amountCents: z.number().int().positive().transform((value, ctx) => {
5827
- const cents$2 = parsePositiveCents(value);
5828
- if (cents$2.ok) return cents$2.value;
5974
+ const cents$3 = parsePositiveCents(value);
5975
+ if (cents$3.ok) return cents$3.value;
5829
5976
  ctx.addIssue({
5830
5977
  code: "custom",
5831
5978
  message: "Expected positive whole cents"
@@ -5895,84 +6042,17 @@ const confirmationPaymentSchema = z.discriminatedUnion("kind", [
5895
6042
  balance: paymentBalanceSchema
5896
6043
  })
5897
6044
  ]);
5898
-
5899
- //#endregion
5900
- //#region ../commerce/src/shop/shipmentEligibility.ts
5901
- /**
5902
- * Whether an order item is eligible for physical shipment.
5903
- *
5904
- * Only product items with `requires_shipping = true` that have not been cancelled
5905
- * are shippable. Digital products, passes, event tickets, course enrollments,
5906
- * and memberships are never shippable.
5907
- */
5908
- function isShippableItem(item) {
5909
- return item.kind === "product" && item.requiresShipping && item.cancelledAt === null;
5910
- }
5911
-
5912
- //#endregion
5913
- //#region ../commerce/src/purchase/refundPolicy.ts
5914
- const SHOP_REFUNDABLE_PAYMENT_METHODS = new Set([
5915
- "stripe",
5916
- "mixed",
5917
- "store_credit"
5918
- ]);
5919
- /**
5920
- * Whether an order's payment method supports refunds through the shop refund flow.
5921
- *
5922
- * Pass redemption, membership access, and free orders cannot be refunded
5923
- * through Stripe or site credit — they need domain-specific handling.
5924
- */
5925
- function isShopRefundablePaymentMethod(paymentMethod) {
5926
- return SHOP_REFUNDABLE_PAYMENT_METHODS.has(paymentMethod);
5927
- }
5928
-
5929
- //#endregion
5930
- //#region ../commerce/src/purchase/orderItemSupport.ts
5931
- function isShopRefundableOrderItem(item) {
5932
- return item.kind === "product" || item.kind === "pass";
5933
- }
5934
- function usesShopRefundFlow(paymentMethod, item) {
5935
- return isShopRefundablePaymentMethod(paymentMethod) && isShopRefundableOrderItem(item);
5936
- }
5937
- function getOrderItemDisplayName(item) {
5938
- return item.metadata.displayName ?? fallbackOrderItemDisplayName(item.kind);
5939
- }
5940
- function effectiveOrderItemNetTotalCents(item) {
5941
- return item.netTotalCents ?? item.totalCents ?? 0;
5942
- }
5943
- function isOrderItemShippable(item) {
5944
- return isShippableItem({
5945
- kind: item.kind,
5946
- requiresShipping: item.kind === "product" ? item.metadata.requiresShipping ?? false : false,
5947
- cancelledAt: item.cancelledAt ?? null
5948
- });
5949
- }
5950
- function partitionActiveUnshippedOrderItems(items, shippedQuantityByItemId) {
5951
- const cancellableItems = [];
5952
- const shippedItems = [];
5953
- for (const item of items) {
5954
- if (item.cancelledAt) continue;
5955
- if ((shippedQuantityByItemId.get(item.id) ?? 0) > 0) {
5956
- shippedItems.push(item);
5957
- continue;
5958
- }
5959
- cancellableItems.push(item);
5960
- }
5961
- return {
5962
- cancellableItems,
5963
- shippedItems
5964
- };
5965
- }
5966
- function fallbackOrderItemDisplayName(kind) {
5967
- switch (kind) {
5968
- case "product": return "Product";
5969
- case "pass": return "Pass";
5970
- case "membership": return "Membership";
5971
- case "event_ticket": return "Booking";
5972
- case "event_series_registration": return "Course";
5973
- case "appointment": return "Appointment";
5974
- }
5975
- }
6045
+ /** What the order took, by card and account credit, independently of which bookings used an entitlement. */
6046
+ const submissionPaymentSchema = z.object({
6047
+ amountPaidCents: moneyFields.amountPaidCents,
6048
+ creditCents: z.number().int().nonnegative().transform(toNonNegativeCents),
6049
+ currency: currencySchema,
6050
+ purchasedItems: z.array(z.object({
6051
+ kind: z.enum(["pass", "membership"]),
6052
+ name: z.string().min(1),
6053
+ priceCents: z.number().int().nonnegative().transform(toNonNegativeCents)
6054
+ })).readonly()
6055
+ });
5976
6056
 
5977
6057
  //#endregion
5978
6058
  //#region ../commerce/src/purchase/orderPaymentState.ts
@@ -6099,93 +6179,19 @@ function buildConfirmationPayment(input) {
6099
6179
  if (validated.success) return ok(validated.data);
6100
6180
  return err(validated.error.issues.some((issue) => issue.path[0] === "passCreditsUsed") ? { kind: "invalid_pass_credits" } : { kind: "missing_settlement_evidence" });
6101
6181
  }
6102
- function settledOrderItemTotalCents(item) {
6103
- return effectiveOrderItemNetTotalCents(item) + (item.creditCents ?? 0);
6104
- }
6105
-
6106
- //#endregion
6107
- //#region ../commerce/src/purchase/confirmationEmailPayment.ts
6108
- function buildNonMonetaryConfirmationEmailPaymentSummary(options) {
6109
- switch (options.paymentMethod) {
6110
- case "free": return { kind: "free" };
6111
- case "pass": return {
6112
- kind: "pass",
6113
- passName: options.passName,
6114
- passCreditsUsed: options.passCreditsUsed,
6115
- ...options.passCreditsRemaining !== undefined ? { passCreditsRemaining: options.passCreditsRemaining } : {}
6116
- };
6117
- case "membership": return {
6118
- kind: "membership",
6119
- membershipName: options.membershipName
6120
- };
6121
- default: return assertNever$3(options.paymentMethod);
6122
- }
6123
- }
6124
- function buildMonetaryConfirmationEmailPaymentSummary(options) {
6125
- if (options.amountPaidCents == null || !options.currency) {
6126
- return undefined;
6127
- }
6128
- return {
6129
- kind: "monetary",
6130
- amountPaidCents: options.amountPaidCents,
6131
- currency: options.currency,
6132
- paymentMethod: options.paymentMethod
6133
- };
6134
- }
6135
- /** Email copy projection; this function never decides settlement. */
6136
- function toConfirmationEmailPaymentSummary(payment) {
6137
- return {
6138
- ...projectConfirmationEmailPaymentSummary(payment),
6139
- ...payment.discount ? { discount: payment.discount } : {}
6140
- };
6141
- }
6142
- function projectConfirmationEmailPaymentSummary(payment) {
6143
- switch (payment.kind) {
6144
- case "free": return { kind: "free" };
6145
- case "waived": return { kind: "waived" };
6146
- case "pass": return {
6147
- kind: "pass",
6148
- passName: payment.passName ?? undefined,
6149
- passCreditsUsed: payment.passCreditsUsed ?? undefined,
6150
- ...payment.passCreditsRemaining !== undefined ? { passCreditsRemaining: payment.passCreditsRemaining } : {}
6151
- };
6152
- case "membership": return {
6153
- kind: "membership",
6154
- membershipName: payment.membershipName ?? undefined
6155
- };
6156
- case "manual_due": return { kind: "manual_due" };
6157
- case "managed_balance_due": return {
6158
- kind: "managed_balance_due",
6159
- dueAt: payment.balance.dueAt
6160
- };
6161
- case "monetary": return {
6162
- kind: "monetary",
6163
- amountPaidCents: payment.amountPaidCents,
6164
- ...payment.balance.kind === "due" ? {
6165
- amountOutstandingCents: payment.balance.amountCents,
6166
- dueAt: payment.balance.dueAt
6167
- } : {},
6168
- currency: payment.currency,
6169
- paymentMethod: payment.paymentMethod
6170
- };
6171
- default: return assertNever$3(payment);
6172
- }
6173
- }
6174
- function buildManualAttendeeConfirmationEmailPaymentSummary(options) {
6175
- return buildNonMonetaryConfirmationEmailPaymentSummary(options);
6176
- }
6177
- function buildTransferredAttendeeConfirmationEmailPaymentSummary(options) {
6178
- switch (options.paymentMethod) {
6179
- case "free":
6180
- case "pass":
6181
- case "membership": return buildNonMonetaryConfirmationEmailPaymentSummary({ paymentMethod: options.paymentMethod });
6182
- case "stripe": return buildMonetaryConfirmationEmailPaymentSummary({
6183
- amountPaidCents: options.amountPaidCents,
6184
- currency: options.currency,
6185
- paymentMethod: "stripe"
6186
- });
6187
- }
6188
- return assertNever$3(options.paymentMethod);
6182
+ /**
6183
+ * What the order took: card receipts and account credit together, as a booking's own payment
6184
+ * counts them, with the credit part kept so the confirmation can say where it came from.
6185
+ */
6186
+ function submissionPaymentFromOrder(position, purchasedItems) {
6187
+ const total = (kind) => position.funding.filter((line) => line.source.kind === kind).reduce((sum, line) => sum + line.amountCents, 0);
6188
+ const creditCents = total("credit_debit");
6189
+ return submissionPaymentSchema.parse({
6190
+ amountPaidCents: total("receipt") + creditCents,
6191
+ creditCents,
6192
+ currency: position.currency,
6193
+ purchasedItems
6194
+ });
6189
6195
  }
6190
6196
 
6191
6197
  //#endregion
@@ -6246,7 +6252,7 @@ function reductionAllocation(cart, selected) {
6246
6252
  };
6247
6253
  }
6248
6254
  const lineIds = selected.allocationLineIds ?? cart.items.map((item) => item.lineId);
6249
- const order = new Map(lineIds.map((id, index) => [id, index]));
6255
+ const order = new Map(lineIds.map((id$1, index) => [id$1, index]));
6250
6256
  const ordered = [...cart.items].sort((a, b) => (order.get(a.lineId) ?? Infinity) - (order.get(b.lineId) ?? Infinity));
6251
6257
  const allocation = allocateReductionCents(ordered.map((item) => ({
6252
6258
  lineId: item.lineId,
@@ -6435,6 +6441,81 @@ function generateOrderNumber(prefix, year, sequenceNumber) {
6435
6441
  return `${prefix}-${year}-${String(sequenceNumber).padStart(4, "0")}`;
6436
6442
  }
6437
6443
 
6444
+ //#endregion
6445
+ //#region ../commerce/src/shop/shipmentEligibility.ts
6446
+ /**
6447
+ * Whether an order item is eligible for physical shipment.
6448
+ *
6449
+ * Only product items with `requires_shipping = true` that have not been cancelled
6450
+ * are shippable. Digital products, passes, event tickets, course enrollments,
6451
+ * and memberships are never shippable.
6452
+ */
6453
+ function isShippableItem(item) {
6454
+ return item.kind === "product" && item.requiresShipping && item.cancelledAt === null;
6455
+ }
6456
+
6457
+ //#endregion
6458
+ //#region ../commerce/src/purchase/refundPolicy.ts
6459
+ const SHOP_REFUNDABLE_PAYMENT_METHODS = new Set([
6460
+ "stripe",
6461
+ "mixed",
6462
+ "store_credit"
6463
+ ]);
6464
+ /**
6465
+ * Whether an order's payment method supports refunds through the shop refund flow.
6466
+ *
6467
+ * Pass redemption, membership access, and free orders cannot be refunded
6468
+ * through Stripe or site credit — they need domain-specific handling.
6469
+ */
6470
+ function isShopRefundablePaymentMethod(paymentMethod) {
6471
+ return SHOP_REFUNDABLE_PAYMENT_METHODS.has(paymentMethod);
6472
+ }
6473
+
6474
+ //#endregion
6475
+ //#region ../commerce/src/purchase/orderItemSupport.ts
6476
+ function isShopRefundableOrderItem(item) {
6477
+ return item.kind === "product" || item.kind === "pass";
6478
+ }
6479
+ function usesShopRefundFlow(paymentMethod, item) {
6480
+ return isShopRefundablePaymentMethod(paymentMethod) && isShopRefundableOrderItem(item);
6481
+ }
6482
+ function getOrderItemDisplayName(item) {
6483
+ return item.metadata.displayName ?? fallbackOrderItemDisplayName(item.kind);
6484
+ }
6485
+ function isOrderItemShippable(item) {
6486
+ return isShippableItem({
6487
+ kind: item.kind,
6488
+ requiresShipping: item.kind === "product" ? item.metadata.requiresShipping ?? false : false,
6489
+ cancelledAt: item.cancelledAt ?? null
6490
+ });
6491
+ }
6492
+ function partitionActiveUnshippedOrderItems(items, shippedQuantityByItemId) {
6493
+ const cancellableItems = [];
6494
+ const shippedItems = [];
6495
+ for (const item of items) {
6496
+ if (item.cancelledAt) continue;
6497
+ if ((shippedQuantityByItemId.get(item.id) ?? 0) > 0) {
6498
+ shippedItems.push(item);
6499
+ continue;
6500
+ }
6501
+ cancellableItems.push(item);
6502
+ }
6503
+ return {
6504
+ cancellableItems,
6505
+ shippedItems
6506
+ };
6507
+ }
6508
+ function fallbackOrderItemDisplayName(kind) {
6509
+ switch (kind) {
6510
+ case "product": return "Product";
6511
+ case "pass": return "Pass";
6512
+ case "membership": return "Membership";
6513
+ case "event_ticket": return "Booking";
6514
+ case "event_series_registration": return "Course";
6515
+ case "appointment": return "Appointment";
6516
+ }
6517
+ }
6518
+
6438
6519
  //#endregion
6439
6520
  //#region ../commerce/src/purchase/orderCancellationPlan.ts
6440
6521
  function planOrderCancellationExecution(options) {
@@ -6732,19 +6813,13 @@ function resolveInstalmentPlanIntroText(input) {
6732
6813
 
6733
6814
  //#endregion
6734
6815
  //#region ../commerce/src/purchase/orderCompletionEmailPlan.ts
6735
- function hasPassBundleFulfillment(metadata) {
6736
- return !!metadata.bundleFulfillment;
6737
- }
6738
- function hasMembershipBundleFulfillment(metadata) {
6739
- return !!metadata.bundleFulfillment;
6740
- }
6741
6816
  const noActions = () => ({
6742
6817
  actions: [],
6743
6818
  warnings: []
6744
6819
  });
6745
6820
  function planEventItem(item, input) {
6746
- const id = item.kind === "event_ticket" ? item.eventAttendeeId : item.eventSeriesRegistrationId;
6747
- if (!id) return {
6821
+ const id$1 = item.kind === "event_ticket" ? item.eventAttendeeId : item.eventSeriesRegistrationId;
6822
+ if (!id$1) return {
6748
6823
  actions: [],
6749
6824
  warnings: [{
6750
6825
  kind: item.kind === "event_ticket" ? "missing_event_attendee_id" : "missing_event_series_registration_id",
@@ -6752,7 +6827,7 @@ function planEventItem(item, input) {
6752
6827
  orderItemId: item.id
6753
6828
  }]
6754
6829
  };
6755
- const facts = input.bookingFacts.get(id);
6830
+ const facts = input.bookingFacts.get(id$1);
6756
6831
  if (!facts) return noActions();
6757
6832
  if (item.kind === "event_ticket" && item.eventAttendeeId) return {
6758
6833
  warnings: [],
@@ -6771,25 +6846,28 @@ function planEventItem(item, input) {
6771
6846
  }]
6772
6847
  };
6773
6848
  }
6774
- function planPassItem(item, input) {
6775
- if (!hasPassBundleFulfillment(item.metadata)) return noActions();
6776
- if (!item.eventAttendeeId) return {
6777
- actions: [],
6778
- warnings: [{
6779
- kind: "missing_event_attendee_id",
6780
- orderId: item.orderId,
6781
- orderItemId: item.id
6782
- }]
6849
+ /** One confirmation per date, so a pass covering several dates needs nothing different from one covering one. */
6850
+ function planCoveredBookings(item, input) {
6851
+ const actions = (input.coveredBookings.get(item.id) ?? []).flatMap((booking) => {
6852
+ switch (booking.kind) {
6853
+ case "occurrence": {
6854
+ const facts = input.bookingFacts.get(booking.bookingId);
6855
+ return facts ? [{
6856
+ kind: "send_covered_occurrence_confirmation",
6857
+ facts
6858
+ }] : [];
6859
+ }
6860
+ case "appointment": return [{
6861
+ kind: "send_appointment_confirmation",
6862
+ orderId: item.orderId,
6863
+ appointmentId: booking.bookingId
6864
+ }];
6865
+ }
6866
+ });
6867
+ return {
6868
+ actions,
6869
+ warnings: []
6783
6870
  };
6784
- const facts = input.bookingFacts.get(item.eventAttendeeId);
6785
- return facts ? {
6786
- warnings: [],
6787
- actions: [{
6788
- kind: "send_pass_bundle_confirmation",
6789
- facts,
6790
- metadata: item.metadata
6791
- }]
6792
- } : noActions();
6793
6871
  }
6794
6872
  function planMembershipItem(item, input) {
6795
6873
  const activation = item.customerMembershipId ? {
@@ -6797,7 +6875,7 @@ function planMembershipItem(item, input) {
6797
6875
  actions: [{
6798
6876
  kind: "send_membership_activation",
6799
6877
  customerMembershipId: item.customerMembershipId,
6800
- amountPaidCents: settledOrderItemTotalCents(item)
6878
+ amountPaidCents: item.purchaseCents
6801
6879
  }]
6802
6880
  } : {
6803
6881
  actions: [],
@@ -6807,30 +6885,16 @@ function planMembershipItem(item, input) {
6807
6885
  orderItemId: item.id
6808
6886
  }]
6809
6887
  };
6810
- if (!hasMembershipBundleFulfillment(item.metadata)) return activation;
6811
- if (!item.eventAttendeeId) return {
6812
- ...activation,
6813
- warnings: [...activation.warnings, {
6814
- kind: "missing_event_attendee_id",
6815
- orderId: item.orderId,
6816
- orderItemId: item.id
6817
- }]
6888
+ return {
6889
+ actions: [...activation.actions, ...planCoveredBookings(item, input).actions],
6890
+ warnings: activation.warnings
6818
6891
  };
6819
- const facts = input.bookingFacts.get(item.eventAttendeeId);
6820
- return facts ? {
6821
- ...activation,
6822
- actions: [...activation.actions, {
6823
- kind: "send_membership_bundle_confirmation",
6824
- facts,
6825
- metadata: item.metadata
6826
- }]
6827
- } : activation;
6828
6892
  }
6829
6893
  function planItem(item, input) {
6830
6894
  switch (item.kind) {
6831
6895
  case "event_ticket":
6832
6896
  case "event_series_registration": return planEventItem(item, input);
6833
- case "pass": return planPassItem(item, input);
6897
+ case "pass": return planCoveredBookings(item, input);
6834
6898
  case "membership": return planMembershipItem(item, input);
6835
6899
  case "appointment": return item.appointmentId ? {
6836
6900
  warnings: [],
@@ -6858,8 +6922,8 @@ function buildOrderCompletionEmailPlan(input) {
6858
6922
  const first = input.items[0];
6859
6923
  if (!first) return noActions();
6860
6924
  const plans = input.items.filter((item, index) => {
6861
- const id = bookingGroupId(item);
6862
- return id === null || !input.items.slice(0, index).some((previous) => bookingGroupId(previous) === id);
6925
+ const id$1 = bookingGroupId(item);
6926
+ return id$1 === null || !input.items.slice(0, index).some((previous) => bookingGroupId(previous) === id$1);
6863
6927
  }).map((item) => planItem(item, input));
6864
6928
  const receipt = input.items.some((item) => item.kind === "product" || item.kind === "pass") ? [{
6865
6929
  kind: "send_order_confirmation",
@@ -6873,71 +6937,6 @@ function buildOrderCompletionEmailPlan(input) {
6873
6937
 
6874
6938
  //#endregion
6875
6939
  //#region ../commerce/src/purchase/orderFulfillmentPlan.ts
6876
- function planOrderItemFulfillment(item, orderPaymentMethod) {
6877
- switch (item.kind) {
6878
- case "event_ticket":
6879
- if (!item.eventAttendeeId) {
6880
- return err(`Order item ${item.id} (event_ticket) has no eventAttendeeId`);
6881
- }
6882
- return ok({
6883
- kind: "event_ticket",
6884
- attendeeId: item.eventAttendeeId,
6885
- paymentStatus: resolveAttendeePaymentStatusForFulfillment(orderPaymentMethod)
6886
- });
6887
- case "product": return ok({ kind: "product" });
6888
- case "pass": {
6889
- const bundleFulfillment = item.metadata.bundleFulfillment;
6890
- const passBundleAttendeeId = item.eventAttendeeId;
6891
- if (!bundleFulfillment) {
6892
- return ok({
6893
- kind: "pass",
6894
- existingCustomerPassId: item.customerPassId,
6895
- passId: item.metadata.passId,
6896
- bundleFulfillment: null
6897
- });
6898
- }
6899
- if (!passBundleAttendeeId) {
6900
- return err(`Order item ${item.id} (pass bundle) has no eventAttendeeId`);
6901
- }
6902
- return ok({
6903
- kind: "pass",
6904
- existingCustomerPassId: item.customerPassId,
6905
- passId: item.metadata.passId,
6906
- bundleFulfillment: {
6907
- attendeeId: passBundleAttendeeId,
6908
- eventInstanceId: bundleFulfillment.eventInstanceId,
6909
- ticketsCount: bundleFulfillment.ticketsCount
6910
- }
6911
- });
6912
- }
6913
- case "event_series_registration":
6914
- if (!item.eventSeriesRegistrationId) {
6915
- return err(`Order item ${item.id} (event_series_registration) has no eventSeriesRegistrationId`);
6916
- }
6917
- if (!item.metadata.eventSeriesId) {
6918
- return err(`Order item ${item.id} (event_series_registration) has no eventSeriesId`);
6919
- }
6920
- return ok({
6921
- kind: "event_series_registration",
6922
- registrationId: item.eventSeriesRegistrationId,
6923
- eventSeriesId: item.metadata.eventSeriesId,
6924
- ...resolveEventSeriesRegistrationPaymentForFulfillment(orderPaymentMethod)
6925
- });
6926
- case "appointment":
6927
- if (!item.appointmentId) {
6928
- return err(`Order item ${item.id} (appointment) has no appointmentId`);
6929
- }
6930
- return ok({
6931
- kind: "appointment",
6932
- appointmentId: item.appointmentId,
6933
- nextStatus: "confirmed",
6934
- customerName: item.metadata.customerName,
6935
- customerEmail: item.metadata.customerEmail,
6936
- displayName: item.metadata.displayName ?? null
6937
- });
6938
- case "membership": return ok({ kind: "membership" });
6939
- }
6940
- }
6941
6940
  function planOrderItemCancellation(item) {
6942
6941
  switch (item.kind) {
6943
6942
  case "event_ticket":
@@ -6965,54 +6964,11 @@ function planOrderItemCancellation(item) {
6965
6964
  appointmentId: item.appointmentId
6966
6965
  });
6967
6966
  case "product": return ok({ kind: "product" });
6968
- case "pass": return ok({
6969
- kind: "pass",
6970
- customerPassId: item.customerPassId,
6971
- bundleAttendeeId: item.eventAttendeeId
6972
- });
6973
- case "membership": return ok({
6974
- kind: "membership",
6975
- customerMembershipId: item.customerMembershipId,
6976
- bundleAttendeeId: item.eventAttendeeId
6977
- });
6978
6967
  }
6979
6968
  }
6980
6969
  function planOrderItemRefundRevocation(item) {
6981
6970
  return planOrderItemCancellation(item);
6982
6971
  }
6983
- function resolveAttendeePaymentStatusForFulfillment(orderPaymentMethod) {
6984
- switch (orderPaymentMethod) {
6985
- case "stripe":
6986
- case "mixed": return "completed";
6987
- case "manual":
6988
- case "store_credit":
6989
- case "pass_redemption":
6990
- case "membership_access":
6991
- case "waived":
6992
- case "free": return "not_required";
6993
- }
6994
- }
6995
- function resolveEventSeriesRegistrationPaymentForFulfillment(orderPaymentMethod) {
6996
- switch (orderPaymentMethod) {
6997
- case "stripe":
6998
- case "mixed": return {
6999
- paymentMethod: "stripe",
7000
- paymentStatus: "completed"
7001
- };
7002
- case "membership_access": return {
7003
- paymentMethod: "membership",
7004
- paymentStatus: "not_required"
7005
- };
7006
- case "manual":
7007
- case "store_credit":
7008
- case "pass_redemption":
7009
- case "waived":
7010
- case "free": return {
7011
- paymentMethod: "free",
7012
- paymentStatus: "not_required"
7013
- };
7014
- }
7015
- }
7016
6972
 
7017
6973
  //#endregion
7018
6974
  //#region ../commerce/src/purchase/orderHistorySource.ts
@@ -7348,36 +7304,6 @@ function parseEventOrderOptionSnapshot(raw) {
7348
7304
 
7349
7305
  //#endregion
7350
7306
  //#region ../commerce/src/purchase/membershipOrderItemMetadata.ts
7351
- function requiredString(value) {
7352
- return typeof value === "string" && value.length > 0 ? value : null;
7353
- }
7354
- function positiveCount(value) {
7355
- return typeof value === "number" && value > 0 ? value : null;
7356
- }
7357
- function isObjectRecord$1(value) {
7358
- return value !== null && typeof value === "object" && !Array.isArray(value);
7359
- }
7360
- function parseBundle(raw) {
7361
- if (raw == null) return ok(undefined);
7362
- if (!isObjectRecord$1(raw)) {
7363
- return err("Invalid membership bundle fulfillment metadata");
7364
- }
7365
- const occurrenceId = requiredString(raw.occurrenceId);
7366
- const ticketsCount = positiveCount(raw.ticketsCount);
7367
- const attendeeEmail = requiredString(raw.attendeeEmail);
7368
- const attendeeName = requiredString(raw.attendeeName);
7369
- const membershipName = requiredString(raw.membershipName);
7370
- if (!occurrenceId || !ticketsCount || !attendeeEmail || !attendeeName || !membershipName) {
7371
- return err("Invalid membership bundle fulfillment metadata");
7372
- }
7373
- return ok({
7374
- occurrenceId: unsafeAsOccurrenceId(occurrenceId),
7375
- ticketsCount,
7376
- attendeeEmail,
7377
- attendeeName,
7378
- membershipName
7379
- });
7380
- }
7381
7307
  function parseMembershipTerms(raw) {
7382
7308
  const membershipId = raw.membershipId === undefined ? null : parseMembershipId(raw.membershipId);
7383
7309
  if (membershipId && !membershipId.ok) return err("Invalid membership order item ID");
@@ -7393,13 +7319,10 @@ function parseMembershipTerms(raw) {
7393
7319
  function parseMembershipOrderItemMetadata(raw, checkoutLine, commission) {
7394
7320
  const terms = parseMembershipTerms(raw);
7395
7321
  if (!terms.ok) return terms;
7396
- const bundleFulfillment = parseBundle(raw.bundleFulfillment);
7397
- if (!bundleFulfillment.ok) return bundleFulfillment;
7398
7322
  return ok({
7399
7323
  ...commission,
7400
7324
  ...checkoutLine,
7401
- ...terms.value,
7402
- ...bundleFulfillment.value ? { bundleFulfillment: bundleFulfillment.value } : {}
7325
+ ...terms.value
7403
7326
  });
7404
7327
  }
7405
7328
 
@@ -7549,31 +7472,6 @@ function parseBookableOrderItemPricingMetadata(raw) {
7549
7472
  chosenAmount: pricing.chosenAmount
7550
7473
  } });
7551
7474
  }
7552
- function parsePassBundleFulfillmentMetadata(raw) {
7553
- if (raw == null) {
7554
- return ok(undefined);
7555
- }
7556
- if (!isObjectRecord(raw)) {
7557
- return err("Invalid pass bundle fulfillment metadata");
7558
- }
7559
- const occurrenceId = typeof raw.occurrenceId === "string" && raw.occurrenceId.length > 0 ? raw.occurrenceId : null;
7560
- const eventInstanceId = raw.eventInstanceId == null ? null : typeof raw.eventInstanceId === "string" && raw.eventInstanceId.length > 0 ? raw.eventInstanceId : undefined;
7561
- const ticketsCount = typeof raw.ticketsCount === "number" && raw.ticketsCount > 0 ? raw.ticketsCount : null;
7562
- const attendeeEmail = typeof raw.attendeeEmail === "string" && raw.attendeeEmail.length > 0 ? raw.attendeeEmail : null;
7563
- const attendeeName = typeof raw.attendeeName === "string" && raw.attendeeName.length > 0 ? raw.attendeeName : null;
7564
- const passName = typeof raw.passName === "string" && raw.passName.length > 0 ? raw.passName : null;
7565
- if (!occurrenceId || eventInstanceId === undefined || !ticketsCount || !attendeeEmail || !attendeeName || !passName) {
7566
- return err("Invalid pass bundle fulfillment metadata");
7567
- }
7568
- return ok({
7569
- occurrenceId: unsafeAsOccurrenceId(occurrenceId),
7570
- eventInstanceId: eventInstanceId ? unsafeAsEventInstanceId(eventInstanceId) : null,
7571
- ticketsCount,
7572
- attendeeEmail,
7573
- attendeeName,
7574
- passName
7575
- });
7576
- }
7577
7475
  function parseOrderItemMetadata(kind, raw) {
7578
7476
  if (!isObjectRecord(raw)) {
7579
7477
  return err(`Order item metadata for kind '${kind}' must be an object`);
@@ -7622,10 +7520,6 @@ function parseOrderItemMetadata(kind, raw) {
7622
7520
  if (!productUseCase.ok) {
7623
7521
  return err(productUseCase.error);
7624
7522
  }
7625
- const bundleFulfillment = parsePassBundleFulfillmentMetadata(raw.bundleFulfillment);
7626
- if (!bundleFulfillment.ok) {
7627
- return err(bundleFulfillment.error);
7628
- }
7629
7523
  if (!passId || creditsTotal == null) {
7630
7524
  return err("Invalid pass order item metadata");
7631
7525
  }
@@ -7635,8 +7529,7 @@ function parseOrderItemMetadata(kind, raw) {
7635
7529
  passId: unsafeAsPassId(passId),
7636
7530
  productUseCase: productUseCase.value,
7637
7531
  creditsTotal,
7638
- validDays,
7639
- ...bundleFulfillment.value ? { bundleFulfillment: bundleFulfillment.value } : {}
7532
+ validDays
7640
7533
  });
7641
7534
  }
7642
7535
  case "event_series_registration": {
@@ -7692,16 +7585,12 @@ function parseOrderItemMetadata(kind, raw) {
7692
7585
  timezone,
7693
7586
  customerEmail,
7694
7587
  customerName,
7695
- ...parseAppointmentPurchaseMetadata(raw),
7696
7588
  ...typeof raw.handAddedFingerprint === "string" ? { handAddedFingerprint: raw.handAddedFingerprint } : {}
7697
7589
  });
7698
7590
  }
7699
7591
  case "membership": return parseMembershipOrderItemMetadata(raw, parseCheckoutLineMetadata(raw), commissionMetadata.value);
7700
7592
  }
7701
7593
  }
7702
- function parseAppointmentPurchaseMetadata(raw) {
7703
- return typeof raw.purchasePassId === "string" ? { purchasePassId: raw.purchasePassId } : {};
7704
- }
7705
7594
 
7706
7595
  //#endregion
7707
7596
  //#region ../commerce/src/purchase/orderListFilters.ts
@@ -8128,21 +8017,6 @@ function unavailable(reason, publicMessage, httpStatus) {
8128
8017
  };
8129
8018
  }
8130
8019
 
8131
- //#endregion
8132
- //#region ../commerce/src/purchase/orderRefundPlanning.ts
8133
- function planOrderRefundSummaryUpdate(options) {
8134
- const paidCents = options.paidCents;
8135
- const currentRefundedCents = options.currentRefundedCents;
8136
- const nextRefundedCents = options.nextRefundedCents;
8137
- if (currentRefundedCents > paidCents) {
8138
- return err("Current refunded amount exceeds paid amount");
8139
- }
8140
- if (nextRefundedCents < currentRefundedCents) {
8141
- return err("Refunded amount cannot decrease");
8142
- }
8143
- return ok({ refundedCents: nextRefundedCents });
8144
- }
8145
-
8146
8020
  //#endregion
8147
8021
  //#region ../commerce/src/purchase/orderRefundPolicy.ts
8148
8022
  const ORDER_REFUND_MODES = ["refund_only", "refund_and_revoke"];
@@ -8193,48 +8067,6 @@ function settleOrderRefundEntitlementAction(options) {
8193
8067
  return ok(options.planned.revokedOrderItemIds);
8194
8068
  }
8195
8069
 
8196
- //#endregion
8197
- //#region ../commerce/src/purchase/persistedCheckoutLines.ts
8198
- function projectPersistedCheckoutLines(items) {
8199
- const lines = [];
8200
- for (const item of items) {
8201
- const quantity = parsePositiveCheckoutQuantity(item.quantity);
8202
- if (!quantity.ok) {
8203
- return err(`Order item ${item.id} has invalid quantity: ${item.quantity}`);
8204
- }
8205
- const settlement = buildRefundableLineSettlement({
8206
- lineId: item.id,
8207
- subtotalCents: item.subtotalCents ?? 0,
8208
- discountCents: item.discountCents ?? 0,
8209
- creditAppliedCents: item.creditCents ?? 0,
8210
- stripeChargeCents: item.netTotalCents ?? item.totalCents ?? 0,
8211
- alreadyRefundedCents: 0
8212
- });
8213
- if (!settlement.ok) {
8214
- return err(settlement.error.message);
8215
- }
8216
- lines.push({
8217
- orderItemId: item.id,
8218
- checkoutLineId: item.metadata.checkoutLineId ?? null,
8219
- kind: item.kind,
8220
- quantity: quantity.value,
8221
- displayName: item.metadata.displayName ?? fallbackDisplayName(item.kind),
8222
- settlement: settlement.value
8223
- });
8224
- }
8225
- return ok(lines);
8226
- }
8227
- function fallbackDisplayName(kind) {
8228
- switch (kind) {
8229
- case "event_ticket": return "Event ticket";
8230
- case "event_series_registration": return "Booking";
8231
- case "appointment": return "Appointment";
8232
- case "membership": return "Membership";
8233
- case "pass": return "Pass";
8234
- case "product": return "Product";
8235
- }
8236
- }
8237
-
8238
8070
  //#endregion
8239
8071
  //#region ../commerce/src/purchase/protectedDepositRefundPolicy.ts
8240
8072
  function planAdminProtectedDepositRefund(input) {
@@ -8313,44 +8145,6 @@ function resolveRequestedAmountCents(request, options) {
8313
8145
 
8314
8146
  //#endregion
8315
8147
  //#region ../commerce/src/purchase/refundRailSplit.ts
8316
- /**
8317
- * For mixed-payment items, compute remaining refundable amount per rail.
8318
- * Must account for prior refunds that already consumed part of each rail.
8319
- *
8320
- * The allocation order (credit before cash) is an accounting convention
8321
- * that determines *how much* goes to each rail — it does NOT imply
8322
- * execution order. The caller decides execution order (typically cash
8323
- * first so Stripe settles before issuing site credit).
8324
- *
8325
- * Pure function — no DB calls. Testable with just numbers.
8326
- */
8327
- function computeRailAwareRefundSplit(originalCashCents, originalCreditCents, priorCashRefunded, priorCreditRefunded, totalRefundCents) {
8328
- const remainingCash = Math.max(0, originalCashCents - priorCashRefunded);
8329
- const remainingCredit = Math.max(0, originalCreditCents - priorCreditRefunded);
8330
- const creditCents = Math.min(remainingCredit, totalRefundCents);
8331
- const cashCents = Math.min(remainingCash, totalRefundCents - creditCents);
8332
- return {
8333
- cashCents: toNonNegativeCents(cashCents),
8334
- creditCents: toNonNegativeCents(creditCents)
8335
- };
8336
- }
8337
- /**
8338
- * Summarize prior successful refunds by rail for a specific order item.
8339
- * Reads from line_allocations in order_refunds records.
8340
- *
8341
- * Pure function — just array reduction.
8342
- */
8343
- function summarizePriorRefundsByRail(refunds, orderItemIds) {
8344
- const hasUnknownMixedAttribution = refunds.some((refund) => refund.refundRail === "mixed" && refund.lineAllocations.some((allocation) => orderItemIds.includes(allocation.orderItemId)));
8345
- if (hasUnknownMixedAttribution) {
8346
- return err({ kind: "mixed_rail_attribution_missing" });
8347
- }
8348
- const totalForRail = (rail) => refunds.filter((refund) => refund.refundRail === rail).flatMap((refund) => refund.lineAllocations).filter((allocation) => orderItemIds.includes(allocation.orderItemId)).reduce((sum, allocation) => sum + allocation.appliedCents, 0);
8349
- return ok({
8350
- cashCents: unsafeAsNonNegativeCents(totalForRail("cash")),
8351
- creditCents: unsafeAsNonNegativeCents(totalForRail("credit"))
8352
- });
8353
- }
8354
8148
  /** Select policy funding once, retaining the recorded source even for site-credit returns. */
8355
8149
  function planBookingRefundFunding(input) {
8356
8150
  const funding = input.allowProtectedDepositOverride ? input.funding : input.policyFunding ?? input.funding;
@@ -8377,6 +8171,34 @@ function planRefundDestinationAllocation(funding, amountCents, method) {
8377
8171
  amountCents: amounts.get(line.id) ?? 0
8378
8172
  }));
8379
8173
  }
8174
+ function fundingLineMatchesSource(line, source) {
8175
+ return source.kind === "credit" ? line.source.kind === "credit_debit" : line.source.kind === "receipt" && line.source.receiptId === source.receiptId;
8176
+ }
8177
+ /**
8178
+ * Names the allocations a new refund takes from. The amount splits across items by what each may still give
8179
+ * back, which may be less than the allocation's capacity when a deposit is protected. The database checks both
8180
+ * caps again under the order lock. A line that gets nothing isn't named, so an item with no money left isn't either.
8181
+ */
8182
+ function planRefundAllocationLines(input) {
8183
+ const amounts = allocateTotalByWeight(input.amountCents, input.capacities.map((line) => ({
8184
+ id: line.orderItemId,
8185
+ weight: line.remainingCents
8186
+ })));
8187
+ const lines = input.funding.filter((line) => fundingLineMatchesSource(line, input.source));
8188
+ return [...amounts].flatMap(([orderItemId, itemCents]) => lines.filter((line) => line.orderItemId === orderItemId).reduce((walk, line) => {
8189
+ const requestedCents = Math.min(walk.left, line.refundableCents);
8190
+ return requestedCents > 0 ? {
8191
+ left: walk.left - requestedCents,
8192
+ planned: [...walk.planned, {
8193
+ allocationId: line.allocationId,
8194
+ requestedCents
8195
+ }]
8196
+ } : walk;
8197
+ }, {
8198
+ left: itemCents,
8199
+ planned: []
8200
+ }).planned);
8201
+ }
8380
8202
 
8381
8203
  //#endregion
8382
8204
  //#region ../commerce/src/purchase/shopRefundPlanning.ts
@@ -8545,9 +8367,88 @@ function orderRefundNeedsReconciliation(refund) {
8545
8367
  return !orderRefundEffectsComplete(refund.entitlementActionStatus) || refund.status === "reconciliation_needed" || refund.status === "failed";
8546
8368
  }
8547
8369
 
8370
+ //#endregion
8371
+ //#region ../commerce/src/purchase/roomWords.ts
8372
+ const PEOPLE_WORD = {
8373
+ guest: "you",
8374
+ staff: "them"
8375
+ };
8376
+ const PLACE_WORD = {
8377
+ women: "women's",
8378
+ men: "men's",
8379
+ mixed: "mixed"
8380
+ };
8381
+ /** The same word at the start of a line. */
8382
+ function placeLabel(place) {
8383
+ const word = PLACE_WORD[place];
8384
+ return word.charAt(0).toUpperCase() + word.slice(1);
8385
+ }
8386
+ const withArticle = (name) => `${/^(?:[aeiou]|8|11|18)/i.test(name) ? "an" : "a"} ${name}`;
8387
+ function bedPhrase(name, place) {
8388
+ return place === null ? `a shared ${name}` : `${withArticle(name)} (shared ${PLACE_WORD[place]} room)`;
8389
+ }
8390
+ function toThemselvesText(name, people, audience) {
8391
+ if (people > 1) return `${people} of ${PEOPLE_WORD[audience]} each have ${withArticle(name)} to ${audience === "guest" ? "yourself" : "themselves"}`;
8392
+ return audience === "guest" ? `You have ${withArticle(name)} to yourself` : `They have ${withArticle(name)} to themselves`;
8393
+ }
8394
+ /** One line of "How you'll stay", or "How they'll stay" in the staff dialog. */
8395
+ function stayLineText(line, audience) {
8396
+ const of = `${line.people} of ${PEOPLE_WORD[audience]}`;
8397
+ switch (line.kind) {
8398
+ case "to_themselves": return toThemselvesText(line.kindName, line.people, audience);
8399
+ case "share": return `${of} share ${withArticle(line.kindName)}`;
8400
+ case "beds": return `${of} ${line.people === 1 ? "has" : "each have"} a bed in ${bedPhrase(line.kindName, line.place)}`;
8401
+ }
8402
+ }
8403
+ function stayNoteText(note, audience) {
8404
+ const they = audience === "guest" ? "you'd" : "they'd";
8405
+ return `There isn't ${withArticle(note.kindName)} free for the ${note.people} of ${PEOPLE_WORD[audience]} together, so ${they} be in separate shared rooms.`;
8406
+ }
8407
+ const morePeopleText = (people) => people === 1 ? "1 more person" : `${people} more people`;
8408
+ const STAY_CHANGED_FOR_GUEST = "Someone else has just booked, so you'd now be in separate rooms. Carry on if that's OK. Here's how you'd stay.";
8409
+ function placementProblemText(problem, audience) {
8410
+ switch (problem.kind) {
8411
+ case "not_enough_places": return `Someone booked the last ${problem.kindName} place while you were ${audience === "guest" ? "choosing" : "adding them"}.`;
8412
+ case "whole_room_needs_more_people": return `${problem.kindName} is for ${problem.forPeople} of ${PEOPLE_WORD[audience]} booking together. Add ${morePeopleText(problem.morePeople)}, or choose another option.`;
8413
+ case "no_longer_together": return audience === "guest" ? STAY_CHANGED_FOR_GUEST : "Someone else has just booked, so they'd now be in separate rooms. Here's how they'd stay. Carry on if that's OK.";
8414
+ case "option_unavailable": return "That room option isn't available any more. Please choose another.";
8415
+ }
8416
+ }
8417
+ /** What to say about a refusal. `siteName` is where a booking made somewhere else can go instead. */
8418
+ function roomBookingRefusalText(refusal, audience) {
8419
+ switch (refusal.kind) {
8420
+ case "rooms_need_choices": return ROOM_REFUSAL_REASON_MESSAGES.roomsNeedChoices;
8421
+ case "not_a_room_event": return "This event doesn't have rooms to choose from.";
8422
+ case "ticket_lines_differ": return "The prices for these rooms have changed. Please check them and choose again.";
8423
+ case "not_enough_places":
8424
+ case "whole_room_needs_more_people":
8425
+ case "no_longer_together":
8426
+ case "option_unavailable": return placementProblemText(refusal, audience);
8427
+ }
8428
+ }
8429
+ /**
8430
+ * The guest's page shows the words for a refusal's reason, with no room to name,
8431
+ * and then asks again: with fresh facts, `placementProblemText` says it better.
8432
+ */
8433
+ const ROOM_REFUSAL_REASON_MESSAGES = {
8434
+ roomNotEnoughPlaces: "Someone booked the last place in that room while you were choosing.",
8435
+ roomNeedsMorePeople: "That room needs more people booking together. Add more people, or choose another option.",
8436
+ roomStayChanged: STAY_CHANGED_FOR_GUEST,
8437
+ roomOptionsChanged: "The room options for this event have changed. Please check them and choose again.",
8438
+ roomsNeedChoices: "Rooms can't be booked here yet. Please book on the organiser's website."
8439
+ };
8440
+
8548
8441
  //#endregion
8549
8442
  //#region ../commerce/src/purchase/event-registration-errors.ts
8550
8443
  const unfinishedBookingAssistanceMessage = "We couldn’t safely find your unfinished booking. Please contact the organiser before trying to book again.";
8444
+ /**
8445
+ * When a pass or membership no longer covers the split the customer saw (another booking used a
8446
+ * credit, or it ended), submit answers with the revised options and one of these.
8447
+ */
8448
+ const fundingChangedMessages = {
8449
+ pass: "Your pass changed since you chose it. Check how you’d like to pay and try again.",
8450
+ membership: "Your membership changed since you chose it. Check how you’d like to pay and try again."
8451
+ };
8551
8452
  const eventRegistrationErrors = {
8552
8453
  invalidAnswers: {
8553
8454
  endsCommand: false,
@@ -8609,6 +8510,11 @@ const eventRegistrationErrors = {
8609
8510
  message: "We couldn't set up payment for this booking, so your place hasn't been reserved and you haven't been charged. Please try again in a few minutes, or contact the organiser if it keeps happening.",
8610
8511
  action: "retry"
8611
8512
  },
8513
+ onlinePaymentUnavailable: {
8514
+ endsCommand: true,
8515
+ message: "Online payment isn't available for this booking, so your place hasn't been reserved and you haven't been charged. Please contact the organiser to book.",
8516
+ action: "none"
8517
+ },
8612
8518
  registrationAttemptEnded: {
8613
8519
  endsCommand: true,
8614
8520
  message: "That booking attempt has ended, so we couldn't finish it. You haven't been charged. Please start your booking again.",
@@ -8619,6 +8525,31 @@ const eventRegistrationErrors = {
8619
8525
  message: "The booking options for this event have changed. Please check the latest options and choose your places again.",
8620
8526
  action: "places"
8621
8527
  },
8528
+ roomNotEnoughPlaces: {
8529
+ endsCommand: false,
8530
+ message: ROOM_REFUSAL_REASON_MESSAGES.roomNotEnoughPlaces,
8531
+ action: "places"
8532
+ },
8533
+ roomNeedsMorePeople: {
8534
+ endsCommand: false,
8535
+ message: ROOM_REFUSAL_REASON_MESSAGES.roomNeedsMorePeople,
8536
+ action: "places"
8537
+ },
8538
+ roomStayChanged: {
8539
+ endsCommand: false,
8540
+ message: ROOM_REFUSAL_REASON_MESSAGES.roomStayChanged,
8541
+ action: "places"
8542
+ },
8543
+ roomOptionsChanged: {
8544
+ endsCommand: false,
8545
+ message: ROOM_REFUSAL_REASON_MESSAGES.roomOptionsChanged,
8546
+ action: "places"
8547
+ },
8548
+ roomsNeedChoices: {
8549
+ endsCommand: false,
8550
+ message: ROOM_REFUSAL_REASON_MESSAGES.roomsNeedChoices,
8551
+ action: "none"
8552
+ },
8622
8553
  registrationAlreadyExists: {
8623
8554
  endsCommand: false,
8624
8555
  message: "You already have a booking for this event. Please check your bookings to see its status. If you need help, contact the organiser.",
@@ -8728,10 +8659,10 @@ function meetsDiscountMinimumTickets(code, ticketsCount) {
8728
8659
  const minimum = discountMinimumTickets(code);
8729
8660
  return minimum !== "misconfigured" && ticketsCount >= minimum;
8730
8661
  }
8731
- function matchesSelectedScope(mode, ids, id) {
8662
+ function matchesSelectedScope(mode, ids$1, id$1) {
8732
8663
  switch (mode) {
8733
8664
  case "all": return true;
8734
- case "selected": return ids.includes(id);
8665
+ case "selected": return ids$1.includes(id$1);
8735
8666
  }
8736
8667
  }
8737
8668
  function matchesEventScope(mode, scopes, context) {
@@ -8760,11 +8691,16 @@ function discountCodeAppliesTo(code, scopes, context, now) {
8760
8691
  }[context.type];
8761
8692
  return enabled && discountCodeAvailabilityMessage(code, now) === null && matchesDiscountContext(code, scopes, context);
8762
8693
  }
8763
- /** Public refusal wording also owns the lifecycle check used by applicability. */
8694
+ /**
8695
+ * Public refusal wording also owns the lifecycle check used by applicability. A gift voucher's code is
8696
+ * switched off once it's redeemed, so an inactive voucher says it's been used; any other inactive code
8697
+ * reads as unknown, so turning a code off doesn't advertise that it existed.
8698
+ */
8764
8699
  function discountCodeAvailabilityMessage(code, now) {
8765
- if (!code.isActive) return "We don't recognise that code.";
8700
+ const voucher = Boolean(code.giftingInstrumentId);
8701
+ if (!code.isActive) return voucher ? "This gift voucher has already been used." : "We don't recognise that code.";
8766
8702
  if (code.startsAt !== null && code.startsAt > now) return "This code isn't active yet.";
8767
- if (code.endsAt !== null && code.endsAt < now) return "This code has ended.";
8703
+ if (code.endsAt !== null && code.endsAt < now) return voucher ? "This gift voucher has expired." : "This code has ended.";
8768
8704
  return null;
8769
8705
  }
8770
8706
  function matchesDiscountContext(code, scopes, context) {
@@ -8926,8 +8862,8 @@ function combinationOffersForSelection(offers, items) {
8926
8862
  const lineIds = new Map(items.map((item) => [item.itemId, item.lineId]));
8927
8863
  return offers.flatMap((offer) => {
8928
8864
  if (offer.kind === "any") return [offer];
8929
- const selected = offer.lineIds.map((id) => lineIds.get(id));
8930
- return selected.every((id) => id !== undefined) ? [{
8865
+ const selected = offer.lineIds.map((id$1) => lineIds.get(id$1));
8866
+ return selected.every((id$1) => id$1 !== undefined) ? [{
8931
8867
  ...offer,
8932
8868
  lineIds: selected
8933
8869
  }] : [];
@@ -8968,8 +8904,8 @@ function planSelectionCombinationPrices(input) {
8968
8904
  function missingOfferLines(input, offer) {
8969
8905
  const selected = new Set(input.lines.map((line) => line.lineId));
8970
8906
  if (offer.kind === "particular") {
8971
- const missing = offer.lineIds.filter((id) => !selected.has(id));
8972
- const added = missing.flatMap((id) => input.addable.filter((line) => line.lineId === id));
8907
+ const missing = offer.lineIds.filter((id$1) => !selected.has(id$1));
8908
+ const added = missing.flatMap((id$1) => input.addable.filter((line) => line.lineId === id$1));
8973
8909
  return added.length === missing.length ? added.sort(compareLine) : null;
8974
8910
  }
8975
8911
  const count = Math.max(0, offer.itemCount - input.lines.length);
@@ -9027,6 +8963,687 @@ function compareCombinationPriceCode(plan, code) {
9027
8963
  return alone.totalCents < combined.totalCents ? alone : combined;
9028
8964
  }
9029
8965
 
8966
+ //#endregion
8967
+ //#region ../commerce/src/purchase/roomVocabulary.ts
8968
+ const ROOM_BOOKING_WAYS = [
8969
+ "private",
8970
+ "shared",
8971
+ "either"
8972
+ ];
8973
+ const ROOM_FOR_WHO = [
8974
+ "mixed",
8975
+ "women",
8976
+ "men",
8977
+ "one_per_room"
8978
+ ];
8979
+ const SHARED_ROOM_ARRANGEMENTS = [
8980
+ "together",
8981
+ "separate",
8982
+ "organiser"
8983
+ ];
8984
+ /** The kind of shared place a guest chose. Nobody is asked their gender: this describes the room. */
8985
+ const ROOM_PLACES = [
8986
+ "women",
8987
+ "men",
8988
+ "mixed"
8989
+ ];
8990
+ const PLACES_FOR = {
8991
+ mixed: ["mixed"],
8992
+ women: ["women"],
8993
+ men: ["men"],
8994
+ one_per_room: ["women", "men"]
8995
+ };
8996
+ /** Which places a room for these people can hold. A one-per-room room becomes one of them with its first guest. */
8997
+ function placesFor(forWho) {
8998
+ return PLACES_FOR[forWho];
8999
+ }
9000
+ /** From a form that keeps its answer about who a room is for while the organiser changes how it's booked. */
9001
+ function roomSetupFrom(way, forWho) {
9002
+ return way === "private" ? { way } : {
9003
+ way,
9004
+ forWho
9005
+ };
9006
+ }
9007
+ function roomSetupColumns(setup) {
9008
+ return setup.way === "private" ? {
9009
+ bookingWay: setup.way,
9010
+ forWho: null
9011
+ } : {
9012
+ bookingWay: setup.way,
9013
+ forWho: setup.forWho
9014
+ };
9015
+ }
9016
+ const MAX_ROOM_BOOKING_PEOPLE = 100;
9017
+ const roomPlaceSchema = z.enum(ROOM_PLACES);
9018
+ const sharedRoomArrangementSchema = z.enum(SHARED_ROOM_ARRANGEMENTS);
9019
+ const roomSetupSchema = z.discriminatedUnion("way", [z.object({ way: z.literal("private") }).strict(), z.object({
9020
+ way: z.enum(["shared", "either"]),
9021
+ forWho: z.enum(ROOM_FOR_WHO)
9022
+ }).strict()]);
9023
+ /** A room's setup from its columns. The columns' own check means a mismatch can't be there, so it's an error if it is. */
9024
+ function parseRoomSetupColumns(columns) {
9025
+ return roomSetupSchema.parse(columns.forWho === null ? { way: columns.bookingWay } : {
9026
+ way: columns.bookingWay,
9027
+ forWho: columns.forWho
9028
+ });
9029
+ }
9030
+ const roomOccupancySchema = z.discriminatedUnion("bookedAs", [
9031
+ z.object({ bookedAs: z.literal("empty") }).strict(),
9032
+ z.object({ bookedAs: z.literal("private") }).strict(),
9033
+ z.object({
9034
+ bookedAs: z.literal("shared"),
9035
+ place: roomPlaceSchema
9036
+ }).strict()
9037
+ ]);
9038
+ const roomPeopleSchema = z.number().int().min(1).max(MAX_ROOM_BOOKING_PEOPLE);
9039
+ /** What someone chose, from a guest, staff or the draft kept through sign-in and payment. */
9040
+ const roomChoicesSchema = z.array(z.discriminatedUnion("way", [
9041
+ z.object({
9042
+ way: z.literal("own"),
9043
+ kindId: z.uuid(),
9044
+ people: roomPeopleSchema
9045
+ }),
9046
+ z.object({
9047
+ way: z.literal("whole_room"),
9048
+ kindId: z.uuid(),
9049
+ people: roomPeopleSchema
9050
+ }),
9051
+ z.object({
9052
+ way: z.literal("sharing"),
9053
+ kindId: z.uuid(),
9054
+ people: roomPeopleSchema,
9055
+ place: roomPlaceSchema
9056
+ })
9057
+ ])).max(MAX_ROOM_BOOKING_PEOPLE);
9058
+ /** What they accepted when they left the rooms step. */
9059
+ const reviewedRoomsSchema = z.array(z.object({
9060
+ kindId: z.uuid(),
9061
+ place: roomPlaceSchema,
9062
+ together: z.boolean()
9063
+ })).max(MAX_ROOM_BOOKING_PEOPLE);
9064
+ /** Placement decides everything from here. */
9065
+ const roomBookingRequestSchema = z.object({
9066
+ choices: roomChoicesSchema,
9067
+ reviewed: reviewedRoomsSchema
9068
+ });
9069
+
9070
+ //#endregion
9071
+ //#region ../commerce/src/purchase/roomPlacement.ts
9072
+ /** The ticket type for someone in a room with this many people in it. */
9073
+ function priceFor(kind, peopleInRoom) {
9074
+ const exact = kind.prices.find((price) => price.peopleInRoom === peopleInRoom);
9075
+ const flat = kind.prices.find((price) => price.peopleInRoom === null);
9076
+ return (exact ?? flat)?.pricingOptionId ?? null;
9077
+ }
9078
+ /** A party bigger than a room takes as many as it needs, filling each. */
9079
+ function roomSizes(people, sleeps) {
9080
+ return Array.from({ length: Math.ceil(people / sleeps) }, (_, index) => Math.min(sleeps, people - index * sleeps));
9081
+ }
9082
+ /** The fewest people above this that a room of this kind has a price for. */
9083
+ function nextPricedSize(kind, size) {
9084
+ const bigger = kind.prices.flatMap((price) => price.peopleInRoom !== null && price.peopleInRoom > size ? [price.peopleInRoom] : []);
9085
+ return bigger.length === 0 ? null : Math.min(...bigger);
9086
+ }
9087
+ /** A private room with no price for this few needs more people, or isn't on offer at all. */
9088
+ function unpricedPrivateRoom(kind, size) {
9089
+ const forPeople = nextPricedSize(kind, size);
9090
+ if (forPeople === null) return {
9091
+ kind: "option_unavailable",
9092
+ kindId: kind.id
9093
+ };
9094
+ return {
9095
+ kind: "whole_room_needs_more_people",
9096
+ kindId: kind.id,
9097
+ kindName: kind.name,
9098
+ forPeople,
9099
+ morePeople: forPeople - size
9100
+ };
9101
+ }
9102
+ function privateUnits(kind, choice) {
9103
+ const sizes = choice.way === "own" ? Array.from({ length: choice.people }, () => 1) : roomSizes(choice.people, kind.sleeps);
9104
+ const priced = sizes.map((size) => ({
9105
+ size,
9106
+ pricingOptionId: priceFor(kind, size)
9107
+ }));
9108
+ const missing = priced.find((unit) => unit.pricingOptionId === null);
9109
+ if (missing) return err(unpricedPrivateRoom(kind, missing.size));
9110
+ return ok(priced.flatMap(({ size, pricingOptionId }) => pricingOptionId === null ? [] : [{
9111
+ kind,
9112
+ size,
9113
+ pricingOptionId
9114
+ }]));
9115
+ }
9116
+ /** Everyone who chose the same sharing option in one booking is one group. */
9117
+ function addSharing(groups, group) {
9118
+ const same = (other) => other.kind.id === group.kind.id && other.place === group.place;
9119
+ return groups.some(same) ? groups.map((other) => same(other) ? {
9120
+ ...other,
9121
+ people: other.people + group.people
9122
+ } : other) : [...groups, group];
9123
+ }
9124
+ function addChoice(request, kind, choice) {
9125
+ if (choice.way !== "sharing") {
9126
+ const units = privateUnits(kind, choice);
9127
+ return units.ok ? ok({
9128
+ ...request,
9129
+ privateUnits: [...request.privateUnits, ...units.value]
9130
+ }) : units;
9131
+ }
9132
+ const pricingOptionId = kind.sleeps > 1 ? priceFor(kind, kind.sleeps) : null;
9133
+ if (pricingOptionId === null) return err({
9134
+ kind: "option_unavailable",
9135
+ kindId: kind.id
9136
+ });
9137
+ return ok({
9138
+ ...request,
9139
+ sharingGroups: addSharing(request.sharingGroups, {
9140
+ kind,
9141
+ place: choice.place,
9142
+ people: choice.people,
9143
+ pricingOptionId
9144
+ })
9145
+ });
9146
+ }
9147
+ function readChoices(facts, choices) {
9148
+ return choices.reduce((request, choice) => {
9149
+ if (!request.ok) return request;
9150
+ const kind = facts.kinds.find((candidate) => candidate.id === choice.kindId);
9151
+ if (!kind || !Number.isInteger(choice.people) || choice.people < 1) return err({
9152
+ kind: "option_unavailable",
9153
+ kindId: choice.kindId
9154
+ });
9155
+ return addChoice(request.value, kind, choice);
9156
+ }, ok({
9157
+ privateUnits: [],
9158
+ sharingGroups: []
9159
+ }));
9160
+ }
9161
+ /** Whether a sharing group still to be placed in this booking could use the room. */
9162
+ function isWantedBy(room, groups) {
9163
+ return groups.some((group) => group.kind.id === room.kindId && roomTakesPlace(room, group.place));
9164
+ }
9165
+ /**
9166
+ * One-way rooms before "either" ones, so flexible rooms stay free longest. Then
9167
+ * rooms this booking's sharing groups can't use, so the order of the choices
9168
+ * can't turn away a booking that fits.
9169
+ */
9170
+ function privateRoomFor(rooms, kindId, groups) {
9171
+ const open$1 = rooms.filter((room) => room.kindId === kindId && room.occupancy.bookedAs === "empty" && room.setup.way !== "shared");
9172
+ return open$1.find((room) => room.setup.way === "private") ?? open$1.find((room) => !isWantedBy(room, groups)) ?? open$1[0];
9173
+ }
9174
+ function placePrivate(working, unit, groups) {
9175
+ const room = privateRoomFor(working.facts.rooms, unit.kind.id, groups);
9176
+ if (!room) return err({
9177
+ kind: "not_enough_places",
9178
+ kindId: unit.kind.id,
9179
+ kindName: unit.kind.name
9180
+ });
9181
+ const seat = {
9182
+ roomId: room.id,
9183
+ kindId: unit.kind.id,
9184
+ kindName: unit.kind.name,
9185
+ pricingOptionId: unit.pricingOptionId,
9186
+ bookedAs: "private",
9187
+ place: null
9188
+ };
9189
+ return ok({
9190
+ ...working,
9191
+ facts: {
9192
+ ...working.facts,
9193
+ rooms: working.facts.rooms.map((other) => other.id === room.id ? {
9194
+ ...other,
9195
+ occupancy: { bookedAs: "private" },
9196
+ freePlaces: 0
9197
+ } : other)
9198
+ },
9199
+ seats: [...working.seats, ...Array.from({ length: unit.size }, () => seat)]
9200
+ });
9201
+ }
9202
+ /** A room becomes a women's or a men's room with its first guest, and never mixes them. */
9203
+ function roomTakesPlace(room, place) {
9204
+ const { setup, occupancy } = room;
9205
+ if (setup.way === "private" || occupancy.bookedAs === "private" || room.freePlaces < 1) return false;
9206
+ return placesFor(setup.forWho).includes(place) && (occupancy.bookedAs === "empty" || occupancy.place === place);
9207
+ }
9208
+ /** One-way rooms first. Within each, part-full rooms before empty ones, which keeps rooms open for private booking. */
9209
+ function sharingRank(room) {
9210
+ return (room.setup.way === "shared" ? 0 : 2) + (room.occupancy.bookedAs === "shared" ? 0 : 1);
9211
+ }
9212
+ function fill(rooms, people) {
9213
+ return rooms.reduce(({ left, taken }, room) => {
9214
+ const count = Math.min(left, room.freePlaces);
9215
+ return {
9216
+ left: left - count,
9217
+ taken: count > 0 ? [...taken, {
9218
+ room,
9219
+ count
9220
+ }] : taken
9221
+ };
9222
+ }, {
9223
+ left: people,
9224
+ taken: []
9225
+ }).taken;
9226
+ }
9227
+ /** A person in each room while there's another room to use, then the rest wherever there's space. */
9228
+ function spread(rooms, people) {
9229
+ const first = rooms.slice(0, people);
9230
+ const leftOver = fill(first.map((room) => ({
9231
+ ...room,
9232
+ freePlaces: room.freePlaces - 1
9233
+ })).concat(rooms.slice(people)), people - first.length);
9234
+ return rooms.flatMap((room) => {
9235
+ const count = (first.includes(room) ? 1 : 0) + (leftOver.find((taken) => taken.room.id === room.id)?.count ?? 0);
9236
+ return count > 0 ? [{
9237
+ room,
9238
+ count
9239
+ }] : [];
9240
+ });
9241
+ }
9242
+ /** All in one room if there's one with space, or else filling each in turn. */
9243
+ function keepTogether(rooms, people) {
9244
+ const whole = rooms.find((room) => room.freePlaces >= people);
9245
+ return whole ? [{
9246
+ room: whole,
9247
+ count: people
9248
+ }] : fill(rooms, people);
9249
+ }
9250
+ /** Rooms later groups can't use come first, and are all this group gets if they're enough. */
9251
+ function roomsLeavingSpaceFor(open$1, people, later) {
9252
+ const spare = open$1.filter((room) => !isWantedBy(room, later));
9253
+ if (spare.reduce((sum, room) => sum + room.freePlaces, 0) >= people) return spare;
9254
+ return [...spare, ...open$1.filter((room) => isWantedBy(room, later))];
9255
+ }
9256
+ function placeSharing(working, group, later) {
9257
+ const { facts } = working;
9258
+ const { kind, place, people } = group;
9259
+ const open$1 = facts.rooms.filter((room) => room.kindId === kind.id && roomTakesPlace(room, place)).map((room, index) => ({
9260
+ room,
9261
+ index
9262
+ })).sort((left, right) => sharingRank(left.room) - sharingRank(right.room) || left.index - right.index).map(({ room }) => room);
9263
+ if (open$1.reduce((sum, room) => sum + room.freePlaces, 0) < people) {
9264
+ return err({
9265
+ kind: "not_enough_places",
9266
+ kindId: kind.id,
9267
+ kindName: kind.name
9268
+ });
9269
+ }
9270
+ const candidates = roomsLeavingSpaceFor(open$1, people, later);
9271
+ const allocations = facts.arrangement === "separate" ? spread(candidates, people) : keepTogether(candidates, people);
9272
+ const countIn = (roomId) => allocations.find((taken) => taken.room.id === roomId)?.count ?? 0;
9273
+ return ok({
9274
+ facts: {
9275
+ ...facts,
9276
+ rooms: facts.rooms.map((room) => countIn(room.id) > 0 ? {
9277
+ ...room,
9278
+ occupancy: {
9279
+ bookedAs: "shared",
9280
+ place
9281
+ },
9282
+ freePlaces: room.freePlaces - countIn(room.id)
9283
+ } : room)
9284
+ },
9285
+ seats: [...working.seats, ...allocations.flatMap(({ room, count }) => Array.from({ length: count }, () => ({
9286
+ roomId: room.id,
9287
+ kindId: kind.id,
9288
+ kindName: kind.name,
9289
+ pricingOptionId: group.pricingOptionId,
9290
+ bookedAs: "shared",
9291
+ place
9292
+ })))],
9293
+ sharing: [...working.sharing, {
9294
+ kindId: kind.id,
9295
+ kindName: kind.name,
9296
+ place,
9297
+ people,
9298
+ together: allocations.length === 1
9299
+ }]
9300
+ });
9301
+ }
9302
+ /** Every room of this kind that can be shared is mixed, so there's no choice of place to mention. */
9303
+ function kindIsAllMixed(facts, kindId) {
9304
+ return facts.rooms.every((room) => room.kindId !== kindId || room.setup.way === "private" || room.setup.forWho === "mixed");
9305
+ }
9306
+ function privateStayLine(unit) {
9307
+ return unit.size === 1 ? {
9308
+ kind: "to_themselves",
9309
+ kindName: unit.kind.name,
9310
+ people: 1
9311
+ } : {
9312
+ kind: "share",
9313
+ kindName: unit.kind.name,
9314
+ people: unit.size
9315
+ };
9316
+ }
9317
+ /** People on their own in one kind of room read as one line. */
9318
+ function mergeToThemselves(lines, line) {
9319
+ const same = (other) => other.kind === "to_themselves" && line.kind === "to_themselves" && other.kindName === line.kindName;
9320
+ return lines.some(same) ? lines.map((other) => same(other) ? {
9321
+ ...other,
9322
+ people: other.people + line.people
9323
+ } : other) : [...lines, line];
9324
+ }
9325
+ function sharingStayLine(facts, outcome) {
9326
+ if (facts.arrangement === "together" && outcome.together && outcome.people > 1) {
9327
+ return {
9328
+ kind: "share",
9329
+ kindName: outcome.kindName,
9330
+ people: outcome.people
9331
+ };
9332
+ }
9333
+ return {
9334
+ kind: "beds",
9335
+ kindName: outcome.kindName,
9336
+ people: outcome.people,
9337
+ place: kindIsAllMixed(facts, outcome.kindId) ? null : outcome.place
9338
+ };
9339
+ }
9340
+ function chargedLines(seats) {
9341
+ const optionIds = [...new Set(seats.map((seat) => seat.pricingOptionId))];
9342
+ return optionIds.map((pricingOptionId) => ({
9343
+ pricingOptionId,
9344
+ quantity: seats.filter((seat) => seat.pricingOptionId === pricingOptionId).length
9345
+ }));
9346
+ }
9347
+ function toPlacement(request, working) {
9348
+ const { facts } = working;
9349
+ return {
9350
+ kind: "placed",
9351
+ guests: working.seats.map((seat, guestPosition) => ({
9352
+ ...seat,
9353
+ guestPosition
9354
+ })),
9355
+ ticketLines: chargedLines(working.seats),
9356
+ sharing: working.sharing,
9357
+ stay: [...request.privateUnits.map(privateStayLine).reduce(mergeToThemselves, []), ...working.sharing.map((outcome) => sharingStayLine(facts, outcome))],
9358
+ notes: facts.arrangement === "together" ? working.sharing.flatMap((outcome) => outcome.together ? [] : [{
9359
+ kind: "separate_rooms",
9360
+ kindName: outcome.kindName,
9361
+ people: outcome.people
9362
+ }]) : []
9363
+ };
9364
+ }
9365
+ /**
9366
+ * Places a booking. Private choices go first, because sharing could otherwise
9367
+ * take the only empty room. A preference about sharing never refuses a booking.
9368
+ */
9369
+ function placeBooking(facts, choices) {
9370
+ const request = readChoices(facts, choices);
9371
+ if (!request.ok) return request.error;
9372
+ const { privateUnits: units, sharingGroups: groups } = request.value;
9373
+ const start = ok({
9374
+ facts,
9375
+ seats: [],
9376
+ sharing: []
9377
+ });
9378
+ const afterPrivate = units.reduce((working, unit) => working.ok ? placePrivate(working.value, unit, groups) : working, start);
9379
+ const placed = groups.reduce((working, group, index) => working.ok ? placeSharing(working.value, group, groups.slice(index + 1)) : working, afterPrivate);
9380
+ return placed.ok ? toPlacement(request.value, placed.value) : placed.error;
9381
+ }
9382
+ /** Each person's price in a whole room still waiting for more people, the same "each" its row shows. */
9383
+ function waitingRoomLines(kind, people) {
9384
+ return roomSizes(people, kind.sleeps).flatMap((size) => {
9385
+ const pricingOptionId = priceFor(kind, size) ?? priceFor(kind, nextPricedSize(kind, size) ?? size);
9386
+ return pricingOptionId ? [{
9387
+ pricingOptionId,
9388
+ quantity: size
9389
+ }] : [];
9390
+ });
9391
+ }
9392
+ /**
9393
+ * What can be counted while the booking as a whole can't go ahead: every choice
9394
+ * that still fits, and a whole room waiting for its other people if there's still
9395
+ * a room for them. A choice whose place has gone isn't counted, so it can't read
9396
+ * as a place they still hold.
9397
+ */
9398
+ function countSoFar(facts, choices) {
9399
+ const { fitting, waiting } = choices.reduce((sofar, choice) => {
9400
+ const placed$1 = placeBooking(facts, [...sofar.fitting, choice]);
9401
+ if (placed$1.kind === "placed") return {
9402
+ ...sofar,
9403
+ fitting: [...sofar.fitting, choice]
9404
+ };
9405
+ if (placed$1.kind !== "whole_room_needs_more_people") return sofar;
9406
+ const withThem = {
9407
+ ...choice,
9408
+ people: choice.people + placed$1.morePeople
9409
+ };
9410
+ return placeBooking(facts, [...sofar.fitting, withThem]).kind === "placed" ? {
9411
+ ...sofar,
9412
+ waiting: [...sofar.waiting, choice]
9413
+ } : sofar;
9414
+ }, {
9415
+ fitting: [],
9416
+ waiting: []
9417
+ });
9418
+ const placed = placeBooking(facts, fitting);
9419
+ const waitingLines = waiting.flatMap((choice) => {
9420
+ const kind = facts.kinds.find((candidate) => candidate.id === choice.kindId);
9421
+ return kind ? waitingRoomLines(kind, choice.people) : [];
9422
+ });
9423
+ const ticketLines = [...placed.kind === "placed" ? placed.ticketLines : [], ...waitingLines];
9424
+ return {
9425
+ people: ticketLines.reduce((sum, line) => sum + line.quantity, 0),
9426
+ ticketLines
9427
+ };
9428
+ }
9429
+ /** The outcome to send with the booking, so the server can tell if it has changed. */
9430
+ function reviewedStay(placement) {
9431
+ return placement.sharing.map(({ kindId, place, together }) => ({
9432
+ kindId,
9433
+ place,
9434
+ together
9435
+ }));
9436
+ }
9437
+ /**
9438
+ * Whether people are now split who weren't told they would be. Being put together
9439
+ * when they'd been warned they wouldn't is good news, and needs no second look.
9440
+ * Only the default setting promises anything about this.
9441
+ */
9442
+ function findLostTogetherness(facts, placement, reviewed) {
9443
+ if (facts.arrangement !== "together") return null;
9444
+ const unseen = placement.sharing.some((outcome) => !outcome.together && !reviewed.some((stay) => stay.kindId === outcome.kindId && stay.place === outcome.place && !stay.together));
9445
+ return unseen ? { kind: "no_longer_together" } : null;
9446
+ }
9447
+
9448
+ //#endregion
9449
+ //#region ../commerce/src/purchase/roomOptions.ts
9450
+ function optionKey(choice) {
9451
+ return choice.way === "sharing" ? `${choice.kindId}:sharing:${choice.place}` : `${choice.kindId}:${choice.way}`;
9452
+ }
9453
+ function sameRoomOption(left, right) {
9454
+ return optionKey(left) === optionKey(right);
9455
+ }
9456
+ const withPeople = (choice, people) => ({
9457
+ ...choice,
9458
+ people
9459
+ });
9460
+ /** The choices with this option set to a number of people. Nobody means it's gone. */
9461
+ function setRoomChoicePeople(choices, option, people) {
9462
+ const others = choices.filter((choice) => !sameRoomOption(choice, option));
9463
+ if (people <= 0) return others;
9464
+ return choices.some((choice) => sameRoomOption(choice, option)) ? choices.map((choice) => sameRoomOption(choice, option) ? withPeople(option, people) : choice) : [...choices, withPeople(option, people)];
9465
+ }
9466
+ /** Every place a room of this kind can be shared as, whoever's in it now. */
9467
+ function sharedPlaces(facts, kindId) {
9468
+ const forWho = facts.rooms.flatMap(({ kindId: roomKind, setup }) => roomKind === kindId && setup.way !== "private" ? [setup.forWho] : []);
9469
+ return ROOM_PLACES.filter((place) => forWho.some((who) => placesFor(who).includes(place)));
9470
+ }
9471
+ function sharingTitle(facts, kindId, place) {
9472
+ return kindIsAllMixed(facts, kindId) ? "Sharing" : `A bed in a shared ${PLACE_WORD[place]} room`;
9473
+ }
9474
+ function wholeRoomDetail(kind, audience) {
9475
+ const sizes = kind.prices.map((price) => price.peopleInRoom ?? 2).filter((size) => size > 1);
9476
+ const fewest = Math.min(...sizes, kind.sleeps);
9477
+ return `For ${fewest < kind.sleeps ? "up to " : ""}${kind.sleeps} of ${audience === "guest" ? "you" : "them"}. Add a place for each.`;
9478
+ }
9479
+ /** The price for the people added so far, or for a full room before there are two of them. */
9480
+ function wholeRoomPrice(kind, people) {
9481
+ return priceFor(kind, people >= 2 ? Math.min(people, kind.sleeps) : kind.sleeps);
9482
+ }
9483
+ /** Sharing first, as most guests want, then the room to yourself. */
9484
+ function optionDrafts(facts, kind, audience) {
9485
+ const rooms = facts.rooms.filter((room) => room.kindId === kind.id);
9486
+ const sharing = kind.sleeps > 1 ? sharedPlaces(facts, kind.id).map((place) => ({
9487
+ choice: {
9488
+ kindId: kind.id,
9489
+ way: "sharing",
9490
+ place
9491
+ },
9492
+ title: sharingTitle(facts, kind.id, place),
9493
+ detail: null,
9494
+ each: false,
9495
+ priceFor: () => priceFor(kind, kind.sleeps)
9496
+ })) : [];
9497
+ const whole = kind.sleeps > 1 && rooms.some((room) => room.setup.way === "private") ? [{
9498
+ choice: {
9499
+ kindId: kind.id,
9500
+ way: "whole_room"
9501
+ },
9502
+ title: "The whole room",
9503
+ detail: wholeRoomDetail(kind, audience),
9504
+ each: true,
9505
+ priceFor: (people) => wholeRoomPrice(kind, people)
9506
+ }] : [];
9507
+ const own = rooms.some((room) => room.setup.way !== "shared") ? [{
9508
+ choice: {
9509
+ kindId: kind.id,
9510
+ way: "own"
9511
+ },
9512
+ title: audience === "guest" ? "On your own" : "On their own",
9513
+ detail: null,
9514
+ each: false,
9515
+ priceFor: () => priceFor(kind, 1)
9516
+ }] : [];
9517
+ return [
9518
+ ...sharing,
9519
+ ...whole,
9520
+ ...own
9521
+ ];
9522
+ }
9523
+ function peopleWithOption(choices, option) {
9524
+ return choices.find((choice) => sameRoomOption(choice, option))?.people ?? 0;
9525
+ }
9526
+ /**
9527
+ * The most people this option could take, asked of placement itself. A choice
9528
+ * that can't stand yet (one person in a room for two) doesn't count against the
9529
+ * others, or adding it would make every other option vanish.
9530
+ */
9531
+ function mostPeopleFor(facts, choices, option) {
9532
+ const others = choices.filter((choice) => !sameRoomOption(choice, option) && placeBooking(facts, [choice]).kind === "placed");
9533
+ const free = facts.rooms.reduce((sum, room) => room.kindId === option.kindId ? sum + room.freePlaces : sum, 0);
9534
+ const fits = (people) => placeBooking(facts, [...others, withPeople(option, people)]).kind === "placed";
9535
+ return Array.from({ length: free }, (_, index) => free - index).find(fits) ?? 0;
9536
+ }
9537
+ function kindOptions(facts, kind, choices, audience) {
9538
+ const options = optionDrafts(facts, kind, audience).flatMap((draft) => {
9539
+ const people = peopleWithOption(choices, draft.choice);
9540
+ const pricingOptionId = draft.priceFor(people);
9541
+ const mostPeople = mostPeopleFor(facts, choices, draft.choice);
9542
+ if (pricingOptionId === null || mostPeople === 0 && people === 0) return [];
9543
+ const { choice, title, detail, each } = draft;
9544
+ return [{
9545
+ key: optionKey(choice),
9546
+ choice,
9547
+ title,
9548
+ detail,
9549
+ each,
9550
+ pricingOptionId,
9551
+ people,
9552
+ mostPeople
9553
+ }];
9554
+ });
9555
+ return {
9556
+ kindId: kind.id,
9557
+ kindName: kind.name,
9558
+ options,
9559
+ fullyBooked: options.length === 0
9560
+ };
9561
+ }
9562
+ /** What to offer for each kind of room. A kind with no price on sale can't be booked, so it isn't listed. */
9563
+ function roomKindOptions(facts, choices, audience) {
9564
+ return facts.kinds.filter((kind) => kind.prices.length > 0).map((kind) => kindOptions(facts, kind, choices, audience));
9565
+ }
9566
+ /**
9567
+ * Every kind on sale has nothing left to offer, asked of placement itself, so a
9568
+ * room with beds that no price can sell still counts as gone. With nothing on sale
9569
+ * at all, it isn't full: bookings just haven't opened, or have closed.
9570
+ */
9571
+ function roomsAreFullyBooked(facts) {
9572
+ const kinds = roomKindOptions(facts, [], "guest");
9573
+ return kinds.length > 0 && kinds.every((kind) => kind.fullyBooked);
9574
+ }
9575
+ /** Whether anyone in this kind of room could end up sharing. */
9576
+ function roomsOfferSharing(facts) {
9577
+ return facts.kinds.some((kind) => kind.sleeps > 1 && sharedPlaces(facts, kind.id).length > 0);
9578
+ }
9579
+ function leftText(count, noun) {
9580
+ if (count < 1 || count > 3) return null;
9581
+ return `${count} ${noun}${count === 1 ? "" : "s"} left`;
9582
+ }
9583
+ /**
9584
+ * What's left of this option, only once there are few enough to matter. A bed is
9585
+ * a place. The whole room and "on your own" both use up a room, so they count
9586
+ * rooms, and the same room can't read as different stock from one row to the next.
9587
+ */
9588
+ function placesLeftText(option, sleeps) {
9589
+ switch (option.choice.way) {
9590
+ case "sharing": return leftText(option.mostPeople, "place");
9591
+ case "whole_room": return leftText(Math.ceil(option.mostPeople / sleeps), "room");
9592
+ case "own": return leftText(option.mostPeople, "room");
9593
+ }
9594
+ }
9595
+
9596
+ //#endregion
9597
+ //#region ../commerce/src/purchase/roomReprice.ts
9598
+ const DAYS_TO_PAY_A_RISE = 7;
9599
+ /** Calendar arithmetic on a YYYY-MM-DD day, which has no time zone to get wrong. */
9600
+ function addDaysToDay(day, days) {
9601
+ const date = new Date(`${day}T00:00:00Z`);
9602
+ date.setUTCDate(date.getUTCDate() + days);
9603
+ return date.toISOString().slice(0, 10);
9604
+ }
9605
+ function repriceContract(input, orderTotalCents, owedCents, previousOwedCents) {
9606
+ const { contract, today } = input;
9607
+ if (!contract) return null;
9608
+ const movedDueDay = owedCents > previousOwedCents && contract.dueDay < today ? addDaysToDay(today, DAYS_TO_PAY_A_RISE) : null;
9609
+ return {
9610
+ totalCents: orderTotalCents,
9611
+ remainingBalanceCents: owedCents,
9612
+ upfrontAmountCents: Math.min(contract.upfrontAmountCents, orderTotalCents),
9613
+ movedDueDay,
9614
+ dueDay: movedDueDay ?? contract.dueDay
9615
+ };
9616
+ }
9617
+ function planRoomReprice(input) {
9618
+ const { item, order, newUnitPriceCents } = input;
9619
+ const newNetCents = Math.max(0, newUnitPriceCents * item.quantity - item.discountCents);
9620
+ const owedByOrderCents = Math.max(0, order.paidCents + order.waivedCents - order.otherItemsNetTotalCents);
9621
+ const chargedCents = Math.max(newNetCents + item.refundedCents, item.collectedCents, owedByOrderCents);
9622
+ const itemSubtotalCents = chargedCents + item.discountCents;
9623
+ const orderSubtotalCents = order.subtotalCents + itemSubtotalCents - item.subtotalCents;
9624
+ const orderTotalCents = Math.max(0, orderSubtotalCents - order.discountCents);
9625
+ const owedCents = Math.max(0, orderTotalCents - order.paidCents - order.waivedCents);
9626
+ const previousOwedCents = Math.max(0, order.subtotalCents - order.discountCents - order.paidCents - order.waivedCents);
9627
+ return {
9628
+ item: {
9629
+ subtotalCents: itemSubtotalCents,
9630
+ netTotalCents: chargedCents
9631
+ },
9632
+ orderSubtotalCents,
9633
+ owedCents,
9634
+ overCents: Math.max(0, chargedCents - newNetCents - item.refundedCents),
9635
+ contract: repriceContract(input, orderTotalCents, owedCents, previousOwedCents)
9636
+ };
9637
+ }
9638
+ /**
9639
+ * What's been kept above what a room now costs, from an item as it stands. This
9640
+ * is what the booking card reads later. Refund availability has the last word on
9641
+ * how much of it can go back.
9642
+ */
9643
+ function roomOverCents(item) {
9644
+ return Math.max(0, item.netTotalCents - item.refundedCents - Math.max(0, item.unitPriceCents * item.quantity - item.discountCents));
9645
+ }
9646
+
9030
9647
  //#endregion
9031
9648
  //#region ../commerce/src/purchase/flexibleBalanceCollection.ts
9032
9649
  function flexibleBalanceCollectionIsAvailable(collection) {
@@ -9091,6 +9708,7 @@ const orderPaymentOperationKeys = [
9091
9708
  "manualReceiptPreparation",
9092
9709
  "waiverPreparation",
9093
9710
  "paymentLinkPreparation",
9711
+ "priceChange",
9094
9712
  "bookingRestore",
9095
9713
  "staffCancellation"
9096
9714
  ];
@@ -9119,6 +9737,38 @@ const orderRefundProtectionSchema = z.object({
9119
9737
  protectedDepositRemainingCents: cents
9120
9738
  }).readonly()).readonly()
9121
9739
  }).readonly();
9740
+ /**
9741
+ * What each item owes and has had. Refunds don't reopen debt, and held credit isn't collected yet.
9742
+ * Cash outstanding is what the database lets a payment or a waiver take: outstanding less held credit.
9743
+ */
9744
+ const orderMoneyItemSchema = z.object({
9745
+ orderItemId: z.string().uuid(),
9746
+ dueCents: cents,
9747
+ collectedCents: cents,
9748
+ waivedCents: cents,
9749
+ outstandingCents: cents,
9750
+ creditHeldCents: cents,
9751
+ cashOutstandingCents: cents,
9752
+ refundedToCustomerCents: cents
9753
+ }).readonly();
9754
+ /** Money a refund can come from. A waiver never appears here, so nothing can name one as a source. */
9755
+ const orderFundingLineSchema = z.object({
9756
+ allocationId: z.string().uuid(),
9757
+ orderItemId: z.string().uuid(),
9758
+ source: z.discriminatedUnion("kind", [z.object({
9759
+ kind: z.literal("receipt"),
9760
+ receiptId: z.string().uuid().transform(unsafeAsOrderPaymentReceiptId),
9761
+ disputed: z.boolean()
9762
+ }), z.object({
9763
+ kind: z.literal("credit_debit"),
9764
+ creditTransactionId: z.string().uuid()
9765
+ })]).readonly(),
9766
+ amountCents: cents,
9767
+ taxCents: cents,
9768
+ settledCents: cents,
9769
+ heldCents: cents,
9770
+ refundableCents: cents
9771
+ }).readonly();
9122
9772
  /** SQL owns the decision. This schema only parses its closed result. */
9123
9773
  const orderPaymentPositionSchema = z.object({
9124
9774
  orderStatus: z.enum([
@@ -9130,6 +9780,8 @@ const orderPaymentPositionSchema = z.object({
9130
9780
  "failed"
9131
9781
  ]),
9132
9782
  refundProtection: orderRefundProtectionSchema,
9783
+ items: z.array(orderMoneyItemSchema).readonly(),
9784
+ funding: z.array(orderFundingLineSchema).readonly(),
9133
9785
  amounts: z.object({
9134
9786
  totalCents: cents,
9135
9787
  collectedCents: cents,
@@ -9175,7 +9827,8 @@ const orderPaymentPositionSchema = z.object({
9175
9827
  expiryRelease: orderPaymentAdmissionSchema,
9176
9828
  manualReceiptPreparation: orderPaymentAdmissionSchema,
9177
9829
  waiverPreparation: orderPaymentAdmissionSchema,
9178
- paymentLinkPreparation: orderPaymentAdmissionSchema
9830
+ paymentLinkPreparation: orderPaymentAdmissionSchema,
9831
+ priceChange: orderPaymentAdmissionSchema
9179
9832
  }).readonly(),
9180
9833
  paymentSelection: z.object({
9181
9834
  kind: z.enum(["full", "custom"]),
@@ -9326,6 +9979,8 @@ function parseArchivedOrderPaymentPosition(snapshot) {
9326
9979
  subject: { kind: "none" },
9327
9980
  funding: []
9328
9981
  },
9982
+ items: [],
9983
+ funding: [],
9329
9984
  paymentSelection: {
9330
9985
  kind: "full",
9331
9986
  minimumCents: 0,
@@ -9344,6 +9999,18 @@ function parseArchivedOrderPaymentPosition(snapshot) {
9344
9999
  currency: snapshot.currency
9345
10000
  });
9346
10001
  }
10002
+ /** The credit paying for an item, whether it's still held or already spent. */
10003
+ function orderItemCreditCents(position, orderItemId) {
10004
+ return (position.items.find((item) => item.orderItemId === orderItemId)?.creditHeldCents ?? 0) + position.funding.filter((line) => line.orderItemId === orderItemId && line.source.kind === "credit_debit").reduce((sum, line) => sum + line.amountCents, 0);
10005
+ }
10006
+ /** Money on this item that can still go back to the customer: not settled, not held for a refund in flight. */
10007
+ function orderItemRefundableCents(position, orderItemId) {
10008
+ return position.funding.filter((line) => line.orderItemId === orderItemId).reduce((total, line) => total + line.refundableCents, 0);
10009
+ }
10010
+ /** Money receipts have put on an item. Applied receipts only: the position leaves out the rest. */
10011
+ function orderItemReceiptCents(position, orderItemId) {
10012
+ return position.funding.filter((line) => line.orderItemId === orderItemId && line.source.kind === "receipt").reduce((sum, line) => sum + line.amountCents, 0);
10013
+ }
9347
10014
  /** Retain per-item SQL caps alongside their source totals; allocators never rebuild them. */
9348
10015
  function projectOrderRefundExposure(protection, paymentReceiptId, orderItemIds) {
9349
10016
  const funding = protection.funding.filter((line) => line.paymentReceiptId === paymentReceiptId && orderItemIds.includes(line.orderItemId));
@@ -9362,13 +10029,34 @@ function projectOrderRefundExposure(protection, paymentReceiptId, orderItemIds)
9362
10029
  protectedDepositRemainingCents: toNonNegativeCents(funding.reduce((sum, line) => sum + line.protectedDepositRemainingCents, 0))
9363
10030
  };
9364
10031
  }
10032
+ /** Applied credit is separate from receipts; credit reservations are never passed here. */
10033
+ function collectedPaymentSource(receipt, amounts) {
10034
+ if (amounts.creditCents <= 0) return {
10035
+ ...receipt,
10036
+ amountCents: amounts.receiptCents
10037
+ };
10038
+ return amounts.receiptCents > 0 ? {
10039
+ kind: "mixed",
10040
+ receipt: {
10041
+ ...receipt,
10042
+ amountCents: amounts.receiptCents
10043
+ },
10044
+ creditCents: amounts.creditCents
10045
+ } : {
10046
+ kind: "credit",
10047
+ amountCents: amounts.creditCents
10048
+ };
10049
+ }
10050
+ function collectedPaymentCents(source) {
10051
+ return source.kind === "mixed" ? source.receipt.amountCents + source.creditCents : source.amountCents;
10052
+ }
9365
10053
 
9366
10054
  //#endregion
9367
10055
  //#region ../commerce/src/purchase/orderPaymentLabels.ts
9368
10056
  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.";
9369
10057
  function orderPaymentLabelFormatters(currency, context) {
9370
10058
  return {
9371
- money: (cents$2) => formatCurrencyAmount(cents$2, currency, { decimals: "auto" }),
10059
+ money: (cents$3) => formatCurrencyAmount(cents$3, currency, { decimals: "auto" }),
9372
10060
  day: (day) => formatDate(day, context, {
9373
10061
  date: "short",
9374
10062
  year: "omit"
@@ -9404,13 +10092,13 @@ function decideBookingOutcome({ lifecycle, collection }) {
9404
10092
  }
9405
10093
  function decideStillToPay({ amounts, collection, deadline }) {
9406
10094
  if (collection.kind !== "available" || amounts.remainderCents === 0) return { kind: "nothing" };
9407
- const cents$2 = amounts.remainderCents;
10095
+ const cents$3 = amounts.remainderCents;
9408
10096
  return deadline.kind === "none" ? {
9409
10097
  kind: "no_deadline",
9410
- cents: cents$2
10098
+ cents: cents$3
9411
10099
  } : {
9412
10100
  kind: deadline.kind,
9413
- cents: cents$2,
10101
+ cents: cents$3,
9414
10102
  day: effectiveDueDay(deadline)
9415
10103
  };
9416
10104
  }
@@ -9737,10 +10425,11 @@ const eventRegistrationSummarySchema = z.object({
9737
10425
  });
9738
10426
  const bookingOutcomesSchema = z.tuple([eventBookingOutcomeSchema]).rest(eventBookingOutcomeSchema).readonly().refine((outcomes) => outcomes.length <= MAX_EVENT_BOOKING_SELECTION_ITEMS, "Too many booking outcomes");
9739
10427
  const bookingReferencesSchema = z.tuple([eventRegistrationStatusReferenceSchema]).rest(eventRegistrationStatusReferenceSchema).readonly().refine((references) => references.length <= MAX_EVENT_BOOKING_SELECTION_ITEMS, "Too many booking references");
9740
- const registrationIdsSchema = z.tuple([uuid]).rest(uuid).readonly().refine((ids) => ids.length <= MAX_EVENT_BOOKING_SELECTION_ITEMS, "Too many registrations");
10428
+ const registrationIdsSchema = z.tuple([uuid]).rest(uuid).readonly().refine((ids$1) => ids$1.length <= MAX_EVENT_BOOKING_SELECTION_ITEMS, "Too many registrations");
9741
10429
  const eventRegisterResponseSchema = z.discriminatedUnion("kind", [
9742
10430
  z.object({
9743
10431
  kind: z.literal("bookingComplete"),
10432
+ submissionPayment: submissionPaymentSchema.nullable().optional(),
9744
10433
  outcome: eventBookingOutcomeSchema,
9745
10434
  outcomes: bookingOutcomesSchema.optional(),
9746
10435
  summary: eventRegistrationSummarySchema,
@@ -9774,6 +10463,13 @@ const eventRegisterResponseSchema = z.discriminatedUnion("kind", [
9774
10463
  emailFollowupMessage: z.string().optional()
9775
10464
  }),
9776
10465
  ...decorations
10466
+ }),
10467
+ z.object({
10468
+ kind: z.literal("fundingChanged"),
10469
+ entitlementKind: z.enum(["pass", "membership"]),
10470
+ message: z.string(),
10471
+ funding: eventSelectionFundingSchema,
10472
+ ...decorations
9777
10473
  })
9778
10474
  ]).superRefine((response, ctx) => {
9779
10475
  if (response.kind === "bookingComplete") validateOutcomeList(response, ctx);
@@ -9782,6 +10478,7 @@ const eventRegisterResponseSchema = z.discriminatedUnion("kind", [
9782
10478
  const checkoutStatusArms = [
9783
10479
  z.object({
9784
10480
  kind: z.literal("resolved"),
10481
+ submissionPayment: submissionPaymentSchema.nullable().optional(),
9785
10482
  outcome: eventBookingOutcomeSchema,
9786
10483
  outcomes: bookingOutcomesSchema.optional()
9787
10484
  }).superRefine(validateOutcomeList),
@@ -14982,6 +15679,38 @@ const ENDPOINT_DEFINITIONS = {
14982
15679
  "server:internal_error"
14983
15680
  ]
14984
15681
  },
15682
+ getEventRoomsRoster: {
15683
+ errors: [],
15684
+ path: "/sites/{siteId}/bookings/event-series/{seriesId}/rooms",
15685
+ method: "GET",
15686
+ tags: ["site-{siteId}", "event-series-{seriesId}"],
15687
+ auth: "user",
15688
+ responseKind: "json"
15689
+ },
15690
+ getChangeEventRoomOptions: {
15691
+ errors: [],
15692
+ path: "/sites/{siteId}/bookings/event-series/{seriesId}/rooms/change/options",
15693
+ method: "GET",
15694
+ tags: [
15695
+ "site-{siteId}",
15696
+ "event-series-{seriesId}",
15697
+ "bookings"
15698
+ ],
15699
+ auth: "user",
15700
+ responseKind: "json"
15701
+ },
15702
+ changeEventRoom: {
15703
+ errors: [],
15704
+ path: "/sites/{siteId}/bookings/event-series/{seriesId}/rooms/change",
15705
+ method: "POST",
15706
+ tags: [
15707
+ "site-{siteId}",
15708
+ "event-series-{seriesId}",
15709
+ "bookings"
15710
+ ],
15711
+ auth: "user",
15712
+ responseKind: "json"
15713
+ },
14985
15714
  listEventSeriesAttendees: {
14986
15715
  path: "/sites/{siteId}/bookings/event-series/{seriesId}/attendees",
14987
15716
  method: "GET",
@@ -17973,6 +18702,15 @@ const mediaUsageLocationSchema = z.discriminatedUnion("kind", [
17973
18702
  serviceId: identifierSchema,
17974
18703
  serviceTitle: z.string()
17975
18704
  }),
18705
+ z.object({
18706
+ kind: z.literal("eventRoomKind"),
18707
+ siteId: identifierSchema,
18708
+ roomKindId: identifierSchema,
18709
+ roomKindName: z.string(),
18710
+ eventSeriesId: identifierSchema,
18711
+ eventId: identifierSchema.nullable(),
18712
+ eventTitle: z.string()
18713
+ }),
17976
18714
  z.object({
17977
18715
  kind: z.literal("newsletterCampaign"),
17978
18716
  siteId: identifierSchema,
@@ -20300,7 +21038,7 @@ function validateLayoutGridConfiguration(data, ctx) {
20300
21038
  schemas.forEach((schema) => {
20301
21039
  const parsed = itemFieldsSchema.safeParse(schema);
20302
21040
  if (!parsed.success) return;
20303
- if (!requiredIds.every((id) => parsed.data.fields.some((field) => field.id === id))) {
21041
+ if (!requiredIds.every((id$1) => parsed.data.fields.some((field) => field.id === id$1))) {
20304
21042
  ctx.addIssue({
20305
21043
  code: "custom",
20306
21044
  path: ["ui", "layoutGridRowField"],
@@ -20794,6 +21532,7 @@ function validateVariantKeys(data, ctx) {
20794
21532
  const BlockKind = z.string();
20795
21533
  const blockSchema = z.object({
20796
21534
  id: z.string().nullable(),
21535
+ identifier: z.string().nullable().optional(),
20797
21536
  kind: BlockKind,
20798
21537
  purpose: z.string().min(1),
20799
21538
  content: z.record(z.string(), z.unknown()).optional(),
@@ -21110,8 +21849,8 @@ const sdkWorkflowConfigSchema = z.object({
21110
21849
  confirmation: sdkWorkflowConfirmationSchema.optional()
21111
21850
  }).strict();
21112
21851
  const sdkWorkflowsSchema = z.array(sdkWorkflowConfigSchema).max(SDK_WORKFLOW_MAX_COUNT, "Maximum 50 workflows per site").refine((workflows) => {
21113
- const ids = workflows.map((workflow) => workflow.id);
21114
- return ids.length === new Set(ids).size;
21852
+ const ids$1 = workflows.map((workflow) => workflow.id);
21853
+ return ids$1.length === new Set(ids$1).size;
21115
21854
  }, { message: "Workflow IDs must be unique" }).optional();
21116
21855
  const riverbankSiteConfigInputSchema = z.object({
21117
21856
  siteId: z.string().uuid(),
@@ -21122,8 +21861,8 @@ const riverbankSiteConfigInputSchema = z.object({
21122
21861
  styles: sdkSiteStyleConfigSchema.optional(),
21123
21862
  layout: sdkSiteLayoutConfigSchema.optional(),
21124
21863
  customBlocks: z.array(sdkCustomBlockInputSchema).max(100, "Maximum 100 custom blocks per site").refine((blocks) => {
21125
- const ids = blocks.map((b) => b.id);
21126
- return ids.length === new Set(ids).size;
21864
+ const ids$1 = blocks.map((b) => b.id);
21865
+ return ids$1.length === new Set(ids$1).size;
21127
21866
  }, { message: "Block IDs must be unique" }).optional(),
21128
21867
  blockFieldOptions: sdkBlockFieldOptionsMapSchema,
21129
21868
  blockFieldExtensions: sdkBlockFieldExtensionsInputSchema.optional(),
@@ -22142,11 +22881,11 @@ function writeErrorDetails(details) {
22142
22881
  console.error("[unprintable details]");
22143
22882
  }
22144
22883
  function tableAsObjects(headers, rows) {
22145
- return rows.map((row) => Object.fromEntries(headers.map((header, index) => [header, row[index] ?? ""])));
22884
+ return rows.map((row) => Object.fromEntries(headers.map((header$1, index) => [header$1, row[index] ?? ""])));
22146
22885
  }
22147
22886
  function writeHumanTable(headers, rows) {
22148
- const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length)));
22149
- console.log(headers.map((header, index) => header.padEnd(widths[index] ?? header.length)).join(" "));
22887
+ const widths = headers.map((header$1, index) => Math.max(header$1.length, ...rows.map((row) => (row[index] ?? "").length)));
22888
+ console.log(headers.map((header$1, index) => header$1.padEnd(widths[index] ?? header$1.length)).join(" "));
22150
22889
  console.log(widths.map((width) => "-".repeat(width)).join(" "));
22151
22890
  for (const row of rows) {
22152
22891
  console.log(row.map((cell, index) => (cell ?? "").padEnd(widths[index] ?? 0)).join(" "));
@@ -23729,14 +24468,6 @@ function parsePublicProductCategorySelector(value) {
23729
24468
 
23730
24469
  //#endregion
23731
24470
  //#region ../api/src/pageReadResponseCache.ts
23732
- var CacheProbeMiss = class extends Error {};
23733
- /** Next has no response-dependent fetch TTL. Only the matching policy may store a page read. */
23734
- var UncachedPageRead = class extends Error {
23735
- constructor(snapshot) {
23736
- super("Page read belongs to another cache policy");
23737
- this.snapshot = snapshot;
23738
- }
23739
- };
23740
24471
  function isRecord$7(value) {
23741
24472
  return typeof value === "object" && value !== null && !Array.isArray(value);
23742
24473
  }
@@ -23751,134 +24482,146 @@ function envelopePage(body) {
23751
24482
  const data = isRecord$7(body) && body.success === true && isRecord$7(body.data) ? body.data : null;
23752
24483
  return data?.type === "content" && isRecord$7(data.content) ? data.content : data;
23753
24484
  }
23754
- function admit(snapshot) {
24485
+ function parseBody(body) {
23755
24486
  try {
23756
- const body = JSON.parse(snapshot.body);
23757
- const page = envelopePage(body);
23758
- if (snapshot.status === 200 && isResolvedPage(page)) return {
23759
- resolved: true,
24487
+ return JSON.parse(body);
24488
+ } catch {
24489
+ return null;
24490
+ }
24491
+ }
24492
+ const header = (snapshot, name) => snapshot.headers.find(([key]) => key.toLowerCase() === name)?.[1];
24493
+ /** Only a complete, resolved page is stored. Anything else passes through and keeps the policy its failure names. */
24494
+ function admit(snapshot) {
24495
+ const page = envelopePage(parseBody(snapshot.body));
24496
+ if (snapshot.status === 200 && isResolvedPage(page)) {
24497
+ if (header(snapshot, PAGE_READ_STORAGE_HEADER) === "no-store") return {
24498
+ kind: "pass-through",
24499
+ dependencies: "availability"
24500
+ };
24501
+ return {
24502
+ kind: "store",
23760
24503
  dependencies: page.dependencies
23761
24504
  };
23762
- } catch {}
24505
+ }
23763
24506
  return {
23764
- resolved: false,
23765
- dependencies: snapshot.status === 200 || snapshot.headers.some(([key, value]) => key === "x-riverbank-page-dependencies" && value === "availability") ? "availability" : "content"
23766
- };
23767
- }
23768
- /** A scoped transport read is shared with Next's background refresh, never across requests. */
23769
- function liveResponse(read) {
23770
- const pending = new Map();
23771
- return () => {
23772
- const existing = pending.get("response");
23773
- if (existing) return existing;
23774
- const response = read().then(async (value) => ({
23775
- body: await value.text(),
23776
- status: value.status,
23777
- headers: [...value.headers.entries()],
23778
- cachedAt: Date.now()
23779
- }));
23780
- pending.set("response", response);
23781
- return response;
24507
+ kind: "pass-through",
24508
+ dependencies: snapshot.status === 200 || header(snapshot, PAGE_READ_DEPENDENCIES_HEADER) === "availability" ? "availability" : "content"
23782
24509
  };
23783
24510
  }
23784
- /** Neutral probes do not register a policy; the chosen entry is then checked with its real tags. */
23785
- async function readPolicy(input, probe = false) {
23786
- const policy = buildPageReadCachePolicy(input.siteId, input.dependency);
23787
- const revalidate = Math.min(policy.revalidate, input.maxAge ?? policy.revalidate);
23788
- const cached = input.cache(async () => {
23789
- const snapshot$1 = await input.read();
23790
- const admission = admit(snapshot$1);
23791
- if (!admission.resolved || admission.dependencies !== input.dependency) throw new UncachedPageRead(snapshot$1);
23792
- return snapshot$1;
23793
- }, [
23794
- "page-read-envelope-v2",
23795
- input.key,
23796
- input.dependency
23797
- ], probe ? {
23798
- revalidate: false,
23799
- tags: []
23800
- } : {
23801
- ...policy,
23802
- revalidate
23803
- });
23804
- const snapshot = await cached();
23805
- if (Date.now() - snapshot.cachedAt < revalidate * 1e3) return snapshot;
23806
- return probe ? null : input.read();
23807
- }
23808
- async function probePolicy(input) {
23809
- return readPolicy({
23810
- ...input,
23811
- read: async () => {
23812
- throw new CacheProbeMiss();
23813
- }
23814
- }, true).catch((error) => {
23815
- if (error instanceof CacheProbeMiss) return null;
23816
- throw error;
23817
- });
24511
+ /**
24512
+ * One cache entry per request, judged by the policy it is looked up with. Content is looked up first, so a
24513
+ * plain page costs one lookup and never registers the availability policy. A page whose snapshot depends on
24514
+ * availability is looked up again under that policy, which checks its tags and 60-second budget. A snapshot
24515
+ * past its own budget is never served: the live read replaces it.
24516
+ */
24517
+ function planPageRead(state, now, budgetSeconds) {
24518
+ const subject = state.live ?? state.cached;
24519
+ if (!subject) return {
24520
+ kind: "lookup",
24521
+ dependencies: "content"
24522
+ };
24523
+ const { dependencies } = admit(subject);
24524
+ if (!state.lookedUp.includes(dependencies)) return {
24525
+ kind: "lookup",
24526
+ dependencies
24527
+ };
24528
+ if (state.live) return {
24529
+ kind: "serve",
24530
+ snapshot: state.live
24531
+ };
24532
+ return now - subject.cachedAt < budgetSeconds(dependencies) * 1e3 ? {
24533
+ kind: "serve",
24534
+ snapshot: subject
24535
+ } : { kind: "read-live" };
23818
24536
  }
23819
- /** Read in a framework cache scope, but never store an unclassified or failed response. */
23820
- async function readInCacheScope(cache, key, read) {
24537
+ /**
24538
+ * `unstable_cache` stores whatever its callback returns, so a response that must not be kept leaves the
24539
+ * callback by this one exception, which `lookup` turns back into a value straight away.
24540
+ */
24541
+ var PassThroughResponse = class extends Error {
24542
+ constructor(snapshot) {
24543
+ super("Page read must not be stored");
24544
+ this.snapshot = snapshot;
24545
+ }
24546
+ };
24547
+ async function lookup(input, dependencies) {
24548
+ const { tags: tags$1 } = buildPageReadCachePolicy(input.siteId, dependencies);
24549
+ const load = async () => {
24550
+ const snapshot = await input.live();
24551
+ if (admit(snapshot).kind === "pass-through") throw new PassThroughResponse(snapshot);
24552
+ return snapshot;
24553
+ };
23821
24554
  try {
23822
- return await cache(async () => {
23823
- throw new UncachedPageRead(await read());
23824
- }, ["page-read-live-v2", key], {
23825
- revalidate: false,
23826
- tags: []
23827
- })();
24555
+ return {
24556
+ cached: await input.cache(load, ["page-read-envelope-v3", input.key], {
24557
+ revalidate: input.budgetSeconds(dependencies),
24558
+ tags: tags$1
24559
+ })(),
24560
+ live: null
24561
+ };
23828
24562
  } catch (error) {
23829
- if (error instanceof UncachedPageRead) return error.snapshot;
24563
+ if (error instanceof PassThroughResponse) return {
24564
+ cached: null,
24565
+ live: error.snapshot
24566
+ };
23830
24567
  throw error;
23831
24568
  }
23832
24569
  }
23833
- async function selectResponse(input) {
23834
- const candidate = await probePolicy({
23835
- ...input,
23836
- dependency: "content"
23837
- }) ?? await probePolicy({
23838
- ...input,
23839
- dependency: "availability"
23840
- });
23841
- if (candidate) {
23842
- try {
23843
- const checked = await readPolicy({
23844
- ...input,
23845
- dependency: admit(candidate).dependencies
24570
+ async function runPlan(input, state) {
24571
+ const step = planPageRead(state, Date.now(), input.budgetSeconds);
24572
+ switch (step.kind) {
24573
+ case "serve": return step.snapshot;
24574
+ case "read-live": return runPlan(input, {
24575
+ ...state,
24576
+ live: await input.live()
24577
+ });
24578
+ case "lookup": {
24579
+ const found = await lookup(input, step.dependencies);
24580
+ return runPlan(input, {
24581
+ lookedUp: [...state.lookedUp, step.dependencies],
24582
+ cached: found.cached ?? state.cached,
24583
+ live: state.live ?? found.live
23846
24584
  });
23847
- if (checked) return checked;
23848
- } catch (error) {
23849
- if (error instanceof UncachedPageRead) return storeResponse(input, error.snapshot);
23850
- throw error;
23851
24585
  }
23852
24586
  }
23853
- return storeResponse(input, await readInCacheScope(input.cache, input.key, input.read));
23854
24587
  }
23855
- async function storeResponse(input, snapshot) {
23856
- const admission = admit(snapshot);
23857
- try {
23858
- return await readPolicy({
23859
- ...input,
23860
- key: admission.resolved ? input.key : `${input.key}:refusal:${snapshot.status}`,
23861
- dependency: admission.dependencies,
23862
- read: async () => snapshot
23863
- }) ?? snapshot;
23864
- } catch (error) {
23865
- if (error instanceof UncachedPageRead) return error.snapshot;
23866
- throw error;
23867
- }
24588
+ /**
24589
+ * One transport read per page read, shared by a miss, a stale entry's refresh and the live fallback.
24590
+ * It starts only when one of them asks for it.
24591
+ */
24592
+ function sharedRead(read) {
24593
+ const transport = { started: null };
24594
+ return () => transport.started ??= read().then(async (value) => ({
24595
+ body: await value.text(),
24596
+ status: value.status,
24597
+ headers: [...value.headers.entries()],
24598
+ cachedAt: Date.now()
24599
+ }));
23868
24600
  }
23869
24601
  async function cachePageReadResponse(input) {
23870
- if (!input.cache) return input.read();
23871
- const result = await selectResponse({
23872
- ...input,
24602
+ if (!input.cache || input.maxAge !== undefined && input.maxAge <= 0) return input.read();
24603
+ const maxAge = input.maxAge;
24604
+ const budgetSeconds = (dependencies) => {
24605
+ const policy = buildPageReadCachePolicy(input.siteId, dependencies).revalidate;
24606
+ return maxAge === undefined ? policy : Math.min(policy, maxAge);
24607
+ };
24608
+ const result = await runPlan({
23873
24609
  cache: input.cache,
23874
- read: liveResponse(input.read)
24610
+ key: input.key,
24611
+ siteId: input.siteId,
24612
+ live: sharedRead(input.read),
24613
+ budgetSeconds
24614
+ }, {
24615
+ lookedUp: [],
24616
+ cached: null,
24617
+ live: null
23875
24618
  });
23876
24619
  return new Response(result.body, {
23877
24620
  status: result.status,
23878
24621
  headers: result.headers
23879
24622
  });
23880
24623
  }
23881
- /** Result adapters use this for cache fallbacks that did not return through the HTTP transport. */
24624
+ /** Result adapters use this when the SDK served a page without the HTTP transport (memory, durable or prebuild fallback). */
23882
24625
  async function observePageReadPolicy(cache, siteId, payload) {
23883
24626
  if (!cache) return;
23884
24627
  const dependency = pageReadDependencies(payload);
@@ -24575,7 +25318,14 @@ async function parseJsonSuccess(endpoint, response, config, decoder) {
24575
25318
  if (!raw.trim()) return buildSuccessEnvelope(coerceResponse(undefined), requestId);
24576
25319
  const parsed = decodeSuccessJson(raw, endpoint, response, config, decoder);
24577
25320
  requireUsableCommitProjection(response, parsed);
24578
- return successJsonEnvelope(parsed, requestId);
25321
+ const envelope = successJsonEnvelope(parsed, requestId);
25322
+ return envelope.success && response.headers.get(PAGE_READ_STORAGE_HEADER) === "no-store" ? {
25323
+ ...envelope,
25324
+ meta: {
25325
+ ...envelope.meta,
25326
+ storage: "no-store"
25327
+ }
25328
+ } : envelope;
24579
25329
  }
24580
25330
  function decodeSuccessJson(raw, endpoint, response, config, decoder) {
24581
25331
  try {
@@ -24867,6 +25617,7 @@ const BOOKING_ACTIVITY_TYPE_VALUES = [
24867
25617
  "appointment_requested",
24868
25618
  "appointment_moved",
24869
25619
  "event_booking_moved",
25620
+ "event_room_changed",
24870
25621
  "event_booking_restored",
24871
25622
  "event_booking_ticket_changed",
24872
25623
  "waitlist_joined",
@@ -27075,12 +27826,12 @@ function buildDashboardSiteNavPlan(ctx) {
27075
27826
  return ctx.publicExperience === "hosted_booking" ? arrangeBookingPageNav(visible) : arrangeWebsiteNav(visible, ctx.bookingsVisible === true);
27076
27827
  }
27077
27828
  function arrangeBookingPageNav(visible) {
27078
- return bookingPageSurfaceOrder.flatMap((id) => {
27079
- const entry = visible.find((candidate) => candidate.id === id);
27829
+ return bookingPageSurfaceOrder.flatMap((id$1) => {
27830
+ const entry = visible.find((candidate) => candidate.id === id$1);
27080
27831
  return entry ? [{
27081
27832
  kind: "link",
27082
- id,
27083
- label: bookingPageLabels[id] ?? entry.label
27833
+ id: id$1,
27834
+ label: bookingPageLabels[id$1] ?? entry.label
27084
27835
  }] : [];
27085
27836
  });
27086
27837
  }
@@ -32283,10 +33034,10 @@ function diffIdentifiedArrays(localById, remoteById, path$3, options) {
32283
33034
  const remoteOrder = Array.from(remoteById.keys());
32284
33035
  const reorderDiff = buildReorderDiff(localOrder, remoteOrder, remoteById, path$3);
32285
33036
  const itemDiffs = [];
32286
- for (const id of collectSortedIdentityKeys(localOrder, remoteOrder)) {
32287
- const local = localById.get(id);
32288
- const remote = remoteById.get(id);
32289
- const nextPath = [...path$3, itemSegment(id)];
33037
+ for (const id$1 of collectSortedIdentityKeys(localOrder, remoteOrder)) {
33038
+ const local = localById.get(id$1);
33039
+ const remote = remoteById.get(id$1);
33040
+ const nextPath = [...path$3, itemSegment(id$1)];
32290
33041
  if (local && !remote) {
32291
33042
  itemDiffs.push({
32292
33043
  kind: "added",
@@ -33078,9 +33829,9 @@ function buildJsonDiff(diff, local, remote, mode) {
33078
33829
  //#endregion
33079
33830
  //#region src/sync/pullDiff.ts
33080
33831
  function buildLookup(values, getIdentifier) {
33081
- const lookup = new Map();
33082
- for (const value of values) lookup.set(getIdentifier(value), value);
33083
- return lookup;
33832
+ const lookup$1 = new Map();
33833
+ for (const value of values) lookup$1.set(getIdentifier(value), value);
33834
+ return lookup$1;
33084
33835
  }
33085
33836
  function recordBasicPullDiff(summary, type) {
33086
33837
  summary[type]++;
@@ -33133,12 +33884,12 @@ function createFormsSummary() {
33133
33884
  };
33134
33885
  }
33135
33886
  function buildLocalEntriesLookup(local) {
33136
- const lookup = new Map();
33137
- if (!local) return lookup;
33887
+ const lookup$1 = new Map();
33888
+ if (!local) return lookup$1;
33138
33889
  for (const [contentType, entries] of local.entries) {
33139
- lookup.set(contentType, buildLookup(entries, (entry) => entry.identifier));
33890
+ lookup$1.set(contentType, buildLookup(entries, (entry) => entry.identifier));
33140
33891
  }
33141
- return lookup;
33892
+ return lookup$1;
33142
33893
  }
33143
33894
  function classifyPullEntry(remoteEntry, localEntry, contentType) {
33144
33895
  if (!localEntry) {
@@ -33465,9 +34216,9 @@ function appendOperationSections$1(lines, category, diffs, operations, formatIte
33465
34216
  }
33466
34217
  }
33467
34218
  function buildDataLookup(entries) {
33468
- const lookup = new Map();
33469
- for (const entry of entries) lookup.set(entry.identifier, { ...entry.data });
33470
- return lookup;
34219
+ const lookup$1 = new Map();
34220
+ for (const entry of entries) lookup$1.set(entry.identifier, { ...entry.data });
34221
+ return lookup$1;
33471
34222
  }
33472
34223
  function buildEntryDataLookups(entries, remoteEntries) {
33473
34224
  const local = new Map();
@@ -33514,9 +34265,9 @@ function formatPageDetails(diff, localPages, remotePages) {
33514
34265
  return findChangedFieldsWithValues(localFields, remoteFields).map((change) => ` ${formatFieldChange(change)}`);
33515
34266
  }
33516
34267
  function buildIdentifierLookup(items) {
33517
- const lookup = new Map();
33518
- for (const item of items) lookup.set(item.identifier, item);
33519
- return lookup;
34268
+ const lookup$1 = new Map();
34269
+ for (const item of items) lookup$1.set(item.identifier, item);
34270
+ return lookup$1;
33520
34271
  }
33521
34272
  /** Format a ContentDiff with field-level before/after values for human display. */
33522
34273
  function formatHumanDiff(diff, local, remote) {
@@ -34936,4 +35687,4 @@ function optionalTitle(data) {
34936
35687
  }
34937
35688
 
34938
35689
  //#endregion
34939
- export { walkLocalContentMedia as $, extractApiErrorMessage as $n, ApiEnvelopeError as $r, commandContexts as $t, formatDiffSummary as A, isLocalConfigured as An, getBookingLaterInstalments as Ar, navigationIdentityMap as At, formatFieldChange as B, DEFAULT_MEDIA_FIELD_KINDS as Bn, publicProductSchema as Br, ACCOUNT_SITE_SEARCH_MAX_LENGTH as Bt, reportFromOutcomes as C, ErrorCodes as Cn, planFlexibleBalanceCreditFirst as Cr, listFiles as Ct, calculateDiff as D, createOutput as Dn, resolveAvailableBookingCollectionOptions as Dr, isMediaValue as Dt, createEmptySyncResult as E, CliExit as En, repriceBookingCollectionOptions as Er, writeJsonFileAtomic as Et, buildJsonDiff as F, cardListKnobBlocks as Fn, eventCalendarListLayoutValues as Fr, createBearerAccountApi as Ft, applyLocalMediaPush as G, MAX_REPEATER_GRID_COLUMNS as Gn, calendarMonthWindowSchema as Gr, createPushConfigCommand as Gt, revalidateLocalMediaPushPlan as H, blockContentSourceSchema as Hn, purchasablePublicPassProductSchema as Hr, navigationCommandItemToManagementInput as Ht, hasPageOperations as I, lookKnobBlocks as In, publicMapLocationResultSchema as Ir, ACCOUNT_SITE_CURSOR_MAX_LENGTH as It, readStableBinaryFile as J, resolveRepeaterGridColumnFieldId as Jn, eventSurfacePresetValues as Jr, revalidatePushConfigPlan as Jt, prepareLocalMediaForPush as K, isAcceptedRepeaterGridSpan as Kn, calendarSourceCursorSchema as Kr, loadPushConfigTarget as Kt, pageMetadataForUpsert as L, NodeSchema as Ln, publicVenueMapLocationSchema as Lr, ACCOUNT_SITE_LIST_LIMIT_DEFAULT as Lt, findChangedFieldsWithValues as M, loadSdkEnvironment as Mn, eventCalendarDefaultViewValues as Mr, convertPulledNavigationToLocal as Mt, formatHumanDiff as N, cardListBlockParts as Nn, eventCalendarDisplayModeValues as Nr, convertPulledPagesToLocal as Nt, calculateFooterDiff as O, getEnvPrefix as On, resolveBookingCollectionOptionFacts as Or, duplicateNavigationIdentityMessage as Ot, calculatePullDiff as P, cardListFamilyBlocks as Pn, eventCalendarListLayoutCompatibleDisplayModeValues as Pr, AccountApiMalformedResponseError as Pt, normalizeMediaValueToIdentifierOnly as Q, ManagementApiError as Qn, publicEventLoaderQuerySchemaShape as Qr, CommandFailure as Qt, calculateEntryDiffs as R, NodeTreeSchema as Rn, publicMembershipProductSchema as Rr, ACCOUNT_SITE_LIST_LIMIT_MAX as Rt, planCliCommandBatchForBindings as S, withRiverbankEnv as Sn, planCheckoutPaymentFlow as Sr, fileExists$1 as St, executeResidualSettingsSyncPlan as T, transportSuggestion as Tn, isBookingCollectionEquivalentToUpfront as Tr, writeJsonFile$1 as Tt, syncLocalMediaForPush as U, blockRequiredFeatureSchema as Un, CALENDAR_SSR_PAGE_SIZE as Ur, normalizeNavigationConfigItemForCommand as Ut, formatFieldPath as V, blockCategoryEnum as Vn, purchasablePublicMembershipProductSchema as Vr, ACCOUNT_SITE_TITLE_MAX_LENGTH as Vt, syncLocalMediaForPull as W, fieldSchema as Wn, calendarMonthDate as Wr, applyPushConfigPlan as Wt, sha256 as X, resolveRepeaterGridSpanFieldId as Xn, monthNumber as Xr, deriveCmsApiUrlFromDashboardUrl as Xt, writeBinaryFileAtomic as Y, resolveRepeaterGridRowFieldId as Yn, eventSurfaceScopeValues as Yr, createBearerAPIClient as Yt, normalizeMediaIdentifierInput as Z, visibilityLevels as Zn, normalizeCalendarFilterId as Zr, mapEnvironmentExecutionOutcomesJson as Zt, commandExecutionToReport as _, executeEnvironmentPlan as _n, nextCombinationHint as _r, metadataTargetFromEnvironment as _t, executeEntryCommandPlanAsReport as a, confirmAction as an, linkPayloadSchema as ar, readAllMeta as at, executeCompiledCliCommandPlanAsReport as b, planEnvironmentWriteAuthorization as bn, checkoutCopy as br, writeMetadataRecordMap as bt, titleFromEntryData as c, formatDateShort as cn, pageDesignIntentSchemaVersion as cr, readFooterMeta as ct, unsafeAsCliEntryIdentifier as d, managementClientFor as dn, areEventBookingRequirementsIdentical as dr, readPagesMeta as dt, unwrapResponse as ei, defineCommand as en, normalizeApiError as er, buildStorageUrl as et, unsafeAsCliFormSlug as f, mapEntryForOutput as fn, eventBookingConsentContentKey as fr, readSettingsMeta as ft, commandCompileFailureToReport as g, runWithInvocation as gn, checkoutStatusArms as gr, metadataFilePath as gt, mutationCounterForEffect as h, resolveCommandPath as hn, resolveSelectionAttendanceMode as hr, ensureMetadataDir as ht, entrySiteCommandTypes as i, bindRequestTimeout as in, sdkSettingsUpdateSchema as ir, readEntries as it, hasPendingChanges as j, isRemoteConfigured as jn, MAX_EVENT_BOOKING_SELECTION_ITEMS as jr, convertPulledFooterToLocal as jt, formatDiffDetail as k, getEnvironmentDebugInfo as kn, getStripeMinimumChargeRequirement as kr, navigationIdentity as kt, unsafeAsCliBlockIdentifier as l, handleCommandError as ln, sdkConfiguredBookingVerticalConfigSchema as lr, readFormsMeta as lt, commandReportToSyncResult as m, parseJsonData as mn, decideSelectionAttendance as mr, writeMediaManifest as mt, entryCommandCompileErrorToReport as n, registerCommand as nn, ApiRequestError as nr, extractMediaIdentifiers as nt, executeEntryCommandPlanAsSyncResult as o, createOutputForCommand as on, portablePageDesignSchema as or, readEventCategoriesMeta as ot, unsafeAsCliPageIdentifier as p, parseJsonArray as pn, INCOMPATIBLE_ATTENDANCE_MESSAGE as pr, readVenuesMeta as pt, admitBinaryWriteDestination as q, parseRepeaterGridInteger as qn, eventScheduleScopeValues as qr, preparePushConfigTarget as qt, entryCommandReportToSyncResult as r, renderedByOwner as rn, sdkEventScheduleSchema as rr, findLegacyEntryFiles as rt, syncResultForEntryCommandCompileError as s, currentInvocationEnvelope as sn, pageDesignDecisionsV2Schema as sr, readEventsMeta as st, compileEntryPushCommands as t, defineCommandGroup as tn, isRecord$5 as tr, downloadMedia as tt, unsafeAsCliContentTypeKey as u, loadManagementTarget as un, API_ENDPOINTS as ur, readNavigationMeta as ut, commandReportHasFailures as v, parseEnvironmentSelection as vn, planSelectionCombinationPrices as vr, readMetadataFile as vt, mergeManySyncResults as w, formatError as wn, flexibleBalanceDueDay as wr, readJsonFile as wt, formatManagementError as x, requireEnvironmentWriteAuthorization as xn, unsafeAsPositiveCheckoutQuantity as xr, ensureDir$1 as xt, executeCliCommandPlan as y, planEnvironmentExecution as yn, eventRegistrationErrors as yr, writeMetadataFile as yt, buildFieldChanges as z, bindingSchema as zn, publicPassProductSchema as zr, ACCOUNT_SITE_LIST_LIMIT_MIN as zt };
35690
+ export { walkLocalContentMedia as $, extractApiErrorMessage as $n, publicVenueMapLocationSchema as $r, commandContexts as $t, formatDiffSummary as A, isLocalConfigured as An, planSelectionCombinationPrices as Ar, navigationIdentityMap as At, formatFieldChange as B, DEFAULT_MEDIA_FIELD_KINDS as Bn, flexibleBalanceDueDay as Br, ACCOUNT_SITE_SEARCH_MAX_LENGTH as Bt, reportFromOutcomes as C, ErrorCodes as Cn, reviewedStay as Cr, listFiles as Ct, calculateDiff as D, createOutput as Dn, roomSetupSchema as Dr, isMediaValue as Dt, createEmptySyncResult as E, CliExit as En, roomOccupancySchema as Er, writeJsonFileAtomic as Et, buildJsonDiff as F, cardListKnobBlocks as Fn, checkoutCopy as Fr, createBearerAccountApi as Ft, applyLocalMediaPush as G, MAX_REPEATER_GRID_COLUMNS as Gn, getStripeMinimumChargeRequirement as Gr, createPushConfigCommand as Gt, revalidateLocalMediaPushPlan as H, blockContentSourceSchema as Hn, repriceBookingCollectionOptions as Hr, navigationCommandItemToManagementInput as Ht, hasPageOperations as I, lookKnobBlocks as In, unsafeAsPositiveCheckoutQuantity as Ir, ACCOUNT_SITE_CURSOR_MAX_LENGTH as It, readStableBinaryFile as J, resolveRepeaterGridColumnFieldId as Jn, eventCalendarDefaultViewValues as Jr, revalidatePushConfigPlan as Jt, prepareLocalMediaForPush as K, isAcceptedRepeaterGridSpan as Kn, getBookingLaterInstalments as Kr, loadPushConfigTarget as Kt, pageMetadataForUpsert as L, NodeSchema as Ln, planCheckoutPaymentFlow as Lr, ACCOUNT_SITE_LIST_LIMIT_DEFAULT as Lt, findChangedFieldsWithValues as M, loadSdkEnvironment as Mn, placementProblemText as Mr, convertPulledNavigationToLocal as Mt, formatHumanDiff as N, cardListBlockParts as Nn, stayLineText as Nr, convertPulledPagesToLocal as Nt, calculateFooterDiff as O, getEnvPrefix as On, sharedRoomArrangementSchema as Or, duplicateNavigationIdentityMessage as Ot, calculatePullDiff as P, cardListFamilyBlocks as Pn, stayNoteText as Pr, AccountApiMalformedResponseError as Pt, normalizeMediaValueToIdentifierOnly as Q, ManagementApiError as Qn, publicMapLocationResultSchema as Qr, CommandFailure as Qt, calculateEntryDiffs as R, NodeTreeSchema as Rn, planFlexibleBalanceCreditFirst as Rr, ACCOUNT_SITE_LIST_LIMIT_MAX as Rt, planCliCommandBatchForBindings as S, withRiverbankEnv as Sn, placeBooking as Sr, fileExists$1 as St, executeResidualSettingsSyncPlan as T, transportSuggestion as Tn, roomChoicesSchema as Tr, writeJsonFile$1 as Tt, syncLocalMediaForPush as U, blockRequiredFeatureSchema as Un, resolveAvailableBookingCollectionOptions as Ur, normalizeNavigationConfigItemForCommand as Ut, formatFieldPath as V, blockCategoryEnum as Vn, isBookingCollectionEquivalentToUpfront as Vr, ACCOUNT_SITE_TITLE_MAX_LENGTH as Vt, syncLocalMediaForPull as W, fieldSchema as Wn, resolveBookingCollectionOptionFacts as Wr, applyPushConfigPlan as Wt, sha256 as X, resolveRepeaterGridSpanFieldId as Xn, eventCalendarListLayoutCompatibleDisplayModeValues as Xr, deriveCmsApiUrlFromDashboardUrl as Xt, writeBinaryFileAtomic as Y, resolveRepeaterGridRowFieldId as Yn, eventCalendarDisplayModeValues as Yr, createBearerAPIClient as Yt, normalizeMediaIdentifierInput as Z, visibilityLevels as Zn, eventCalendarListLayoutValues as Zr, mapEnvironmentExecutionOutcomesJson as Zt, commandExecutionToReport as _, executeEnvironmentPlan as _n, placesLeftText as _r, metadataTargetFromEnvironment as _t, executeEntryCommandPlanAsReport as a, CALENDAR_SSR_PAGE_SIZE as ai, confirmAction as an, linkPayloadSchema as ar, readAllMeta as at, executeCompiledCliCommandPlanAsReport as b, planEnvironmentWriteAuthorization as bn, sameRoomOption as br, writeMetadataRecordMap as bt, titleFromEntryData as c, calendarSourceCursorSchema as ci, formatDateShort as cn, pageDesignIntentSchemaVersion as cr, readFooterMeta as ct, unsafeAsCliEntryIdentifier as d, eventSurfaceScopeValues as di, managementClientFor as dn, areEventBookingRequirementsIdentical as dr, readPagesMeta as dt, publicMembershipProductSchema as ei, defineCommand as en, normalizeApiError as er, buildStorageUrl as et, unsafeAsCliFormSlug as f, monthNumber as fi, mapEntryForOutput as fn, eventBookingConsentContentKey as fr, readSettingsMeta as ft, commandCompileFailureToReport as g, unwrapResponse as gi, runWithInvocation as gn, checkoutStatusArms as gr, metadataFilePath as gt, mutationCounterForEffect as h, ApiEnvelopeError as hi, resolveCommandPath as hn, resolveSelectionAttendanceMode as hr, ensureMetadataDir as ht, entrySiteCommandTypes as i, purchasablePublicPassProductSchema as ii, bindRequestTimeout as in, sdkSettingsUpdateSchema as ir, readEntries as it, hasPendingChanges as j, isRemoteConfigured as jn, eventRegistrationErrors as jr, convertPulledFooterToLocal as jt, formatDiffDetail as k, getEnvironmentDebugInfo as kn, nextCombinationHint as kr, navigationIdentity as kt, unsafeAsCliBlockIdentifier as l, eventScheduleScopeValues as li, handleCommandError as ln, sdkConfiguredBookingVerticalConfigSchema as lr, readFormsMeta as lt, commandReportToSyncResult as m, publicEventLoaderQuerySchemaShape as mi, parseJsonData as mn, decideSelectionAttendance as mr, writeMediaManifest as mt, entryCommandCompileErrorToReport as n, publicProductSchema as ni, registerCommand as nn, ApiRequestError as nr, extractMediaIdentifiers as nt, executeEntryCommandPlanAsSyncResult as o, calendarMonthDate as oi, createOutputForCommand as on, portablePageDesignSchema as or, readEventCategoriesMeta as ot, unsafeAsCliPageIdentifier as p, normalizeCalendarFilterId as pi, parseJsonArray as pn, INCOMPATIBLE_ATTENDANCE_MESSAGE as pr, readVenuesMeta as pt, admitBinaryWriteDestination as q, parseRepeaterGridInteger as qn, MAX_EVENT_BOOKING_SELECTION_ITEMS as qr, preparePushConfigTarget as qt, entryCommandReportToSyncResult as r, purchasablePublicMembershipProductSchema as ri, renderedByOwner as rn, sdkEventScheduleSchema as rr, findLegacyEntryFiles as rt, syncResultForEntryCommandCompileError as s, calendarMonthWindowSchema as si, currentInvocationEnvelope as sn, pageDesignDecisionsV2Schema as sr, readEventsMeta as st, compileEntryPushCommands as t, publicPassProductSchema as ti, defineCommandGroup as tn, isRecord$5 as tr, downloadMedia as tt, unsafeAsCliContentTypeKey as u, eventSurfacePresetValues as ui, loadManagementTarget as un, API_ENDPOINTS as ur, readNavigationMeta as ut, commandReportHasFailures as v, parseEnvironmentSelection as vn, roomKindOptions as vr, readMetadataFile as vt, mergeManySyncResults as w, formatError as wn, reviewedRoomsSchema as wr, readJsonFile as wt, formatManagementError as x, requireEnvironmentWriteAuthorization as xn, countSoFar as xr, ensureDir$1 as xt, executeCliCommandPlan as y, planEnvironmentExecution as yn, roomsOfferSharing as yr, writeMetadataFile as yt, buildFieldChanges as z, bindingSchema as zn, bookingCollectionDatesOpen as zr, ACCOUNT_SITE_LIST_LIMIT_MIN as zt };