@final-commerce/common 2.12.0-staging.5 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -454,42 +454,21 @@ var PaymentProcessor = /* @__PURE__ */ ((PaymentProcessor2) => {
454
454
  })(PaymentProcessor || {});
455
455
 
456
456
  // enums/booking.enum.ts
457
- var BookingType = /* @__PURE__ */ ((BookingType2) => {
458
- BookingType2["RENTAL"] = "rental";
459
- BookingType2["APPOINTMENT"] = "appointment";
460
- BookingType2["OVERNIGHT"] = "overnight";
461
- BookingType2["GROUP"] = "group";
462
- return BookingType2;
457
+ var BookingType = /* @__PURE__ */ ((BookingType3) => {
458
+ BookingType3["RENTAL"] = "rental";
459
+ BookingType3["APPOINTMENT"] = "appointment";
460
+ BookingType3["OVERNIGHT"] = "overnight";
461
+ BookingType3["GROUP"] = "group";
462
+ return BookingType3;
463
463
  })(BookingType || {});
464
464
  var BookingRatePeriod = /* @__PURE__ */ ((BookingRatePeriod2) => {
465
465
  BookingRatePeriod2["SLOT"] = "slot";
466
- BookingRatePeriod2["HOUR"] = "hour";
467
- BookingRatePeriod2["SESSION"] = "session";
468
466
  BookingRatePeriod2["DAY"] = "day";
469
467
  BookingRatePeriod2["NIGHT"] = "night";
470
468
  BookingRatePeriod2["WEEK"] = "week";
471
469
  BookingRatePeriod2["MONTH"] = "month";
472
470
  return BookingRatePeriod2;
473
471
  })(BookingRatePeriod || {});
474
- var BookingDurationUnit = /* @__PURE__ */ ((BookingDurationUnit2) => {
475
- BookingDurationUnit2["MINUTE"] = "minute";
476
- BookingDurationUnit2["HOUR"] = "hour";
477
- BookingDurationUnit2["DAY"] = "day";
478
- BookingDurationUnit2["NIGHT"] = "night";
479
- BookingDurationUnit2["WEEK"] = "week";
480
- BookingDurationUnit2["MONTH"] = "month";
481
- return BookingDurationUnit2;
482
- })(BookingDurationUnit || {});
483
- var BookingSessionSale = /* @__PURE__ */ ((BookingSessionSale2) => {
484
- BookingSessionSale2["SESSION"] = "session";
485
- BookingSessionSale2["COURSE"] = "course";
486
- return BookingSessionSale2;
487
- })(BookingSessionSale || {});
488
- var BookingArriveLeave = /* @__PURE__ */ ((BookingArriveLeave2) => {
489
- BookingArriveLeave2["SET_TIMES"] = "set-times";
490
- BookingArriveLeave2["OPENING_HOURS"] = "opening-hours";
491
- return BookingArriveLeave2;
492
- })(BookingArriveLeave || {});
493
472
  var BookingResourceKind = /* @__PURE__ */ ((BookingResourceKind2) => {
494
473
  BookingResourceKind2["ASSET"] = "asset";
495
474
  BookingResourceKind2["ROOM"] = "room";
@@ -1802,6 +1781,157 @@ function lineStockMoves(item, quantity, reservations = []) {
1802
1781
  });
1803
1782
  }
1804
1783
 
1784
+ // utils/shell-settings.util.ts
1785
+ var DEFAULT_SHELL_SETTINGS = {
1786
+ pinSwitchUser: false,
1787
+ pinSession: false,
1788
+ stationLock: 0,
1789
+ buildTimeout: 0,
1790
+ lockedAccess: false,
1791
+ cashManagement: true,
1792
+ tips: {
1793
+ enabled: true,
1794
+ tip1: { label: "Good", value: 15 },
1795
+ tip2: { label: "Great", value: 18 },
1796
+ tip3: { label: "Amazing!", value: 25 },
1797
+ customTipLabel: "Custom",
1798
+ noTipLabel: "No tip"
1799
+ }
1800
+ };
1801
+ var FIELD_ORDER = ["station"];
1802
+ var TIP_ORDER = ["station", "outlet", "flow", "company"];
1803
+ var TOP_FIELDS = [
1804
+ "pinSwitchUser",
1805
+ "pinSession",
1806
+ "stationLock",
1807
+ "buildTimeout",
1808
+ "lockedAccess",
1809
+ "cashManagement"
1810
+ ];
1811
+ var TIP_FIELDS = ["enabled", "tip1", "tip2", "tip3", "customTipLabel", "noTipLabel"];
1812
+ function pick(levels, order, read, fallback) {
1813
+ for (const level of order) {
1814
+ const settings = levels[level];
1815
+ if (!settings) continue;
1816
+ const value = read(settings);
1817
+ if (value !== void 0 && value !== null) return { value, source: level };
1818
+ }
1819
+ return { value: fallback, source: "default" };
1820
+ }
1821
+ function resolveShellSettingsWithSources(levels) {
1822
+ const settings = { ...DEFAULT_SHELL_SETTINGS, tips: { ...DEFAULT_SHELL_SETTINGS.tips } };
1823
+ const sources = { fields: {}, tips: {} };
1824
+ for (const field of TOP_FIELDS) {
1825
+ const { value, source } = pick(levels, FIELD_ORDER, (s) => s[field], DEFAULT_SHELL_SETTINGS[field]);
1826
+ settings[field] = value;
1827
+ sources.fields[field] = source;
1828
+ }
1829
+ for (const field of TIP_FIELDS) {
1830
+ const { value, source } = pick(levels, TIP_ORDER, (s) => s.tips?.[field], DEFAULT_SHELL_SETTINGS.tips[field]);
1831
+ settings.tips[field] = value;
1832
+ sources.tips[field] = source;
1833
+ }
1834
+ return { settings, sources };
1835
+ }
1836
+ function resolveShellSettings(levels) {
1837
+ return resolveShellSettingsWithSources(levels).settings;
1838
+ }
1839
+ var SHELL_TIP_PERCENT_MIN = 1;
1840
+ var SHELL_TIP_PERCENT_MAX = 100;
1841
+ var SHELL_TIP_LABEL_MAX_LENGTH = 20;
1842
+ var isLabel = (raw) => typeof raw === "string" && raw.trim().length > 0 && raw.length <= SHELL_TIP_LABEL_MAX_LENGTH;
1843
+ var isShellTipPercent = (raw) => typeof raw === "number" && Number.isInteger(raw) && raw >= SHELL_TIP_PERCENT_MIN && raw <= SHELL_TIP_PERCENT_MAX;
1844
+ function shellTipSettingsProblems(tips) {
1845
+ if (!tips) return [];
1846
+ const problems = [];
1847
+ if (tips.enabled !== void 0 && typeof tips.enabled !== "boolean") {
1848
+ problems.push({ field: "tips.enabled", code: "boolean" });
1849
+ }
1850
+ for (const key of ["tip1", "tip2", "tip3"]) {
1851
+ const option = tips[key];
1852
+ if (option === void 0) continue;
1853
+ if (!option || typeof option !== "object") {
1854
+ problems.push({ field: `tips.${key}`, code: "preset" });
1855
+ continue;
1856
+ }
1857
+ if (!isShellTipPercent(option.value)) problems.push({ field: `tips.${key}`, code: "percent" });
1858
+ if (!isLabel(option.label)) problems.push({ field: `tips.${key}`, code: "label" });
1859
+ }
1860
+ for (const key of ["customTipLabel", "noTipLabel"]) {
1861
+ if (tips[key] !== void 0 && !isLabel(tips[key])) problems.push({ field: `tips.${key}`, code: "label" });
1862
+ }
1863
+ return problems;
1864
+ }
1865
+ function shellSettingsProblems(settings) {
1866
+ if (!settings) return [];
1867
+ const problems = [];
1868
+ for (const field of ["pinSwitchUser", "pinSession", "lockedAccess", "cashManagement"]) {
1869
+ if (settings[field] !== void 0 && typeof settings[field] !== "boolean")
1870
+ problems.push({ field, code: "boolean" });
1871
+ }
1872
+ for (const field of ["stationLock", "buildTimeout"]) {
1873
+ const value = settings[field];
1874
+ if (value !== void 0 && !(typeof value === "number" && Number.isInteger(value) && value >= 0)) {
1875
+ problems.push({ field, code: "timeout" });
1876
+ }
1877
+ }
1878
+ return [...problems, ...shellTipSettingsProblems(settings.tips)];
1879
+ }
1880
+ var SHELL_FLOW_SETTINGS_PREFIX = "flowSettingsKey";
1881
+ var SHELL_FLOW_TIPS_KEY = `${SHELL_FLOW_SETTINGS_PREFIX}.tips`;
1882
+ var readBoolean = (raw) => {
1883
+ if (raw === void 0 || raw === "") return void 0;
1884
+ const v = raw.trim().toLowerCase();
1885
+ if (v === "true") return true;
1886
+ if (v === "false") return false;
1887
+ return void 0;
1888
+ };
1889
+ function readTipOption(raw) {
1890
+ if (!raw || typeof raw !== "object") return void 0;
1891
+ const { label, value } = raw;
1892
+ const n = typeof value === "number" ? value : parseFloat(String(value ?? ""));
1893
+ if (typeof label !== "string" || !Number.isFinite(n) || n < 0) return void 0;
1894
+ return { label, value: n };
1895
+ }
1896
+ function readShellTipSettings(raw) {
1897
+ if (!raw || typeof raw !== "object") return void 0;
1898
+ const r = raw;
1899
+ const tips = {};
1900
+ if (typeof r.enabled === "boolean") tips.enabled = r.enabled;
1901
+ const tip1 = readTipOption(r.tip1);
1902
+ const tip2 = readTipOption(r.tip2);
1903
+ const tip3 = readTipOption(r.tip3);
1904
+ if (tip1) tips.tip1 = tip1;
1905
+ if (tip2) tips.tip2 = tip2;
1906
+ if (tip3) tips.tip3 = tip3;
1907
+ if (typeof r.customTipLabel === "string") tips.customTipLabel = r.customTipLabel;
1908
+ if (typeof r.noTipLabel === "string") tips.noTipLabel = r.noTipLabel;
1909
+ return Object.keys(tips).length > 0 ? tips : void 0;
1910
+ }
1911
+ var parseJson = (raw) => {
1912
+ if (!raw) return void 0;
1913
+ try {
1914
+ return JSON.parse(raw);
1915
+ } catch {
1916
+ return void 0;
1917
+ }
1918
+ };
1919
+ function shellSettingsFromFlowSettings(dict) {
1920
+ const tips = readShellTipSettings(parseJson(dict?.[SHELL_FLOW_TIPS_KEY]));
1921
+ return tips ? { tips } : {};
1922
+ }
1923
+ function flowSettingsFromShellSettings(settings) {
1924
+ return settings.tips && Object.keys(settings.tips).length > 0 ? { [SHELL_FLOW_TIPS_KEY]: JSON.stringify(settings.tips) } : {};
1925
+ }
1926
+ function shellSettingsFromCompanyTips(enabled, options) {
1927
+ const tips = {
1928
+ ...readShellTipSettings(typeof options === "string" ? parseJson(options) : options)
1929
+ };
1930
+ const on = typeof enabled === "boolean" ? enabled : readBoolean(typeof enabled === "string" ? enabled : void 0);
1931
+ if (on !== void 0) tips.enabled = on;
1932
+ return Object.keys(tips).length > 0 ? { tips } : {};
1933
+ }
1934
+
1805
1935
  // units/family-code.ts
1806
1936
  var MAX_SLUG_LENGTH = 32;
1807
1937
  var FALLBACK_SLUG = "family";
@@ -3350,7 +3480,6 @@ var ORDER_STATE_EVENTS = {
3350
3480
  };
3351
3481
 
3352
3482
  // booking/types.ts
3353
- var UNLIMITED_PLACES = Number.MAX_SAFE_INTEGER;
3354
3483
  var BookingRulesError = class extends Error {
3355
3484
  constructor(message) {
3356
3485
  super(message);
@@ -3419,39 +3548,153 @@ function atZonedMinute(dayStart, minutes, timeZone) {
3419
3548
  const { year, month, day } = zonedParts(dayStart, timeZone);
3420
3549
  return instantFromLocal(year, month, day, minutes, timeZone);
3421
3550
  }
3422
- function sameDayMonthsLaterDate(year, month, day, months) {
3423
- const target = new Date(Date.UTC(year, month - 1 + months, 1));
3424
- const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();
3425
- return [target.getUTCFullYear(), target.getUTCMonth() + 1, Math.min(day, lastDay)];
3551
+
3552
+ // booking/grid.ts
3553
+ var MINUTE2 = 6e4;
3554
+ var MAX_RANGE_DAYS = 366;
3555
+ var asTime = (value, field) => {
3556
+ if (value == null) return void 0;
3557
+ const time = new Date(value).getTime();
3558
+ if (Number.isNaN(time)) throw new BookingRulesError(`Booking rules: ${field} is not a date, got "${String(value)}"`);
3559
+ return time;
3560
+ };
3561
+ function parseHhMm(value, field) {
3562
+ const [hours, minutes] = value.split(":").map(Number);
3563
+ if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
3564
+ throw new BookingRulesError(`Booking rules: ${field} must be "HH:mm", got "${value}"`);
3565
+ }
3566
+ return hours * 60 + minutes;
3426
3567
  }
3427
- function addClockDuration(from, { count, unit: unit2 }) {
3428
- if (unit2 === "minute" /* MINUTE */) return new Date(from.getTime() + count * MINUTE);
3429
- if (unit2 === "hour" /* HOUR */) return new Date(from.getTime() + count * 60 * MINUTE);
3430
- throw new BookingRulesError(
3431
- `Booking rules: ${count} ${unit2} is not minutes or hours \u2014 it needs the shop's time zone`
3568
+ function windowEndsAt(rule, now) {
3569
+ const { maxAdvanceDays, bookableTo } = rule.window;
3570
+ const ends = Math.min(
3571
+ maxAdvanceDays ? now.getTime() + maxAdvanceDays * 1440 * MINUTE2 : Number.POSITIVE_INFINITY,
3572
+ asTime(bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
3432
3573
  );
3574
+ return Number.isFinite(ends) ? new Date(ends) : null;
3433
3575
  }
3434
- var DAYS_IN = {
3435
- ["day" /* DAY */]: 1,
3436
- ["night" /* NIGHT */]: 1,
3437
- ["week" /* WEEK */]: 7
3438
- };
3439
- function addDuration(from, duration, timeZone) {
3440
- const { count, unit: unit2 } = duration;
3441
- if (unit2 === "minute" /* MINUTE */ || unit2 === "hour" /* HOUR */) return addClockDuration(from, duration);
3442
- const days = DAYS_IN[unit2];
3443
- if (days === void 0 && unit2 !== "month" /* MONTH */) {
3444
- throw new BookingRulesError(`Booking rules: "${unit2}" is not a duration unit`);
3445
- }
3446
- if (!Number.isInteger(count)) throw new BookingRulesError(`Booking rules: ${count} ${unit2} is not a whole number`);
3447
- const { year, month, day, hour, minute, second } = zonedParts(from, timeZone);
3448
- const [toYear, toMonth, toDay] = days === void 0 ? sameDayMonthsLaterDate(year, month, day, count) : [year, month, day + days * count];
3449
- const wallClock = instantFromLocal(toYear, toMonth, toDay, hour * 60 + minute, timeZone);
3450
- return new Date(wallClock.getTime() + second * 1e3 + from.getUTCMilliseconds());
3576
+ function periodSlot(dayStart, timeZone, rule, openMinute, closeMinute) {
3577
+ const { ratePeriod, slot, checkInTime, checkOutTime } = rule;
3578
+ const at = (minutes) => atZonedMinute(dayStart, minutes, timeZone);
3579
+ if (ratePeriod === "night" /* NIGHT */) {
3580
+ if (!checkInTime || !checkOutTime) {
3581
+ throw new BookingRulesError("Overnight booking rules need both checkInTime and checkOutTime");
3582
+ }
3583
+ const checkIn = parseHhMm(checkInTime, "checkInTime");
3584
+ const checkOut = parseHhMm(checkOutTime, "checkOutTime");
3585
+ return {
3586
+ startAt: at(checkIn),
3587
+ endAt: at(1440 + checkOut),
3588
+ // Housekeeping sits between check-out and the next check-in: it costs no night.
3589
+ bufferEndAt: at(1440 + checkIn),
3590
+ canStart: true
3591
+ };
3592
+ }
3593
+ const from = ratePeriod === "day" /* DAY */ ? openMinute ?? 0 : 0;
3594
+ const to = ratePeriod === "day" /* DAY */ ? closeMinute ?? 1440 : 1440;
3595
+ return {
3596
+ startAt: at(from),
3597
+ endAt: at(to),
3598
+ bufferEndAt: at(to + (slot.bufferMinutes ?? 0)),
3599
+ canStart: true
3600
+ };
3601
+ }
3602
+ function freeGaps(openAt, closeAt, busy) {
3603
+ const inside = busy.map(({ startAt, bufferEndAt }) => ({ from: +startAt, to: +bufferEndAt })).filter(({ from, to }) => to > openAt && from < closeAt).sort((first, second) => first.from - second.from);
3604
+ const gaps = [];
3605
+ let cursor = openAt;
3606
+ for (const { from, to } of inside) {
3607
+ if (from > cursor) gaps.push({ from: cursor, to: from, endsAtBooking: true });
3608
+ cursor = Math.max(cursor, to);
3609
+ if (cursor >= closeAt) break;
3610
+ }
3611
+ if (cursor < closeAt) gaps.push({ from: cursor, to: closeAt, endsAtBooking: false });
3612
+ return gaps;
3613
+ }
3614
+ function buildGrid(rule, timeZone, from, to, now, busy = []) {
3615
+ if (to.getTime() - from.getTime() > MAX_RANGE_DAYS * 1440 * MINUTE2) {
3616
+ throw new BookingRulesError(`A booking range may span at most ${MAX_RANGE_DAYS} days`);
3617
+ }
3618
+ const { availability, slot, window, ratePeriod } = rule;
3619
+ const periodMode = ratePeriod !== "slot" /* SLOT */;
3620
+ const weeklyHours = availability.weeklyHours ?? [];
3621
+ const notBefore = Math.max(
3622
+ now.getTime() + (window.minNoticeMinutes ?? 0) * MINUTE2,
3623
+ asTime(window.bookableFrom, "window.bookableFrom") ?? 0,
3624
+ asTime(availability.availableFrom, "availability.availableFrom") ?? 0
3625
+ );
3626
+ const notAfter = windowEndsAt(rule, now)?.getTime() ?? Number.POSITIVE_INFINITY;
3627
+ const blocked = (availability.offMarket ?? []).map(({ from: blockFrom, to: blockTo }) => ({
3628
+ from: asTime(blockFrom, "availability.offMarket.from"),
3629
+ to: asTime(blockTo, "availability.offMarket.to")
3630
+ }));
3631
+ const arrivalDays = availability.arrivalDays;
3632
+ const step = slot.lengthMinutes + (slot.bufferMinutes ?? 0);
3633
+ const slots = [];
3634
+ const lastDay = startOfZonedDay(to, timeZone).getTime();
3635
+ let dayStart = startOfZonedDay(from, timeZone);
3636
+ while (dayStart.getTime() <= lastDay) {
3637
+ const weekday = zonedParts(dayStart, timeZone).weekday;
3638
+ const rows = weeklyHours.filter((entry) => entry.weekday === weekday);
3639
+ if (periodMode) {
3640
+ const openToday = weeklyHours.length === 0 || rows.length > 0;
3641
+ if (openToday) {
3642
+ const built = periodSlot(dayStart, timeZone, rule, rows[0]?.openMinute, rows[0]?.closeMinute);
3643
+ slots.push({ ...built, canStart: !arrivalDays?.length || arrivalDays.includes(weekday) });
3644
+ }
3645
+ } else {
3646
+ for (const row of rows) {
3647
+ const openAt = +atZonedMinute(dayStart, row.openMinute, timeZone);
3648
+ const closeAt = +atZonedMinute(dayStart, row.closeMinute, timeZone);
3649
+ for (const gap of freeGaps(openAt, closeAt, busy)) {
3650
+ const mustFit = (gap.endsAtBooking ? step : slot.lengthMinutes) * MINUTE2;
3651
+ for (let start = gap.from; start + mustFit <= gap.to; start += step * MINUTE2) {
3652
+ slots.push({
3653
+ startAt: new Date(start),
3654
+ endAt: new Date(start + slot.lengthMinutes * MINUTE2),
3655
+ bufferEndAt: new Date(start + step * MINUTE2),
3656
+ canStart: true
3657
+ });
3658
+ }
3659
+ }
3660
+ }
3661
+ }
3662
+ dayStart = nextZonedDay(dayStart, timeZone);
3663
+ }
3664
+ const askedFrom = from.getTime();
3665
+ const askedTo = to.getTime();
3666
+ return slots.filter(({ startAt, bufferEndAt }) => {
3667
+ const start = startAt.getTime();
3668
+ if (start < askedFrom || start >= askedTo) return false;
3669
+ if (start < notBefore || start > notAfter) return false;
3670
+ return !blocked.some(
3671
+ ({ from: blockFrom, to: blockTo }) => start < blockTo && bufferEndAt.getTime() > blockFrom
3672
+ );
3673
+ }).sort((first, second) => +first.startAt - +second.startAt);
3674
+ }
3675
+ function slotsForWindow(grid, startAt, endAt) {
3676
+ const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
3677
+ if (startIndex < 0) {
3678
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
3679
+ }
3680
+ if (!grid[startIndex].canStart) {
3681
+ throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
3682
+ }
3683
+ const covered = [];
3684
+ for (let index = startIndex; index < grid.length; index++) {
3685
+ const entry = grid[index];
3686
+ const previous = covered[covered.length - 1];
3687
+ if (previous && entry.startAt.getTime() !== previous.bufferEndAt.getTime()) break;
3688
+ covered.push(entry);
3689
+ if (entry.endAt.getTime() === endAt.getTime()) return covered;
3690
+ if (entry.endAt.getTime() > endAt.getTime()) break;
3691
+ }
3692
+ throw new BookingRulesError(
3693
+ `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
3694
+ );
3451
3695
  }
3452
3696
 
3453
3697
  // booking/availability.ts
3454
- var placesOnTheWire = (entry) => Number.isFinite(entry.capacity) ? entry : { ...entry, capacity: UNLIMITED_PLACES, free: UNLIMITED_PLACES, unlimited: true };
3455
3698
  var withinPresence = (slot, timeZone, presence) => {
3456
3699
  if (!presence?.length) return true;
3457
3700
  const dayStart = startOfZonedDay(slot.startAt, timeZone);
@@ -3469,11 +3712,6 @@ function occupancyIn(occupied, productId, startAt, bufferEndAt, shared) {
3469
3712
  foreignProductId: foreign?.productId
3470
3713
  };
3471
3714
  }
3472
- var inEveryOutletPool = (entry) => !entry.outletId;
3473
- function occupiedAtOutlet(occupied, rule, outletId) {
3474
- if (bookingMethodOf(rule) !== "sessions" || !outletId) return occupied;
3475
- return occupied.filter((entry) => inEveryOutletPool(entry) || entry.outletId === outletId);
3476
- }
3477
3715
  var stateFor = (hasShift, offerable, free) => {
3478
3716
  if (offerable === 0) {
3479
3717
  return hasShift() ? "fullyBooked" /* FULLY_BOOKED */ : "noHoursInRange" /* NO_HOURS_IN_RANGE */;
@@ -3503,36 +3741,26 @@ function shopDayRange(fromDayKey, count, timeZone) {
3503
3741
  function buildAvailability({
3504
3742
  productId,
3505
3743
  bookingRulesId,
3744
+ bookingType,
3506
3745
  rule,
3507
3746
  resources,
3508
- occupied: everyOutlet,
3509
- outletId,
3747
+ occupied,
3510
3748
  from,
3511
3749
  to,
3512
- now,
3513
- timeZone
3750
+ now
3514
3751
  }) {
3515
- const occupied = occupiedAtOutlet(everyOutlet, rule, outletId);
3516
3752
  const shared = rule.slot.sharedAcrossProducts ?? false;
3517
- const bookableUntil = windowEndsAtInZone(rule, now, timeZone ?? null);
3518
- const parts = bookingRuleParts(rule);
3753
+ const bookableUntil = windowEndsAt(rule, now);
3519
3754
  const header = {
3520
3755
  productId,
3521
3756
  bookingRulesId,
3757
+ bookingType,
3522
3758
  ratePeriod: rule.ratePeriod,
3523
- // Time slots / sessions / date ranges — so a reader never re-classifies `ratePeriod` itself.
3524
- bookingMethod: bookingMethodOf(rule),
3525
3759
  // Passed through for the UI to label: a group slot under minimumToRun may not run.
3526
3760
  minimumToRun: rule.slot.minimumToRun,
3527
3761
  minStay: rule.slot.minStay,
3528
3762
  maxStay: rule.slot.maxStay,
3529
- // The same limits with their own units, both rule shapes. `minStay` / `maxStay` above go at B13 step 9.
3530
- minStayLength: parts.method === "date-ranges" ? parts.minStay : void 0,
3531
- maxStayLength: parts.method === "date-ranges" ? parts.maxStay : void 0,
3532
- // The per-booking limits, so a stepper is bounded by the rules (G7) instead of a number in the flow.
3533
- maxQtyPerBooking: rule.slot.maxQtyPerBooking,
3534
- maxPartySize: rule.slot.maxPartySize,
3535
- // Why a day can come back empty. Past this instant the rule refuses every start, so the UI
3763
+ // Why a day can come back empty. Past this instant the rule refuses everything, so the UI
3536
3764
  // can say "beyond the booking window" where it would otherwise claim "nothing free".
3537
3765
  bookableUntil,
3538
3766
  // The comparison itself, not just the boundary: deciding whether a day lies past the
@@ -3555,7 +3783,7 @@ function buildAvailability({
3555
3783
  const byInstant = /* @__PURE__ */ new Map();
3556
3784
  const freeSlotsPerResource = /* @__PURE__ */ new Map();
3557
3785
  for (const { resource, slots: slots2 } of grids) {
3558
- const capacity = capacityOf(rule, resource);
3786
+ const capacity = resource.seats ?? 1;
3559
3787
  const mine = byResource.get(resource.id) ?? [];
3560
3788
  for (const slot of slots2) {
3561
3789
  const { taken, foreignProductId } = occupancyIn(mine, productId, slot.startAt, slot.bufferEndAt, shared);
@@ -3572,9 +3800,7 @@ function buildAvailability({
3572
3800
  entry.booked += foreignProductId ? capacity : taken;
3573
3801
  entry.free += free;
3574
3802
  entry.canStart = entry.canStart || slot.canStart;
3575
- entry.resources.push(
3576
- placesOnTheWire({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free })
3577
- );
3803
+ entry.resources.push({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free });
3578
3804
  if (free > 0) freeSlotsPerResource.set(resource.id, (freeSlotsPerResource.get(resource.id) ?? 0) + 1);
3579
3805
  byInstant.set(+slot.startAt, entry);
3580
3806
  }
@@ -3596,10 +3822,9 @@ function buildAvailability({
3596
3822
  )
3597
3823
  };
3598
3824
  });
3599
- const slots = [...byInstant.values()].map(placesOnTheWire).map((slot) => withMaxQtyNow(slot, slot.resources, rule.slot.maxQtyPerBooking)).sort((first, second) => +first.startAt - +second.startAt);
3825
+ const slots = [...byInstant.values()].sort((first, second) => +first.startAt - +second.startAt);
3600
3826
  return {
3601
3827
  ...header,
3602
- course: soldAsCourse(rule) ? courseAvailability(rule, resources, byResource, productId, shared, now) : void 0,
3603
3828
  resources: inWindow,
3604
3829
  slots,
3605
3830
  /**
@@ -3611,53 +3836,6 @@ function buildAvailability({
3611
3836
  days: [...new Set(slots.map((slot) => slot.dayKey))]
3612
3837
  };
3613
3838
  }
3614
- function courseAvailability(rule, resources, byResource, productId, shared, now) {
3615
- if (resources.length === 0) return void 0;
3616
- const sessions = courseSessions(rule, resources[0].timeZone);
3617
- const alreadyStarted = courseStartedInZone(rule, sessions, now, resources[0].timeZone);
3618
- const beyondWindow = startsPastMaxAdvance(rule, sessions[0].startAt, now, resources[0].timeZone);
3619
- const free = resources.map((resource) => {
3620
- const mine = byResource.get(resource.id) ?? [];
3621
- const everySession = sessions.every((session) => withinPresence(session, resource.timeZone, resource.presence));
3622
- const freePerSession = sessions.map((session) => {
3623
- const { taken, foreignProductId } = occupancyIn(mine, productId, session.startAt, session.bufferEndAt, shared);
3624
- return foreignProductId ? 0 : Math.max(capacityOf(rule, resource) - taken, 0);
3625
- });
3626
- const fewest = everySession && !alreadyStarted && !beyondWindow ? Math.min(...freePerSession) : 0;
3627
- return Number.isFinite(fewest) ? { resourceId: resource.id, free: fewest } : { resourceId: resource.id, free: UNLIMITED_PLACES, unlimited: true };
3628
- });
3629
- return withMaxQtyNow(
3630
- {
3631
- sessions: sessions.length,
3632
- alreadyStarted,
3633
- beyondWindow,
3634
- sessionTimes: sessions.map(({ startAt, endAt }) => ({ startAt, endAt })),
3635
- startAt: sessions[0].startAt,
3636
- endAt: sessions[sessions.length - 1].endAt,
3637
- resources: free
3638
- },
3639
- free,
3640
- rule.slot.maxQtyPerBooking
3641
- );
3642
- }
3643
- function pickFreeResource(slot, qty = 1) {
3644
- return slot.resources.find((entry) => entry.free >= qty);
3645
- }
3646
- function withMaxQtyNow(entry, resources, maxQtyPerBooking) {
3647
- const largest = resources.some((resource) => resource.unlimited) ? Number.POSITIVE_INFINITY : Math.max(0, ...resources.map((resource) => resource.free));
3648
- const maxQtyNow = Math.min(largest, maxQtyPerBooking ?? Number.POSITIVE_INFINITY);
3649
- return Number.isFinite(maxQtyNow) ? { ...entry, maxQtyNow } : entry;
3650
- }
3651
- function fewestFreeOver(slots, from, to) {
3652
- const cells = slots.filter(({ startAt, endAt }) => +startAt >= +from && +endAt <= +to);
3653
- if (cells.length === 0) return [];
3654
- return cells[0].resources.map((resource) => ({
3655
- ...resource,
3656
- free: Math.min(
3657
- ...cells.map((cell) => cell.resources.find(({ resourceId }) => resourceId === resource.resourceId)?.free ?? 0)
3658
- )
3659
- }));
3660
- }
3661
3839
  function presentAt(resources, rows, outletId) {
3662
3840
  const byResource = /* @__PURE__ */ new Map();
3663
3841
  for (const row of rows) {
@@ -3671,846 +3849,24 @@ function presentAt(resources, rows, outletId) {
3671
3849
  });
3672
3850
  }
3673
3851
 
3674
- // booking/durations.ts
3675
- var { MINUTE: MINUTE2, HOUR, DAY, NIGHT, WEEK, MONTH } = BookingDurationUnit;
3676
- var NONE = [];
3677
- var CLOCK = [MINUTE2, HOUR];
3678
- var everyType = (units) => Object.fromEntries(Object.values(BookingRatePeriod).map((ratePeriod) => [ratePeriod, units]));
3679
- var STAY = {
3680
- slot: NONE,
3681
- session: NONE,
3682
- hour: [HOUR, DAY, WEEK],
3683
- night: [NIGHT, WEEK, MONTH],
3684
- day: [DAY, WEEK, MONTH],
3685
- week: [WEEK],
3686
- month: [MONTH]
3687
- };
3688
- var ALLOWED_UNITS = {
3689
- "timeSlots.length": { ...everyType(NONE), slot: CLOCK },
3690
- "slot.buffer": { ...everyType(CLOCK), night: NONE },
3691
- "window.hold": everyType(CLOCK),
3692
- "window.minNotice": everyType([MINUTE2, HOUR, DAY, WEEK]),
3693
- "window.maxAdvance": everyType([MINUTE2, HOUR, DAY, WEEK, MONTH]),
3694
- "dateRanges.minStay": STAY,
3695
- "dateRanges.maxStay": STAY
3696
- };
3697
- function allowedDurationUnits(rule, field) {
3698
- const units = ALLOWED_UNITS[field]?.[rule.ratePeriod];
3699
- if (!units) throw new BookingRulesError(`Booking rules: no duration "${field}" for rate period "${rule.ratePeriod}"`);
3700
- return units;
3701
- }
3702
- var DURATION_AT = {
3703
- "timeSlots.length": (rule) => rule.timeSlots?.length,
3704
- "slot.buffer": (rule) => rule.slot.buffer,
3705
- "window.hold": (rule) => rule.window.hold,
3706
- "window.minNotice": (rule) => rule.window.minNotice,
3707
- "window.maxAdvance": (rule) => rule.window.maxAdvance,
3708
- "dateRanges.minStay": (rule) => rule.dateRanges?.minStay,
3709
- "dateRanges.maxStay": (rule) => rule.dateRanges?.maxStay
3710
- };
3711
- function durationProblems(rule) {
3712
- const problems = Object.keys(DURATION_AT).flatMap((field) => {
3713
- const duration = DURATION_AT[field](rule);
3714
- const problem = duration && problemOf(field, duration, allowedDurationUnits(rule, field), rule.ratePeriod);
3715
- return problem ? [problem] : [];
3716
- });
3717
- if (problems.length > 0) return problems;
3718
- return [stayAboveMax(rule.dateRanges?.minStay, rule.dateRanges?.maxStay), noticeAboveAdvance(rule.window)].filter(
3719
- (problem) => !!problem
3720
- );
3721
- }
3722
- function problemOf(field, duration, allowed, ratePeriod) {
3723
- if (!Number.isInteger(duration.count) || duration.count < 1) {
3724
- const message = `${field}: count must be a whole number of at least 1, got ${String(duration.count)}`;
3725
- return { field, kind: "count", message };
3726
- }
3727
- if (allowed.length === 0) {
3728
- return { field, kind: "not-for-type", message: `${field}: does not apply to ${ratePeriod} rules` };
3729
- }
3730
- if (!allowed.includes(duration.unit)) {
3731
- return { field, kind: "unit", allowed, message: `${field}: takes ${allowed.join(", ")}, got ${duration.unit}` };
3732
- }
3733
- return void 0;
3734
- }
3735
- var MINUTES_RANGE = {
3736
- minute: [1, 1],
3737
- hour: [60, 60],
3738
- day: [1440, 1440],
3739
- night: [1440, 1440],
3740
- week: [7 * 1440, 7 * 1440],
3741
- month: [28 * 1440, 31 * 1440]
3742
- };
3743
- var clockShiftOf = (unit2) => unit2 === MINUTE2 || unit2 === HOUR ? 0 : 60;
3744
- var shortestMinutesOf = ({ count, unit: unit2 }) => count * MINUTES_RANGE[unit2][0] - clockShiftOf(unit2);
3745
- var longestMinutesOf = ({ count, unit: unit2 }) => count * MINUTES_RANGE[unit2][1] + clockShiftOf(unit2);
3746
- var durationText = ({ count, unit: unit2 }) => `${count} ${unit2}${count === 1 ? "" : "s"}`;
3747
- var DAYS_IN_UNIT = { day: 1, night: 1, week: 7 };
3748
- var MINUTES_IN_UNIT = { minute: 1, hour: 60 };
3749
- function exactly(min, max) {
3750
- if (min.unit === max.unit) return [min.count, max.count];
3751
- for (const table of [DAYS_IN_UNIT, MINUTES_IN_UNIT]) {
3752
- const [minSize, maxSize] = [table[min.unit], table[max.unit]];
3753
- if (minSize && maxSize) return [min.count * minSize, max.count * maxSize];
3754
- }
3755
- return void 0;
3756
- }
3757
- function minLongerThanMax(min, max) {
3758
- const exact = exactly(min, max);
3759
- return exact ? exact[0] > exact[1] : longestMinutesOf(min) > shortestMinutesOf(max);
3760
- }
3761
- function stayAboveMax(min, max) {
3762
- if (!min || !max || !minLongerThanMax(min, max)) return void 0;
3763
- const message = `dateRanges.maxStay: Max ${durationText(max)} can be shorter than Min ${durationText(min)}`;
3764
- return { field: "dateRanges.maxStay", kind: "min-above-max", min, max, message };
3765
- }
3766
- function noticeAboveAdvance({
3767
- minNotice,
3768
- maxAdvance
3769
- }) {
3770
- if (!minNotice || !maxAdvance || !minLongerThanMax(minNotice, maxAdvance)) return void 0;
3771
- const message = `window.maxAdvance: ${durationText(maxAdvance)} ahead can be shorter than the notice of ${durationText(minNotice)}`;
3772
- return { field: "window.maxAdvance", kind: "min-above-max", min: minNotice, max: maxAdvance, message };
3773
- }
3774
-
3775
3852
  // booking/plan.ts
3776
3853
  var DEFAULT_HOLD_MINUTES = 10;
3777
3854
  function planWindow({ rule, timeZone, presence, startAt, endAt, now, busy = [] }) {
3778
- if (!soldAsCourse(rule)) checkStartWithinMaxAdvance(rule, timeZone, startAt, now);
3779
3855
  const grid = buildGrid(rule, timeZone, startAt, endAt, now, busy).filter(
3780
3856
  (slot) => withinPresence(slot, timeZone, presence)
3781
3857
  );
3782
3858
  const slots = slotsForWindow(grid, startAt, endAt);
3783
- const last = slots[slots.length - 1];
3784
- const parts = bookingRuleParts(rule);
3785
- const wholePeriods = parts.method === "date-ranges" && parts.wholePeriods;
3786
- const periods = wholePeriods ? wholePeriodsIn(rule.ratePeriod, timeZone, startAt, last.endAt, slots.length) : slots.length;
3787
- checkStay(parts, timeZone, startAt, periods);
3788
- const { buffer } = ruleDurationsOf(rule);
3789
- const bufferEndAt = rule.ratePeriod === "hour" /* HOUR */ || wholePeriods ? buffer ? addDuration(last.endAt, buffer, timeZone) : new Date(last.endAt.getTime()) : last.bufferEndAt;
3790
- return { slots, periods, endAt: last.endAt, bufferEndAt };
3791
- }
3792
- function checkStartWithinMaxAdvance(rule, timeZone, startAt, now) {
3793
- if (startsPastMaxAdvance(rule, startAt, now, timeZone)) {
3794
- throw new BookingRulesError(`${startAt.toISOString()} is past the booking window of these rules`);
3795
- }
3796
- }
3797
- function checkStay(parts, timeZone, startAt, periods) {
3798
- if (parts.method !== "date-ranges") return;
3799
- const stay = { count: periods, unit: periodUnitOf(parts) };
3800
- const length = (duration) => stayLength(parts.ratePeriod, duration, startAt, timeZone);
3801
- const { minStay, maxStay } = parts;
3802
- if (minStay && length(stay) < length(minStay)) {
3803
- throw new BookingRulesError(
3804
- `These rules ask for a stay of at least ${durationText(minStay)}, got ${durationText(stay)}`
3805
- );
3806
- }
3807
- if (maxStay && length(stay) > length(maxStay)) {
3808
- throw new BookingRulesError(
3809
- `These rules allow a stay of at most ${durationText(maxStay)}, got ${durationText(stay)}`
3810
- );
3811
- }
3812
- }
3813
- function stayLength(ratePeriod, duration, startAt, timeZone) {
3814
- if (ratePeriod === "hour" /* HOUR */) return addDuration(startAt, duration, timeZone).getTime();
3815
- const { count, unit: unit2 } = duration;
3816
- if (unit2 === "day" /* DAY */ || unit2 === "night" /* NIGHT */) return count;
3817
- if (unit2 === "week" /* WEEK */) return 7 * count;
3818
- if (unit2 !== "month" /* MONTH */) {
3819
- throw new BookingRulesError(`Booking rules: a ${ratePeriod} stay cannot be counted in ${unit2}s`);
3820
- }
3821
- const { year, month, day } = zonedParts(startAt, timeZone);
3822
- const [toYear, toMonth, toDay] = sameDayMonthsLaterDate(year, month, day, count);
3823
- return (Date.UTC(toYear, toMonth - 1, toDay) - Date.UTC(year, month - 1, day)) / 864e5;
3824
- }
3825
- function windowForPeriods({ rule, timeZone, startAt, periods, now }) {
3826
- if (!Number.isInteger(periods) || periods < 1) {
3827
- throw new BookingRulesError(`periods must be a whole number of at least 1, got ${String(periods)}`);
3828
- }
3829
- checkStartWithinMaxAdvance(rule, timeZone, startAt, now);
3830
- const parts = bookingRuleParts(rule);
3831
- checkStay(parts, timeZone, startAt, periods);
3832
- const wholePeriods = parts.method === "date-ranges" && parts.wholePeriods;
3833
- const monthsEnd = wholePeriods && rule.ratePeriod === "month" /* MONTH */ ? sameDayMonthsLater(startAt, periods, timeZone) : null;
3834
- const cells = wholePeriods && rule.ratePeriod === "week" /* WEEK */ ? periods * 7 : periods;
3835
- const lastDay = monthsEnd ?? new Date(startAt.getTime() + (cells + 2) * 1440 * 6e4);
3836
- const grid = buildGrid(
3837
- rule,
3838
- timeZone,
3839
- startAt,
3840
- new Date(Math.min(lastDay.getTime() + 1440 * 6e4, startAt.getTime() + 366 * 1440 * 6e4)),
3841
- now
3842
- );
3843
- const startIndex = grid.findIndex((cell) => cell.startAt.getTime() === startAt.getTime());
3844
- if (startIndex < 0)
3845
- throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
3846
- const endAt = monthsEnd ?? grid[startIndex + cells - 1]?.endAt;
3847
- if (!endAt)
3848
- throw new BookingRulesError(`${periods} period(s) from ${startAt.toISOString()} run past the bookable grid`);
3849
- slotsForWindow(grid, startAt, endAt);
3850
- return { startAt, endAt };
3851
- }
3852
- function rentalEnds(input) {
3853
- const { rule, timeZone, startAt, now, untilDay } = input;
3854
- const parts = bookingRuleParts(rule);
3855
- if (parts.method !== "date-ranges") throw new BookingRulesError("Only date-range rules book a stay");
3856
- checkStartWithinMaxAdvance(rule, timeZone, startAt, now);
3857
- const horizon = shopDayRange(untilDay, 1, timeZone).to;
3858
- if (horizon <= startAt) throw new BookingRulesError(`untilDay ${untilDay} is before the stay starts`);
3859
- const gridUntil = (end) => buildGrid(rule, timeZone, startAt, new Date(Math.min(end, startAt.getTime() + 366 * 1440 * 6e4)), now);
3860
- let walk = walkRentalEnds(gridUntil(horizon.getTime() + 1440 * 6e4), input, parts, horizon);
3861
- if (!walk.ends.length && walk.refusal && walk.ranOut)
3862
- walk = walkRentalEnds(gridUntil(Infinity), input, parts, horizon);
3863
- if (walk.ends.length) return walk.ends;
3864
- throw walk.refusal ?? new BookingRulesError(
3865
- `No stay from ${startAt.toISOString()} fits these rules: the bookable days run out before the shortest allowed stay`
3866
- );
3867
- }
3868
- function walkRentalEnds(grid, { rule, timeZone, startAt, untilDay }, parts, horizon) {
3869
- const startIndex = grid.findIndex((cell) => cell.startAt.getTime() === startAt.getTime());
3870
- if (startIndex < 0) {
3871
- throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
3872
- }
3873
- slotsForWindow(grid, startAt, grid[startIndex].endAt);
3874
- const ends = [];
3875
- let refusal;
3876
- for (const cell of grid.slice(startIndex)) {
3877
- if (cell.endAt > horizon && (ends.length || !refusal)) {
3878
- refusal ??= new BookingRulesError(`No stay from ${startAt.toISOString()} ends on or before ${untilDay}`);
3879
- return { ends, refusal, ranOut: false };
3880
- }
3881
- const slots = refusalOr(() => slotsForWindow(grid, startAt, cell.endAt));
3882
- if (slots instanceof BookingRulesError) return { ends, refusal, ranOut: false };
3883
- const periods = refusalOr(
3884
- () => parts.wholePeriods ? wholePeriodsIn(rule.ratePeriod, timeZone, startAt, cell.endAt, slots.length) : slots.length
3885
- );
3886
- if (periods instanceof BookingRulesError) continue;
3887
- const stay = refusalOr(() => checkStay(parts, timeZone, startAt, periods));
3888
- if (stay instanceof BookingRulesError) {
3889
- if (ends.length) return { ends, refusal, ranOut: false };
3890
- refusal = stay;
3891
- continue;
3892
- }
3893
- ends.push(rentalEndOf(slots, periods, timeZone));
3894
- }
3895
- return { ends, refusal, ranOut: true };
3896
- }
3897
- function rentalEndOf(slots, periods, timeZone) {
3898
- const endAt = slots[slots.length - 1].endAt;
3899
- return {
3900
- periods,
3901
- endAt: endAt.toISOString(),
3902
- lastDayKey: shopDayKey(new Date(endAt.getTime() - 1), timeZone),
3903
- coveredSlots: slots.map((slot) => ({
3904
- startAt: slot.startAt.toISOString(),
3905
- dayKey: shopDayKey(slot.startAt, timeZone)
3906
- }))
3907
- };
3908
- }
3909
- function refusalOr(run) {
3910
- try {
3911
- return run();
3912
- } catch (error) {
3913
- if (error instanceof BookingRulesError) return error;
3914
- throw error;
3915
- }
3916
- }
3917
- function sameDayMonthsLater(startAt, months, timeZone) {
3918
- const { year, month, day } = zonedParts(startAt, timeZone);
3919
- return instantFromLocal(...sameDayMonthsLaterDate(year, month, day, months), 0, timeZone);
3920
- }
3921
- function wholePeriodsIn(ratePeriod, timeZone, startAt, endAt, days) {
3922
- if (ratePeriod === "week" /* WEEK */) {
3923
- if (days % 7 !== 0) throw new BookingRulesError(`Book whole weeks: ${days} day(s) is not a number of weeks`);
3924
- return days / 7;
3925
- }
3926
- if (ratePeriod !== "month" /* MONTH */) {
3927
- throw new BookingRulesError("Whole periods are for week and month rules only");
3928
- }
3929
- const start = zonedParts(startAt, timeZone);
3930
- const end = zonedParts(endAt, timeZone);
3931
- const months = (end.year - start.year) * 12 + (end.month - start.month);
3932
- const lastDayOfEndMonth = new Date(Date.UTC(end.year, end.month, 0)).getUTCDate();
3933
- if (months < 1 || end.day !== Math.min(start.day, lastDayOfEndMonth)) {
3934
- throw new BookingRulesError("Book whole months: the stay must end on the same day of a later month");
3935
- }
3936
- return months;
3937
- }
3938
- function courseSessions(rule, timeZone) {
3939
- const [from, to] = rule.sessions?.weekly?.length ? weeklyCourseRange(rule) : datesCourseRange(rule.sessions?.dates ?? [], timeZone);
3940
- const sessions = sessionCells(rule, timeZone, from, to).sort((first, second) => +first.startAt - +second.startAt);
3941
- if (sessions.length === 0) throw new BookingRulesError("These course dates hold no session");
3942
- return sessions;
3943
- }
3944
- function courseSpan(rule, timeZone) {
3945
- const sessions = courseSessions(rule, timeZone);
3946
- return { from: sessions[0].startAt, to: sessions[sessions.length - 1].bufferEndAt };
3947
- }
3948
- function weeklyCourseRange(rule) {
3949
- const { bookableFrom, bookableTo } = rule.window;
3950
- if (!bookableFrom || !bookableTo) throw new BookingRulesError("A course needs both course dates");
3951
- return [new Date(bookableFrom), new Date(bookableTo)];
3952
- }
3953
- function datesCourseRange(dates, timeZone) {
3954
- if (dates.length === 0) throw new BookingRulesError("A course needs its sessions");
3955
- const days = dates.map(({ date }) => date).sort();
3956
- const [firstYear, firstMonth, firstDay] = calendarDate(days[0]);
3957
- const [lastYear, lastMonth, lastDay] = calendarDate(days[days.length - 1]);
3958
- return [
3959
- instantFromLocal(firstYear, firstMonth, firstDay, 0, timeZone),
3960
- instantFromLocal(lastYear, lastMonth, lastDay + 1, 0, timeZone)
3961
- ];
3962
- }
3963
- var courseStarted = (rule, sessions, now) => sessions[0].startAt.getTime() < now.getTime() + (rule.window.minNoticeMinutes ?? 0) * 6e4;
3964
- function courseStartedInZone(rule, sessions, now, timeZone) {
3965
- const { minNotice } = ruleDurationsOf(rule);
3966
- return sessions[0].startAt.getTime() < (minNotice ? addDuration(now, minNotice, timeZone) : now).getTime();
3967
- }
3968
- function planCourse({ rule, timeZone, presence, now }) {
3969
- const sessions = courseSessions(rule, timeZone);
3970
- if (!sessions.every((session) => withinPresence(session, timeZone, presence))) {
3971
- throw new BookingRulesError("This resource is not there for every session of the course");
3972
- }
3973
- if (courseStartedInZone(rule, sessions, now, timeZone))
3974
- throw new BookingRulesError("This course has already started");
3975
- if (startsPastMaxAdvance(rule, sessions[0].startAt, now, timeZone)) {
3976
- throw new BookingRulesError("This course starts past the booking window of these rules");
3977
- }
3978
- return sessions;
3979
- }
3980
- function holdExpiresAt(rule, now) {
3981
- return addClockDuration(now, holdOf(rule) ?? DEFAULT_HOLD);
3982
- }
3983
- var DEFAULT_HOLD = { count: DEFAULT_HOLD_MINUTES, unit: "minute" /* MINUTE */ };
3984
- function holdOf(rule) {
3985
- const { hold } = ruleDurationsOf(rule);
3986
- if (!hold) return void 0;
3987
- const field = rule.window.hold ? "window.hold" : "window.holdMinutes";
3988
- if (!Number.isInteger(hold.count)) {
3989
- throw new BookingRulesError(`${field} must be a whole number of ${hold.unit}s, got ${hold.count}`);
3990
- }
3991
- if (hold.count < 1) throw new BookingRulesError(`${field} must be at least 1 ${hold.unit}, got ${hold.count}`);
3992
- return hold;
3993
- }
3994
- function checkQtyPerBooking(rule, qty) {
3995
- const max = rule.slot.maxQtyPerBooking;
3996
- if (max !== void 0 && qty > max) {
3997
- throw new BookingRulesError(`These rules allow at most ${max} per booking, got ${qty}`);
3998
- }
3999
- }
4000
- function checkPartySize(rule, partySize) {
4001
- const max = rule.slot.maxPartySize;
4002
- if (max !== void 0 && partySize > max) {
4003
- throw new BookingRulesError(`These rules allow at most ${max} people per booking, got ${partySize}`);
4004
- }
4005
- }
4006
- function bookingMethodOf(rule) {
4007
- if (rule.ratePeriod === "slot" /* SLOT */) return "time-slots";
4008
- if (rule.ratePeriod === "session" /* SESSION */) return "sessions";
4009
- return "date-ranges";
4010
- }
4011
- var soldAsCourse = (rule) => rule.ratePeriod === "session" /* SESSION */ && rule.sessions?.sold === "course" /* COURSE */;
4012
- function capacityOf(rule, resource) {
4013
- if (rule.ratePeriod !== "session" /* SESSION */) return resource.seats ?? 1;
4014
- if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4015
- return rule.sessions.spots ?? Number.POSITIVE_INFINITY;
4016
- }
4017
- function bookingRuleParts(rule) {
4018
- const method = bookingMethodOf(rule);
4019
- if (method === "sessions") {
4020
- if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4021
- return { method, sessions: rule.sessions };
4022
- }
4023
- if (method === "time-slots") {
4024
- const timeSlots = rule.timeSlots ? newTimeSlotsOf(rule.timeSlots) : oldTimeSlotsOf(rule);
4025
- const { count } = timeSlots.length;
4026
- if (!Number.isInteger(count) || count < 1) {
4027
- const field = rule.timeSlots ? "timeSlots.length" : "slot.lengthMinutes";
4028
- throw new BookingRulesError(`Booking rules: ${field} must be a whole number of at least 1, got ${count}`);
4029
- }
4030
- return { method, ...timeSlots };
3859
+ const { minStay, maxStay } = rule.slot;
3860
+ if (minStay && slots.length < minStay) {
3861
+ throw new BookingRulesError(`These rules ask for at least ${minStay} period(s), got ${slots.length}`);
4031
3862
  }
4032
- if (!rule.dateRanges) return { method, ratePeriod: rule.ratePeriod, ...oldDateRangesOf(rule) };
4033
- const wholePeriods = rule.ratePeriod === "week" /* WEEK */ || rule.ratePeriod === "month" /* MONTH */;
4034
- return { method, ratePeriod: rule.ratePeriod, wholePeriods, ...rule.dateRanges };
4035
- }
4036
- function newTimeSlotsOf({ length, weeklyHours }) {
4037
- if (!weeklyHours?.length) throw new BookingRulesError("Booking rules: timeSlots.weeklyHours needs at least one day");
4038
- return { length, weeklyHours };
4039
- }
4040
- function oldTimeSlotsOf({ slot, availability }) {
4041
- if (slot.lengthMinutes == null) throw new BookingRulesError("Time-slot rules need their slot length");
4042
- return {
4043
- length: { count: slot.lengthMinutes, unit: "minute" /* MINUTE */ },
4044
- weeklyHours: availability.weeklyHours ?? []
4045
- };
4046
- }
4047
- function oldDateRangesOf(rule) {
4048
- const { slot, availability } = rule;
4049
- const wholePeriods = slot.wholePeriods ?? false;
4050
- const stay = (count) => count ? { count, unit: periodUnitOf({ ratePeriod: rule.ratePeriod, wholePeriods }) } : void 0;
4051
- return {
4052
- // Old `[]` meant "open every day" — the new form says that by having no rows.
4053
- weeklyHours: availability.weeklyHours?.length ? availability.weeklyHours : void 0,
4054
- arrivalDays: availability.arrivalDays,
4055
- checkInTime: rule.checkInTime,
4056
- checkOutTime: rule.checkOutTime,
4057
- checkTimesByWeekday: rule.checkTimesByWeekday,
4058
- minStay: stay(slot.minStay),
4059
- maxStay: stay(slot.maxStay),
4060
- wholePeriods
4061
- };
4062
- }
4063
- function periodUnitOf({
4064
- ratePeriod,
4065
- wholePeriods
4066
- }) {
4067
- const units = {
4068
- ["hour" /* HOUR */]: "hour" /* HOUR */,
4069
- ["night" /* NIGHT */]: "night" /* NIGHT */,
4070
- ["day" /* DAY */]: "day" /* DAY */,
4071
- ["week" /* WEEK */]: wholePeriods ? "week" /* WEEK */ : "day" /* DAY */,
4072
- ["month" /* MONTH */]: wholePeriods ? "month" /* MONTH */ : "day" /* DAY */
4073
- };
4074
- const unit2 = units[ratePeriod];
4075
- if (!unit2) throw new BookingRulesError(`Booking rules: "${ratePeriod}" is not a date-range rate period`);
4076
- return unit2;
4077
- }
4078
- var OLD_BUFFER = {
4079
- path: "slot.bufferMinutes",
4080
- home: {
4081
- "time-slots": "slot.buffer",
4082
- sessions: "slot.buffer",
4083
- // The old night grid never read it: housekeeping is the gap between check-out and check-in (O-1).
4084
- "date-ranges": ({ ratePeriod }) => ratePeriod === "night" /* NIGHT */ ? { unread: "nights clean between check-out and check-in" } : "slot.buffer"
4085
- }
4086
- };
4087
- var OLD_FIELDS = [
4088
- {
4089
- path: "slot.lengthMinutes",
4090
- home: {
4091
- "time-slots": "timeSlots.length",
4092
- sessions: { unread: "placeholder" },
4093
- "date-ranges": { unread: "placeholder" }
4094
- }
4095
- },
4096
- OLD_BUFFER,
4097
- {
4098
- path: "slot.minStay",
4099
- home: {
4100
- "time-slots": { dropped: "time-slots rules have no stay limits" },
4101
- sessions: { dropped: "sessions rules have no stay limits" },
4102
- "date-ranges": "dateRanges.minStay"
4103
- }
4104
- },
4105
- {
4106
- path: "slot.maxStay",
4107
- home: {
4108
- "time-slots": { dropped: "time-slots rules have no stay limits" },
4109
- sessions: { dropped: "sessions rules have no stay limits" },
4110
- "date-ranges": "dateRanges.maxStay"
4111
- }
4112
- },
4113
- {
4114
- path: "window.holdMinutes",
4115
- home: { "time-slots": "window.hold", sessions: "window.hold", "date-ranges": "window.hold" }
4116
- },
4117
- {
4118
- path: "window.minNoticeMinutes",
4119
- home: { "time-slots": "window.minNotice", sessions: "window.minNotice", "date-ranges": "window.minNotice" }
4120
- },
4121
- // The two old max-advance fields are one fact, as the old readers took it: minutes, else days × 1440.
4122
- ...["window.maxAdvanceMinutes", "window.maxAdvanceDays"].map((path) => ({
4123
- path,
4124
- carried: maxAdvanceMinutesOf,
4125
- home: { "time-slots": "window.maxAdvance", sessions: "window.maxAdvance", "date-ranges": "window.maxAdvance" }
4126
- })),
4127
- {
4128
- path: "availability.weeklyHours",
4129
- home: {
4130
- "time-slots": "timeSlots.weeklyHours",
4131
- sessions: { unread: "sessions read their timetable" },
4132
- "date-ranges": "dateRanges.weeklyHours"
4133
- }
4134
- },
4135
- {
4136
- path: "availability.arrivalDays",
4137
- home: {
4138
- "time-slots": { unread: "date ranges only" },
4139
- sessions: { unread: "date ranges only" },
4140
- "date-ranges": "dateRanges.arrivalDays"
4141
- }
4142
- },
4143
- // An `opening-hours` night has no check times (FC-1503): switching to it drops the old ones, said in a note.
4144
- ...["checkInTime", "checkOutTime", "checkTimesByWeekday"].map((path) => ({
4145
- path,
4146
- home: {
4147
- "time-slots": { unread: "date ranges only" },
4148
- sessions: { unread: "date ranges only" },
4149
- "date-ranges": ({ dateRanges }) => dateRanges?.arriveLeave === "opening-hours" /* OPENING_HOURS */ ? { dropped: "opening-hours nights have no check times" } : `dateRanges.${path}`
4150
- }
4151
- }))
4152
- ];
4153
- var homeOf = (field, rule) => {
4154
- const home = field.home[bookingMethodOf(rule)];
4155
- return typeof home === "function" ? home(rule) : home;
4156
- };
4157
- var carriedValueOf = (rule, field) => field.carried ? field.carried(rule) : valueAt(rule, field.path);
4158
- var carries = (value) => value != null && value !== 0 && !(Array.isArray(value) && value.length === 0);
4159
- function ruleInNewShape(rule) {
4160
- const set = { ...typePartInNewShape(rule), ...durationsInNewShape(rule) };
4161
- const unset = [...OLD_FIELDS.map(({ path }) => path), "slot.wholePeriods"].filter(
4162
- (path) => valueAt(rule, path) !== void 0
4163
- );
4164
- const written = writtenRule(rule, set, unset);
4165
- bookingRuleParts(written);
4166
- refuseLostValues(rule, written);
4167
- const changesBehaviour = sellsOneDayOfWeekOrMonth(rule) ? "whole-periods" : void 0;
4168
- const notes = [
4169
- ...droppedFieldNotes(rule, written),
4170
- ...changesBehaviour ? [`${rule.ratePeriod} rule now sells whole ${rule.ratePeriod}s, was one day per booking`] : []
4171
- ];
4172
- return { set, unset, problems: durationProblems(written), notes, ...changesBehaviour && { changesBehaviour } };
4173
- }
4174
- function typePartInNewShape(rule) {
4175
- const method = bookingMethodOf(rule);
4176
- if (method === "sessions") return {};
4177
- if (method === "time-slots") return { timeSlots: newTimeSlotsOf(rule.timeSlots ?? oldTimeSlotsOf(rule)) };
4178
- if (rule.dateRanges) return { dateRanges: rule.dateRanges };
4179
- const dateRanges = oldDateRangesOf(rule);
4180
- delete dateRanges.wholePeriods;
4181
- return { dateRanges: definedOnly(dateRanges) };
4182
- }
4183
- function durationsInNewShape(rule) {
4184
- const { buffer, minNotice } = ruleDurationsOf(rule);
4185
- return definedOnly({
4186
- "slot.buffer": rule.slot.buffer ?? (typeof homeOf(OLD_BUFFER, rule) === "string" ? buffer : void 0),
4187
- "window.hold": holdOf(rule) ?? DEFAULT_HOLD,
4188
- "window.minNotice": minNotice,
4189
- "window.maxAdvance": ruleDurationsOf(rule).maxAdvance
4190
- });
4191
- }
4192
- var sellsOneDayOfWeekOrMonth = ({ ratePeriod, slot, dateRanges }) => !dateRanges && (ratePeriod === "week" /* WEEK */ || ratePeriod === "month" /* MONTH */) && !slot.wholePeriods;
4193
- function droppedFieldNotes(rule, written) {
4194
- const weekOrMonth = rule.ratePeriod === "week" /* WEEK */ || rule.ratePeriod === "month" /* MONTH */;
4195
- return [
4196
- ...OLD_FIELDS.flatMap((field) => {
4197
- const home = homeOf(field, rule);
4198
- const dropped = typeof home === "object" && "dropped" in home && carries(carriedValueOf(rule, field));
4199
- return dropped ? [`${field.path} is dropped: ${home.dropped}`] : [];
4200
- }),
4201
- ...rule.slot.wholePeriods && !weekOrMonth ? ["slot.wholePeriods is dropped: only week and month rules have it"] : [],
4202
- ...rule.ratePeriod === "hour" /* HOUR */ && !written.dateRanges?.weeklyHours?.length ? ["hour rule has no opening hours: nothing can be booked"] : [],
4203
- ...rule.window.holdMinutes == null && !rule.window.hold ? [`window.hold is set to the default ${DEFAULT_HOLD_MINUTES} minutes`] : []
4204
- ];
4205
- }
4206
- function writtenRule(rule, set, unset) {
4207
- const written = {
4208
- ...rule,
4209
- slot: { ...rule.slot },
4210
- window: { ...rule.window },
4211
- availability: { ...rule.availability }
4212
- };
4213
- for (const path of unset) {
4214
- const [head, leaf] = path.split(".");
4215
- if (leaf) delete written[head][leaf];
4216
- else delete written[head];
4217
- }
4218
- for (const [path, value] of Object.entries(set)) {
4219
- const [head, leaf] = path.split(".");
4220
- if (leaf) written[head][leaf] = value;
4221
- else written[head] = value;
4222
- }
4223
- return written;
4224
- }
4225
- function refuseLostValues(rule, written) {
4226
- for (const field of OLD_FIELDS) {
4227
- const home = homeOf(field, rule);
4228
- if (typeof home === "string" && carries(carriedValueOf(rule, field)) && valueAt(written, home) == null) {
4229
- throw new BookingRulesError(`Booking rules: ${home} is missing \u2014 the rule's old value would be lost`);
4230
- }
4231
- }
4232
- }
4233
- var definedOnly = (value) => Object.fromEntries(Object.entries(value).filter(([, entry]) => entry != null));
4234
- var valueAt = (rule, path) => path.split(".").reduce((node, key) => node?.[key], rule);
4235
-
4236
- // booking/grid.ts
4237
- var MINUTE3 = 6e4;
4238
- var HOUR_MINUTES = 60;
4239
- var MAX_RANGE_DAYS = 366;
4240
- var asTime = (value, field) => {
4241
- if (value == null) return void 0;
4242
- const time = new Date(value).getTime();
4243
- if (Number.isNaN(time)) throw new BookingRulesError(`Booking rules: ${field} is not a date, got "${String(value)}"`);
4244
- return time;
4245
- };
4246
- function parseHhMm(value, field) {
4247
- const [hours, minutes] = value.split(":").map(Number);
4248
- if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
4249
- throw new BookingRulesError(`Booking rules: ${field} must be "HH:mm", got "${value}"`);
4250
- }
4251
- return hours * 60 + minutes;
4252
- }
4253
- function windowEndsAt(rule, now) {
4254
- const maxAdvanceMinutes = maxAdvanceMinutesOf(rule);
4255
- const ends = Math.min(
4256
- maxAdvanceMinutes ? now.getTime() + maxAdvanceMinutes * MINUTE3 : Number.POSITIVE_INFINITY,
4257
- asTime(rule.window.bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
4258
- );
4259
- return Number.isFinite(ends) ? new Date(ends) : null;
4260
- }
4261
- function windowEndsAtInZone(rule, now, timeZone) {
4262
- const ends = Math.min(
4263
- lastStartOf(rule, now, timeZone),
4264
- asTime(rule.window.bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
4265
- );
4266
- return Number.isFinite(ends) ? new Date(ends) : null;
4267
- }
4268
- function lastStartOf(rule, now, timeZone) {
4269
- const { maxAdvance } = ruleDurationsOf(rule);
4270
- if (!maxAdvance) return Number.POSITIVE_INFINITY;
4271
- const reached = addInZone(now, maxAdvance, timeZone, "window.maxAdvance");
4272
- if (maxAdvance.unit === "minute" /* MINUTE */ || maxAdvance.unit === "hour" /* HOUR */) {
4273
- return reached.getTime();
4274
- }
4275
- const zone = timeZone;
4276
- return nextZonedDay(startOfZonedDay(reached, zone), zone).getTime() - 1;
4277
- }
4278
- var startsPastMaxAdvance = (rule, startAt, now, timeZone) => startAt.getTime() > lastStartOf(rule, now, timeZone);
4279
- function addInZone(from, duration, timeZone, field) {
4280
- if (timeZone) return addDuration(from, duration, timeZone);
4281
- if (duration.unit === "minute" /* MINUTE */ || duration.unit === "hour" /* HOUR */) {
4282
- return addClockDuration(from, duration);
4283
- }
4284
- throw new BookingRulesError(`Booking rules: ${field} in ${duration.unit}s needs the shop's time zone`);
4285
- }
4286
- function maxAdvanceMinutesOf(rule) {
4287
- const { maxAdvanceMinutes, maxAdvanceDays } = rule.window;
4288
- return maxAdvanceMinutes ?? (maxAdvanceDays ?? 0) * 1440;
4289
- }
4290
- var asMinutes = (minutes) => minutes == null ? void 0 : { count: minutes, unit: "minute" /* MINUTE */ };
4291
- var inMinutes = (minutes) => minutes === 0 ? void 0 : asMinutes(minutes);
4292
- function notNegative(duration, field) {
4293
- if (duration && !(Number.isFinite(duration.count) && duration.count >= 0)) {
4294
- throw new BookingRulesError(`Booking rules: ${field} must be a number of at least 0, got ${duration.count}`);
4295
- }
4296
- return duration;
4297
- }
4298
- function ruleDurationsOf(rule) {
4299
- const { slot, window } = rule;
4300
- return {
4301
- buffer: notNegative(
4302
- slot.buffer ?? inMinutes(slot.bufferMinutes),
4303
- slot.buffer ? "slot.buffer" : "slot.bufferMinutes"
4304
- ),
4305
- hold: window.hold ?? asMinutes(window.holdMinutes),
4306
- minNotice: notNegative(
4307
- window.minNotice ?? inMinutes(window.minNoticeMinutes),
4308
- window.minNotice ? "window.minNotice" : "window.minNoticeMinutes"
4309
- ),
4310
- maxAdvance: window.maxAdvance ?? oldMaxAdvanceOf(window)
4311
- };
4312
- }
4313
- function oldMaxAdvanceOf({
4314
- maxAdvanceMinutes,
4315
- maxAdvanceDays
4316
- }) {
4317
- const days = maxAdvanceDays ?? 0;
4318
- if (maxAdvanceMinutes == null || days > 0 && maxAdvanceMinutes === days * 1440) {
4319
- return days > 0 ? { count: days, unit: "day" /* DAY */ } : void 0;
4320
- }
4321
- return maxAdvanceMinutes ? { count: maxAdvanceMinutes, unit: "minute" /* MINUTE */ } : void 0;
4322
- }
4323
- function periodSlot(dayStart, timeZone, parts, buffer, openMinute, closeMinute) {
4324
- const { ratePeriod } = parts;
4325
- const at = (minutes) => atZonedMinute(dayStart, minutes, timeZone);
4326
- if (ratePeriod === "night" /* NIGHT */ && parts.arriveLeave !== "opening-hours" /* OPENING_HOURS */) {
4327
- const arrival = zonedParts(dayStart, timeZone).weekday;
4328
- const departure = (arrival + 1) % 7;
4329
- return {
4330
- startAt: at(checkTimesOf(parts, arrival).checkIn),
4331
- endAt: at(1440 + checkTimesOf(parts, departure).checkOut),
4332
- // Housekeeping sits between check-out and the next check-in: it costs no night.
4333
- bufferEndAt: at(1440 + checkTimesOf(parts, departure).checkIn),
4334
- canStart: true
4335
- };
4336
- }
4337
- const from = ratePeriod === "day" /* DAY */ ? openMinute ?? 0 : 0;
4338
- const to = ratePeriod === "day" /* DAY */ ? closeMinute ?? 1440 : 1440;
4339
- const turnaround = parts.wholePeriods || ratePeriod === "night" /* NIGHT */ ? void 0 : buffer;
4340
- return {
4341
- startAt: at(from),
4342
- endAt: at(to),
4343
- bufferEndAt: turnaround ? addDuration(at(to), turnaround, timeZone) : at(to),
4344
- canStart: true
4345
- };
4346
- }
4347
- function checkTimesOf(rule, weekday) {
4348
- const row = rule.checkTimesByWeekday?.find((entry) => entry.weekday === weekday);
4349
- const checkInTime = row?.checkInTime ?? rule.checkInTime;
4350
- const checkOutTime = row?.checkOutTime ?? rule.checkOutTime;
4351
- if (!checkInTime || !checkOutTime) {
4352
- throw new BookingRulesError("Overnight booking rules need both checkInTime and checkOutTime");
4353
- }
4354
- return { checkIn: parseHhMm(checkInTime, "checkInTime"), checkOut: parseHhMm(checkOutTime, "checkOutTime") };
4355
- }
4356
- function freeGaps(openAt, closeAt, busy) {
4357
- const inside = busy.map(({ startAt, bufferEndAt }) => ({ from: +startAt, to: +bufferEndAt })).filter(({ from, to }) => to > openAt && from < closeAt).sort((first, second) => first.from - second.from);
4358
- const gaps = [];
4359
- let cursor = openAt;
4360
- for (const { from, to } of inside) {
4361
- if (from > cursor) gaps.push({ from: cursor, to: from, endsAtBooking: true });
4362
- cursor = Math.max(cursor, to);
4363
- if (cursor >= closeAt) break;
4364
- }
4365
- if (cursor < closeAt) gaps.push({ from: cursor, to: closeAt, endsAtBooking: false });
4366
- return gaps;
4367
- }
4368
- function sessionCells(rule, timeZone, from, to) {
4369
- if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4370
- const { weekly = [], dates = [] } = rule.sessions;
4371
- const { buffer } = ruleDurationsOf(rule);
4372
- const cell = (startAt, endAt) => ({
4373
- startAt: new Date(startAt),
4374
- endAt: new Date(endAt),
4375
- bufferEndAt: buffer ? addDuration(new Date(endAt), buffer, timeZone) : new Date(endAt),
4376
- canStart: true
4377
- });
4378
- const cells = dates.map(({ date, startMinute, endMinute }) => {
4379
- const [year, month, day] = calendarDate(date);
4380
- return cell(
4381
- +instantFromLocal(year, month, day, startMinute, timeZone),
4382
- +instantFromLocal(year, month, day, endMinute, timeZone)
4383
- );
4384
- });
4385
- const lastDay = startOfZonedDay(to, timeZone).getTime();
4386
- for (let day = startOfZonedDay(from, timeZone); day.getTime() <= lastDay; day = nextZonedDay(day, timeZone)) {
4387
- const weekday = zonedParts(day, timeZone).weekday;
4388
- for (const row of weekly.filter((entry) => entry.weekday === weekday)) {
4389
- cells.push(cell(+atZonedMinute(day, row.startMinute, timeZone), +atZonedMinute(day, row.endMinute, timeZone)));
4390
- }
4391
- }
4392
- const blocked = offMarketOf(rule);
4393
- return cells.filter(({ startAt, bufferEndAt }) => {
4394
- const start = startAt.getTime();
4395
- return start >= from.getTime() && start <= to.getTime() && !isBlocked(blocked, start, bufferEndAt.getTime());
4396
- });
4397
- }
4398
- function calendarDate(value) {
4399
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value ?? "");
4400
- const [year, month, day] = match ? match.slice(1).map(Number) : [];
4401
- const real = match && new Date(Date.UTC(year, month - 1, day)).toISOString().slice(0, 10) === value;
4402
- if (!real) throw new BookingRulesError(`Booking rules: "${value}" is not a date (YYYY-MM-DD)`);
4403
- return [year, month, day];
4404
- }
4405
- var offMarketOf = (rule) => (rule.availability.offMarket ?? []).map(({ from: blockFrom, to: blockTo }) => ({
4406
- from: asTime(blockFrom, "availability.offMarket.from"),
4407
- to: asTime(blockTo, "availability.offMarket.to")
4408
- }));
4409
- var isBlocked = (blocked, start, bufferEnd) => blocked.some(({ from, to }) => start < to && bufferEnd > from);
4410
- function hourCells(openAt, closeAt) {
4411
- const cells = [];
4412
- for (let start = openAt; start + HOUR_MINUTES * MINUTE3 <= closeAt; start += HOUR_MINUTES * MINUTE3) {
4413
- const endAt = new Date(start + HOUR_MINUTES * MINUTE3);
4414
- cells.push({ startAt: new Date(start), endAt, bufferEndAt: endAt, canStart: true });
4415
- }
4416
- return cells;
4417
- }
4418
- function cellsOf(rule, parts, timeZone, from, to, busy) {
4419
- if (parts.method === "sessions") return sessionCells(rule, timeZone, from, to);
4420
- const { buffer } = ruleDurationsOf(rule);
4421
- const cells = [];
4422
- const lastDay = startOfZonedDay(to, timeZone).getTime();
4423
- for (let day = startOfZonedDay(from, timeZone); day.getTime() <= lastDay; day = nextZonedDay(day, timeZone)) {
4424
- cells.push(
4425
- ...parts.method === "time-slots" ? timeSlotCells(parts, buffer, day, timeZone, busy) : periodCells(parts, buffer, day, timeZone)
4426
- );
4427
- }
4428
- return cells;
4429
- }
4430
- function timeSlotCells(parts, buffer, dayStart, timeZone, busy) {
4431
- const weekday = zonedParts(dayStart, timeZone).weekday;
4432
- return parts.weeklyHours.filter((entry) => entry.weekday === weekday).flatMap(
4433
- (row) => freeGaps(
4434
- +atZonedMinute(dayStart, row.openMinute, timeZone),
4435
- +atZonedMinute(dayStart, row.closeMinute, timeZone),
4436
- busy
4437
- ).flatMap((gap) => cellsInGap(gap, parts.length, buffer, timeZone))
4438
- );
4439
- }
4440
- function cellsInGap(gap, length, buffer, timeZone) {
4441
- const cells = [];
4442
- for (let start = gap.from; ; ) {
4443
- const endAt = addDuration(new Date(start), length, timeZone);
4444
- const bufferEndAt = buffer ? addDuration(endAt, buffer, timeZone) : new Date(endAt.getTime());
4445
- if ((gap.endsAtBooking ? bufferEndAt : endAt).getTime() > gap.to) return cells;
4446
- cells.push({ startAt: new Date(start), endAt, bufferEndAt, canStart: true });
4447
- start = bufferEndAt.getTime();
4448
- }
4449
- }
4450
- function periodCells(parts, buffer, dayStart, timeZone) {
4451
- const weekday = zonedParts(dayStart, timeZone).weekday;
4452
- const rows = (parts.weeklyHours ?? []).filter((entry) => entry.weekday === weekday);
4453
- if (parts.ratePeriod === "hour" /* HOUR */) {
4454
- return rows.flatMap(
4455
- (row) => hourCells(
4456
- +atZonedMinute(dayStart, row.openMinute, timeZone),
4457
- +atZonedMinute(dayStart, row.closeMinute, timeZone)
4458
- )
4459
- );
4460
- }
4461
- if (parts.weeklyHours?.length && rows.length === 0) return [];
4462
- const built = periodSlot(dayStart, timeZone, parts, buffer, rows[0]?.openMinute, rows[0]?.closeMinute);
4463
- return [{ ...built, canStart: !parts.arrivalDays?.length || parts.arrivalDays.includes(weekday) }];
4464
- }
4465
- function buildGrid(rule, timeZone, from, to, now, busy = []) {
4466
- if (to.getTime() - from.getTime() > MAX_RANGE_DAYS * 1440 * MINUTE3) {
4467
- throw new BookingRulesError(`A booking range may span at most ${MAX_RANGE_DAYS} days`);
4468
- }
4469
- const { availability, window } = rule;
4470
- const { minNotice } = ruleDurationsOf(rule);
4471
- const notBefore = Math.max(
4472
- (minNotice ? addDuration(now, minNotice, timeZone) : now).getTime(),
4473
- asTime(window.bookableFrom, "window.bookableFrom") ?? 0,
4474
- asTime(availability.availableFrom, "availability.availableFrom") ?? 0
4475
- );
4476
- const notAfter = asTime(window.bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY;
4477
- const lastStart = lastStartOf(rule, now, timeZone);
4478
- const blocked = offMarketOf(rule);
4479
- const slots = cellsOf(rule, bookingRuleParts(rule), timeZone, from, to, busy);
4480
- const askedFrom = from.getTime();
4481
- const askedTo = to.getTime();
4482
- return slots.filter(({ startAt, bufferEndAt }) => {
4483
- const start = startAt.getTime();
4484
- if (start < askedFrom || start >= askedTo) return false;
4485
- if (start < notBefore || start > notAfter) return false;
4486
- return !isBlocked(blocked, start, bufferEndAt.getTime());
4487
- }).flatMap((cell) => cell.startAt.getTime() > lastStart ? pastMaxAdvance(cell, rule) : [cell]).sort((first, second) => +first.startAt - +second.startAt);
4488
- }
4489
- function pastMaxAdvance(cell, rule) {
4490
- if (soldAsCourse(rule)) return [cell];
4491
- return bookingMethodOf(rule) === "date-ranges" ? [{ ...cell, canStart: false }] : [];
4492
- }
4493
- function slotsForWindow(grid, startAt, endAt) {
4494
- const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
4495
- if (startIndex < 0) {
4496
- throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
4497
- }
4498
- if (!grid[startIndex].canStart) {
4499
- throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
4500
- }
4501
- const covered = [];
4502
- for (let index = startIndex; index < grid.length; index++) {
4503
- const entry = grid[index];
4504
- const previous = covered[covered.length - 1];
4505
- if (previous && entry.startAt.getTime() !== previous.bufferEndAt.getTime()) break;
4506
- covered.push(entry);
4507
- if (entry.endAt.getTime() === endAt.getTime()) return covered;
4508
- if (entry.endAt.getTime() > endAt.getTime()) break;
3863
+ if (maxStay && slots.length > maxStay) {
3864
+ throw new BookingRulesError(`These rules allow at most ${maxStay} period(s), got ${slots.length}`);
4509
3865
  }
4510
- throw new BookingRulesError(
4511
- `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
4512
- );
3866
+ const last = slots[slots.length - 1];
3867
+ return { slots, endAt: last.endAt, bufferEndAt: last.bufferEndAt };
4513
3868
  }
3869
+ var holdExpiresAt = (rule, now) => new Date(now.getTime() + (rule.window.holdMinutes ?? DEFAULT_HOLD_MINUTES) * 6e4);
4514
3870
 
4515
3871
  // shipping/fold-text.ts
4516
3872
  function foldText(value) {
@@ -4946,13 +4302,10 @@ export {
4946
4302
  AttributeType,
4947
4303
  BNPL_METHOD_STATUS,
4948
4304
  BNPL_SKIP_REASON,
4949
- BookingArriveLeave,
4950
- BookingDurationUnit,
4951
4305
  BookingRatePeriod,
4952
4306
  BookingResourceKind,
4953
4307
  BookingResourceStatus,
4954
4308
  BookingRulesError,
4955
- BookingSessionSale,
4956
4309
  BookingType,
4957
4310
  CANADA_PROVINCES,
4958
4311
  CONDITION_OPERATORS,
@@ -4967,6 +4320,7 @@ export {
4967
4320
  DEFAULT_DISPLAY_STATE_MAP,
4968
4321
  DEFAULT_HOLD_MINUTES,
4969
4322
  DEFAULT_RESOLVED_CONFIG,
4323
+ DEFAULT_SHELL_SETTINGS,
4970
4324
  DEFAULT_UNIT_ID,
4971
4325
  DualWriteStrategy,
4972
4326
  EUFixedRates,
@@ -5022,6 +4376,11 @@ export {
5022
4376
  ResidualPaymentMethod,
5023
4377
  ResidualStatus,
5024
4378
  ResourceAvailabilityState,
4379
+ SHELL_FLOW_SETTINGS_PREFIX,
4380
+ SHELL_FLOW_TIPS_KEY,
4381
+ SHELL_TIP_LABEL_MAX_LENGTH,
4382
+ SHELL_TIP_PERCENT_MAX,
4383
+ SHELL_TIP_PERCENT_MIN,
5025
4384
  SHIPPING_COUNTRIES,
5026
4385
  STATE_SCHEMA,
5027
4386
  STRIPE_SUPPORTED_COUNTRIES,
@@ -5042,7 +4401,6 @@ export {
5042
4401
  StripeStatus,
5043
4402
  TimePeriod,
5044
4403
  TopMetericsSort,
5045
- UNLIMITED_PLACES,
5046
4404
  UserTypes,
5047
4405
  addAmounts,
5048
4406
  addressPlaceKeys,
@@ -5051,7 +4409,6 @@ export {
5051
4409
  adyenStoreRequiresStateOrProvince,
5052
4410
  adyenSupportsTaxNumberAbsent,
5053
4411
  adyenTaxNumberFormat,
5054
- allowedDurationUnits,
5055
4412
  amountToString,
5056
4413
  ancestorChain,
5057
4414
  applyAssignment,
@@ -5061,21 +4418,15 @@ export {
5061
4418
  baseFulfillmentDefinitions,
5062
4419
  baseOf,
5063
4420
  basePaymentDefinitions,
5064
- bookingMethodOf,
5065
- bookingRuleParts,
5066
4421
  buildAvailability,
5067
4422
  buildGrid,
5068
4423
  buildOrderContext,
5069
4424
  buildPosPresetConfig,
5070
4425
  buildResolvedConfig,
5071
4426
  calculatePercentage,
5072
- calendarDate,
5073
4427
  canTransition,
5074
- capacityOf,
5075
4428
  cheapestCompositeItem,
5076
4429
  cheapestCompositePrice,
5077
- checkPartySize,
5078
- checkQtyPerBooking,
5079
4430
  compositeItemCost,
5080
4431
  compositeItemUnavailable,
5081
4432
  compositeMakeable,
@@ -5084,10 +4435,6 @@ export {
5084
4435
  compositeVariantInStock,
5085
4436
  conditionSummary,
5086
4437
  convertFixedFeeToLocalCurrency,
5087
- courseSessions,
5088
- courseSpan,
5089
- courseStarted,
5090
- courseStartedInZone,
5091
4438
  createAmount,
5092
4439
  crossAxisRuleApplies,
5093
4440
  currentAssignees,
@@ -5096,13 +4443,11 @@ export {
5096
4443
  deriveUnitId,
5097
4444
  displayRuleMatchesPair,
5098
4445
  divideAmount,
5099
- durationProblems,
5100
- durationText,
5101
4446
  evaluateCondition,
5102
4447
  evaluateConditionSet,
5103
4448
  extendPrice,
5104
4449
  extendPriceFor,
5105
- fewestFreeOver,
4450
+ flowSettingsFromShellSettings,
5106
4451
  formatCurrency,
5107
4452
  formatInUnit,
5108
4453
  formatMinorUnitsToString,
@@ -5136,6 +4481,7 @@ export {
5136
4481
  isFulfillmentState,
5137
4482
  isInCart,
5138
4483
  isPaymentState,
4484
+ isShellTipPercent,
5139
4485
  isSupportedCurrency,
5140
4486
  isSystemFamilyCode,
5141
4487
  isValidQuantity,
@@ -5144,9 +4490,7 @@ export {
5144
4490
  listCountries,
5145
4491
  listProvinces,
5146
4492
  listShippingCountries,
5147
- longestMinutesOf,
5148
4493
  mapToLegacyStatus,
5149
- maxAdvanceMinutesOf,
5150
4494
  maxPrecisionFor,
5151
4495
  mergeFragment,
5152
4496
  modifiersSellable,
@@ -5158,15 +4502,11 @@ export {
5158
4502
  normalizePostCode,
5159
4503
  normalizeProvince,
5160
4504
  occupancyIn,
5161
- occupiedAtOutlet,
5162
- oldMaxAdvanceOf,
5163
4505
  orderAssignments,
5164
4506
  parseAmountToMinorUnits,
5165
4507
  parseCurrencyCode,
5166
4508
  parseStripeCurrencyCode,
5167
- pickFreeResource,
5168
4509
  placeKey,
5169
- planCourse,
5170
4510
  planWindow,
5171
4511
  poolDemand,
5172
4512
  poolOf,
@@ -5176,27 +4516,27 @@ export {
5176
4516
  presentAt,
5177
4517
  priceForTotal,
5178
4518
  provincesForPostCode,
4519
+ readShellTipSettings,
5179
4520
  removeFragment,
5180
- rentalEnds,
5181
4521
  resolveFamily,
5182
4522
  resolveModifiersForProduct,
4523
+ resolveShellSettings,
4524
+ resolveShellSettingsWithSources,
5183
4525
  resolveShipping,
5184
4526
  resolveTemplate,
5185
4527
  resolveUnit,
5186
4528
  roundToPrecision,
5187
- ruleDurationsOf,
5188
- ruleInNewShape,
5189
4529
  sameFamily,
5190
- sessionCells,
5191
4530
  setOrderState,
4531
+ shellSettingsFromCompanyTips,
4532
+ shellSettingsFromFlowSettings,
4533
+ shellSettingsProblems,
4534
+ shellTipSettingsProblems,
5192
4535
  shipsToCountry,
5193
4536
  shopDayKey,
5194
4537
  shopDayRange,
5195
- shortestMinutesOf,
5196
4538
  signReportForDisplay,
5197
4539
  slotsForWindow,
5198
- soldAsCourse,
5199
- startsPastMaxAdvance,
5200
4540
  stringifyMinorUnits,
5201
4541
  subtractAmounts,
5202
4542
  toBase,
@@ -5207,8 +4547,6 @@ export {
5207
4547
  validateShippingZone,
5208
4548
  violatesFinancialInvariant,
5209
4549
  windowEndsAt,
5210
- windowEndsAtInZone,
5211
- windowForPeriods,
5212
4550
  withinPresence
5213
4551
  };
5214
4552
  //# sourceMappingURL=index.mjs.map