@final-commerce/common 2.11.1 → 2.12.0-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -31,10 +31,12 @@ __export(index_exports, {
31
31
  AttributeType: () => AttributeType,
32
32
  BNPL_METHOD_STATUS: () => BNPL_METHOD_STATUS,
33
33
  BNPL_SKIP_REASON: () => BNPL_SKIP_REASON,
34
+ BookingDurationUnit: () => BookingDurationUnit,
34
35
  BookingRatePeriod: () => BookingRatePeriod,
35
36
  BookingResourceKind: () => BookingResourceKind,
36
37
  BookingResourceStatus: () => BookingResourceStatus,
37
38
  BookingRulesError: () => BookingRulesError,
39
+ BookingSessionSale: () => BookingSessionSale,
38
40
  BookingType: () => BookingType,
39
41
  CANADA_PROVINCES: () => CANADA_PROVINCES,
40
42
  CONDITION_OPERATORS: () => CONDITION_OPERATORS,
@@ -124,6 +126,7 @@ __export(index_exports, {
124
126
  StripeStatus: () => StripeStatus,
125
127
  TimePeriod: () => TimePeriod,
126
128
  TopMetericsSort: () => TopMetericsSort,
129
+ UNLIMITED_PLACES: () => UNLIMITED_PLACES,
127
130
  UserTypes: () => UserTypes,
128
131
  addAmounts: () => addAmounts,
129
132
  addressPlaceKeys: () => addressPlaceKeys,
@@ -132,6 +135,7 @@ __export(index_exports, {
132
135
  adyenStoreRequiresStateOrProvince: () => adyenStoreRequiresStateOrProvince,
133
136
  adyenSupportsTaxNumberAbsent: () => adyenSupportsTaxNumberAbsent,
134
137
  adyenTaxNumberFormat: () => adyenTaxNumberFormat,
138
+ allowedDurationUnits: () => allowedDurationUnits,
135
139
  amountToString: () => amountToString,
136
140
  ancestorChain: () => ancestorChain,
137
141
  applyAssignment: () => applyAssignment,
@@ -141,15 +145,21 @@ __export(index_exports, {
141
145
  baseFulfillmentDefinitions: () => baseFulfillmentDefinitions,
142
146
  baseOf: () => baseOf,
143
147
  basePaymentDefinitions: () => basePaymentDefinitions,
148
+ bookingMethodOf: () => bookingMethodOf,
149
+ bookingRuleParts: () => bookingRuleParts,
144
150
  buildAvailability: () => buildAvailability,
145
151
  buildGrid: () => buildGrid,
146
152
  buildOrderContext: () => buildOrderContext,
147
153
  buildPosPresetConfig: () => buildPosPresetConfig,
148
154
  buildResolvedConfig: () => buildResolvedConfig,
149
155
  calculatePercentage: () => calculatePercentage,
156
+ calendarDate: () => calendarDate,
150
157
  canTransition: () => canTransition,
158
+ capacityOf: () => capacityOf,
151
159
  cheapestCompositeItem: () => cheapestCompositeItem,
152
160
  cheapestCompositePrice: () => cheapestCompositePrice,
161
+ checkPartySize: () => checkPartySize,
162
+ checkQtyPerBooking: () => checkQtyPerBooking,
153
163
  compositeItemCost: () => compositeItemCost,
154
164
  compositeItemUnavailable: () => compositeItemUnavailable,
155
165
  compositeMakeable: () => compositeMakeable,
@@ -158,6 +168,9 @@ __export(index_exports, {
158
168
  compositeVariantInStock: () => compositeVariantInStock,
159
169
  conditionSummary: () => conditionSummary,
160
170
  convertFixedFeeToLocalCurrency: () => convertFixedFeeToLocalCurrency,
171
+ courseSessions: () => courseSessions,
172
+ courseStarted: () => courseStarted,
173
+ courseStartedInZone: () => courseStartedInZone,
161
174
  createAmount: () => createAmount,
162
175
  crossAxisRuleApplies: () => crossAxisRuleApplies,
163
176
  currentAssignees: () => currentAssignees,
@@ -166,10 +179,13 @@ __export(index_exports, {
166
179
  deriveUnitId: () => deriveUnitId,
167
180
  displayRuleMatchesPair: () => displayRuleMatchesPair,
168
181
  divideAmount: () => divideAmount,
182
+ durationProblems: () => durationProblems,
183
+ durationText: () => durationText,
169
184
  evaluateCondition: () => evaluateCondition,
170
185
  evaluateConditionSet: () => evaluateConditionSet,
171
186
  extendPrice: () => extendPrice,
172
187
  extendPriceFor: () => extendPriceFor,
188
+ fewestFreeOver: () => fewestFreeOver,
173
189
  formatCurrency: () => formatCurrency,
174
190
  formatInUnit: () => formatInUnit,
175
191
  formatMinorUnitsToString: () => formatMinorUnitsToString,
@@ -211,7 +227,9 @@ __export(index_exports, {
211
227
  listCountries: () => listCountries,
212
228
  listProvinces: () => listProvinces,
213
229
  listShippingCountries: () => listShippingCountries,
230
+ longestMinutesOf: () => longestMinutesOf,
214
231
  mapToLegacyStatus: () => mapToLegacyStatus,
232
+ maxAdvanceMinutesOf: () => maxAdvanceMinutesOf,
215
233
  maxPrecisionFor: () => maxPrecisionFor,
216
234
  mergeFragment: () => mergeFragment,
217
235
  modifiersSellable: () => modifiersSellable,
@@ -223,11 +241,14 @@ __export(index_exports, {
223
241
  normalizePostCode: () => normalizePostCode,
224
242
  normalizeProvince: () => normalizeProvince,
225
243
  occupancyIn: () => occupancyIn,
244
+ oldMaxAdvanceOf: () => oldMaxAdvanceOf,
226
245
  orderAssignments: () => orderAssignments,
227
246
  parseAmountToMinorUnits: () => parseAmountToMinorUnits,
228
247
  parseCurrencyCode: () => parseCurrencyCode,
229
248
  parseStripeCurrencyCode: () => parseStripeCurrencyCode,
249
+ pickFreeResource: () => pickFreeResource,
230
250
  placeKey: () => placeKey,
251
+ planCourse: () => planCourse,
231
252
  planWindow: () => planWindow,
232
253
  poolDemand: () => poolDemand,
233
254
  poolOf: () => poolOf,
@@ -238,19 +259,25 @@ __export(index_exports, {
238
259
  priceForTotal: () => priceForTotal,
239
260
  provincesForPostCode: () => provincesForPostCode,
240
261
  removeFragment: () => removeFragment,
262
+ rentalEnds: () => rentalEnds,
241
263
  resolveFamily: () => resolveFamily,
242
264
  resolveModifiersForProduct: () => resolveModifiersForProduct,
243
265
  resolveShipping: () => resolveShipping,
244
266
  resolveTemplate: () => resolveTemplate,
245
267
  resolveUnit: () => resolveUnit,
246
268
  roundToPrecision: () => roundToPrecision,
269
+ ruleDurationsOf: () => ruleDurationsOf,
270
+ ruleInNewShape: () => ruleInNewShape,
247
271
  sameFamily: () => sameFamily,
272
+ sessionCells: () => sessionCells,
248
273
  setOrderState: () => setOrderState,
249
274
  shipsToCountry: () => shipsToCountry,
250
275
  shopDayKey: () => shopDayKey,
251
276
  shopDayRange: () => shopDayRange,
277
+ shortestMinutesOf: () => shortestMinutesOf,
252
278
  signReportForDisplay: () => signReportForDisplay,
253
279
  slotsForWindow: () => slotsForWindow,
280
+ soldAsCourse: () => soldAsCourse,
254
281
  stringifyMinorUnits: () => stringifyMinorUnits,
255
282
  subtractAmounts: () => subtractAmounts,
256
283
  toBase: () => toBase,
@@ -261,6 +288,8 @@ __export(index_exports, {
261
288
  validateShippingZone: () => validateShippingZone,
262
289
  violatesFinancialInvariant: () => violatesFinancialInvariant,
263
290
  windowEndsAt: () => windowEndsAt,
291
+ windowEndsAtInZone: () => windowEndsAtInZone,
292
+ windowForPeriods: () => windowForPeriods,
264
293
  withinPresence: () => withinPresence
265
294
  });
266
295
  module.exports = __toCommonJS(index_exports);
@@ -721,21 +750,37 @@ var PaymentProcessor = /* @__PURE__ */ ((PaymentProcessor2) => {
721
750
  })(PaymentProcessor || {});
722
751
 
723
752
  // enums/booking.enum.ts
724
- var BookingType = /* @__PURE__ */ ((BookingType3) => {
725
- BookingType3["RENTAL"] = "rental";
726
- BookingType3["APPOINTMENT"] = "appointment";
727
- BookingType3["OVERNIGHT"] = "overnight";
728
- BookingType3["GROUP"] = "group";
729
- return BookingType3;
753
+ var BookingType = /* @__PURE__ */ ((BookingType2) => {
754
+ BookingType2["RENTAL"] = "rental";
755
+ BookingType2["APPOINTMENT"] = "appointment";
756
+ BookingType2["OVERNIGHT"] = "overnight";
757
+ BookingType2["GROUP"] = "group";
758
+ return BookingType2;
730
759
  })(BookingType || {});
731
760
  var BookingRatePeriod = /* @__PURE__ */ ((BookingRatePeriod2) => {
732
761
  BookingRatePeriod2["SLOT"] = "slot";
762
+ BookingRatePeriod2["HOUR"] = "hour";
763
+ BookingRatePeriod2["SESSION"] = "session";
733
764
  BookingRatePeriod2["DAY"] = "day";
734
765
  BookingRatePeriod2["NIGHT"] = "night";
735
766
  BookingRatePeriod2["WEEK"] = "week";
736
767
  BookingRatePeriod2["MONTH"] = "month";
737
768
  return BookingRatePeriod2;
738
769
  })(BookingRatePeriod || {});
770
+ var BookingDurationUnit = /* @__PURE__ */ ((BookingDurationUnit2) => {
771
+ BookingDurationUnit2["MINUTE"] = "minute";
772
+ BookingDurationUnit2["HOUR"] = "hour";
773
+ BookingDurationUnit2["DAY"] = "day";
774
+ BookingDurationUnit2["NIGHT"] = "night";
775
+ BookingDurationUnit2["WEEK"] = "week";
776
+ BookingDurationUnit2["MONTH"] = "month";
777
+ return BookingDurationUnit2;
778
+ })(BookingDurationUnit || {});
779
+ var BookingSessionSale = /* @__PURE__ */ ((BookingSessionSale2) => {
780
+ BookingSessionSale2["SESSION"] = "session";
781
+ BookingSessionSale2["COURSE"] = "course";
782
+ return BookingSessionSale2;
783
+ })(BookingSessionSale || {});
739
784
  var BookingResourceKind = /* @__PURE__ */ ((BookingResourceKind2) => {
740
785
  BookingResourceKind2["ASSET"] = "asset";
741
786
  BookingResourceKind2["ROOM"] = "room";
@@ -3596,6 +3641,7 @@ var ORDER_STATE_EVENTS = {
3596
3641
  };
3597
3642
 
3598
3643
  // booking/types.ts
3644
+ var UNLIMITED_PLACES = Number.MAX_SAFE_INTEGER;
3599
3645
  var BookingRulesError = class extends Error {
3600
3646
  constructor(message) {
3601
3647
  super(message);
@@ -3664,153 +3710,39 @@ function atZonedMinute(dayStart, minutes, timeZone) {
3664
3710
  const { year, month, day } = zonedParts(dayStart, timeZone);
3665
3711
  return instantFromLocal(year, month, day, minutes, timeZone);
3666
3712
  }
3667
-
3668
- // booking/grid.ts
3669
- var MINUTE2 = 6e4;
3670
- var MAX_RANGE_DAYS = 366;
3671
- var asTime = (value, field) => {
3672
- if (value == null) return void 0;
3673
- const time = new Date(value).getTime();
3674
- if (Number.isNaN(time)) throw new BookingRulesError(`Booking rules: ${field} is not a date, got "${String(value)}"`);
3675
- return time;
3676
- };
3677
- function parseHhMm(value, field) {
3678
- const [hours, minutes] = value.split(":").map(Number);
3679
- if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
3680
- throw new BookingRulesError(`Booking rules: ${field} must be "HH:mm", got "${value}"`);
3681
- }
3682
- return hours * 60 + minutes;
3683
- }
3684
- function windowEndsAt(rule, now) {
3685
- const { maxAdvanceDays, bookableTo } = rule.window;
3686
- const ends = Math.min(
3687
- maxAdvanceDays ? now.getTime() + maxAdvanceDays * 1440 * MINUTE2 : Number.POSITIVE_INFINITY,
3688
- asTime(bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
3689
- );
3690
- return Number.isFinite(ends) ? new Date(ends) : null;
3691
- }
3692
- function periodSlot(dayStart, timeZone, rule, openMinute, closeMinute) {
3693
- const { ratePeriod, slot, checkInTime, checkOutTime } = rule;
3694
- const at = (minutes) => atZonedMinute(dayStart, minutes, timeZone);
3695
- if (ratePeriod === "night" /* NIGHT */) {
3696
- if (!checkInTime || !checkOutTime) {
3697
- throw new BookingRulesError("Overnight booking rules need both checkInTime and checkOutTime");
3698
- }
3699
- const checkIn = parseHhMm(checkInTime, "checkInTime");
3700
- const checkOut = parseHhMm(checkOutTime, "checkOutTime");
3701
- return {
3702
- startAt: at(checkIn),
3703
- endAt: at(1440 + checkOut),
3704
- // Housekeeping sits between check-out and the next check-in: it costs no night.
3705
- bufferEndAt: at(1440 + checkIn),
3706
- canStart: true
3707
- };
3708
- }
3709
- const from = ratePeriod === "day" /* DAY */ ? openMinute ?? 0 : 0;
3710
- const to = ratePeriod === "day" /* DAY */ ? closeMinute ?? 1440 : 1440;
3711
- return {
3712
- startAt: at(from),
3713
- endAt: at(to),
3714
- bufferEndAt: at(to + (slot.bufferMinutes ?? 0)),
3715
- canStart: true
3716
- };
3717
- }
3718
- function freeGaps(openAt, closeAt, busy) {
3719
- const inside = busy.map(({ startAt, bufferEndAt }) => ({ from: +startAt, to: +bufferEndAt })).filter(({ from, to }) => to > openAt && from < closeAt).sort((first, second) => first.from - second.from);
3720
- const gaps = [];
3721
- let cursor = openAt;
3722
- for (const { from, to } of inside) {
3723
- if (from > cursor) gaps.push({ from: cursor, to: from, endsAtBooking: true });
3724
- cursor = Math.max(cursor, to);
3725
- if (cursor >= closeAt) break;
3726
- }
3727
- if (cursor < closeAt) gaps.push({ from: cursor, to: closeAt, endsAtBooking: false });
3728
- return gaps;
3729
- }
3730
- function buildGrid(rule, timeZone, from, to, now, busy = []) {
3731
- if (to.getTime() - from.getTime() > MAX_RANGE_DAYS * 1440 * MINUTE2) {
3732
- throw new BookingRulesError(`A booking range may span at most ${MAX_RANGE_DAYS} days`);
3733
- }
3734
- const { availability, slot, window, ratePeriod } = rule;
3735
- const periodMode = ratePeriod !== "slot" /* SLOT */;
3736
- const weeklyHours = availability.weeklyHours ?? [];
3737
- const notBefore = Math.max(
3738
- now.getTime() + (window.minNoticeMinutes ?? 0) * MINUTE2,
3739
- asTime(window.bookableFrom, "window.bookableFrom") ?? 0,
3740
- asTime(availability.availableFrom, "availability.availableFrom") ?? 0
3741
- );
3742
- const notAfter = windowEndsAt(rule, now)?.getTime() ?? Number.POSITIVE_INFINITY;
3743
- const blocked = (availability.offMarket ?? []).map(({ from: blockFrom, to: blockTo }) => ({
3744
- from: asTime(blockFrom, "availability.offMarket.from"),
3745
- to: asTime(blockTo, "availability.offMarket.to")
3746
- }));
3747
- const arrivalDays = availability.arrivalDays;
3748
- const step = slot.lengthMinutes + (slot.bufferMinutes ?? 0);
3749
- const slots = [];
3750
- const lastDay = startOfZonedDay(to, timeZone).getTime();
3751
- let dayStart = startOfZonedDay(from, timeZone);
3752
- while (dayStart.getTime() <= lastDay) {
3753
- const weekday = zonedParts(dayStart, timeZone).weekday;
3754
- const rows = weeklyHours.filter((entry) => entry.weekday === weekday);
3755
- if (periodMode) {
3756
- const openToday = weeklyHours.length === 0 || rows.length > 0;
3757
- if (openToday) {
3758
- const built = periodSlot(dayStart, timeZone, rule, rows[0]?.openMinute, rows[0]?.closeMinute);
3759
- slots.push({ ...built, canStart: !arrivalDays?.length || arrivalDays.includes(weekday) });
3760
- }
3761
- } else {
3762
- for (const row of rows) {
3763
- const openAt = +atZonedMinute(dayStart, row.openMinute, timeZone);
3764
- const closeAt = +atZonedMinute(dayStart, row.closeMinute, timeZone);
3765
- for (const gap of freeGaps(openAt, closeAt, busy)) {
3766
- const mustFit = (gap.endsAtBooking ? step : slot.lengthMinutes) * MINUTE2;
3767
- for (let start = gap.from; start + mustFit <= gap.to; start += step * MINUTE2) {
3768
- slots.push({
3769
- startAt: new Date(start),
3770
- endAt: new Date(start + slot.lengthMinutes * MINUTE2),
3771
- bufferEndAt: new Date(start + step * MINUTE2),
3772
- canStart: true
3773
- });
3774
- }
3775
- }
3776
- }
3777
- }
3778
- dayStart = nextZonedDay(dayStart, timeZone);
3779
- }
3780
- const askedFrom = from.getTime();
3781
- const askedTo = to.getTime();
3782
- return slots.filter(({ startAt, bufferEndAt }) => {
3783
- const start = startAt.getTime();
3784
- if (start < askedFrom || start >= askedTo) return false;
3785
- if (start < notBefore || start > notAfter) return false;
3786
- return !blocked.some(
3787
- ({ from: blockFrom, to: blockTo }) => start < blockTo && bufferEndAt.getTime() > blockFrom
3788
- );
3789
- }).sort((first, second) => +first.startAt - +second.startAt);
3713
+ function sameDayMonthsLaterDate(year, month, day, months) {
3714
+ const target = new Date(Date.UTC(year, month - 1 + months, 1));
3715
+ const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();
3716
+ return [target.getUTCFullYear(), target.getUTCMonth() + 1, Math.min(day, lastDay)];
3790
3717
  }
3791
- function slotsForWindow(grid, startAt, endAt) {
3792
- const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
3793
- if (startIndex < 0) {
3794
- throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
3795
- }
3796
- if (!grid[startIndex].canStart) {
3797
- throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
3798
- }
3799
- const covered = [];
3800
- for (let index = startIndex; index < grid.length; index++) {
3801
- const entry = grid[index];
3802
- const previous = covered[covered.length - 1];
3803
- if (previous && entry.startAt.getTime() !== previous.bufferEndAt.getTime()) break;
3804
- covered.push(entry);
3805
- if (entry.endAt.getTime() === endAt.getTime()) return covered;
3806
- if (entry.endAt.getTime() > endAt.getTime()) break;
3807
- }
3718
+ function addClockDuration(from, { count, unit: unit2 }) {
3719
+ if (unit2 === "minute" /* MINUTE */) return new Date(from.getTime() + count * MINUTE);
3720
+ if (unit2 === "hour" /* HOUR */) return new Date(from.getTime() + count * 60 * MINUTE);
3808
3721
  throw new BookingRulesError(
3809
- `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
3722
+ `Booking rules: ${count} ${unit2} is not minutes or hours \u2014 it needs the shop's time zone`
3810
3723
  );
3811
3724
  }
3725
+ var DAYS_IN = {
3726
+ ["day" /* DAY */]: 1,
3727
+ ["night" /* NIGHT */]: 1,
3728
+ ["week" /* WEEK */]: 7
3729
+ };
3730
+ function addDuration(from, duration, timeZone) {
3731
+ const { count, unit: unit2 } = duration;
3732
+ if (unit2 === "minute" /* MINUTE */ || unit2 === "hour" /* HOUR */) return addClockDuration(from, duration);
3733
+ const days = DAYS_IN[unit2];
3734
+ if (days === void 0 && unit2 !== "month" /* MONTH */) {
3735
+ throw new BookingRulesError(`Booking rules: "${unit2}" is not a duration unit`);
3736
+ }
3737
+ if (!Number.isInteger(count)) throw new BookingRulesError(`Booking rules: ${count} ${unit2} is not a whole number`);
3738
+ const { year, month, day, hour, minute, second } = zonedParts(from, timeZone);
3739
+ const [toYear, toMonth, toDay] = days === void 0 ? sameDayMonthsLaterDate(year, month, day, count) : [year, month, day + days * count];
3740
+ const wallClock = instantFromLocal(toYear, toMonth, toDay, hour * 60 + minute, timeZone);
3741
+ return new Date(wallClock.getTime() + second * 1e3 + from.getUTCMilliseconds());
3742
+ }
3812
3743
 
3813
3744
  // booking/availability.ts
3745
+ var placesOnTheWire = (entry) => Number.isFinite(entry.capacity) ? entry : { ...entry, capacity: UNLIMITED_PLACES, free: UNLIMITED_PLACES, unlimited: true };
3814
3746
  var withinPresence = (slot, timeZone, presence) => {
3815
3747
  if (!presence?.length) return true;
3816
3748
  const dayStart = startOfZonedDay(slot.startAt, timeZone);
@@ -3857,25 +3789,33 @@ function shopDayRange(fromDayKey, count, timeZone) {
3857
3789
  function buildAvailability({
3858
3790
  productId,
3859
3791
  bookingRulesId,
3860
- bookingType,
3861
3792
  rule,
3862
3793
  resources,
3863
3794
  occupied,
3864
3795
  from,
3865
3796
  to,
3866
- now
3797
+ now,
3798
+ timeZone
3867
3799
  }) {
3868
3800
  const shared = rule.slot.sharedAcrossProducts ?? false;
3869
- const bookableUntil = windowEndsAt(rule, now);
3801
+ const bookableUntil = windowEndsAtInZone(rule, now, timeZone ?? null);
3802
+ const parts = bookingRuleParts(rule);
3870
3803
  const header = {
3871
3804
  productId,
3872
3805
  bookingRulesId,
3873
- bookingType,
3874
3806
  ratePeriod: rule.ratePeriod,
3807
+ // Time slots / sessions / date ranges — so a reader never re-classifies `ratePeriod` itself.
3808
+ bookingMethod: bookingMethodOf(rule),
3875
3809
  // Passed through for the UI to label: a group slot under minimumToRun may not run.
3876
3810
  minimumToRun: rule.slot.minimumToRun,
3877
3811
  minStay: rule.slot.minStay,
3878
3812
  maxStay: rule.slot.maxStay,
3813
+ // The same limits with their own units, both rule shapes. `minStay` / `maxStay` above go at B13 step 9.
3814
+ minStayLength: parts.method === "date-ranges" ? parts.minStay : void 0,
3815
+ maxStayLength: parts.method === "date-ranges" ? parts.maxStay : void 0,
3816
+ // The per-booking limits, so a stepper is bounded by the rules (G7) instead of a number in the flow.
3817
+ maxQtyPerBooking: rule.slot.maxQtyPerBooking,
3818
+ maxPartySize: rule.slot.maxPartySize,
3879
3819
  // Why a day can come back empty. Past this instant the rule refuses everything, so the UI
3880
3820
  // can say "beyond the booking window" where it would otherwise claim "nothing free".
3881
3821
  bookableUntil,
@@ -3899,7 +3839,7 @@ function buildAvailability({
3899
3839
  const byInstant = /* @__PURE__ */ new Map();
3900
3840
  const freeSlotsPerResource = /* @__PURE__ */ new Map();
3901
3841
  for (const { resource, slots: slots2 } of grids) {
3902
- const capacity = resource.seats ?? 1;
3842
+ const capacity = capacityOf(rule, resource);
3903
3843
  const mine = byResource.get(resource.id) ?? [];
3904
3844
  for (const slot of slots2) {
3905
3845
  const { taken, foreignProductId } = occupancyIn(mine, productId, slot.startAt, slot.bufferEndAt, shared);
@@ -3916,7 +3856,9 @@ function buildAvailability({
3916
3856
  entry.booked += foreignProductId ? capacity : taken;
3917
3857
  entry.free += free;
3918
3858
  entry.canStart = entry.canStart || slot.canStart;
3919
- entry.resources.push({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free });
3859
+ entry.resources.push(
3860
+ placesOnTheWire({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free })
3861
+ );
3920
3862
  if (free > 0) freeSlotsPerResource.set(resource.id, (freeSlotsPerResource.get(resource.id) ?? 0) + 1);
3921
3863
  byInstant.set(+slot.startAt, entry);
3922
3864
  }
@@ -3938,9 +3880,10 @@ function buildAvailability({
3938
3880
  )
3939
3881
  };
3940
3882
  });
3941
- const slots = [...byInstant.values()].sort((first, second) => +first.startAt - +second.startAt);
3883
+ const slots = [...byInstant.values()].map(placesOnTheWire).map((slot) => withMaxQtyNow(slot, slot.resources, rule.slot.maxQtyPerBooking)).sort((first, second) => +first.startAt - +second.startAt);
3942
3884
  return {
3943
3885
  ...header,
3886
+ course: soldAsCourse(rule) ? courseAvailability(rule, resources, byResource, productId, shared, now) : void 0,
3944
3887
  resources: inWindow,
3945
3888
  slots,
3946
3889
  /**
@@ -3952,6 +3895,51 @@ function buildAvailability({
3952
3895
  days: [...new Set(slots.map((slot) => slot.dayKey))]
3953
3896
  };
3954
3897
  }
3898
+ function courseAvailability(rule, resources, byResource, productId, shared, now) {
3899
+ if (resources.length === 0) return void 0;
3900
+ const sessions = courseSessions(rule, resources[0].timeZone);
3901
+ const alreadyStarted = courseStartedInZone(rule, sessions, now, resources[0].timeZone);
3902
+ const free = resources.map((resource) => {
3903
+ const mine = byResource.get(resource.id) ?? [];
3904
+ const everySession = sessions.every((session) => withinPresence(session, resource.timeZone, resource.presence));
3905
+ const freePerSession = sessions.map((session) => {
3906
+ const { taken, foreignProductId } = occupancyIn(mine, productId, session.startAt, session.bufferEndAt, shared);
3907
+ return foreignProductId ? 0 : Math.max(capacityOf(rule, resource) - taken, 0);
3908
+ });
3909
+ const fewest = everySession && !alreadyStarted ? Math.min(...freePerSession) : 0;
3910
+ return Number.isFinite(fewest) ? { resourceId: resource.id, free: fewest } : { resourceId: resource.id, free: UNLIMITED_PLACES, unlimited: true };
3911
+ });
3912
+ return withMaxQtyNow(
3913
+ {
3914
+ sessions: sessions.length,
3915
+ alreadyStarted,
3916
+ sessionTimes: sessions.map(({ startAt, endAt }) => ({ startAt, endAt })),
3917
+ startAt: sessions[0].startAt,
3918
+ endAt: sessions[sessions.length - 1].endAt,
3919
+ resources: free
3920
+ },
3921
+ free,
3922
+ rule.slot.maxQtyPerBooking
3923
+ );
3924
+ }
3925
+ function pickFreeResource(slot, qty = 1) {
3926
+ return slot.resources.find((entry) => entry.free >= qty);
3927
+ }
3928
+ function withMaxQtyNow(entry, resources, maxQtyPerBooking) {
3929
+ const largest = resources.some((resource) => resource.unlimited) ? Number.POSITIVE_INFINITY : Math.max(0, ...resources.map((resource) => resource.free));
3930
+ const maxQtyNow = Math.min(largest, maxQtyPerBooking ?? Number.POSITIVE_INFINITY);
3931
+ return Number.isFinite(maxQtyNow) ? { ...entry, maxQtyNow } : entry;
3932
+ }
3933
+ function fewestFreeOver(slots, from, to) {
3934
+ const cells = slots.filter(({ startAt, endAt }) => +startAt >= +from && +endAt <= +to);
3935
+ if (cells.length === 0) return [];
3936
+ return cells[0].resources.map((resource) => ({
3937
+ ...resource,
3938
+ free: Math.min(
3939
+ ...cells.map((cell) => cell.resources.find(({ resourceId }) => resourceId === resource.resourceId)?.free ?? 0)
3940
+ )
3941
+ }));
3942
+ }
3955
3943
  function presentAt(resources, rows, outletId) {
3956
3944
  const byResource = /* @__PURE__ */ new Map();
3957
3945
  for (const row of rows) {
@@ -3965,6 +3953,107 @@ function presentAt(resources, rows, outletId) {
3965
3953
  });
3966
3954
  }
3967
3955
 
3956
+ // booking/durations.ts
3957
+ var { MINUTE: MINUTE2, HOUR, DAY, NIGHT, WEEK, MONTH } = BookingDurationUnit;
3958
+ var NONE = [];
3959
+ var CLOCK = [MINUTE2, HOUR];
3960
+ var everyType = (units) => Object.fromEntries(Object.values(BookingRatePeriod).map((ratePeriod) => [ratePeriod, units]));
3961
+ var STAY = {
3962
+ slot: NONE,
3963
+ session: NONE,
3964
+ hour: [HOUR, DAY, WEEK],
3965
+ night: [NIGHT, WEEK, MONTH],
3966
+ day: [DAY, WEEK, MONTH],
3967
+ week: [WEEK],
3968
+ month: [MONTH]
3969
+ };
3970
+ var ALLOWED_UNITS = {
3971
+ "timeSlots.length": { ...everyType(NONE), slot: CLOCK },
3972
+ "slot.buffer": { ...everyType(CLOCK), night: NONE },
3973
+ "window.hold": everyType(CLOCK),
3974
+ "window.minNotice": everyType([MINUTE2, HOUR, DAY, WEEK]),
3975
+ "window.maxAdvance": everyType([MINUTE2, HOUR, DAY, WEEK, MONTH]),
3976
+ "dateRanges.minStay": STAY,
3977
+ "dateRanges.maxStay": STAY
3978
+ };
3979
+ function allowedDurationUnits(rule, field) {
3980
+ const units = ALLOWED_UNITS[field]?.[rule.ratePeriod];
3981
+ if (!units) throw new BookingRulesError(`Booking rules: no duration "${field}" for rate period "${rule.ratePeriod}"`);
3982
+ return units;
3983
+ }
3984
+ var DURATION_AT = {
3985
+ "timeSlots.length": (rule) => rule.timeSlots?.length,
3986
+ "slot.buffer": (rule) => rule.slot.buffer,
3987
+ "window.hold": (rule) => rule.window.hold,
3988
+ "window.minNotice": (rule) => rule.window.minNotice,
3989
+ "window.maxAdvance": (rule) => rule.window.maxAdvance,
3990
+ "dateRanges.minStay": (rule) => rule.dateRanges?.minStay,
3991
+ "dateRanges.maxStay": (rule) => rule.dateRanges?.maxStay
3992
+ };
3993
+ function durationProblems(rule) {
3994
+ const problems = Object.keys(DURATION_AT).flatMap((field) => {
3995
+ const duration = DURATION_AT[field](rule);
3996
+ const problem = duration && problemOf(field, duration, allowedDurationUnits(rule, field), rule.ratePeriod);
3997
+ return problem ? [problem] : [];
3998
+ });
3999
+ if (problems.length > 0) return problems;
4000
+ return [stayAboveMax(rule.dateRanges?.minStay, rule.dateRanges?.maxStay), noticeAboveAdvance(rule.window)].filter(
4001
+ (problem) => !!problem
4002
+ );
4003
+ }
4004
+ function problemOf(field, duration, allowed, ratePeriod) {
4005
+ if (!Number.isInteger(duration.count) || duration.count < 1) {
4006
+ const message = `${field}: count must be a whole number of at least 1, got ${String(duration.count)}`;
4007
+ return { field, kind: "count", message };
4008
+ }
4009
+ if (allowed.length === 0) {
4010
+ return { field, kind: "not-for-type", message: `${field}: does not apply to ${ratePeriod} rules` };
4011
+ }
4012
+ if (!allowed.includes(duration.unit)) {
4013
+ return { field, kind: "unit", allowed, message: `${field}: takes ${allowed.join(", ")}, got ${duration.unit}` };
4014
+ }
4015
+ return void 0;
4016
+ }
4017
+ var MINUTES_RANGE = {
4018
+ minute: [1, 1],
4019
+ hour: [60, 60],
4020
+ day: [1440, 1440],
4021
+ night: [1440, 1440],
4022
+ week: [7 * 1440, 7 * 1440],
4023
+ month: [28 * 1440, 31 * 1440]
4024
+ };
4025
+ var clockShiftOf = (unit2) => unit2 === MINUTE2 || unit2 === HOUR ? 0 : 60;
4026
+ var shortestMinutesOf = ({ count, unit: unit2 }) => count * MINUTES_RANGE[unit2][0] - clockShiftOf(unit2);
4027
+ var longestMinutesOf = ({ count, unit: unit2 }) => count * MINUTES_RANGE[unit2][1] + clockShiftOf(unit2);
4028
+ var durationText = ({ count, unit: unit2 }) => `${count} ${unit2}${count === 1 ? "" : "s"}`;
4029
+ var DAYS_IN_UNIT = { day: 1, night: 1, week: 7 };
4030
+ var MINUTES_IN_UNIT = { minute: 1, hour: 60 };
4031
+ function exactly(min, max) {
4032
+ if (min.unit === max.unit) return [min.count, max.count];
4033
+ for (const table of [DAYS_IN_UNIT, MINUTES_IN_UNIT]) {
4034
+ const [minSize, maxSize] = [table[min.unit], table[max.unit]];
4035
+ if (minSize && maxSize) return [min.count * minSize, max.count * maxSize];
4036
+ }
4037
+ return void 0;
4038
+ }
4039
+ function minLongerThanMax(min, max) {
4040
+ const exact = exactly(min, max);
4041
+ return exact ? exact[0] > exact[1] : longestMinutesOf(min) > shortestMinutesOf(max);
4042
+ }
4043
+ function stayAboveMax(min, max) {
4044
+ if (!min || !max || !minLongerThanMax(min, max)) return void 0;
4045
+ const message = `dateRanges.maxStay: Max ${durationText(max)} can be shorter than Min ${durationText(min)}`;
4046
+ return { field: "dateRanges.maxStay", kind: "min-above-max", min, max, message };
4047
+ }
4048
+ function noticeAboveAdvance({
4049
+ minNotice,
4050
+ maxAdvance
4051
+ }) {
4052
+ if (!minNotice || !maxAdvance || !minLongerThanMax(minNotice, maxAdvance)) return void 0;
4053
+ const message = `window.maxAdvance: ${durationText(maxAdvance)} ahead can be shorter than the notice of ${durationText(minNotice)}`;
4054
+ return { field: "window.maxAdvance", kind: "min-above-max", min: minNotice, max: maxAdvance, message };
4055
+ }
4056
+
3968
4057
  // booking/plan.ts
3969
4058
  var DEFAULT_HOLD_MINUTES = 10;
3970
4059
  function planWindow({ rule, timeZone, presence, startAt, endAt, now, busy = [] }) {
@@ -3972,17 +4061,687 @@ function planWindow({ rule, timeZone, presence, startAt, endAt, now, busy = [] }
3972
4061
  (slot) => withinPresence(slot, timeZone, presence)
3973
4062
  );
3974
4063
  const slots = slotsForWindow(grid, startAt, endAt);
3975
- const { minStay, maxStay } = rule.slot;
3976
- if (minStay && slots.length < minStay) {
3977
- throw new BookingRulesError(`These rules ask for at least ${minStay} period(s), got ${slots.length}`);
4064
+ const last = slots[slots.length - 1];
4065
+ const parts = bookingRuleParts(rule);
4066
+ const wholePeriods = parts.method === "date-ranges" && parts.wholePeriods;
4067
+ const periods = wholePeriods ? wholePeriodsIn(rule.ratePeriod, timeZone, startAt, last.endAt, slots.length) : slots.length;
4068
+ checkStay(parts, timeZone, startAt, periods);
4069
+ const { buffer } = ruleDurationsOf(rule);
4070
+ const bufferEndAt = rule.ratePeriod === "hour" /* HOUR */ || wholePeriods ? buffer ? addDuration(last.endAt, buffer, timeZone) : new Date(last.endAt.getTime()) : last.bufferEndAt;
4071
+ return { slots, periods, endAt: last.endAt, bufferEndAt };
4072
+ }
4073
+ function checkStay(parts, timeZone, startAt, periods) {
4074
+ if (parts.method !== "date-ranges") return;
4075
+ const stay = { count: periods, unit: periodUnitOf(parts) };
4076
+ const length = (duration) => stayLength(parts.ratePeriod, duration, startAt, timeZone);
4077
+ const { minStay, maxStay } = parts;
4078
+ if (minStay && length(stay) < length(minStay)) {
4079
+ throw new BookingRulesError(
4080
+ `These rules ask for a stay of at least ${durationText(minStay)}, got ${durationText(stay)}`
4081
+ );
3978
4082
  }
3979
- if (maxStay && slots.length > maxStay) {
3980
- throw new BookingRulesError(`These rules allow at most ${maxStay} period(s), got ${slots.length}`);
4083
+ if (maxStay && length(stay) > length(maxStay)) {
4084
+ throw new BookingRulesError(
4085
+ `These rules allow a stay of at most ${durationText(maxStay)}, got ${durationText(stay)}`
4086
+ );
3981
4087
  }
3982
- const last = slots[slots.length - 1];
3983
- return { slots, endAt: last.endAt, bufferEndAt: last.bufferEndAt };
3984
4088
  }
3985
- var holdExpiresAt = (rule, now) => new Date(now.getTime() + (rule.window.holdMinutes ?? DEFAULT_HOLD_MINUTES) * 6e4);
4089
+ function stayLength(ratePeriod, duration, startAt, timeZone) {
4090
+ if (ratePeriod === "hour" /* HOUR */) return addDuration(startAt, duration, timeZone).getTime();
4091
+ const { count, unit: unit2 } = duration;
4092
+ if (unit2 === "day" /* DAY */ || unit2 === "night" /* NIGHT */) return count;
4093
+ if (unit2 === "week" /* WEEK */) return 7 * count;
4094
+ if (unit2 !== "month" /* MONTH */) {
4095
+ throw new BookingRulesError(`Booking rules: a ${ratePeriod} stay cannot be counted in ${unit2}s`);
4096
+ }
4097
+ const { year, month, day } = zonedParts(startAt, timeZone);
4098
+ const [toYear, toMonth, toDay] = sameDayMonthsLaterDate(year, month, day, count);
4099
+ return (Date.UTC(toYear, toMonth - 1, toDay) - Date.UTC(year, month - 1, day)) / 864e5;
4100
+ }
4101
+ function windowForPeriods({ rule, timeZone, startAt, periods, now }) {
4102
+ if (!Number.isInteger(periods) || periods < 1) {
4103
+ throw new BookingRulesError(`periods must be a whole number of at least 1, got ${String(periods)}`);
4104
+ }
4105
+ const parts = bookingRuleParts(rule);
4106
+ checkStay(parts, timeZone, startAt, periods);
4107
+ const wholePeriods = parts.method === "date-ranges" && parts.wholePeriods;
4108
+ const monthsEnd = wholePeriods && rule.ratePeriod === "month" /* MONTH */ ? sameDayMonthsLater(startAt, periods, timeZone) : null;
4109
+ const cells = wholePeriods && rule.ratePeriod === "week" /* WEEK */ ? periods * 7 : periods;
4110
+ const lastDay = monthsEnd ?? new Date(startAt.getTime() + (cells + 2) * 1440 * 6e4);
4111
+ const grid = buildGrid(
4112
+ rule,
4113
+ timeZone,
4114
+ startAt,
4115
+ new Date(Math.min(lastDay.getTime() + 1440 * 6e4, startAt.getTime() + 366 * 1440 * 6e4)),
4116
+ now
4117
+ );
4118
+ const startIndex = grid.findIndex((cell) => cell.startAt.getTime() === startAt.getTime());
4119
+ if (startIndex < 0)
4120
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
4121
+ const endAt = monthsEnd ?? grid[startIndex + cells - 1]?.endAt;
4122
+ if (!endAt)
4123
+ throw new BookingRulesError(`${periods} period(s) from ${startAt.toISOString()} run past the bookable grid`);
4124
+ slotsForWindow(grid, startAt, endAt);
4125
+ return { startAt, endAt };
4126
+ }
4127
+ function rentalEnds(input) {
4128
+ const { rule, timeZone, startAt, now, untilDay } = input;
4129
+ const parts = bookingRuleParts(rule);
4130
+ if (parts.method !== "date-ranges") throw new BookingRulesError("Only date-range rules book a stay");
4131
+ const horizon = shopDayRange(untilDay, 1, timeZone).to;
4132
+ if (horizon <= startAt) throw new BookingRulesError(`untilDay ${untilDay} is before the stay starts`);
4133
+ const gridUntil = (end) => buildGrid(rule, timeZone, startAt, new Date(Math.min(end, startAt.getTime() + 366 * 1440 * 6e4)), now);
4134
+ let walk = walkRentalEnds(gridUntil(horizon.getTime() + 1440 * 6e4), input, parts, horizon);
4135
+ if (!walk.ends.length && walk.refusal && walk.ranOut)
4136
+ walk = walkRentalEnds(gridUntil(Infinity), input, parts, horizon);
4137
+ if (walk.ends.length) return walk.ends;
4138
+ throw walk.refusal ?? new BookingRulesError(
4139
+ `No stay from ${startAt.toISOString()} fits these rules: the bookable days run out before the shortest allowed stay`
4140
+ );
4141
+ }
4142
+ function walkRentalEnds(grid, { rule, timeZone, startAt, untilDay }, parts, horizon) {
4143
+ const startIndex = grid.findIndex((cell) => cell.startAt.getTime() === startAt.getTime());
4144
+ if (startIndex < 0) {
4145
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
4146
+ }
4147
+ slotsForWindow(grid, startAt, grid[startIndex].endAt);
4148
+ const ends = [];
4149
+ let refusal;
4150
+ for (const cell of grid.slice(startIndex)) {
4151
+ if (cell.endAt > horizon && (ends.length || !refusal)) {
4152
+ refusal ??= new BookingRulesError(`No stay from ${startAt.toISOString()} ends on or before ${untilDay}`);
4153
+ return { ends, refusal, ranOut: false };
4154
+ }
4155
+ const slots = refusalOr(() => slotsForWindow(grid, startAt, cell.endAt));
4156
+ if (slots instanceof BookingRulesError) return { ends, refusal, ranOut: false };
4157
+ const periods = refusalOr(
4158
+ () => parts.wholePeriods ? wholePeriodsIn(rule.ratePeriod, timeZone, startAt, cell.endAt, slots.length) : slots.length
4159
+ );
4160
+ if (periods instanceof BookingRulesError) continue;
4161
+ const stay = refusalOr(() => checkStay(parts, timeZone, startAt, periods));
4162
+ if (stay instanceof BookingRulesError) {
4163
+ if (ends.length) return { ends, refusal, ranOut: false };
4164
+ refusal = stay;
4165
+ continue;
4166
+ }
4167
+ ends.push(rentalEndOf(slots, periods, timeZone));
4168
+ }
4169
+ return { ends, refusal, ranOut: true };
4170
+ }
4171
+ function rentalEndOf(slots, periods, timeZone) {
4172
+ const endAt = slots[slots.length - 1].endAt;
4173
+ return {
4174
+ periods,
4175
+ endAt: endAt.toISOString(),
4176
+ lastDayKey: shopDayKey(new Date(endAt.getTime() - 1), timeZone),
4177
+ coveredSlots: slots.map((slot) => ({
4178
+ startAt: slot.startAt.toISOString(),
4179
+ dayKey: shopDayKey(slot.startAt, timeZone)
4180
+ }))
4181
+ };
4182
+ }
4183
+ function refusalOr(run) {
4184
+ try {
4185
+ return run();
4186
+ } catch (error) {
4187
+ if (error instanceof BookingRulesError) return error;
4188
+ throw error;
4189
+ }
4190
+ }
4191
+ function sameDayMonthsLater(startAt, months, timeZone) {
4192
+ const { year, month, day } = zonedParts(startAt, timeZone);
4193
+ return instantFromLocal(...sameDayMonthsLaterDate(year, month, day, months), 0, timeZone);
4194
+ }
4195
+ function wholePeriodsIn(ratePeriod, timeZone, startAt, endAt, days) {
4196
+ if (ratePeriod === "week" /* WEEK */) {
4197
+ if (days % 7 !== 0) throw new BookingRulesError(`Book whole weeks: ${days} day(s) is not a number of weeks`);
4198
+ return days / 7;
4199
+ }
4200
+ if (ratePeriod !== "month" /* MONTH */) {
4201
+ throw new BookingRulesError("Whole periods are for week and month rules only");
4202
+ }
4203
+ const start = zonedParts(startAt, timeZone);
4204
+ const end = zonedParts(endAt, timeZone);
4205
+ const months = (end.year - start.year) * 12 + (end.month - start.month);
4206
+ const lastDayOfEndMonth = new Date(Date.UTC(end.year, end.month, 0)).getUTCDate();
4207
+ if (months < 1 || end.day !== Math.min(start.day, lastDayOfEndMonth)) {
4208
+ throw new BookingRulesError("Book whole months: the stay must end on the same day of a later month");
4209
+ }
4210
+ return months;
4211
+ }
4212
+ function courseSessions(rule, timeZone) {
4213
+ const { bookableFrom, bookableTo } = rule.window;
4214
+ if (!bookableFrom || !bookableTo) throw new BookingRulesError("A course needs both course dates");
4215
+ const sessions = sessionCells(rule, timeZone, new Date(bookableFrom), new Date(bookableTo)).sort(
4216
+ (first, second) => +first.startAt - +second.startAt
4217
+ );
4218
+ if (sessions.length === 0) throw new BookingRulesError("These course dates hold no session");
4219
+ return sessions;
4220
+ }
4221
+ var courseStarted = (rule, sessions, now) => sessions[0].startAt.getTime() < now.getTime() + (rule.window.minNoticeMinutes ?? 0) * 6e4;
4222
+ function courseStartedInZone(rule, sessions, now, timeZone) {
4223
+ const { minNotice } = ruleDurationsOf(rule);
4224
+ return sessions[0].startAt.getTime() < (minNotice ? addDuration(now, minNotice, timeZone) : now).getTime();
4225
+ }
4226
+ function planCourse({ rule, timeZone, presence, now }) {
4227
+ const sessions = courseSessions(rule, timeZone);
4228
+ if (!sessions.every((session) => withinPresence(session, timeZone, presence))) {
4229
+ throw new BookingRulesError("This resource is not there for every session of the course");
4230
+ }
4231
+ if (courseStartedInZone(rule, sessions, now, timeZone))
4232
+ throw new BookingRulesError("This course has already started");
4233
+ return sessions;
4234
+ }
4235
+ function holdExpiresAt(rule, now) {
4236
+ return addClockDuration(now, holdOf(rule) ?? DEFAULT_HOLD);
4237
+ }
4238
+ var DEFAULT_HOLD = { count: DEFAULT_HOLD_MINUTES, unit: "minute" /* MINUTE */ };
4239
+ function holdOf(rule) {
4240
+ const { hold } = ruleDurationsOf(rule);
4241
+ if (!hold) return void 0;
4242
+ const field = rule.window.hold ? "window.hold" : "window.holdMinutes";
4243
+ if (!Number.isInteger(hold.count)) {
4244
+ throw new BookingRulesError(`${field} must be a whole number of ${hold.unit}s, got ${hold.count}`);
4245
+ }
4246
+ if (hold.count < 1) throw new BookingRulesError(`${field} must be at least 1 ${hold.unit}, got ${hold.count}`);
4247
+ return hold;
4248
+ }
4249
+ function checkQtyPerBooking(rule, qty) {
4250
+ const max = rule.slot.maxQtyPerBooking;
4251
+ if (max !== void 0 && qty > max) {
4252
+ throw new BookingRulesError(`These rules allow at most ${max} per booking, got ${qty}`);
4253
+ }
4254
+ }
4255
+ function checkPartySize(rule, partySize) {
4256
+ const max = rule.slot.maxPartySize;
4257
+ if (max !== void 0 && partySize > max) {
4258
+ throw new BookingRulesError(`These rules allow at most ${max} people per booking, got ${partySize}`);
4259
+ }
4260
+ }
4261
+ function bookingMethodOf(rule) {
4262
+ if (rule.ratePeriod === "slot" /* SLOT */) return "time-slots";
4263
+ if (rule.ratePeriod === "session" /* SESSION */) return "sessions";
4264
+ return "date-ranges";
4265
+ }
4266
+ var soldAsCourse = (rule) => rule.ratePeriod === "session" /* SESSION */ && rule.sessions?.sold === "course" /* COURSE */;
4267
+ function capacityOf(rule, resource) {
4268
+ if (rule.ratePeriod !== "session" /* SESSION */) return resource.seats ?? 1;
4269
+ if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4270
+ return rule.sessions.spots ?? Number.POSITIVE_INFINITY;
4271
+ }
4272
+ function bookingRuleParts(rule) {
4273
+ const method = bookingMethodOf(rule);
4274
+ if (method === "sessions") {
4275
+ if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4276
+ return { method, sessions: rule.sessions };
4277
+ }
4278
+ if (method === "time-slots") {
4279
+ const timeSlots = rule.timeSlots ? newTimeSlotsOf(rule.timeSlots) : oldTimeSlotsOf(rule);
4280
+ const { count } = timeSlots.length;
4281
+ if (!Number.isInteger(count) || count < 1) {
4282
+ const field = rule.timeSlots ? "timeSlots.length" : "slot.lengthMinutes";
4283
+ throw new BookingRulesError(`Booking rules: ${field} must be a whole number of at least 1, got ${count}`);
4284
+ }
4285
+ return { method, ...timeSlots };
4286
+ }
4287
+ if (!rule.dateRanges) return { method, ratePeriod: rule.ratePeriod, ...oldDateRangesOf(rule) };
4288
+ const wholePeriods = rule.ratePeriod === "week" /* WEEK */ || rule.ratePeriod === "month" /* MONTH */;
4289
+ return { method, ratePeriod: rule.ratePeriod, wholePeriods, ...rule.dateRanges };
4290
+ }
4291
+ function newTimeSlotsOf({ length, weeklyHours }) {
4292
+ if (!weeklyHours?.length) throw new BookingRulesError("Booking rules: timeSlots.weeklyHours needs at least one day");
4293
+ return { length, weeklyHours };
4294
+ }
4295
+ function oldTimeSlotsOf({ slot, availability }) {
4296
+ if (slot.lengthMinutes == null) throw new BookingRulesError("Time-slot rules need their slot length");
4297
+ return {
4298
+ length: { count: slot.lengthMinutes, unit: "minute" /* MINUTE */ },
4299
+ weeklyHours: availability.weeklyHours ?? []
4300
+ };
4301
+ }
4302
+ function oldDateRangesOf(rule) {
4303
+ const { slot, availability } = rule;
4304
+ const wholePeriods = slot.wholePeriods ?? false;
4305
+ const stay = (count) => count ? { count, unit: periodUnitOf({ ratePeriod: rule.ratePeriod, wholePeriods }) } : void 0;
4306
+ return {
4307
+ // Old `[]` meant "open every day" — the new form says that by having no rows.
4308
+ weeklyHours: availability.weeklyHours?.length ? availability.weeklyHours : void 0,
4309
+ arrivalDays: availability.arrivalDays,
4310
+ checkInTime: rule.checkInTime,
4311
+ checkOutTime: rule.checkOutTime,
4312
+ checkTimesByWeekday: rule.checkTimesByWeekday,
4313
+ minStay: stay(slot.minStay),
4314
+ maxStay: stay(slot.maxStay),
4315
+ wholePeriods
4316
+ };
4317
+ }
4318
+ function periodUnitOf({
4319
+ ratePeriod,
4320
+ wholePeriods
4321
+ }) {
4322
+ const units = {
4323
+ ["hour" /* HOUR */]: "hour" /* HOUR */,
4324
+ ["night" /* NIGHT */]: "night" /* NIGHT */,
4325
+ ["day" /* DAY */]: "day" /* DAY */,
4326
+ ["week" /* WEEK */]: wholePeriods ? "week" /* WEEK */ : "day" /* DAY */,
4327
+ ["month" /* MONTH */]: wholePeriods ? "month" /* MONTH */ : "day" /* DAY */
4328
+ };
4329
+ const unit2 = units[ratePeriod];
4330
+ if (!unit2) throw new BookingRulesError(`Booking rules: "${ratePeriod}" is not a date-range rate period`);
4331
+ return unit2;
4332
+ }
4333
+ var OLD_BUFFER = {
4334
+ path: "slot.bufferMinutes",
4335
+ home: {
4336
+ "time-slots": "slot.buffer",
4337
+ sessions: "slot.buffer",
4338
+ // The old night grid never read it: housekeeping is the gap between check-out and check-in (O-1).
4339
+ "date-ranges": ({ ratePeriod }) => ratePeriod === "night" /* NIGHT */ ? { unread: "nights clean between check-out and check-in" } : "slot.buffer"
4340
+ }
4341
+ };
4342
+ var OLD_FIELDS = [
4343
+ {
4344
+ path: "slot.lengthMinutes",
4345
+ home: {
4346
+ "time-slots": "timeSlots.length",
4347
+ sessions: { unread: "placeholder" },
4348
+ "date-ranges": { unread: "placeholder" }
4349
+ }
4350
+ },
4351
+ OLD_BUFFER,
4352
+ {
4353
+ path: "slot.minStay",
4354
+ home: {
4355
+ "time-slots": { dropped: "time-slots rules have no stay limits" },
4356
+ sessions: { dropped: "sessions rules have no stay limits" },
4357
+ "date-ranges": "dateRanges.minStay"
4358
+ }
4359
+ },
4360
+ {
4361
+ path: "slot.maxStay",
4362
+ home: {
4363
+ "time-slots": { dropped: "time-slots rules have no stay limits" },
4364
+ sessions: { dropped: "sessions rules have no stay limits" },
4365
+ "date-ranges": "dateRanges.maxStay"
4366
+ }
4367
+ },
4368
+ {
4369
+ path: "window.holdMinutes",
4370
+ home: { "time-slots": "window.hold", sessions: "window.hold", "date-ranges": "window.hold" }
4371
+ },
4372
+ {
4373
+ path: "window.minNoticeMinutes",
4374
+ home: { "time-slots": "window.minNotice", sessions: "window.minNotice", "date-ranges": "window.minNotice" }
4375
+ },
4376
+ // The two old max-advance fields are one fact, as the old readers took it: minutes, else days × 1440.
4377
+ ...["window.maxAdvanceMinutes", "window.maxAdvanceDays"].map((path) => ({
4378
+ path,
4379
+ carried: maxAdvanceMinutesOf,
4380
+ home: { "time-slots": "window.maxAdvance", sessions: "window.maxAdvance", "date-ranges": "window.maxAdvance" }
4381
+ })),
4382
+ {
4383
+ path: "availability.weeklyHours",
4384
+ home: {
4385
+ "time-slots": "timeSlots.weeklyHours",
4386
+ sessions: { unread: "sessions read their timetable" },
4387
+ "date-ranges": "dateRanges.weeklyHours"
4388
+ }
4389
+ },
4390
+ ...["availability.arrivalDays", "checkInTime", "checkOutTime", "checkTimesByWeekday"].map((path) => ({
4391
+ path,
4392
+ home: {
4393
+ "time-slots": { unread: "date ranges only" },
4394
+ sessions: { unread: "date ranges only" },
4395
+ "date-ranges": `dateRanges.${path.replace("availability.", "")}`
4396
+ }
4397
+ }))
4398
+ ];
4399
+ var homeOf = (field, rule) => {
4400
+ const home = field.home[bookingMethodOf(rule)];
4401
+ return typeof home === "function" ? home(rule) : home;
4402
+ };
4403
+ var carriedValueOf = (rule, field) => field.carried ? field.carried(rule) : valueAt(rule, field.path);
4404
+ var carries = (value) => value != null && value !== 0 && !(Array.isArray(value) && value.length === 0);
4405
+ function ruleInNewShape(rule) {
4406
+ const set = { ...typePartInNewShape(rule), ...durationsInNewShape(rule) };
4407
+ const unset = [...OLD_FIELDS.map(({ path }) => path), "slot.wholePeriods"].filter(
4408
+ (path) => valueAt(rule, path) !== void 0
4409
+ );
4410
+ const written = writtenRule(rule, set, unset);
4411
+ bookingRuleParts(written);
4412
+ refuseLostValues(rule, written);
4413
+ const changesBehaviour = sellsOneDayOfWeekOrMonth(rule) ? "whole-periods" : void 0;
4414
+ const notes = [
4415
+ ...droppedFieldNotes(rule, written),
4416
+ ...changesBehaviour ? [`${rule.ratePeriod} rule now sells whole ${rule.ratePeriod}s, was one day per booking`] : []
4417
+ ];
4418
+ return { set, unset, problems: durationProblems(written), notes, ...changesBehaviour && { changesBehaviour } };
4419
+ }
4420
+ function typePartInNewShape(rule) {
4421
+ const method = bookingMethodOf(rule);
4422
+ if (method === "sessions") return {};
4423
+ if (method === "time-slots") return { timeSlots: newTimeSlotsOf(rule.timeSlots ?? oldTimeSlotsOf(rule)) };
4424
+ if (rule.dateRanges) return { dateRanges: rule.dateRanges };
4425
+ const dateRanges = oldDateRangesOf(rule);
4426
+ delete dateRanges.wholePeriods;
4427
+ return { dateRanges: definedOnly(dateRanges) };
4428
+ }
4429
+ function durationsInNewShape(rule) {
4430
+ const { buffer, minNotice } = ruleDurationsOf(rule);
4431
+ return definedOnly({
4432
+ "slot.buffer": rule.slot.buffer ?? (typeof homeOf(OLD_BUFFER, rule) === "string" ? buffer : void 0),
4433
+ "window.hold": holdOf(rule) ?? DEFAULT_HOLD,
4434
+ "window.minNotice": minNotice,
4435
+ "window.maxAdvance": ruleDurationsOf(rule).maxAdvance
4436
+ });
4437
+ }
4438
+ var sellsOneDayOfWeekOrMonth = ({ ratePeriod, slot, dateRanges }) => !dateRanges && (ratePeriod === "week" /* WEEK */ || ratePeriod === "month" /* MONTH */) && !slot.wholePeriods;
4439
+ function droppedFieldNotes(rule, written) {
4440
+ const weekOrMonth = rule.ratePeriod === "week" /* WEEK */ || rule.ratePeriod === "month" /* MONTH */;
4441
+ return [
4442
+ ...OLD_FIELDS.flatMap((field) => {
4443
+ const home = homeOf(field, rule);
4444
+ const dropped = typeof home === "object" && "dropped" in home && carries(carriedValueOf(rule, field));
4445
+ return dropped ? [`${field.path} is dropped: ${home.dropped}`] : [];
4446
+ }),
4447
+ ...rule.slot.wholePeriods && !weekOrMonth ? ["slot.wholePeriods is dropped: only week and month rules have it"] : [],
4448
+ ...rule.ratePeriod === "hour" /* HOUR */ && !written.dateRanges?.weeklyHours?.length ? ["hour rule has no opening hours: nothing can be booked"] : [],
4449
+ ...rule.window.holdMinutes == null && !rule.window.hold ? [`window.hold is set to the default ${DEFAULT_HOLD_MINUTES} minutes`] : []
4450
+ ];
4451
+ }
4452
+ function writtenRule(rule, set, unset) {
4453
+ const written = {
4454
+ ...rule,
4455
+ slot: { ...rule.slot },
4456
+ window: { ...rule.window },
4457
+ availability: { ...rule.availability }
4458
+ };
4459
+ for (const path of unset) {
4460
+ const [head, leaf] = path.split(".");
4461
+ if (leaf) delete written[head][leaf];
4462
+ else delete written[head];
4463
+ }
4464
+ for (const [path, value] of Object.entries(set)) {
4465
+ const [head, leaf] = path.split(".");
4466
+ if (leaf) written[head][leaf] = value;
4467
+ else written[head] = value;
4468
+ }
4469
+ return written;
4470
+ }
4471
+ function refuseLostValues(rule, written) {
4472
+ for (const field of OLD_FIELDS) {
4473
+ const home = homeOf(field, rule);
4474
+ if (typeof home === "string" && carries(carriedValueOf(rule, field)) && valueAt(written, home) == null) {
4475
+ throw new BookingRulesError(`Booking rules: ${home} is missing \u2014 the rule's old value would be lost`);
4476
+ }
4477
+ }
4478
+ }
4479
+ var definedOnly = (value) => Object.fromEntries(Object.entries(value).filter(([, entry]) => entry != null));
4480
+ var valueAt = (rule, path) => path.split(".").reduce((node, key) => node?.[key], rule);
4481
+
4482
+ // booking/grid.ts
4483
+ var MINUTE3 = 6e4;
4484
+ var HOUR_MINUTES = 60;
4485
+ var MAX_RANGE_DAYS = 366;
4486
+ var asTime = (value, field) => {
4487
+ if (value == null) return void 0;
4488
+ const time = new Date(value).getTime();
4489
+ if (Number.isNaN(time)) throw new BookingRulesError(`Booking rules: ${field} is not a date, got "${String(value)}"`);
4490
+ return time;
4491
+ };
4492
+ function parseHhMm(value, field) {
4493
+ const [hours, minutes] = value.split(":").map(Number);
4494
+ if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
4495
+ throw new BookingRulesError(`Booking rules: ${field} must be "HH:mm", got "${value}"`);
4496
+ }
4497
+ return hours * 60 + minutes;
4498
+ }
4499
+ function windowEndsAt(rule, now) {
4500
+ const maxAdvanceMinutes = maxAdvanceMinutesOf(rule);
4501
+ const ends = Math.min(
4502
+ maxAdvanceMinutes ? now.getTime() + maxAdvanceMinutes * MINUTE3 : Number.POSITIVE_INFINITY,
4503
+ asTime(rule.window.bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
4504
+ );
4505
+ return Number.isFinite(ends) ? new Date(ends) : null;
4506
+ }
4507
+ function windowEndsAtInZone(rule, now, timeZone) {
4508
+ const { maxAdvance } = ruleDurationsOf(rule);
4509
+ const ends = Math.min(
4510
+ maxAdvance ? addInZone(now, maxAdvance, timeZone, "window.maxAdvance").getTime() : Number.POSITIVE_INFINITY,
4511
+ asTime(rule.window.bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
4512
+ );
4513
+ return Number.isFinite(ends) ? new Date(ends) : null;
4514
+ }
4515
+ function addInZone(from, duration, timeZone, field) {
4516
+ if (timeZone) return addDuration(from, duration, timeZone);
4517
+ if (duration.unit === "minute" /* MINUTE */ || duration.unit === "hour" /* HOUR */) {
4518
+ return addClockDuration(from, duration);
4519
+ }
4520
+ throw new BookingRulesError(`Booking rules: ${field} in ${duration.unit}s needs the shop's time zone`);
4521
+ }
4522
+ function maxAdvanceMinutesOf(rule) {
4523
+ const { maxAdvanceMinutes, maxAdvanceDays } = rule.window;
4524
+ return maxAdvanceMinutes ?? (maxAdvanceDays ?? 0) * 1440;
4525
+ }
4526
+ var asMinutes = (minutes) => minutes == null ? void 0 : { count: minutes, unit: "minute" /* MINUTE */ };
4527
+ var inMinutes = (minutes) => minutes === 0 ? void 0 : asMinutes(minutes);
4528
+ function notNegative(duration, field) {
4529
+ if (duration && !(Number.isFinite(duration.count) && duration.count >= 0)) {
4530
+ throw new BookingRulesError(`Booking rules: ${field} must be a number of at least 0, got ${duration.count}`);
4531
+ }
4532
+ return duration;
4533
+ }
4534
+ function ruleDurationsOf(rule) {
4535
+ const { slot, window } = rule;
4536
+ return {
4537
+ buffer: notNegative(
4538
+ slot.buffer ?? inMinutes(slot.bufferMinutes),
4539
+ slot.buffer ? "slot.buffer" : "slot.bufferMinutes"
4540
+ ),
4541
+ hold: window.hold ?? asMinutes(window.holdMinutes),
4542
+ minNotice: notNegative(
4543
+ window.minNotice ?? inMinutes(window.minNoticeMinutes),
4544
+ window.minNotice ? "window.minNotice" : "window.minNoticeMinutes"
4545
+ ),
4546
+ maxAdvance: window.maxAdvance ?? oldMaxAdvanceOf(window)
4547
+ };
4548
+ }
4549
+ function oldMaxAdvanceOf({
4550
+ maxAdvanceMinutes,
4551
+ maxAdvanceDays
4552
+ }) {
4553
+ const days = maxAdvanceDays ?? 0;
4554
+ if (maxAdvanceMinutes == null || days > 0 && maxAdvanceMinutes === days * 1440) {
4555
+ return days > 0 ? { count: days, unit: "day" /* DAY */ } : void 0;
4556
+ }
4557
+ return maxAdvanceMinutes ? { count: maxAdvanceMinutes, unit: "minute" /* MINUTE */ } : void 0;
4558
+ }
4559
+ function periodSlot(dayStart, timeZone, parts, buffer, openMinute, closeMinute) {
4560
+ const { ratePeriod } = parts;
4561
+ const at = (minutes) => atZonedMinute(dayStart, minutes, timeZone);
4562
+ if (ratePeriod === "night" /* NIGHT */) {
4563
+ const arrival = zonedParts(dayStart, timeZone).weekday;
4564
+ const departure = (arrival + 1) % 7;
4565
+ return {
4566
+ startAt: at(checkTimesOf(parts, arrival).checkIn),
4567
+ endAt: at(1440 + checkTimesOf(parts, departure).checkOut),
4568
+ // Housekeeping sits between check-out and the next check-in: it costs no night.
4569
+ bufferEndAt: at(1440 + checkTimesOf(parts, departure).checkIn),
4570
+ canStart: true
4571
+ };
4572
+ }
4573
+ const from = ratePeriod === "day" /* DAY */ ? openMinute ?? 0 : 0;
4574
+ const to = ratePeriod === "day" /* DAY */ ? closeMinute ?? 1440 : 1440;
4575
+ const turnaround = parts.wholePeriods ? void 0 : buffer;
4576
+ return {
4577
+ startAt: at(from),
4578
+ endAt: at(to),
4579
+ bufferEndAt: turnaround ? addDuration(at(to), turnaround, timeZone) : at(to),
4580
+ canStart: true
4581
+ };
4582
+ }
4583
+ function checkTimesOf(rule, weekday) {
4584
+ const row = rule.checkTimesByWeekday?.find((entry) => entry.weekday === weekday);
4585
+ const checkInTime = row?.checkInTime ?? rule.checkInTime;
4586
+ const checkOutTime = row?.checkOutTime ?? rule.checkOutTime;
4587
+ if (!checkInTime || !checkOutTime) {
4588
+ throw new BookingRulesError("Overnight booking rules need both checkInTime and checkOutTime");
4589
+ }
4590
+ return { checkIn: parseHhMm(checkInTime, "checkInTime"), checkOut: parseHhMm(checkOutTime, "checkOutTime") };
4591
+ }
4592
+ function freeGaps(openAt, closeAt, busy) {
4593
+ const inside = busy.map(({ startAt, bufferEndAt }) => ({ from: +startAt, to: +bufferEndAt })).filter(({ from, to }) => to > openAt && from < closeAt).sort((first, second) => first.from - second.from);
4594
+ const gaps = [];
4595
+ let cursor = openAt;
4596
+ for (const { from, to } of inside) {
4597
+ if (from > cursor) gaps.push({ from: cursor, to: from, endsAtBooking: true });
4598
+ cursor = Math.max(cursor, to);
4599
+ if (cursor >= closeAt) break;
4600
+ }
4601
+ if (cursor < closeAt) gaps.push({ from: cursor, to: closeAt, endsAtBooking: false });
4602
+ return gaps;
4603
+ }
4604
+ function sessionCells(rule, timeZone, from, to) {
4605
+ if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4606
+ const { weekly = [], dates = [] } = rule.sessions;
4607
+ const { buffer } = ruleDurationsOf(rule);
4608
+ const cell = (startAt, endAt) => ({
4609
+ startAt: new Date(startAt),
4610
+ endAt: new Date(endAt),
4611
+ bufferEndAt: buffer ? addDuration(new Date(endAt), buffer, timeZone) : new Date(endAt),
4612
+ canStart: true
4613
+ });
4614
+ const cells = dates.map(({ date, startMinute, endMinute }) => {
4615
+ const [year, month, day] = calendarDate(date);
4616
+ return cell(
4617
+ +instantFromLocal(year, month, day, startMinute, timeZone),
4618
+ +instantFromLocal(year, month, day, endMinute, timeZone)
4619
+ );
4620
+ });
4621
+ const lastDay = startOfZonedDay(to, timeZone).getTime();
4622
+ for (let day = startOfZonedDay(from, timeZone); day.getTime() <= lastDay; day = nextZonedDay(day, timeZone)) {
4623
+ const weekday = zonedParts(day, timeZone).weekday;
4624
+ for (const row of weekly.filter((entry) => entry.weekday === weekday)) {
4625
+ cells.push(cell(+atZonedMinute(day, row.startMinute, timeZone), +atZonedMinute(day, row.endMinute, timeZone)));
4626
+ }
4627
+ }
4628
+ const blocked = offMarketOf(rule);
4629
+ return cells.filter(({ startAt, bufferEndAt }) => {
4630
+ const start = startAt.getTime();
4631
+ return start >= from.getTime() && start <= to.getTime() && !isBlocked(blocked, start, bufferEndAt.getTime());
4632
+ });
4633
+ }
4634
+ function calendarDate(value) {
4635
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value ?? "");
4636
+ const [year, month, day] = match ? match.slice(1).map(Number) : [];
4637
+ const real = match && new Date(Date.UTC(year, month - 1, day)).toISOString().slice(0, 10) === value;
4638
+ if (!real) throw new BookingRulesError(`Booking rules: "${value}" is not a date (YYYY-MM-DD)`);
4639
+ return [year, month, day];
4640
+ }
4641
+ var offMarketOf = (rule) => (rule.availability.offMarket ?? []).map(({ from: blockFrom, to: blockTo }) => ({
4642
+ from: asTime(blockFrom, "availability.offMarket.from"),
4643
+ to: asTime(blockTo, "availability.offMarket.to")
4644
+ }));
4645
+ var isBlocked = (blocked, start, bufferEnd) => blocked.some(({ from, to }) => start < to && bufferEnd > from);
4646
+ function hourCells(openAt, closeAt) {
4647
+ const cells = [];
4648
+ for (let start = openAt; start + HOUR_MINUTES * MINUTE3 <= closeAt; start += HOUR_MINUTES * MINUTE3) {
4649
+ const endAt = new Date(start + HOUR_MINUTES * MINUTE3);
4650
+ cells.push({ startAt: new Date(start), endAt, bufferEndAt: endAt, canStart: true });
4651
+ }
4652
+ return cells;
4653
+ }
4654
+ function cellsOf(rule, parts, timeZone, from, to, busy) {
4655
+ if (parts.method === "sessions") return sessionCells(rule, timeZone, from, to);
4656
+ const { buffer } = ruleDurationsOf(rule);
4657
+ const cells = [];
4658
+ const lastDay = startOfZonedDay(to, timeZone).getTime();
4659
+ for (let day = startOfZonedDay(from, timeZone); day.getTime() <= lastDay; day = nextZonedDay(day, timeZone)) {
4660
+ cells.push(
4661
+ ...parts.method === "time-slots" ? timeSlotCells(parts, buffer, day, timeZone, busy) : periodCells(parts, buffer, day, timeZone)
4662
+ );
4663
+ }
4664
+ return cells;
4665
+ }
4666
+ function timeSlotCells(parts, buffer, dayStart, timeZone, busy) {
4667
+ const weekday = zonedParts(dayStart, timeZone).weekday;
4668
+ return parts.weeklyHours.filter((entry) => entry.weekday === weekday).flatMap(
4669
+ (row) => freeGaps(
4670
+ +atZonedMinute(dayStart, row.openMinute, timeZone),
4671
+ +atZonedMinute(dayStart, row.closeMinute, timeZone),
4672
+ busy
4673
+ ).flatMap((gap) => cellsInGap(gap, parts.length, buffer, timeZone))
4674
+ );
4675
+ }
4676
+ function cellsInGap(gap, length, buffer, timeZone) {
4677
+ const cells = [];
4678
+ for (let start = gap.from; ; ) {
4679
+ const endAt = addDuration(new Date(start), length, timeZone);
4680
+ const bufferEndAt = buffer ? addDuration(endAt, buffer, timeZone) : new Date(endAt.getTime());
4681
+ if ((gap.endsAtBooking ? bufferEndAt : endAt).getTime() > gap.to) return cells;
4682
+ cells.push({ startAt: new Date(start), endAt, bufferEndAt, canStart: true });
4683
+ start = bufferEndAt.getTime();
4684
+ }
4685
+ }
4686
+ function periodCells(parts, buffer, dayStart, timeZone) {
4687
+ const weekday = zonedParts(dayStart, timeZone).weekday;
4688
+ const rows = (parts.weeklyHours ?? []).filter((entry) => entry.weekday === weekday);
4689
+ if (parts.ratePeriod === "hour" /* HOUR */) {
4690
+ return rows.flatMap(
4691
+ (row) => hourCells(
4692
+ +atZonedMinute(dayStart, row.openMinute, timeZone),
4693
+ +atZonedMinute(dayStart, row.closeMinute, timeZone)
4694
+ )
4695
+ );
4696
+ }
4697
+ if (parts.weeklyHours?.length && rows.length === 0) return [];
4698
+ const built = periodSlot(dayStart, timeZone, parts, buffer, rows[0]?.openMinute, rows[0]?.closeMinute);
4699
+ return [{ ...built, canStart: !parts.arrivalDays?.length || parts.arrivalDays.includes(weekday) }];
4700
+ }
4701
+ function buildGrid(rule, timeZone, from, to, now, busy = []) {
4702
+ if (to.getTime() - from.getTime() > MAX_RANGE_DAYS * 1440 * MINUTE3) {
4703
+ throw new BookingRulesError(`A booking range may span at most ${MAX_RANGE_DAYS} days`);
4704
+ }
4705
+ const { availability, window } = rule;
4706
+ const { minNotice } = ruleDurationsOf(rule);
4707
+ const notBefore = Math.max(
4708
+ (minNotice ? addDuration(now, minNotice, timeZone) : now).getTime(),
4709
+ asTime(window.bookableFrom, "window.bookableFrom") ?? 0,
4710
+ asTime(availability.availableFrom, "availability.availableFrom") ?? 0
4711
+ );
4712
+ const notAfter = windowEndsAtInZone(rule, now, timeZone)?.getTime() ?? Number.POSITIVE_INFINITY;
4713
+ const blocked = offMarketOf(rule);
4714
+ const slots = cellsOf(rule, bookingRuleParts(rule), timeZone, from, to, busy);
4715
+ const askedFrom = from.getTime();
4716
+ const askedTo = to.getTime();
4717
+ return slots.filter(({ startAt, bufferEndAt }) => {
4718
+ const start = startAt.getTime();
4719
+ if (start < askedFrom || start >= askedTo) return false;
4720
+ if (start < notBefore || start > notAfter) return false;
4721
+ return !isBlocked(blocked, start, bufferEndAt.getTime());
4722
+ }).sort((first, second) => +first.startAt - +second.startAt);
4723
+ }
4724
+ function slotsForWindow(grid, startAt, endAt) {
4725
+ const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
4726
+ if (startIndex < 0) {
4727
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
4728
+ }
4729
+ if (!grid[startIndex].canStart) {
4730
+ throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
4731
+ }
4732
+ const covered = [];
4733
+ for (let index = startIndex; index < grid.length; index++) {
4734
+ const entry = grid[index];
4735
+ const previous = covered[covered.length - 1];
4736
+ if (previous && entry.startAt.getTime() !== previous.bufferEndAt.getTime()) break;
4737
+ covered.push(entry);
4738
+ if (entry.endAt.getTime() === endAt.getTime()) return covered;
4739
+ if (entry.endAt.getTime() > endAt.getTime()) break;
4740
+ }
4741
+ throw new BookingRulesError(
4742
+ `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
4743
+ );
4744
+ }
3986
4745
 
3987
4746
  // shipping/fold-text.ts
3988
4747
  function foldText(value) {
@@ -4419,10 +5178,12 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4419
5178
  AttributeType,
4420
5179
  BNPL_METHOD_STATUS,
4421
5180
  BNPL_SKIP_REASON,
5181
+ BookingDurationUnit,
4422
5182
  BookingRatePeriod,
4423
5183
  BookingResourceKind,
4424
5184
  BookingResourceStatus,
4425
5185
  BookingRulesError,
5186
+ BookingSessionSale,
4426
5187
  BookingType,
4427
5188
  CANADA_PROVINCES,
4428
5189
  CONDITION_OPERATORS,
@@ -4512,6 +5273,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4512
5273
  StripeStatus,
4513
5274
  TimePeriod,
4514
5275
  TopMetericsSort,
5276
+ UNLIMITED_PLACES,
4515
5277
  UserTypes,
4516
5278
  addAmounts,
4517
5279
  addressPlaceKeys,
@@ -4520,6 +5282,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4520
5282
  adyenStoreRequiresStateOrProvince,
4521
5283
  adyenSupportsTaxNumberAbsent,
4522
5284
  adyenTaxNumberFormat,
5285
+ allowedDurationUnits,
4523
5286
  amountToString,
4524
5287
  ancestorChain,
4525
5288
  applyAssignment,
@@ -4529,15 +5292,21 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4529
5292
  baseFulfillmentDefinitions,
4530
5293
  baseOf,
4531
5294
  basePaymentDefinitions,
5295
+ bookingMethodOf,
5296
+ bookingRuleParts,
4532
5297
  buildAvailability,
4533
5298
  buildGrid,
4534
5299
  buildOrderContext,
4535
5300
  buildPosPresetConfig,
4536
5301
  buildResolvedConfig,
4537
5302
  calculatePercentage,
5303
+ calendarDate,
4538
5304
  canTransition,
5305
+ capacityOf,
4539
5306
  cheapestCompositeItem,
4540
5307
  cheapestCompositePrice,
5308
+ checkPartySize,
5309
+ checkQtyPerBooking,
4541
5310
  compositeItemCost,
4542
5311
  compositeItemUnavailable,
4543
5312
  compositeMakeable,
@@ -4546,6 +5315,9 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4546
5315
  compositeVariantInStock,
4547
5316
  conditionSummary,
4548
5317
  convertFixedFeeToLocalCurrency,
5318
+ courseSessions,
5319
+ courseStarted,
5320
+ courseStartedInZone,
4549
5321
  createAmount,
4550
5322
  crossAxisRuleApplies,
4551
5323
  currentAssignees,
@@ -4554,10 +5326,13 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4554
5326
  deriveUnitId,
4555
5327
  displayRuleMatchesPair,
4556
5328
  divideAmount,
5329
+ durationProblems,
5330
+ durationText,
4557
5331
  evaluateCondition,
4558
5332
  evaluateConditionSet,
4559
5333
  extendPrice,
4560
5334
  extendPriceFor,
5335
+ fewestFreeOver,
4561
5336
  formatCurrency,
4562
5337
  formatInUnit,
4563
5338
  formatMinorUnitsToString,
@@ -4599,7 +5374,9 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4599
5374
  listCountries,
4600
5375
  listProvinces,
4601
5376
  listShippingCountries,
5377
+ longestMinutesOf,
4602
5378
  mapToLegacyStatus,
5379
+ maxAdvanceMinutesOf,
4603
5380
  maxPrecisionFor,
4604
5381
  mergeFragment,
4605
5382
  modifiersSellable,
@@ -4611,11 +5388,14 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4611
5388
  normalizePostCode,
4612
5389
  normalizeProvince,
4613
5390
  occupancyIn,
5391
+ oldMaxAdvanceOf,
4614
5392
  orderAssignments,
4615
5393
  parseAmountToMinorUnits,
4616
5394
  parseCurrencyCode,
4617
5395
  parseStripeCurrencyCode,
5396
+ pickFreeResource,
4618
5397
  placeKey,
5398
+ planCourse,
4619
5399
  planWindow,
4620
5400
  poolDemand,
4621
5401
  poolOf,
@@ -4626,19 +5406,25 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4626
5406
  priceForTotal,
4627
5407
  provincesForPostCode,
4628
5408
  removeFragment,
5409
+ rentalEnds,
4629
5410
  resolveFamily,
4630
5411
  resolveModifiersForProduct,
4631
5412
  resolveShipping,
4632
5413
  resolveTemplate,
4633
5414
  resolveUnit,
4634
5415
  roundToPrecision,
5416
+ ruleDurationsOf,
5417
+ ruleInNewShape,
4635
5418
  sameFamily,
5419
+ sessionCells,
4636
5420
  setOrderState,
4637
5421
  shipsToCountry,
4638
5422
  shopDayKey,
4639
5423
  shopDayRange,
5424
+ shortestMinutesOf,
4640
5425
  signReportForDisplay,
4641
5426
  slotsForWindow,
5427
+ soldAsCourse,
4642
5428
  stringifyMinorUnits,
4643
5429
  subtractAmounts,
4644
5430
  toBase,
@@ -4649,6 +5435,8 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4649
5435
  validateShippingZone,
4650
5436
  violatesFinancialInvariant,
4651
5437
  windowEndsAt,
5438
+ windowEndsAtInZone,
5439
+ windowForPeriods,
4652
5440
  withinPresence
4653
5441
  });
4654
5442
  //# sourceMappingURL=index.js.map