@final-commerce/common 2.12.0-staging.6 → 2.12.1-preprod.1

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";
@@ -562,6 +541,30 @@ var ShippingZoneError = /* @__PURE__ */ ((ShippingZoneError2) => {
562
541
  return ShippingZoneError2;
563
542
  })(ShippingZoneError || {});
564
543
 
544
+ // enums/tax.enum.ts
545
+ var TaxRegistrationKind = /* @__PURE__ */ ((TaxRegistrationKind2) => {
546
+ TaxRegistrationKind2["GST_HST"] = "GST_HST";
547
+ TaxRegistrationKind2["PST"] = "PST";
548
+ TaxRegistrationKind2["QST"] = "QST";
549
+ return TaxRegistrationKind2;
550
+ })(TaxRegistrationKind || {});
551
+ var TaxSource = /* @__PURE__ */ ((TaxSource2) => {
552
+ TaxSource2["MERCHANT"] = "merchant";
553
+ TaxSource2["AUTOMATIC"] = "automatic";
554
+ return TaxSource2;
555
+ })(TaxSource || {});
556
+ var OutOfProvinceTaxes = /* @__PURE__ */ ((OutOfProvinceTaxes2) => {
557
+ OutOfProvinceTaxes2["AUTOMATIC"] = "automatic";
558
+ OutOfProvinceTaxes2["HOME"] = "home";
559
+ return OutOfProvinceTaxes2;
560
+ })(OutOfProvinceTaxes || {});
561
+ var TaxWarningCode = /* @__PURE__ */ ((TaxWarningCode2) => {
562
+ TaxWarningCode2["NOT_REGISTERED"] = "NOT_REGISTERED";
563
+ TaxWarningCode2["NO_RULES_FOR_PLACE"] = "NO_RULES_FOR_PLACE";
564
+ TaxWarningCode2["NO_TABLE"] = "NO_TABLE";
565
+ return TaxWarningCode2;
566
+ })(TaxWarningCode || {});
567
+
565
568
  // enums/sales-line.enum.ts
566
569
  var SalesLineAction = /* @__PURE__ */ ((SalesLineAction2) => {
567
570
  SalesLineAction2["SALE"] = "sale";
@@ -1802,6 +1805,183 @@ function lineStockMoves(item, quantity, reservations = []) {
1802
1805
  });
1803
1806
  }
1804
1807
 
1808
+ // utils/shell-settings.util.ts
1809
+ var DEFAULT_SHELL_SETTINGS = {
1810
+ pinSwitchUser: false,
1811
+ pinSession: false,
1812
+ stationLock: 0,
1813
+ buildTimeout: 0,
1814
+ lockedAccess: false,
1815
+ cashManagement: true,
1816
+ tips: {
1817
+ enabled: true,
1818
+ tip1: { label: "Good", value: 15 },
1819
+ tip2: { label: "Great", value: 18 },
1820
+ tip3: { label: "Amazing!", value: 25 },
1821
+ customTipLabel: "Custom",
1822
+ noTipLabel: "No tip"
1823
+ }
1824
+ };
1825
+ var FIELD_ORDER = ["station"];
1826
+ var TIP_ORDER = ["station", "outlet", "flow", "company"];
1827
+ var TOP_FIELDS = [
1828
+ "pinSwitchUser",
1829
+ "pinSession",
1830
+ "stationLock",
1831
+ "buildTimeout",
1832
+ "lockedAccess",
1833
+ "cashManagement"
1834
+ ];
1835
+ var TIP_FIELDS = ["enabled", "tip1", "tip2", "tip3", "customTipLabel", "noTipLabel"];
1836
+ function pick(levels, order, read, fallback) {
1837
+ for (const level of order) {
1838
+ const settings = levels[level];
1839
+ if (!settings) continue;
1840
+ const value = read(settings);
1841
+ if (value !== void 0 && value !== null) return { value, source: level };
1842
+ }
1843
+ return { value: fallback, source: "default" };
1844
+ }
1845
+ function resolveShellSettingsWithSources(levels) {
1846
+ const settings = { ...DEFAULT_SHELL_SETTINGS, tips: { ...DEFAULT_SHELL_SETTINGS.tips } };
1847
+ const sources = { fields: {}, tips: {} };
1848
+ for (const field of TOP_FIELDS) {
1849
+ const { value, source } = pick(levels, FIELD_ORDER, (s) => s[field], DEFAULT_SHELL_SETTINGS[field]);
1850
+ settings[field] = value;
1851
+ sources.fields[field] = source;
1852
+ }
1853
+ for (const field of TIP_FIELDS) {
1854
+ const { value, source } = pick(levels, TIP_ORDER, (s) => s.tips?.[field], DEFAULT_SHELL_SETTINGS.tips[field]);
1855
+ settings.tips[field] = value;
1856
+ sources.tips[field] = source;
1857
+ }
1858
+ return { settings, sources };
1859
+ }
1860
+ function resolveShellSettings(levels) {
1861
+ return resolveShellSettingsWithSources(levels).settings;
1862
+ }
1863
+ var SHELL_TIP_PERCENT_MIN = 1;
1864
+ var SHELL_TIP_PERCENT_MAX = 100;
1865
+ var SHELL_TIP_LABEL_MAX_LENGTH = 20;
1866
+ var isLabel = (raw) => typeof raw === "string" && raw.trim().length > 0 && raw.length <= SHELL_TIP_LABEL_MAX_LENGTH;
1867
+ var isShellTipPercent = (raw) => typeof raw === "number" && Number.isInteger(raw) && raw >= SHELL_TIP_PERCENT_MIN && raw <= SHELL_TIP_PERCENT_MAX;
1868
+ function shellTipSettingsProblems(tips) {
1869
+ if (!tips) return [];
1870
+ const problems = [];
1871
+ if (tips.enabled !== void 0 && typeof tips.enabled !== "boolean") {
1872
+ problems.push({ field: "tips.enabled", code: "boolean" });
1873
+ }
1874
+ for (const key of ["tip1", "tip2", "tip3"]) {
1875
+ const option = tips[key];
1876
+ if (option === void 0) continue;
1877
+ if (!option || typeof option !== "object") {
1878
+ problems.push({ field: `tips.${key}`, code: "preset" });
1879
+ continue;
1880
+ }
1881
+ if (!isShellTipPercent(option.value)) problems.push({ field: `tips.${key}`, code: "percent" });
1882
+ if (!isLabel(option.label)) problems.push({ field: `tips.${key}`, code: "label" });
1883
+ }
1884
+ for (const key of ["customTipLabel", "noTipLabel"]) {
1885
+ if (tips[key] !== void 0 && !isLabel(tips[key])) problems.push({ field: `tips.${key}`, code: "label" });
1886
+ }
1887
+ return problems;
1888
+ }
1889
+ function shellSettingsProblems(settings) {
1890
+ if (!settings) return [];
1891
+ const problems = [];
1892
+ for (const field of ["pinSwitchUser", "pinSession", "lockedAccess", "cashManagement"]) {
1893
+ if (settings[field] !== void 0 && typeof settings[field] !== "boolean")
1894
+ problems.push({ field, code: "boolean" });
1895
+ }
1896
+ for (const field of ["stationLock", "buildTimeout"]) {
1897
+ const value = settings[field];
1898
+ if (value !== void 0 && !(typeof value === "number" && Number.isInteger(value) && value >= 0)) {
1899
+ problems.push({ field, code: "timeout" });
1900
+ }
1901
+ }
1902
+ return [...problems, ...shellTipSettingsProblems(settings.tips)];
1903
+ }
1904
+ var SHELL_FLOW_SETTINGS_PREFIX = "flowSettingsKey";
1905
+ var SHELL_FLOW_TIPS_KEY = `${SHELL_FLOW_SETTINGS_PREFIX}.tips`;
1906
+ var readBoolean = (raw) => {
1907
+ if (raw === void 0 || raw === "") return void 0;
1908
+ const v = raw.trim().toLowerCase();
1909
+ if (v === "true") return true;
1910
+ if (v === "false") return false;
1911
+ return void 0;
1912
+ };
1913
+ function readTipOption(raw) {
1914
+ if (!raw || typeof raw !== "object") return void 0;
1915
+ const { label, value } = raw;
1916
+ const n = typeof value === "number" ? value : parseFloat(String(value ?? ""));
1917
+ if (typeof label !== "string" || !Number.isFinite(n) || n < 0) return void 0;
1918
+ return { label, value: n };
1919
+ }
1920
+ function readShellTipSettings(raw) {
1921
+ if (!raw || typeof raw !== "object") return void 0;
1922
+ const r = raw;
1923
+ const tips = {};
1924
+ if (typeof r.enabled === "boolean") tips.enabled = r.enabled;
1925
+ const tip1 = readTipOption(r.tip1);
1926
+ const tip2 = readTipOption(r.tip2);
1927
+ const tip3 = readTipOption(r.tip3);
1928
+ if (tip1) tips.tip1 = tip1;
1929
+ if (tip2) tips.tip2 = tip2;
1930
+ if (tip3) tips.tip3 = tip3;
1931
+ if (typeof r.customTipLabel === "string") tips.customTipLabel = r.customTipLabel;
1932
+ if (typeof r.noTipLabel === "string") tips.noTipLabel = r.noTipLabel;
1933
+ return Object.keys(tips).length > 0 ? tips : void 0;
1934
+ }
1935
+ var parseJson = (raw) => {
1936
+ if (!raw) return void 0;
1937
+ try {
1938
+ return JSON.parse(raw);
1939
+ } catch {
1940
+ return void 0;
1941
+ }
1942
+ };
1943
+ function shellSettingsFromFlowSettings(dict) {
1944
+ const tips = readShellTipSettings(parseJson(dict?.[SHELL_FLOW_TIPS_KEY]));
1945
+ return tips ? { tips } : {};
1946
+ }
1947
+ function flowSettingsFromShellSettings(settings) {
1948
+ return settings.tips && Object.keys(settings.tips).length > 0 ? { [SHELL_FLOW_TIPS_KEY]: JSON.stringify(settings.tips) } : {};
1949
+ }
1950
+ function shellSettingsFromCompanyTips(enabled, options) {
1951
+ const tips = {
1952
+ ...readShellTipSettings(typeof options === "string" ? parseJson(options) : options)
1953
+ };
1954
+ const on = typeof enabled === "boolean" ? enabled : readBoolean(typeof enabled === "string" ? enabled : void 0);
1955
+ if (on !== void 0) tips.enabled = on;
1956
+ return Object.keys(tips).length > 0 ? { tips } : {};
1957
+ }
1958
+
1959
+ // utils/contact-keys.util.ts
1960
+ function emailKey(email) {
1961
+ const key = email?.trim().toLowerCase();
1962
+ return key && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(key) ? key : null;
1963
+ }
1964
+ function phoneKey(phone) {
1965
+ const raw = phone?.trim();
1966
+ if (!raw) return null;
1967
+ const digits = raw.replace(/\D/g, "");
1968
+ if (raw.startsWith("+")) return digits.length >= 8 && digits.length <= 15 ? `+${digits}` : null;
1969
+ if (digits.length === 10) return `+1${digits}`;
1970
+ if (digits.length === 11 && digits.startsWith("1")) return `+${digits}`;
1971
+ return null;
1972
+ }
1973
+ var CUSTOMER_CONTACT_VERIFIED = "CUSTOMER_CONTACT_VERIFIED";
1974
+ var CUSTOMER_EMAIL_TAKEN = "CUSTOMER_EMAIL_TAKEN";
1975
+ function sameContact(a, b, key) {
1976
+ return (key(a) ?? a?.trim().toLowerCase() ?? "") === (key(b) ?? b?.trim().toLowerCase() ?? "");
1977
+ }
1978
+ function verifiedContactChange(existing, change) {
1979
+ if (!existing.verifiedShopperAt) return null;
1980
+ if (change.email !== void 0 && !sameContact(existing.email, change.email, emailKey)) return "email";
1981
+ if (change.phone !== void 0 && !sameContact(existing.phone, change.phone, phoneKey)) return "phone";
1982
+ return null;
1983
+ }
1984
+
1805
1985
  // units/family-code.ts
1806
1986
  var MAX_SLUG_LENGTH = 32;
1807
1987
  var FALLBACK_SLUG = "family";
@@ -1844,6 +2024,7 @@ var FULFILLMENT_STATES = [
1844
2024
  "in_progress",
1845
2025
  "fulfilled",
1846
2026
  "partially_fulfilled",
2027
+ "return_pending",
1847
2028
  "returned",
1848
2029
  "partially_returned",
1849
2030
  "cancelled"
@@ -1869,10 +2050,7 @@ var CONDITION_OPERATORS = [
1869
2050
  function isConditionOperator(value) {
1870
2051
  return CONDITION_OPERATORS.includes(value);
1871
2052
  }
1872
- var PATH_MODES = [
1873
- "strict",
1874
- "permissive"
1875
- ];
2053
+ var PATH_MODES = ["strict", "permissive"];
1876
2054
 
1877
2055
  // order-state-machine/state-schema.ts
1878
2056
  var PAYMENT_DEFS = [
@@ -1893,6 +2071,9 @@ var FULFILLMENT_DEFS = [
1893
2071
  { id: "in_progress", label: "In Progress", terminal: false },
1894
2072
  { id: "fulfilled", label: "Fulfilled", terminal: true },
1895
2073
  { id: "partially_fulfilled", label: "Partially Fulfilled", terminal: false },
2074
+ // The store accepted the shopper's return request: the goods are on their way back, no money has moved yet.
2075
+ // The refund lands `partially_returned` / `returned` as it does from `fulfilled`.
2076
+ { id: "return_pending", label: "Return Accepted", terminal: false },
1896
2077
  { id: "returned", label: "Returned", terminal: true },
1897
2078
  { id: "partially_returned", label: "Partially Returned", terminal: false },
1898
2079
  { id: "cancelled", label: "Cancelled", terminal: true }
@@ -1922,6 +2103,8 @@ var STATE_SCHEMA = Object.freeze({
1922
2103
  var REFUND_ALLOWED_FULFILLMENT = /* @__PURE__ */ new Set(["fulfilled", "returned", "partially_returned", "cancelled"]);
1923
2104
  var PAYMENT_COLLECTION_ORDER = ["unpaid", "partially_paid", "paid"];
1924
2105
  var UNRETURNED_MONEY_STATES = /* @__PURE__ */ new Set(["partially_paid", "paid", "partially_refunded"]);
2106
+ var RETURN_FROM_FULFILLMENT = /* @__PURE__ */ new Set(["fulfilled", "partially_fulfilled", "partially_returned"]);
2107
+ var RETURN_PENDING_PAYMENTS = /* @__PURE__ */ new Set(["paid", "partially_refunded"]);
1925
2108
  var REFUNDED_FULFILLMENT_LANDINGS = /* @__PURE__ */ new Set(["returned", "cancelled"]);
1926
2109
  var FINANCIAL_INVARIANTS = [
1927
2110
  {
@@ -1969,6 +2152,11 @@ var FINANCIAL_INVARIANTS = [
1969
2152
  description: "A voided order exists only at cancelled fulfillment: a voided order cannot re-enter fulfillment, and a voided \xD7 non-cancelled pair cannot be materialized from nothing (complements no-leave-voided, which only freezes the payment axis). Moves INTO voided from a live payment state are the void flow\u2019s concern, not this rule\u2019s",
1970
2153
  check: (from, to) => (from === null || from.payment === "voided") && to.payment === "voided" && to.fulfillment !== "cancelled"
1971
2154
  },
2155
+ {
2156
+ id: "return-pending-needs-goods-out",
2157
+ description: "Fulfillment enters return_pending (return accepted) only from fulfilled, partially_fulfilled or partially_returned, and holds it only while payment is paid or partially_refunded \u2014 goods must have gone out and money must still be held",
2158
+ check: (from, to) => to.fulfillment === "return_pending" && (!RETURN_PENDING_PAYMENTS.has(to.payment) || from?.fulfillment !== "return_pending" && !(from && RETURN_FROM_FULFILLMENT.has(from.fulfillment)))
2159
+ },
1972
2160
  {
1973
2161
  id: "no-reopen-refunded-fulfillment",
1974
2162
  description: "A fully refunded order cannot re-enter fulfillment \u2014 it may only relabel between its canonical landings, returned and cancelled (complements no-leave-refunded, which only freezes the payment axis)",
@@ -2060,7 +2248,9 @@ var DISPLAY_LABEL_OVERRIDES = {
2060
2248
  "paid|on_hold": "Parked - Paid",
2061
2249
  "paid|fulfilled": "Completed",
2062
2250
  "partially_refunded|fulfilled": "Partially Refunded",
2063
- "partially_refunded|partially_returned": "Partially Refunded"
2251
+ "partially_refunded|partially_returned": "Partially Refunded",
2252
+ "paid|return_pending": "Return Accepted",
2253
+ "partially_refunded|return_pending": "Return Accepted"
2064
2254
  };
2065
2255
  var TERMINAL_LABEL_OVERRIDES = {
2066
2256
  voided: "Cancelled"
@@ -2202,6 +2392,7 @@ function buildOrderContext(order, extras) {
2202
2392
  }
2203
2393
 
2204
2394
  // order-state-machine/display-state.ts
2395
+ var ATOMS_ADDED_AFTER_SNAPSHOT = /* @__PURE__ */ new Set(["return_pending"]);
2205
2396
  function atomLabel(atom, defs) {
2206
2397
  return defs.find((d) => d.id === atom)?.label ?? atom;
2207
2398
  }
@@ -2215,6 +2406,10 @@ function deriveDisplayState(payment, fulfillment, config) {
2215
2406
  return { label: rule.label, color: rule.color, icon: rule.icon };
2216
2407
  }
2217
2408
  }
2409
+ if (ATOMS_ADDED_AFTER_SNAPSHOT.has(fulfillment)) {
2410
+ const fallback = DEFAULT_DISPLAY_STATE_MAP.find((rule) => displayRuleMatchesPair(rule, payment, fulfillment));
2411
+ if (fallback) return { label: fallback.label, color: fallback.color, icon: fallback.icon };
2412
+ }
2218
2413
  return {
2219
2414
  label: `${atomLabel(payment, STATE_SCHEMA.paymentStates)} / ${atomLabel(fulfillment, STATE_SCHEMA.fulfillmentStates)}`
2220
2415
  };
@@ -3350,7 +3545,6 @@ var ORDER_STATE_EVENTS = {
3350
3545
  };
3351
3546
 
3352
3547
  // booking/types.ts
3353
- var UNLIMITED_PLACES = Number.MAX_SAFE_INTEGER;
3354
3548
  var BookingRulesError = class extends Error {
3355
3549
  constructor(message) {
3356
3550
  super(message);
@@ -3419,39 +3613,153 @@ function atZonedMinute(dayStart, minutes, timeZone) {
3419
3613
  const { year, month, day } = zonedParts(dayStart, timeZone);
3420
3614
  return instantFromLocal(year, month, day, minutes, timeZone);
3421
3615
  }
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)];
3616
+
3617
+ // booking/grid.ts
3618
+ var MINUTE2 = 6e4;
3619
+ var MAX_RANGE_DAYS = 366;
3620
+ var asTime = (value, field) => {
3621
+ if (value == null) return void 0;
3622
+ const time = new Date(value).getTime();
3623
+ if (Number.isNaN(time)) throw new BookingRulesError(`Booking rules: ${field} is not a date, got "${String(value)}"`);
3624
+ return time;
3625
+ };
3626
+ function parseHhMm(value, field) {
3627
+ const [hours, minutes] = value.split(":").map(Number);
3628
+ if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
3629
+ throw new BookingRulesError(`Booking rules: ${field} must be "HH:mm", got "${value}"`);
3630
+ }
3631
+ return hours * 60 + minutes;
3426
3632
  }
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`
3633
+ function windowEndsAt(rule, now) {
3634
+ const { maxAdvanceDays, bookableTo } = rule.window;
3635
+ const ends = Math.min(
3636
+ maxAdvanceDays ? now.getTime() + maxAdvanceDays * 1440 * MINUTE2 : Number.POSITIVE_INFINITY,
3637
+ asTime(bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
3432
3638
  );
3639
+ return Number.isFinite(ends) ? new Date(ends) : null;
3433
3640
  }
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());
3641
+ function periodSlot(dayStart, timeZone, rule, openMinute, closeMinute) {
3642
+ const { ratePeriod, slot, checkInTime, checkOutTime } = rule;
3643
+ const at = (minutes) => atZonedMinute(dayStart, minutes, timeZone);
3644
+ if (ratePeriod === "night" /* NIGHT */) {
3645
+ if (!checkInTime || !checkOutTime) {
3646
+ throw new BookingRulesError("Overnight booking rules need both checkInTime and checkOutTime");
3647
+ }
3648
+ const checkIn = parseHhMm(checkInTime, "checkInTime");
3649
+ const checkOut = parseHhMm(checkOutTime, "checkOutTime");
3650
+ return {
3651
+ startAt: at(checkIn),
3652
+ endAt: at(1440 + checkOut),
3653
+ // Housekeeping sits between check-out and the next check-in: it costs no night.
3654
+ bufferEndAt: at(1440 + checkIn),
3655
+ canStart: true
3656
+ };
3657
+ }
3658
+ const from = ratePeriod === "day" /* DAY */ ? openMinute ?? 0 : 0;
3659
+ const to = ratePeriod === "day" /* DAY */ ? closeMinute ?? 1440 : 1440;
3660
+ return {
3661
+ startAt: at(from),
3662
+ endAt: at(to),
3663
+ bufferEndAt: at(to + (slot.bufferMinutes ?? 0)),
3664
+ canStart: true
3665
+ };
3666
+ }
3667
+ function freeGaps(openAt, closeAt, busy) {
3668
+ const inside = busy.map(({ startAt, bufferEndAt }) => ({ from: +startAt, to: +bufferEndAt })).filter(({ from, to }) => to > openAt && from < closeAt).sort((first, second) => first.from - second.from);
3669
+ const gaps = [];
3670
+ let cursor = openAt;
3671
+ for (const { from, to } of inside) {
3672
+ if (from > cursor) gaps.push({ from: cursor, to: from, endsAtBooking: true });
3673
+ cursor = Math.max(cursor, to);
3674
+ if (cursor >= closeAt) break;
3675
+ }
3676
+ if (cursor < closeAt) gaps.push({ from: cursor, to: closeAt, endsAtBooking: false });
3677
+ return gaps;
3678
+ }
3679
+ function buildGrid(rule, timeZone, from, to, now, busy = []) {
3680
+ if (to.getTime() - from.getTime() > MAX_RANGE_DAYS * 1440 * MINUTE2) {
3681
+ throw new BookingRulesError(`A booking range may span at most ${MAX_RANGE_DAYS} days`);
3682
+ }
3683
+ const { availability, slot, window, ratePeriod } = rule;
3684
+ const periodMode = ratePeriod !== "slot" /* SLOT */;
3685
+ const weeklyHours = availability.weeklyHours ?? [];
3686
+ const notBefore = Math.max(
3687
+ now.getTime() + (window.minNoticeMinutes ?? 0) * MINUTE2,
3688
+ asTime(window.bookableFrom, "window.bookableFrom") ?? 0,
3689
+ asTime(availability.availableFrom, "availability.availableFrom") ?? 0
3690
+ );
3691
+ const notAfter = windowEndsAt(rule, now)?.getTime() ?? Number.POSITIVE_INFINITY;
3692
+ const blocked = (availability.offMarket ?? []).map(({ from: blockFrom, to: blockTo }) => ({
3693
+ from: asTime(blockFrom, "availability.offMarket.from"),
3694
+ to: asTime(blockTo, "availability.offMarket.to")
3695
+ }));
3696
+ const arrivalDays = availability.arrivalDays;
3697
+ const step = slot.lengthMinutes + (slot.bufferMinutes ?? 0);
3698
+ const slots = [];
3699
+ const lastDay = startOfZonedDay(to, timeZone).getTime();
3700
+ let dayStart = startOfZonedDay(from, timeZone);
3701
+ while (dayStart.getTime() <= lastDay) {
3702
+ const weekday = zonedParts(dayStart, timeZone).weekday;
3703
+ const rows = weeklyHours.filter((entry) => entry.weekday === weekday);
3704
+ if (periodMode) {
3705
+ const openToday = weeklyHours.length === 0 || rows.length > 0;
3706
+ if (openToday) {
3707
+ const built = periodSlot(dayStart, timeZone, rule, rows[0]?.openMinute, rows[0]?.closeMinute);
3708
+ slots.push({ ...built, canStart: !arrivalDays?.length || arrivalDays.includes(weekday) });
3709
+ }
3710
+ } else {
3711
+ for (const row of rows) {
3712
+ const openAt = +atZonedMinute(dayStart, row.openMinute, timeZone);
3713
+ const closeAt = +atZonedMinute(dayStart, row.closeMinute, timeZone);
3714
+ for (const gap of freeGaps(openAt, closeAt, busy)) {
3715
+ const mustFit = (gap.endsAtBooking ? step : slot.lengthMinutes) * MINUTE2;
3716
+ for (let start = gap.from; start + mustFit <= gap.to; start += step * MINUTE2) {
3717
+ slots.push({
3718
+ startAt: new Date(start),
3719
+ endAt: new Date(start + slot.lengthMinutes * MINUTE2),
3720
+ bufferEndAt: new Date(start + step * MINUTE2),
3721
+ canStart: true
3722
+ });
3723
+ }
3724
+ }
3725
+ }
3726
+ }
3727
+ dayStart = nextZonedDay(dayStart, timeZone);
3728
+ }
3729
+ const askedFrom = from.getTime();
3730
+ const askedTo = to.getTime();
3731
+ return slots.filter(({ startAt, bufferEndAt }) => {
3732
+ const start = startAt.getTime();
3733
+ if (start < askedFrom || start >= askedTo) return false;
3734
+ if (start < notBefore || start > notAfter) return false;
3735
+ return !blocked.some(
3736
+ ({ from: blockFrom, to: blockTo }) => start < blockTo && bufferEndAt.getTime() > blockFrom
3737
+ );
3738
+ }).sort((first, second) => +first.startAt - +second.startAt);
3739
+ }
3740
+ function slotsForWindow(grid, startAt, endAt) {
3741
+ const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
3742
+ if (startIndex < 0) {
3743
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
3744
+ }
3745
+ if (!grid[startIndex].canStart) {
3746
+ throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
3747
+ }
3748
+ const covered = [];
3749
+ for (let index = startIndex; index < grid.length; index++) {
3750
+ const entry = grid[index];
3751
+ const previous = covered[covered.length - 1];
3752
+ if (previous && entry.startAt.getTime() !== previous.bufferEndAt.getTime()) break;
3753
+ covered.push(entry);
3754
+ if (entry.endAt.getTime() === endAt.getTime()) return covered;
3755
+ if (entry.endAt.getTime() > endAt.getTime()) break;
3756
+ }
3757
+ throw new BookingRulesError(
3758
+ `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
3759
+ );
3451
3760
  }
3452
3761
 
3453
3762
  // booking/availability.ts
3454
- var placesOnTheWire = (entry) => Number.isFinite(entry.capacity) ? entry : { ...entry, capacity: UNLIMITED_PLACES, free: UNLIMITED_PLACES, unlimited: true };
3455
3763
  var withinPresence = (slot, timeZone, presence) => {
3456
3764
  if (!presence?.length) return true;
3457
3765
  const dayStart = startOfZonedDay(slot.startAt, timeZone);
@@ -3469,11 +3777,6 @@ function occupancyIn(occupied, productId, startAt, bufferEndAt, shared) {
3469
3777
  foreignProductId: foreign?.productId
3470
3778
  };
3471
3779
  }
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
3780
  var stateFor = (hasShift, offerable, free) => {
3478
3781
  if (offerable === 0) {
3479
3782
  return hasShift() ? "fullyBooked" /* FULLY_BOOKED */ : "noHoursInRange" /* NO_HOURS_IN_RANGE */;
@@ -3503,36 +3806,26 @@ function shopDayRange(fromDayKey, count, timeZone) {
3503
3806
  function buildAvailability({
3504
3807
  productId,
3505
3808
  bookingRulesId,
3809
+ bookingType,
3506
3810
  rule,
3507
3811
  resources,
3508
- occupied: everyOutlet,
3509
- outletId,
3812
+ occupied,
3510
3813
  from,
3511
3814
  to,
3512
- now,
3513
- timeZone
3815
+ now
3514
3816
  }) {
3515
- const occupied = occupiedAtOutlet(everyOutlet, rule, outletId);
3516
3817
  const shared = rule.slot.sharedAcrossProducts ?? false;
3517
- const bookableUntil = windowEndsAtInZone(rule, now, timeZone ?? null);
3518
- const parts = bookingRuleParts(rule);
3818
+ const bookableUntil = windowEndsAt(rule, now);
3519
3819
  const header = {
3520
3820
  productId,
3521
3821
  bookingRulesId,
3822
+ bookingType,
3522
3823
  ratePeriod: rule.ratePeriod,
3523
- // Time slots / sessions / date ranges — so a reader never re-classifies `ratePeriod` itself.
3524
- bookingMethod: bookingMethodOf(rule),
3525
3824
  // Passed through for the UI to label: a group slot under minimumToRun may not run.
3526
3825
  minimumToRun: rule.slot.minimumToRun,
3527
3826
  minStay: rule.slot.minStay,
3528
3827
  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
3828
+ // Why a day can come back empty. Past this instant the rule refuses everything, so the UI
3536
3829
  // can say "beyond the booking window" where it would otherwise claim "nothing free".
3537
3830
  bookableUntil,
3538
3831
  // The comparison itself, not just the boundary: deciding whether a day lies past the
@@ -3555,7 +3848,7 @@ function buildAvailability({
3555
3848
  const byInstant = /* @__PURE__ */ new Map();
3556
3849
  const freeSlotsPerResource = /* @__PURE__ */ new Map();
3557
3850
  for (const { resource, slots: slots2 } of grids) {
3558
- const capacity = capacityOf(rule, resource);
3851
+ const capacity = resource.seats ?? 1;
3559
3852
  const mine = byResource.get(resource.id) ?? [];
3560
3853
  for (const slot of slots2) {
3561
3854
  const { taken, foreignProductId } = occupancyIn(mine, productId, slot.startAt, slot.bufferEndAt, shared);
@@ -3572,9 +3865,7 @@ function buildAvailability({
3572
3865
  entry.booked += foreignProductId ? capacity : taken;
3573
3866
  entry.free += free;
3574
3867
  entry.canStart = entry.canStart || slot.canStart;
3575
- entry.resources.push(
3576
- placesOnTheWire({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free })
3577
- );
3868
+ entry.resources.push({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free });
3578
3869
  if (free > 0) freeSlotsPerResource.set(resource.id, (freeSlotsPerResource.get(resource.id) ?? 0) + 1);
3579
3870
  byInstant.set(+slot.startAt, entry);
3580
3871
  }
@@ -3596,10 +3887,9 @@ function buildAvailability({
3596
3887
  )
3597
3888
  };
3598
3889
  });
3599
- const slots = [...byInstant.values()].map(placesOnTheWire).map((slot) => withMaxQtyNow(slot, slot.resources, rule.slot.maxQtyPerBooking)).sort((first, second) => +first.startAt - +second.startAt);
3890
+ const slots = [...byInstant.values()].sort((first, second) => +first.startAt - +second.startAt);
3600
3891
  return {
3601
3892
  ...header,
3602
- course: soldAsCourse(rule) ? courseAvailability(rule, resources, byResource, productId, shared, now) : void 0,
3603
3893
  resources: inWindow,
3604
3894
  slots,
3605
3895
  /**
@@ -3611,53 +3901,6 @@ function buildAvailability({
3611
3901
  days: [...new Set(slots.map((slot) => slot.dayKey))]
3612
3902
  };
3613
3903
  }
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
3904
  function presentAt(resources, rows, outletId) {
3662
3905
  const byResource = /* @__PURE__ */ new Map();
3663
3906
  for (const row of rows) {
@@ -3671,852 +3914,24 @@ function presentAt(resources, rows, outletId) {
3671
3914
  });
3672
3915
  }
3673
3916
 
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
3917
  // booking/plan.ts
3776
3918
  var DEFAULT_HOLD_MINUTES = 10;
3777
3919
  function planWindow({ rule, timeZone, presence, startAt, endAt, now, busy = [] }) {
3778
- if (!soldAsCourse(rule)) checkStartWithinMaxAdvance(rule, timeZone, startAt, now);
3779
3920
  const grid = buildGrid(rule, timeZone, startAt, endAt, now, busy).filter(
3780
3921
  (slot) => withinPresence(slot, timeZone, presence)
3781
3922
  );
3782
- const slots = slotsForWindow(grid, startAt, endAt, cellChainOf(rule, timeZone));
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, cellChainOf(rule, timeZone));
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, cellChainOf(rule, timeZone)));
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 };
4031
- }
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
- var endToStart = (previous, next) => next.startAt.getTime() === previous.bufferEndAt.getTime();
4494
- function cellChainOf(rule, timeZone) {
4495
- if (rule.ratePeriod !== "day" /* DAY */) return endToStart;
4496
- const dayOf = (slot) => startOfZonedDay(slot.startAt, timeZone);
4497
- return (previous, next) => +dayOf(next) === +nextZonedDay(dayOf(previous), timeZone);
4498
- }
4499
- function slotsForWindow(grid, startAt, endAt, chain = endToStart) {
4500
- const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
4501
- if (startIndex < 0) {
4502
- throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
4503
- }
4504
- if (!grid[startIndex].canStart) {
4505
- throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
3923
+ const slots = slotsForWindow(grid, startAt, endAt);
3924
+ const { minStay, maxStay } = rule.slot;
3925
+ if (minStay && slots.length < minStay) {
3926
+ throw new BookingRulesError(`These rules ask for at least ${minStay} period(s), got ${slots.length}`);
4506
3927
  }
4507
- const covered = [];
4508
- for (let index = startIndex; index < grid.length; index++) {
4509
- const entry = grid[index];
4510
- const previous = covered[covered.length - 1];
4511
- if (previous && !chain(previous, entry)) break;
4512
- covered.push(entry);
4513
- if (entry.endAt.getTime() === endAt.getTime()) return covered;
4514
- if (entry.endAt.getTime() > endAt.getTime()) break;
3928
+ if (maxStay && slots.length > maxStay) {
3929
+ throw new BookingRulesError(`These rules allow at most ${maxStay} period(s), got ${slots.length}`);
4515
3930
  }
4516
- throw new BookingRulesError(
4517
- `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
4518
- );
3931
+ const last = slots[slots.length - 1];
3932
+ return { slots, endAt: last.endAt, bufferEndAt: last.bufferEndAt };
4519
3933
  }
3934
+ var holdExpiresAt = (rule, now) => new Date(now.getTime() + (rule.window.holdMinutes ?? DEFAULT_HOLD_MINUTES) * 6e4);
4520
3935
 
4521
3936
  // shipping/fold-text.ts
4522
3937
  function foldText(value) {
@@ -4782,6 +4197,8 @@ function quote(option, zoneId, itemsTotal) {
4782
4197
  amountToFree: freeOver != null && amount > 0 ? freeOver - itemsTotal : null,
4783
4198
  minDays: option.minDays ?? null,
4784
4199
  maxDays: option.maxDays ?? null,
4200
+ minMinutes: option.minMinutes ?? null,
4201
+ maxMinutes: option.maxMinutes ?? null,
4785
4202
  outletId: option.outletId ?? null
4786
4203
  };
4787
4204
  }
@@ -4796,6 +4213,21 @@ function countriesShippedTo(zones) {
4796
4213
  return [...countries].sort();
4797
4214
  }
4798
4215
 
4216
+ // shipping/time.ts
4217
+ function shippingDuration(minMinutes, maxMinutes) {
4218
+ const min = minMinutes ?? maxMinutes;
4219
+ const max = maxMinutes ?? minMinutes;
4220
+ if (min == null || max == null) return null;
4221
+ const wholeHours = max > 0 && min % 60 === 0 && max % 60 === 0;
4222
+ return wholeHours ? { unit: "hour", min: min / 60, max: max / 60 } : { unit: "minute", min, max };
4223
+ }
4224
+ function formatShippingDuration(minMinutes, maxMinutes, locale, display = "long") {
4225
+ const duration = shippingDuration(minMinutes, maxMinutes);
4226
+ if (!duration) return null;
4227
+ const unit2 = new Intl.NumberFormat(locale ?? "en", { style: "unit", unit: duration.unit, unitDisplay: display });
4228
+ return duration.min === duration.max ? unit2.format(duration.max) : `${duration.min}\u2013${unit2.format(duration.max)}`;
4229
+ }
4230
+
4799
4231
  // shipping/validate.ts
4800
4232
  function validateShippingZone(zone) {
4801
4233
  const problems = [...placeProblems(zone)];
@@ -4824,7 +4256,15 @@ function fitsKind(place, kind) {
4824
4256
  return false;
4825
4257
  }
4826
4258
  var isAmount = (value) => Number.isInteger(value) && value >= 0;
4827
- var isDays = (value) => value == null || isAmount(value);
4259
+ var isTime = (value) => value == null || isAmount(value);
4260
+ var inOrder = (min, max) => (min ?? 0) <= (max ?? Infinity);
4261
+ function timeIsValid(option) {
4262
+ const { minDays, maxDays, minMinutes, maxMinutes } = option;
4263
+ if (![minDays, maxDays, minMinutes, maxMinutes].every(isTime)) return false;
4264
+ const hasDays = minDays != null || maxDays != null;
4265
+ const hasMinutes = minMinutes != null || maxMinutes != null;
4266
+ return !(hasDays && hasMinutes) && inOrder(minDays, maxDays) && inOrder(minMinutes, maxMinutes);
4267
+ }
4828
4268
  function optionProblems(option) {
4829
4269
  const problems = [];
4830
4270
  const isPickup = option.type === "pickup" /* PICKUP */;
@@ -4832,9 +4272,7 @@ function optionProblems(option) {
4832
4272
  problems.push("INVALID_PRICE" /* INVALID_PRICE */);
4833
4273
  }
4834
4274
  if (!isPickup && !option.name?.trim()) problems.push("MISSING_NAME" /* MISSING_NAME */);
4835
- if (!isDays(option.minDays) || !isDays(option.maxDays) || (option.minDays ?? 0) > (option.maxDays ?? Infinity)) {
4836
- problems.push("INVALID_DAYS" /* INVALID_DAYS */);
4837
- }
4275
+ if (!timeIsValid(option)) problems.push("INVALID_DAYS" /* INVALID_DAYS */);
4838
4276
  if (!tiersAreValid(option)) problems.push("INVALID_TIERS" /* INVALID_TIERS */);
4839
4277
  if (option.channels.length === 0) problems.push("NO_CHANNEL" /* NO_CHANNEL */);
4840
4278
  if (isPickup && !option.outletId) problems.push("PICKUP_WITHOUT_STORE" /* PICKUP_WITHOUT_STORE */);
@@ -4846,6 +4284,224 @@ function tiersAreValid(option) {
4846
4284
  return tiers.every((tier) => Number.isInteger(tier.from) && tier.from > 0 && isAmount(tier.price)) && new Set(froms).size === froms.length;
4847
4285
  }
4848
4286
 
4287
+ // tax/sha1.ts
4288
+ function utf8Bytes(text) {
4289
+ const bytes = [];
4290
+ for (const char of text) {
4291
+ const cp = char.codePointAt(0);
4292
+ if (cp < 128) bytes.push(cp);
4293
+ else if (cp < 2048) bytes.push(192 | cp >> 6, 128 | cp & 63);
4294
+ else if (cp < 65536) bytes.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
4295
+ else bytes.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
4296
+ }
4297
+ return bytes;
4298
+ }
4299
+ var rotl = (x, n) => x << n | x >>> 32 - n;
4300
+ function sha1Hex(text) {
4301
+ const bytes = utf8Bytes(text);
4302
+ const bitLength = bytes.length * 8;
4303
+ bytes.push(128);
4304
+ while (bytes.length % 64 !== 56) bytes.push(0);
4305
+ const high = Math.floor(bitLength / 4294967296);
4306
+ for (const word of [high, bitLength >>> 0])
4307
+ bytes.push(word >>> 24 & 255, word >>> 16 & 255, word >>> 8 & 255, word & 255);
4308
+ const h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
4309
+ const w = new Array(80);
4310
+ for (let offset = 0; offset < bytes.length; offset += 64) {
4311
+ for (let i = 0; i < 16; i++) {
4312
+ const j = offset + i * 4;
4313
+ w[i] = bytes[j] << 24 | bytes[j + 1] << 16 | bytes[j + 2] << 8 | bytes[j + 3];
4314
+ }
4315
+ for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
4316
+ let [a, b, c, d, e] = h;
4317
+ for (let i = 0; i < 80; i++) {
4318
+ const [f, k] = i < 20 ? [b & c | ~b & d, 1518500249] : i < 40 ? [b ^ c ^ d, 1859775393] : i < 60 ? [b & c | b & d | c & d, 2400959708] : [b ^ c ^ d, 3395469782];
4319
+ const t = rotl(a, 5) + f + e + k + w[i] | 0;
4320
+ e = d;
4321
+ d = c;
4322
+ c = rotl(b, 30);
4323
+ b = a;
4324
+ a = t;
4325
+ }
4326
+ h[0] = h[0] + a | 0;
4327
+ h[1] = h[1] + b | 0;
4328
+ h[2] = h[2] + c | 0;
4329
+ h[3] = h[3] + d | 0;
4330
+ h[4] = h[4] + e | 0;
4331
+ }
4332
+ return h.map((x) => (x >>> 0).toString(16).padStart(8, "0")).join("");
4333
+ }
4334
+
4335
+ // tax/table.ts
4336
+ var STANDARD_TAX_TYPE = "standard";
4337
+ var TYPE_FIELDS = ["key", "name", "description", "sortOrder", "active"];
4338
+ var RATE_FIELDS = [
4339
+ "code",
4340
+ "name",
4341
+ "kind",
4342
+ "places",
4343
+ "rate",
4344
+ "from",
4345
+ "to",
4346
+ "order",
4347
+ "compound",
4348
+ "registrationPlace",
4349
+ "harmonized",
4350
+ "parts",
4351
+ "sourceUrl",
4352
+ "status"
4353
+ ];
4354
+ var RULE_FIELDS = ["taxType", "codes", "rate", "from", "to", "sourceUrl", "status", "note"];
4355
+ function canonical(row, fields) {
4356
+ return JSON.stringify(fields.map((field) => row[field] ?? null));
4357
+ }
4358
+ var sortedCanonical = (rows, fields) => rows.map((row) => canonical(row, fields)).sort();
4359
+ function automaticTaxTableVersion(table) {
4360
+ return sha1Hex(
4361
+ JSON.stringify([
4362
+ sortedCanonical(table.types, TYPE_FIELDS),
4363
+ sortedCanonical(table.rates, RATE_FIELDS),
4364
+ sortedCanonical(table.rules, RULE_FIELDS)
4365
+ ])
4366
+ );
4367
+ }
4368
+ var toTypeRow = ({ key, name, description, sortOrder, active }) => ({
4369
+ key,
4370
+ name,
4371
+ description,
4372
+ sortOrder,
4373
+ active
4374
+ });
4375
+ var toRateRow = (rate) => ({
4376
+ code: rate.code,
4377
+ name: rate.name,
4378
+ kind: rate.kind,
4379
+ places: rate.places,
4380
+ rate: rate.rate,
4381
+ from: rate.from,
4382
+ to: rate.to,
4383
+ order: rate.order,
4384
+ compound: rate.compound,
4385
+ registrationPlace: rate.registrationPlace,
4386
+ harmonized: rate.harmonized,
4387
+ parts: rate.parts?.map(({ code, name, rate: partRate, level }) => ({ code, name, rate: partRate, level })),
4388
+ sourceUrl: rate.sourceUrl,
4389
+ status: rate.status
4390
+ });
4391
+ var toRuleRow = ({
4392
+ taxType,
4393
+ codes: codes2,
4394
+ rate,
4395
+ from,
4396
+ to,
4397
+ sourceUrl,
4398
+ status,
4399
+ note
4400
+ }) => ({
4401
+ taxType,
4402
+ codes: codes2,
4403
+ rate,
4404
+ from,
4405
+ to,
4406
+ sourceUrl,
4407
+ status,
4408
+ note
4409
+ });
4410
+ function buildAutomaticTaxTable(rows) {
4411
+ const table = {
4412
+ types: [...rows.types].sort((a, b) => a.sortOrder - b.sortOrder).map(toTypeRow),
4413
+ rates: rows.rates.map(toRateRow),
4414
+ rules: rows.rules.map(toRuleRow)
4415
+ };
4416
+ return { version: automaticTaxTableVersion(table), ...table };
4417
+ }
4418
+ function registrationPlacesByKind(rates) {
4419
+ const places = /* @__PURE__ */ new Map();
4420
+ for (const rate of rates) {
4421
+ const list = places.get(rate.kind) ?? [];
4422
+ if (!list.includes(rate.registrationPlace)) list.push(rate.registrationPlace);
4423
+ places.set(rate.kind, list);
4424
+ }
4425
+ return places;
4426
+ }
4427
+
4428
+ // tax/exceptions.ts
4429
+ var TaxExceptionSource = /* @__PURE__ */ ((TaxExceptionSource2) => {
4430
+ TaxExceptionSource2["PRODUCT"] = "product";
4431
+ TaxExceptionSource2["CATEGORY"] = "category";
4432
+ return TaxExceptionSource2;
4433
+ })(TaxExceptionSource || {});
4434
+ var TAX_EXCEPTION_REASON_MAX = 200;
4435
+
4436
+ // shopper/types.ts
4437
+ var SHOPPER_CONSENT_SOURCES = ["checkout", "my-account", "store-account"];
4438
+ var SHOPPER_RETURN_METHODS = ["mail", "in-store"];
4439
+ var SHOPPER_RETURN_STATUSES = ["requested", "accepted", "declined"];
4440
+ var SHOPPER_RETURN_DECLINE_REASON_MAX = 500;
4441
+ var SHOPPER_ERROR_CODES = {
4442
+ ORDER_NOT_FOUND: "ORDER_NOT_FOUND",
4443
+ RETURN_ALREADY_REQUESTED: "RETURN_ALREADY_REQUESTED",
4444
+ RETURN_NOT_ALLOWED: "RETURN_NOT_ALLOWED",
4445
+ RETURN_ALREADY_DECIDED: "RETURN_ALREADY_DECIDED",
4446
+ STORE_HAS_NO_SUPPORT_EMAIL: "STORE_HAS_NO_SUPPORT_EMAIL",
4447
+ TOO_MANY_ADDRESSES: "TOO_MANY_ADDRESSES",
4448
+ STORE_NOT_LINKED: "STORE_NOT_LINKED",
4449
+ STORED_METHOD_NOT_FOUND: "STORED_METHOD_NOT_FOUND"
4450
+ };
4451
+
4452
+ // shopper/email.ts
4453
+ function normalizeShopperEmail(email) {
4454
+ if (typeof email !== "string") return null;
4455
+ const value = email.trim().toLowerCase();
4456
+ return /^[^\s@]+@[^\s@]+$/.test(value) ? value : null;
4457
+ }
4458
+
4459
+ // shopper/card.ts
4460
+ function cardFromProcessorData(processorData) {
4461
+ if (typeof processorData !== "string" || !processorData) return {};
4462
+ let data;
4463
+ try {
4464
+ data = JSON.parse(processorData);
4465
+ } catch {
4466
+ return {};
4467
+ }
4468
+ if (!data || typeof data !== "object") return {};
4469
+ const fields = new Map(Object.entries(data));
4470
+ const text = (...keys) => keys.map((key) => fields.get(key)).find((value) => typeof value === "string" && !!value.trim());
4471
+ const brand = text("Brand", "brand")?.trim();
4472
+ const digits = text("Card Number", "card", "card_number")?.replace(/\D/g, "");
4473
+ const issuer = text("Issuer", "issuer")?.trim();
4474
+ return {
4475
+ ...brand ? { cardBrand: brand.charAt(0).toUpperCase() + brand.slice(1) } : {},
4476
+ ...digits && digits.length >= 4 ? { cardLastFour: digits.slice(-4) } : {},
4477
+ ...issuer ? { cardIssuer: issuer } : {}
4478
+ };
4479
+ }
4480
+
4481
+ // shopper/payments.ts
4482
+ var CARD_TYPES = /* @__PURE__ */ new Set(["card", "terminal", "taptopay", "moto", "cloud", "bluetooth"]);
4483
+ function kindOf(paymentType) {
4484
+ if (paymentType === "cash") return "cash";
4485
+ if (paymentType === "redeem") return "gift_card";
4486
+ if (paymentType === "pay_later") return "pay_later";
4487
+ if (CARD_TYPES.has(paymentType)) return "card";
4488
+ return "other";
4489
+ }
4490
+ function shopperPaymentsOf(legs) {
4491
+ return (legs ?? []).map((leg) => {
4492
+ const type = (leg.paymentType ?? "").trim();
4493
+ const kind = kindOf(type.toLowerCase());
4494
+ const card = kind === "card" ? cardFromProcessorData(leg.emv) : {};
4495
+ return {
4496
+ kind,
4497
+ // Cards: the issuer's name, else the brand. Other tenders the store named itself keep that name.
4498
+ name: kind === "card" ? card.cardIssuer ?? card.cardBrand ?? null : kind === "other" ? type || null : null,
4499
+ lastFour: card.cardLastFour ?? null,
4500
+ amount: (leg.amount ?? 0) + (leg.tip?.amount ?? 0)
4501
+ };
4502
+ });
4503
+ }
4504
+
4849
4505
  // constants/adyen.constants.ts
4850
4506
  var ADYEN_ROLLOUT_COUNTRY_CODES = /* @__PURE__ */ new Set(["CA"]);
4851
4507
  function isAdyenRolloutCountry(alpha2) {
@@ -4952,18 +4608,17 @@ export {
4952
4608
  AttributeType,
4953
4609
  BNPL_METHOD_STATUS,
4954
4610
  BNPL_SKIP_REASON,
4955
- BookingArriveLeave,
4956
- BookingDurationUnit,
4957
4611
  BookingRatePeriod,
4958
4612
  BookingResourceKind,
4959
4613
  BookingResourceStatus,
4960
4614
  BookingRulesError,
4961
- BookingSessionSale,
4962
4615
  BookingType,
4963
4616
  CANADA_PROVINCES,
4964
4617
  CONDITION_OPERATORS,
4965
4618
  COUNTRY_CURRENCIES,
4966
4619
  CURRENCY_CONFIG,
4620
+ CUSTOMER_CONTACT_VERIFIED,
4621
+ CUSTOMER_EMAIL_TAKEN,
4967
4622
  CompanyType,
4968
4623
  CurrencyCode,
4969
4624
  CustomTableAvailability,
@@ -4973,6 +4628,7 @@ export {
4973
4628
  DEFAULT_DISPLAY_STATE_MAP,
4974
4629
  DEFAULT_HOLD_MINUTES,
4975
4630
  DEFAULT_RESOLVED_CONFIG,
4631
+ DEFAULT_SHELL_SETTINGS,
4976
4632
  DEFAULT_UNIT_ID,
4977
4633
  DualWriteStrategy,
4978
4634
  EUFixedRates,
@@ -5001,6 +4657,7 @@ export {
5001
4657
  ORDER_STATE_TOPIC,
5002
4658
  OrderPlatform,
5003
4659
  OtherFixedRates,
4660
+ OutOfProvinceTaxes,
5004
4661
  OwnerType,
5005
4662
  PATH_MODES,
5006
4663
  PAYMENT_CHANNELS,
@@ -5028,7 +4685,18 @@ export {
5028
4685
  ResidualPaymentMethod,
5029
4686
  ResidualStatus,
5030
4687
  ResourceAvailabilityState,
4688
+ SHELL_FLOW_SETTINGS_PREFIX,
4689
+ SHELL_FLOW_TIPS_KEY,
4690
+ SHELL_TIP_LABEL_MAX_LENGTH,
4691
+ SHELL_TIP_PERCENT_MAX,
4692
+ SHELL_TIP_PERCENT_MIN,
5031
4693
  SHIPPING_COUNTRIES,
4694
+ SHOPPER_CONSENT_SOURCES,
4695
+ SHOPPER_ERROR_CODES,
4696
+ SHOPPER_RETURN_DECLINE_REASON_MAX,
4697
+ SHOPPER_RETURN_METHODS,
4698
+ SHOPPER_RETURN_STATUSES,
4699
+ STANDARD_TAX_TYPE,
5032
4700
  STATE_SCHEMA,
5033
4701
  STRIPE_SUPPORTED_COUNTRIES,
5034
4702
  SYSTEM_FAMILIES,
@@ -5046,9 +4714,13 @@ export {
5046
4714
  StationStatus,
5047
4715
  StripeCurrencyCode,
5048
4716
  StripeStatus,
4717
+ TAX_EXCEPTION_REASON_MAX,
4718
+ TaxExceptionSource,
4719
+ TaxRegistrationKind,
4720
+ TaxSource,
4721
+ TaxWarningCode,
5049
4722
  TimePeriod,
5050
4723
  TopMetericsSort,
5051
- UNLIMITED_PLACES,
5052
4724
  UserTypes,
5053
4725
  addAmounts,
5054
4726
  addressPlaceKeys,
@@ -5057,32 +4729,27 @@ export {
5057
4729
  adyenStoreRequiresStateOrProvince,
5058
4730
  adyenSupportsTaxNumberAbsent,
5059
4731
  adyenTaxNumberFormat,
5060
- allowedDurationUnits,
5061
4732
  amountToString,
5062
4733
  ancestorChain,
5063
4734
  applyAssignment,
5064
4735
  assertUnitSane,
4736
+ automaticTaxTableVersion,
5065
4737
  availableIn,
5066
4738
  baseFor,
5067
4739
  baseFulfillmentDefinitions,
5068
4740
  baseOf,
5069
4741
  basePaymentDefinitions,
5070
- bookingMethodOf,
5071
- bookingRuleParts,
4742
+ buildAutomaticTaxTable,
5072
4743
  buildAvailability,
5073
4744
  buildGrid,
5074
4745
  buildOrderContext,
5075
4746
  buildPosPresetConfig,
5076
4747
  buildResolvedConfig,
5077
4748
  calculatePercentage,
5078
- calendarDate,
5079
4749
  canTransition,
5080
- capacityOf,
5081
- cellChainOf,
4750
+ cardFromProcessorData,
5082
4751
  cheapestCompositeItem,
5083
4752
  cheapestCompositePrice,
5084
- checkPartySize,
5085
- checkQtyPerBooking,
5086
4753
  compositeItemCost,
5087
4754
  compositeItemUnavailable,
5088
4755
  compositeMakeable,
@@ -5091,10 +4758,6 @@ export {
5091
4758
  compositeVariantInStock,
5092
4759
  conditionSummary,
5093
4760
  convertFixedFeeToLocalCurrency,
5094
- courseSessions,
5095
- courseSpan,
5096
- courseStarted,
5097
- courseStartedInZone,
5098
4761
  createAmount,
5099
4762
  crossAxisRuleApplies,
5100
4763
  currentAssignees,
@@ -5103,17 +4766,17 @@ export {
5103
4766
  deriveUnitId,
5104
4767
  displayRuleMatchesPair,
5105
4768
  divideAmount,
5106
- durationProblems,
5107
- durationText,
4769
+ emailKey,
5108
4770
  evaluateCondition,
5109
4771
  evaluateConditionSet,
5110
4772
  extendPrice,
5111
4773
  extendPriceFor,
5112
- fewestFreeOver,
4774
+ flowSettingsFromShellSettings,
5113
4775
  formatCurrency,
5114
4776
  formatInUnit,
5115
4777
  formatMinorUnitsToString,
5116
4778
  formatQuantity,
4779
+ formatShippingDuration,
5117
4780
  fromBase,
5118
4781
  fromMinorUnits,
5119
4782
  generateMongoID,
@@ -5143,6 +4806,7 @@ export {
5143
4806
  isFulfillmentState,
5144
4807
  isInCart,
5145
4808
  isPaymentState,
4809
+ isShellTipPercent,
5146
4810
  isSupportedCurrency,
5147
4811
  isSystemFamilyCode,
5148
4812
  isValidQuantity,
@@ -5151,9 +4815,7 @@ export {
5151
4815
  listCountries,
5152
4816
  listProvinces,
5153
4817
  listShippingCountries,
5154
- longestMinutesOf,
5155
4818
  mapToLegacyStatus,
5156
- maxAdvanceMinutesOf,
5157
4819
  maxPrecisionFor,
5158
4820
  mergeFragment,
5159
4821
  modifiersSellable,
@@ -5164,16 +4826,14 @@ export {
5164
4826
  normalizeMongoIdString,
5165
4827
  normalizePostCode,
5166
4828
  normalizeProvince,
4829
+ normalizeShopperEmail,
5167
4830
  occupancyIn,
5168
- occupiedAtOutlet,
5169
- oldMaxAdvanceOf,
5170
4831
  orderAssignments,
5171
4832
  parseAmountToMinorUnits,
5172
4833
  parseCurrencyCode,
5173
4834
  parseStripeCurrencyCode,
5174
- pickFreeResource,
4835
+ phoneKey,
5175
4836
  placeKey,
5176
- planCourse,
5177
4837
  planWindow,
5178
4838
  poolDemand,
5179
4839
  poolOf,
@@ -5183,27 +4843,31 @@ export {
5183
4843
  presentAt,
5184
4844
  priceForTotal,
5185
4845
  provincesForPostCode,
4846
+ readShellTipSettings,
4847
+ registrationPlacesByKind,
5186
4848
  removeFragment,
5187
- rentalEnds,
5188
4849
  resolveFamily,
5189
4850
  resolveModifiersForProduct,
4851
+ resolveShellSettings,
4852
+ resolveShellSettingsWithSources,
5190
4853
  resolveShipping,
5191
4854
  resolveTemplate,
5192
4855
  resolveUnit,
5193
4856
  roundToPrecision,
5194
- ruleDurationsOf,
5195
- ruleInNewShape,
5196
4857
  sameFamily,
5197
- sessionCells,
5198
4858
  setOrderState,
4859
+ sha1Hex,
4860
+ shellSettingsFromCompanyTips,
4861
+ shellSettingsFromFlowSettings,
4862
+ shellSettingsProblems,
4863
+ shellTipSettingsProblems,
4864
+ shippingDuration,
5199
4865
  shipsToCountry,
5200
4866
  shopDayKey,
5201
4867
  shopDayRange,
5202
- shortestMinutesOf,
4868
+ shopperPaymentsOf,
5203
4869
  signReportForDisplay,
5204
4870
  slotsForWindow,
5205
- soldAsCourse,
5206
- startsPastMaxAdvance,
5207
4871
  stringifyMinorUnits,
5208
4872
  subtractAmounts,
5209
4873
  toBase,
@@ -5212,10 +4876,9 @@ export {
5212
4876
  validateFragmentCompatibility,
5213
4877
  validateOrderStatuses,
5214
4878
  validateShippingZone,
4879
+ verifiedContactChange,
5215
4880
  violatesFinancialInvariant,
5216
4881
  windowEndsAt,
5217
- windowEndsAtInZone,
5218
- windowForPeriods,
5219
4882
  withinPresence
5220
4883
  };
5221
4884
  //# sourceMappingURL=index.mjs.map