@final-commerce/common 2.4.1-staging2.1 → 2.4.1-staging2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -422,6 +422,7 @@ var StripeCurrencyCode = /* @__PURE__ */ ((StripeCurrencyCode2) => {
422
422
  var ProductType = /* @__PURE__ */ ((ProductType2) => {
423
423
  ProductType2["SIMPLE"] = "simple";
424
424
  ProductType2["VARIABLE"] = "variable";
425
+ ProductType2["BOOKING"] = "booking";
425
426
  return ProductType2;
426
427
  })(ProductType || {});
427
428
  var ProductStatus = /* @__PURE__ */ ((ProductStatus2) => {
@@ -439,6 +440,50 @@ var PaymentProcessor = /* @__PURE__ */ ((PaymentProcessor2) => {
439
440
  return PaymentProcessor2;
440
441
  })(PaymentProcessor || {});
441
442
 
443
+ // enums/booking.enum.ts
444
+ var BookingType = /* @__PURE__ */ ((BookingType3) => {
445
+ BookingType3["RENTAL"] = "rental";
446
+ BookingType3["APPOINTMENT"] = "appointment";
447
+ BookingType3["OVERNIGHT"] = "overnight";
448
+ BookingType3["GROUP"] = "group";
449
+ return BookingType3;
450
+ })(BookingType || {});
451
+ var BookingRatePeriod = /* @__PURE__ */ ((BookingRatePeriod2) => {
452
+ BookingRatePeriod2["SLOT"] = "slot";
453
+ BookingRatePeriod2["DAY"] = "day";
454
+ BookingRatePeriod2["NIGHT"] = "night";
455
+ BookingRatePeriod2["WEEK"] = "week";
456
+ BookingRatePeriod2["MONTH"] = "month";
457
+ return BookingRatePeriod2;
458
+ })(BookingRatePeriod || {});
459
+ var BookingResourceKind = /* @__PURE__ */ ((BookingResourceKind2) => {
460
+ BookingResourceKind2["ASSET"] = "asset";
461
+ BookingResourceKind2["ROOM"] = "room";
462
+ BookingResourceKind2["PROPERTY"] = "property";
463
+ BookingResourceKind2["SPACE"] = "space";
464
+ BookingResourceKind2["STAFF"] = "staff";
465
+ BookingResourceKind2["TABLE"] = "table";
466
+ return BookingResourceKind2;
467
+ })(BookingResourceKind || {});
468
+ var ReservationStatus = /* @__PURE__ */ ((ReservationStatus2) => {
469
+ ReservationStatus2["HELD"] = "held";
470
+ ReservationStatus2["CONFIRMED"] = "confirmed";
471
+ ReservationStatus2["CANCELLED"] = "cancelled";
472
+ ReservationStatus2["EXPIRED"] = "expired";
473
+ return ReservationStatus2;
474
+ })(ReservationStatus || {});
475
+ var BookingResourceStatus = /* @__PURE__ */ ((BookingResourceStatus2) => {
476
+ BookingResourceStatus2["ACTIVE"] = "active";
477
+ BookingResourceStatus2["INACTIVE"] = "inactive";
478
+ return BookingResourceStatus2;
479
+ })(BookingResourceStatus || {});
480
+ var ResourceAvailabilityState = /* @__PURE__ */ ((ResourceAvailabilityState2) => {
481
+ ResourceAvailabilityState2["AVAILABLE"] = "available";
482
+ ResourceAvailabilityState2["FULLY_BOOKED"] = "fullyBooked";
483
+ ResourceAvailabilityState2["NO_HOURS_IN_RANGE"] = "noHoursInRange";
484
+ return ResourceAvailabilityState2;
485
+ })(ResourceAvailabilityState || {});
486
+
442
487
  // utils/currency.util.ts
443
488
  var CURRENCY_CONFIG = {
444
489
  // Major currencies with 2 decimal places
@@ -1650,6 +1695,15 @@ function sumRefundQuantities(refunds) {
1650
1695
  }
1651
1696
  return t;
1652
1697
  }
1698
+ var asCount = (value) => typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
1699
+ function countsOf(row) {
1700
+ const quantity = asCount(row.quantity);
1701
+ return {
1702
+ quantity,
1703
+ fulfilled: Math.min(asCount(row.fulfilledQuantity), quantity),
1704
+ returned: Math.min(asCount(row.returnedQuantity), quantity)
1705
+ };
1706
+ }
1653
1707
  function buildOrderContext(order, extras) {
1654
1708
  const o = order ?? {};
1655
1709
  const total = typeof o.total === "number" && Number.isFinite(o.total) ? o.total : 0;
@@ -1657,6 +1711,7 @@ function buildOrderContext(order, extras) {
1657
1711
  const paymentMethods = o.paymentMethods ?? [];
1658
1712
  const refunds = o.refunds ?? o.refund ?? [];
1659
1713
  const lineItems = o.lineItems ?? [];
1714
+ const reservations = o.reservations ?? [];
1660
1715
  const totalPaid = sumNumbers(paymentMethods);
1661
1716
  const totalRefunded = sumRefundQuantities(refunds);
1662
1717
  const isFullyPaid = total > 0 ? balance <= 0 : totalPaid > 0 && balance <= 0;
@@ -1664,13 +1719,11 @@ function buildOrderContext(order, extras) {
1664
1719
  let itemCount = 0;
1665
1720
  let fulfilledItemCount = 0;
1666
1721
  let returnedItemCount = 0;
1667
- for (const li of lineItems) {
1668
- const q = typeof li.quantity === "number" && Number.isFinite(li.quantity) ? Math.max(0, li.quantity) : 0;
1669
- itemCount += q;
1670
- const fq = typeof li.fulfilledQuantity === "number" && Number.isFinite(li.fulfilledQuantity) ? Math.max(0, li.fulfilledQuantity) : 0;
1671
- fulfilledItemCount += Math.min(fq, q);
1672
- const rq = typeof li.returnedQuantity === "number" && Number.isFinite(li.returnedQuantity) ? Math.max(0, li.returnedQuantity) : 0;
1673
- returnedItemCount += Math.min(rq, q);
1722
+ for (const row of [...lineItems, ...reservations]) {
1723
+ const { quantity, fulfilled, returned } = countsOf(row);
1724
+ itemCount += quantity;
1725
+ fulfilledItemCount += fulfilled;
1726
+ returnedItemCount += returned;
1674
1727
  }
1675
1728
  const isFullyReturned = itemCount > 0 ? returnedItemCount >= itemCount : returnedItemCount > 0;
1676
1729
  const hasPartialReturns = returnedItemCount > 0 && !isFullyReturned;
@@ -1680,7 +1733,8 @@ function buildOrderContext(order, extras) {
1680
1733
  balance,
1681
1734
  paymentMethods,
1682
1735
  refunds,
1683
- lineItems
1736
+ lineItems,
1737
+ reservations
1684
1738
  },
1685
1739
  computed: {
1686
1740
  balance,
@@ -2760,6 +2814,395 @@ var ORDER_STATE_EVENTS = {
2760
2814
  configUpdated: "config-updated"
2761
2815
  };
2762
2816
 
2817
+ // booking/types.ts
2818
+ var BookingRulesError = class extends Error {
2819
+ constructor(message) {
2820
+ super(message);
2821
+ this.name = "BookingRulesError";
2822
+ }
2823
+ };
2824
+
2825
+ // booking/zoned-time.ts
2826
+ var MINUTE = 6e4;
2827
+ var formatters = /* @__PURE__ */ new Map();
2828
+ var formatterFor = (timeZone) => {
2829
+ const existing = formatters.get(timeZone);
2830
+ if (existing) return existing;
2831
+ let created;
2832
+ try {
2833
+ created = new Intl.DateTimeFormat("en-US", {
2834
+ timeZone,
2835
+ hour12: false,
2836
+ year: "numeric",
2837
+ month: "2-digit",
2838
+ day: "2-digit",
2839
+ hour: "2-digit",
2840
+ minute: "2-digit",
2841
+ second: "2-digit",
2842
+ weekday: "short"
2843
+ });
2844
+ } catch {
2845
+ throw new BookingRulesError(`Booking rules: "${timeZone}" is not a known time zone`);
2846
+ }
2847
+ formatters.set(timeZone, created);
2848
+ return created;
2849
+ };
2850
+ var WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
2851
+ function zonedParts(instant, timeZone) {
2852
+ const parts = {};
2853
+ for (const { type, value } of formatterFor(timeZone).formatToParts(instant)) parts[type] = value;
2854
+ const hour = Number(parts.hour) % 24;
2855
+ return {
2856
+ year: Number(parts.year),
2857
+ month: Number(parts.month),
2858
+ day: Number(parts.day),
2859
+ hour,
2860
+ minute: Number(parts.minute),
2861
+ second: Number(parts.second),
2862
+ weekday: WEEKDAYS.indexOf(parts.weekday)
2863
+ };
2864
+ }
2865
+ function offsetAt(instant, timeZone) {
2866
+ const { year, month, day, hour, minute, second } = zonedParts(instant, timeZone);
2867
+ return Date.UTC(year, month - 1, day, hour, minute, second) - Math.floor(instant.getTime() / 1e3) * 1e3;
2868
+ }
2869
+ function instantFromLocal(year, month, day, minutes, timeZone) {
2870
+ const naive = Date.UTC(year, month - 1, day) + minutes * MINUTE;
2871
+ const firstGuess = naive - offsetAt(new Date(naive), timeZone);
2872
+ return new Date(naive - offsetAt(new Date(firstGuess), timeZone));
2873
+ }
2874
+ function startOfZonedDay(instant, timeZone) {
2875
+ const { year, month, day } = zonedParts(instant, timeZone);
2876
+ return instantFromLocal(year, month, day, 0, timeZone);
2877
+ }
2878
+ function nextZonedDay(dayStart, timeZone) {
2879
+ const { year, month, day } = zonedParts(dayStart, timeZone);
2880
+ return instantFromLocal(year, month, day + 1, 0, timeZone);
2881
+ }
2882
+ function atZonedMinute(dayStart, minutes, timeZone) {
2883
+ const { year, month, day } = zonedParts(dayStart, timeZone);
2884
+ return instantFromLocal(year, month, day, minutes, timeZone);
2885
+ }
2886
+
2887
+ // booking/grid.ts
2888
+ var MINUTE2 = 6e4;
2889
+ var MAX_RANGE_DAYS = 366;
2890
+ var asTime = (value, field) => {
2891
+ if (value == null) return void 0;
2892
+ const time = new Date(value).getTime();
2893
+ if (Number.isNaN(time)) throw new BookingRulesError(`Booking rules: ${field} is not a date, got "${String(value)}"`);
2894
+ return time;
2895
+ };
2896
+ function parseHhMm(value, field) {
2897
+ const [hours, minutes] = value.split(":").map(Number);
2898
+ if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
2899
+ throw new BookingRulesError(`Booking rules: ${field} must be "HH:mm", got "${value}"`);
2900
+ }
2901
+ return hours * 60 + minutes;
2902
+ }
2903
+ function windowEndsAt(rule, now) {
2904
+ const { maxAdvanceDays, bookableTo } = rule.window;
2905
+ const ends = Math.min(
2906
+ maxAdvanceDays ? now.getTime() + maxAdvanceDays * 1440 * MINUTE2 : Number.POSITIVE_INFINITY,
2907
+ asTime(bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
2908
+ );
2909
+ return Number.isFinite(ends) ? new Date(ends) : null;
2910
+ }
2911
+ function periodSlot(dayStart, timeZone, rule, openMinute, closeMinute) {
2912
+ const { ratePeriod, slot, checkInTime, checkOutTime } = rule;
2913
+ const at = (minutes) => atZonedMinute(dayStart, minutes, timeZone);
2914
+ if (ratePeriod === "night" /* NIGHT */) {
2915
+ if (!checkInTime || !checkOutTime) {
2916
+ throw new BookingRulesError("Overnight booking rules need both checkInTime and checkOutTime");
2917
+ }
2918
+ const checkIn = parseHhMm(checkInTime, "checkInTime");
2919
+ const checkOut = parseHhMm(checkOutTime, "checkOutTime");
2920
+ return {
2921
+ startAt: at(checkIn),
2922
+ endAt: at(1440 + checkOut),
2923
+ // Housekeeping sits between check-out and the next check-in: it costs no night.
2924
+ bufferEndAt: at(1440 + checkIn),
2925
+ canStart: true
2926
+ };
2927
+ }
2928
+ const from = ratePeriod === "day" /* DAY */ ? openMinute ?? 0 : 0;
2929
+ const to = ratePeriod === "day" /* DAY */ ? closeMinute ?? 1440 : 1440;
2930
+ return {
2931
+ startAt: at(from),
2932
+ endAt: at(to),
2933
+ bufferEndAt: at(to + (slot.bufferMinutes ?? 0)),
2934
+ canStart: true
2935
+ };
2936
+ }
2937
+ function freeGaps(openAt, closeAt, busy) {
2938
+ const inside = busy.map(({ startAt, bufferEndAt }) => ({ from: +startAt, to: +bufferEndAt })).filter(({ from, to }) => to > openAt && from < closeAt).sort((first, second) => first.from - second.from);
2939
+ const gaps = [];
2940
+ let cursor = openAt;
2941
+ for (const { from, to } of inside) {
2942
+ if (from > cursor) gaps.push({ from: cursor, to: from, endsAtBooking: true });
2943
+ cursor = Math.max(cursor, to);
2944
+ if (cursor >= closeAt) break;
2945
+ }
2946
+ if (cursor < closeAt) gaps.push({ from: cursor, to: closeAt, endsAtBooking: false });
2947
+ return gaps;
2948
+ }
2949
+ function buildGrid(rule, timeZone, from, to, now, busy = []) {
2950
+ if (to.getTime() - from.getTime() > MAX_RANGE_DAYS * 1440 * MINUTE2) {
2951
+ throw new BookingRulesError(`A booking range may span at most ${MAX_RANGE_DAYS} days`);
2952
+ }
2953
+ const { availability, slot, window, ratePeriod } = rule;
2954
+ const periodMode = ratePeriod !== "slot" /* SLOT */;
2955
+ const weeklyHours = availability.weeklyHours ?? [];
2956
+ const notBefore = Math.max(
2957
+ now.getTime() + (window.minNoticeMinutes ?? 0) * MINUTE2,
2958
+ asTime(window.bookableFrom, "window.bookableFrom") ?? 0,
2959
+ asTime(availability.availableFrom, "availability.availableFrom") ?? 0
2960
+ );
2961
+ const notAfter = windowEndsAt(rule, now)?.getTime() ?? Number.POSITIVE_INFINITY;
2962
+ const blocked = (availability.offMarket ?? []).map(({ from: blockFrom, to: blockTo }) => ({
2963
+ from: asTime(blockFrom, "availability.offMarket.from"),
2964
+ to: asTime(blockTo, "availability.offMarket.to")
2965
+ }));
2966
+ const arrivalDays = availability.arrivalDays;
2967
+ const step = slot.lengthMinutes + (slot.bufferMinutes ?? 0);
2968
+ const slots = [];
2969
+ const lastDay = startOfZonedDay(to, timeZone).getTime();
2970
+ let dayStart = startOfZonedDay(from, timeZone);
2971
+ while (dayStart.getTime() <= lastDay) {
2972
+ const weekday = zonedParts(dayStart, timeZone).weekday;
2973
+ const rows = weeklyHours.filter((entry) => entry.weekday === weekday);
2974
+ if (periodMode) {
2975
+ const openToday = weeklyHours.length === 0 || rows.length > 0;
2976
+ if (openToday) {
2977
+ const built = periodSlot(dayStart, timeZone, rule, rows[0]?.openMinute, rows[0]?.closeMinute);
2978
+ slots.push({ ...built, canStart: !arrivalDays?.length || arrivalDays.includes(weekday) });
2979
+ }
2980
+ } else {
2981
+ for (const row of rows) {
2982
+ const openAt = +atZonedMinute(dayStart, row.openMinute, timeZone);
2983
+ const closeAt = +atZonedMinute(dayStart, row.closeMinute, timeZone);
2984
+ for (const gap of freeGaps(openAt, closeAt, busy)) {
2985
+ const mustFit = (gap.endsAtBooking ? step : slot.lengthMinutes) * MINUTE2;
2986
+ for (let start = gap.from; start + mustFit <= gap.to; start += step * MINUTE2) {
2987
+ slots.push({
2988
+ startAt: new Date(start),
2989
+ endAt: new Date(start + slot.lengthMinutes * MINUTE2),
2990
+ bufferEndAt: new Date(start + step * MINUTE2),
2991
+ canStart: true
2992
+ });
2993
+ }
2994
+ }
2995
+ }
2996
+ }
2997
+ dayStart = nextZonedDay(dayStart, timeZone);
2998
+ }
2999
+ const askedFrom = from.getTime();
3000
+ const askedTo = to.getTime();
3001
+ return slots.filter(({ startAt, bufferEndAt }) => {
3002
+ const start = startAt.getTime();
3003
+ if (start < askedFrom || start >= askedTo) return false;
3004
+ if (start < notBefore || start > notAfter) return false;
3005
+ return !blocked.some(
3006
+ ({ from: blockFrom, to: blockTo }) => start < blockTo && bufferEndAt.getTime() > blockFrom
3007
+ );
3008
+ }).sort((first, second) => +first.startAt - +second.startAt);
3009
+ }
3010
+ function slotsForWindow(grid, startAt, endAt) {
3011
+ const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
3012
+ if (startIndex < 0) {
3013
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
3014
+ }
3015
+ if (!grid[startIndex].canStart) {
3016
+ throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
3017
+ }
3018
+ const covered = [];
3019
+ for (let index = startIndex; index < grid.length; index++) {
3020
+ const entry = grid[index];
3021
+ const previous = covered[covered.length - 1];
3022
+ if (previous && entry.startAt.getTime() !== previous.bufferEndAt.getTime()) break;
3023
+ covered.push(entry);
3024
+ if (entry.endAt.getTime() === endAt.getTime()) return covered;
3025
+ if (entry.endAt.getTime() > endAt.getTime()) break;
3026
+ }
3027
+ throw new BookingRulesError(
3028
+ `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
3029
+ );
3030
+ }
3031
+
3032
+ // booking/availability.ts
3033
+ var withinPresence = (slot, timeZone, presence) => {
3034
+ if (!presence?.length) return true;
3035
+ const dayStart = startOfZonedDay(slot.startAt, timeZone);
3036
+ const weekday = zonedParts(dayStart, timeZone).weekday;
3037
+ return presence.some(
3038
+ (shift) => shift.weekday === weekday && slot.startAt.getTime() >= atZonedMinute(dayStart, shift.openMinute, timeZone).getTime() && slot.endAt.getTime() <= atZonedMinute(dayStart, shift.closeMinute, timeZone).getTime()
3039
+ );
3040
+ };
3041
+ var overlaps = (entry, startAt, bufferEndAt) => entry.startAt.getTime() < bufferEndAt.getTime() && entry.bufferEndAt.getTime() > startAt.getTime();
3042
+ function occupancyIn(occupied, productId, startAt, bufferEndAt, shared) {
3043
+ const clashing = occupied.filter((entry) => overlaps(entry, startAt, bufferEndAt));
3044
+ const foreign = shared ? void 0 : clashing.find((entry) => entry.productId !== productId);
3045
+ return {
3046
+ taken: clashing.filter((entry) => shared || entry.productId === productId).reduce((sum, entry) => sum + entry.qty, 0),
3047
+ foreignProductId: foreign?.productId
3048
+ };
3049
+ }
3050
+ var stateFor = (hasShift, offerable, free) => {
3051
+ if (offerable === 0) {
3052
+ return hasShift() ? "fullyBooked" /* FULLY_BOOKED */ : "noHoursInRange" /* NO_HOURS_IN_RANGE */;
3053
+ }
3054
+ return free === 0 ? "fullyBooked" /* FULLY_BOOKED */ : "available" /* AVAILABLE */;
3055
+ };
3056
+ function shopDayKey(instant, timeZone) {
3057
+ const { year, month, day } = zonedParts(instant, timeZone);
3058
+ const pad = (value) => String(value).padStart(2, "0");
3059
+ return `${year}-${pad(month)}-${pad(day)}`;
3060
+ }
3061
+ function shopDayRange(fromDayKey, count, timeZone) {
3062
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(fromDayKey ?? "");
3063
+ if (!match) {
3064
+ throw new BookingRulesError(`Booking rules: "${fromDayKey}" is not a shop day (YYYY-MM-DD)`);
3065
+ }
3066
+ if (!Number.isInteger(count) || count < 1) {
3067
+ throw new BookingRulesError(`Booking rules: "${count}" is not a number of days`);
3068
+ }
3069
+ const [, year, month, day] = match.map(Number);
3070
+ const from = instantFromLocal(year, month, day, 0, timeZone);
3071
+ if (shopDayKey(from, timeZone) !== fromDayKey) {
3072
+ throw new BookingRulesError(`Booking rules: "${fromDayKey}" is not a real day`);
3073
+ }
3074
+ return { from, to: instantFromLocal(year, month, day + count, 0, timeZone) };
3075
+ }
3076
+ function buildAvailability({
3077
+ productId,
3078
+ bookingRulesId,
3079
+ bookingType,
3080
+ rule,
3081
+ resources,
3082
+ occupied,
3083
+ from,
3084
+ to,
3085
+ now
3086
+ }) {
3087
+ const shared = rule.slot.sharedAcrossProducts ?? false;
3088
+ const bookableUntil = windowEndsAt(rule, now);
3089
+ const header = {
3090
+ productId,
3091
+ bookingRulesId,
3092
+ bookingType,
3093
+ ratePeriod: rule.ratePeriod,
3094
+ // Passed through for the UI to label: a group slot under minimumToRun may not run.
3095
+ minimumToRun: rule.slot.minimumToRun,
3096
+ minStay: rule.slot.minStay,
3097
+ maxStay: rule.slot.maxStay,
3098
+ // Why a day can come back empty. Past this instant the rule refuses everything, so the UI
3099
+ // can say "beyond the booking window" where it would otherwise claim "nothing free".
3100
+ bookableUntil,
3101
+ // The comparison itself, not just the boundary: deciding whether a day lies past the
3102
+ // window is a rule, and a UI that re-derives it owns a copy of that rule — which is how
3103
+ // the same empty grid ends up explained one way on the till and another in a flow.
3104
+ beyondWindow: !!bookableUntil && from.getTime() > bookableUntil.getTime()
3105
+ };
3106
+ const byResource = /* @__PURE__ */ new Map();
3107
+ for (const entry of occupied) {
3108
+ byResource.set(entry.resourceId, [...byResource.get(entry.resourceId) ?? [], entry]);
3109
+ }
3110
+ const grids = resources.map((resource) => {
3111
+ const mine = byResource.get(resource.id) ?? [];
3112
+ const busy = (resource.seats ?? 1) === 1 ? mine : [];
3113
+ const slots2 = buildGrid(rule, resource.timeZone, from, to, now, busy).filter(
3114
+ (slot) => withinPresence(slot, resource.timeZone, resource.presence)
3115
+ );
3116
+ return { resource, slots: slots2 };
3117
+ });
3118
+ const byInstant = /* @__PURE__ */ new Map();
3119
+ const freeSlotsPerResource = /* @__PURE__ */ new Map();
3120
+ for (const { resource, slots: slots2 } of grids) {
3121
+ const capacity = resource.seats ?? 1;
3122
+ const mine = byResource.get(resource.id) ?? [];
3123
+ for (const slot of slots2) {
3124
+ const { taken, foreignProductId } = occupancyIn(mine, productId, slot.startAt, slot.bufferEndAt, shared);
3125
+ const free = foreignProductId ? 0 : Math.max(capacity - taken, 0);
3126
+ const entry = byInstant.get(+slot.startAt) ?? {
3127
+ ...slot,
3128
+ capacity: 0,
3129
+ booked: 0,
3130
+ free: 0,
3131
+ resources: [],
3132
+ dayKey: shopDayKey(slot.startAt, resource.timeZone)
3133
+ };
3134
+ entry.capacity += capacity;
3135
+ entry.booked += foreignProductId ? capacity : taken;
3136
+ entry.free += free;
3137
+ entry.canStart = entry.canStart || slot.canStart;
3138
+ entry.resources.push({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free });
3139
+ if (free > 0) freeSlotsPerResource.set(resource.id, (freeSlotsPerResource.get(resource.id) ?? 0) + 1);
3140
+ byInstant.set(+slot.startAt, entry);
3141
+ }
3142
+ }
3143
+ const inWindow = grids.map(({ resource, slots: slots2 }) => {
3144
+ const free = freeSlotsPerResource.get(resource.id) ?? 0;
3145
+ return {
3146
+ resourceId: resource.id,
3147
+ name: resource.name,
3148
+ slots: slots2.length,
3149
+ free,
3150
+ // Lazily: the shift grid is a second walk, and only an empty answer needs it.
3151
+ state: stateFor(
3152
+ () => buildGrid(rule, resource.timeZone, from, to, now).filter(
3153
+ (slot) => withinPresence(slot, resource.timeZone, resource.presence)
3154
+ ).length > 0,
3155
+ slots2.length,
3156
+ free
3157
+ )
3158
+ };
3159
+ });
3160
+ const slots = [...byInstant.values()].sort((first, second) => +first.startAt - +second.startAt);
3161
+ return {
3162
+ ...header,
3163
+ resources: inWindow,
3164
+ slots,
3165
+ /**
3166
+ * The clock every instant above reads on. Returned rather than assumed: without it a caller
3167
+ * has to fetch the zone from somewhere else and hope it is the same one the grid used.
3168
+ */
3169
+ timeZone: resources[0]?.timeZone ?? null,
3170
+ /** The shop days this answer covers, in order — what a day picker lists. */
3171
+ days: [...new Set(slots.map((slot) => slot.dayKey))]
3172
+ };
3173
+ }
3174
+ function presentAt(resources, rows, outletId) {
3175
+ const byResource = /* @__PURE__ */ new Map();
3176
+ for (const row of rows) {
3177
+ byResource.set(row.resourceId, [...byResource.get(row.resourceId) ?? [], row]);
3178
+ }
3179
+ return resources.flatMap((resource) => {
3180
+ const own = byResource.get(resource.id) ?? [];
3181
+ if (own.length === 0 || !outletId) return [{ resource }];
3182
+ const here = own.find((row) => row.outletId === outletId);
3183
+ return here ? [{ resource, presence: here.weeklyHours }] : [];
3184
+ });
3185
+ }
3186
+
3187
+ // booking/plan.ts
3188
+ var DEFAULT_HOLD_MINUTES = 10;
3189
+ function planWindow({ rule, timeZone, presence, startAt, endAt, now, busy = [] }) {
3190
+ const grid = buildGrid(rule, timeZone, startAt, endAt, now, busy).filter(
3191
+ (slot) => withinPresence(slot, timeZone, presence)
3192
+ );
3193
+ const slots = slotsForWindow(grid, startAt, endAt);
3194
+ const { minStay, maxStay } = rule.slot;
3195
+ if (minStay && slots.length < minStay) {
3196
+ throw new BookingRulesError(`These rules ask for at least ${minStay} period(s), got ${slots.length}`);
3197
+ }
3198
+ if (maxStay && slots.length > maxStay) {
3199
+ throw new BookingRulesError(`These rules allow at most ${maxStay} period(s), got ${slots.length}`);
3200
+ }
3201
+ const last = slots[slots.length - 1];
3202
+ return { slots, endAt: last.endAt, bufferEndAt: last.bufferEndAt };
3203
+ }
3204
+ var holdExpiresAt = (rule, now) => new Date(now.getTime() + (rule.window.holdMinutes ?? DEFAULT_HOLD_MINUTES) * 6e4);
3205
+
2763
3206
  // constants/adyen.constants.ts
2764
3207
  var ADYEN_ROLLOUT_COUNTRY_CODES = /* @__PURE__ */ new Set(["CA"]);
2765
3208
  function isAdyenRolloutCountry(alpha2) {
@@ -2797,6 +3240,11 @@ export {
2797
3240
  ADYEN_TAX_NUMBER_FORMATS,
2798
3241
  ADYEN_TAX_NUMBER_MIN_LENGTH,
2799
3242
  AttributeType,
3243
+ BookingRatePeriod,
3244
+ BookingResourceKind,
3245
+ BookingResourceStatus,
3246
+ BookingRulesError,
3247
+ BookingType,
2800
3248
  CONDITION_OPERATORS,
2801
3249
  COUNTRY_CURRENCIES,
2802
3250
  CURRENCY_CONFIG,
@@ -2807,6 +3255,7 @@ export {
2807
3255
  DEFAULT_CONFIG,
2808
3256
  DEFAULT_CROSS_AXIS_RULES,
2809
3257
  DEFAULT_DISPLAY_STATE_MAP,
3258
+ DEFAULT_HOLD_MINUTES,
2810
3259
  DEFAULT_RESOLVED_CONFIG,
2811
3260
  DEFAULT_UNIT_ID,
2812
3261
  DualWriteStrategy,
@@ -2850,8 +3299,10 @@ export {
2850
3299
  REPORT_NEGATE_PATHS,
2851
3300
  ReceiptSendChannel,
2852
3301
  ReceiptType,
3302
+ ReservationStatus,
2853
3303
  ResidualPaymentMethod,
2854
3304
  ResidualStatus,
3305
+ ResourceAvailabilityState,
2855
3306
  STATE_SCHEMA,
2856
3307
  STRIPE_SUPPORTED_COUNTRIES,
2857
3308
  SYSTEM_FAMILIES,
@@ -2877,6 +3328,8 @@ export {
2877
3328
  baseFulfillmentDefinitions,
2878
3329
  baseOf,
2879
3330
  basePaymentDefinitions,
3331
+ buildAvailability,
3332
+ buildGrid,
2880
3333
  buildOrderContext,
2881
3334
  buildPosPresetConfig,
2882
3335
  buildResolvedConfig,
@@ -2916,6 +3369,7 @@ export {
2916
3369
  getPricingRegionFromCountry,
2917
3370
  getSettlementTotal,
2918
3371
  getTotalCollected,
3372
+ holdExpiresAt,
2919
3373
  inferStatesFromLegacyStatus,
2920
3374
  isAdyenRolloutCountry,
2921
3375
  isConditionOperator,
@@ -2930,9 +3384,12 @@ export {
2930
3384
  mergeFragment,
2931
3385
  multiplyAmount,
2932
3386
  normalizeMongoIdString,
3387
+ occupancyIn,
2933
3388
  parseAmountToMinorUnits,
2934
3389
  parseCurrencyCode,
2935
3390
  parseStripeCurrencyCode,
3391
+ planWindow,
3392
+ presentAt,
2936
3393
  removeFragment,
2937
3394
  resolveFamily,
2938
3395
  resolveTemplate,
@@ -2940,13 +3397,18 @@ export {
2940
3397
  roundToPrecision,
2941
3398
  sameFamily,
2942
3399
  setOrderState,
3400
+ shopDayKey,
3401
+ shopDayRange,
2943
3402
  signReportForDisplay,
3403
+ slotsForWindow,
2944
3404
  stringifyMinorUnits,
2945
3405
  subtractAmounts,
2946
3406
  toBase,
2947
3407
  toMinorUnits,
2948
3408
  validateConfig,
2949
3409
  validateFragmentCompatibility,
2950
- violatesFinancialInvariant
3410
+ violatesFinancialInvariant,
3411
+ windowEndsAt,
3412
+ withinPresence
2951
3413
  };
2952
3414
  //# sourceMappingURL=index.mjs.map