@pisell/pisellos 2.3.129 → 2.3.131

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.
Files changed (102) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +3 -1
  3. package/dist/modules/BusinessAvailability/index.d.ts +30 -0
  4. package/dist/modules/BusinessAvailability/index.js +204 -0
  5. package/dist/modules/FulfillmentTiming/index.d.ts +11 -0
  6. package/dist/modules/FulfillmentTiming/index.js +407 -0
  7. package/dist/modules/FulfillmentTiming/types.d.ts +67 -0
  8. package/dist/modules/FulfillmentTiming/types.js +1 -0
  9. package/dist/modules/OpenData/types.d.ts +8 -0
  10. package/dist/modules/Order/index.d.ts +11 -2
  11. package/dist/modules/Order/index.js +370 -253
  12. package/dist/modules/Order/pickupTiming.d.ts +46 -0
  13. package/dist/modules/Order/pickupTiming.js +53 -0
  14. package/dist/modules/Order/types.d.ts +13 -1
  15. package/dist/modules/Order/utils.js +16 -6
  16. package/dist/modules/Payment/index.js +9 -10
  17. package/dist/modules/Schedule/index.d.ts +8 -0
  18. package/dist/modules/Schedule/index.js +141 -39
  19. package/dist/modules/index.d.ts +1 -0
  20. package/dist/modules/index.js +1 -0
  21. package/dist/plugins/request.d.ts +7 -0
  22. package/dist/server/utils/small-ticket.d.ts +1 -85
  23. package/dist/server/utils/small-ticket.js +2 -2542
  24. package/dist/shared/payment/loadPaymentMethods.d.ts +9 -0
  25. package/dist/shared/payment/loadPaymentMethods.js +66 -0
  26. package/dist/shared/receipt/loadCustomerInvoiceLayout.d.ts +22 -0
  27. package/dist/shared/receipt/loadCustomerInvoiceLayout.js +142 -0
  28. package/dist/shared/receipt/small-ticket.d.ts +85 -0
  29. package/dist/shared/receipt/small-ticket.js +2576 -0
  30. package/dist/shared/sales/loadSalesOrderSnapshot.d.ts +9 -0
  31. package/dist/shared/sales/loadSalesOrderSnapshot.js +21 -0
  32. package/dist/solution/BaseSales/index.d.ts +28 -15
  33. package/dist/solution/BaseSales/index.js +1346 -1101
  34. package/dist/solution/BaseSales/pickupTiming.d.ts +43 -0
  35. package/dist/solution/BaseSales/pickupTiming.js +589 -0
  36. package/dist/solution/BaseSales/types.d.ts +11 -0
  37. package/dist/solution/BaseSales/utils/parseSalesResponse.js +3 -0
  38. package/dist/solution/BookingByStep/index.d.ts +1 -1
  39. package/dist/solution/BookingTicket/index.d.ts +2 -2
  40. package/dist/solution/BookingTicket/index.js +41 -13
  41. package/dist/solution/BookingTicket/utils/cartView.js +3 -1
  42. package/dist/solution/OrderInvoicePreview/index.d.ts +56 -0
  43. package/dist/solution/OrderInvoicePreview/index.js +269 -0
  44. package/dist/solution/UnifiedBookingSales/businessAvailability.d.ts +27 -0
  45. package/dist/solution/UnifiedBookingSales/businessAvailability.js +292 -0
  46. package/dist/solution/UnifiedBookingSales/index.d.ts +24 -4
  47. package/dist/solution/UnifiedBookingSales/index.js +953 -709
  48. package/dist/solution/UnifiedBookingSales/types.d.ts +2 -0
  49. package/dist/solution/index.d.ts +1 -0
  50. package/dist/solution/index.js +2 -1
  51. package/lib/index.d.ts +2 -0
  52. package/lib/index.js +21 -1
  53. package/lib/model/strategy/adapter/promotion/index.js +46 -1
  54. package/lib/modules/BusinessAvailability/index.d.ts +30 -0
  55. package/lib/modules/BusinessAvailability/index.js +146 -0
  56. package/lib/modules/FulfillmentTiming/index.d.ts +11 -0
  57. package/lib/modules/FulfillmentTiming/index.js +359 -0
  58. package/lib/modules/FulfillmentTiming/types.d.ts +67 -0
  59. package/lib/modules/FulfillmentTiming/types.js +5 -0
  60. package/lib/modules/OpenData/types.d.ts +8 -0
  61. package/lib/modules/Order/index.d.ts +11 -2
  62. package/lib/modules/Order/index.js +101 -14
  63. package/lib/modules/Order/pickupTiming.d.ts +46 -0
  64. package/lib/modules/Order/pickupTiming.js +61 -0
  65. package/lib/modules/Order/types.d.ts +13 -1
  66. package/lib/modules/Order/utils.js +12 -4
  67. package/lib/modules/Payment/index.js +3 -4
  68. package/lib/modules/Schedule/index.d.ts +8 -0
  69. package/lib/modules/Schedule/index.js +68 -12
  70. package/lib/modules/index.d.ts +1 -0
  71. package/lib/modules/index.js +11 -0
  72. package/lib/plugins/request.d.ts +7 -0
  73. package/lib/server/utils/small-ticket.d.ts +1 -85
  74. package/lib/server/utils/small-ticket.js +9 -2305
  75. package/lib/shared/payment/loadPaymentMethods.d.ts +9 -0
  76. package/lib/shared/payment/loadPaymentMethods.js +40 -0
  77. package/lib/shared/receipt/loadCustomerInvoiceLayout.d.ts +22 -0
  78. package/lib/shared/receipt/loadCustomerInvoiceLayout.js +86 -0
  79. package/lib/shared/receipt/small-ticket.d.ts +85 -0
  80. package/lib/shared/receipt/small-ticket.js +2342 -0
  81. package/lib/shared/sales/loadSalesOrderSnapshot.d.ts +9 -0
  82. package/lib/shared/sales/loadSalesOrderSnapshot.js +22 -0
  83. package/lib/solution/BaseSales/index.d.ts +28 -15
  84. package/lib/solution/BaseSales/index.js +161 -25
  85. package/lib/solution/BaseSales/pickupTiming.d.ts +43 -0
  86. package/lib/solution/BaseSales/pickupTiming.js +269 -0
  87. package/lib/solution/BaseSales/types.d.ts +11 -0
  88. package/lib/solution/BaseSales/utils/parseSalesResponse.js +3 -0
  89. package/lib/solution/BookingByStep/index.d.ts +1 -1
  90. package/lib/solution/BookingTicket/index.d.ts +2 -2
  91. package/lib/solution/BookingTicket/index.js +37 -4
  92. package/lib/solution/BookingTicket/utils/cartView.js +3 -1
  93. package/lib/solution/OrderInvoicePreview/index.d.ts +56 -0
  94. package/lib/solution/OrderInvoicePreview/index.js +192 -0
  95. package/lib/solution/UnifiedBookingSales/businessAvailability.d.ts +27 -0
  96. package/lib/solution/UnifiedBookingSales/businessAvailability.js +138 -0
  97. package/lib/solution/UnifiedBookingSales/index.d.ts +24 -4
  98. package/lib/solution/UnifiedBookingSales/index.js +184 -46
  99. package/lib/solution/UnifiedBookingSales/types.d.ts +2 -0
  100. package/lib/solution/index.d.ts +1 -0
  101. package/lib/solution/index.js +11 -0
  102. package/package.json +1 -1
@@ -216,6 +216,8 @@ export interface UnifiedBookingSalesDiscountResult {
216
216
  summaryAfter?: unknown;
217
217
  }
218
218
  export interface UnifiedBookingSalesApi {
219
+ /** Uses cached business settings and evaluates the current store-local clock. */
220
+ getBusinessAvailability: () => Promise<import('../../modules/BusinessAvailability').BusinessAvailability>;
219
221
  loadOpenData: (params: UnifiedBookingSalesLoadOpenDataParams) => Promise<OpenDataConfig>;
220
222
  /** Returns the latest OpenData payload cached by this solution instance. */
221
223
  getOpenData: () => Promise<OpenDataConfig | null>;
@@ -9,3 +9,4 @@ export * from './ScanOrder';
9
9
  export * from './BaseSales';
10
10
  export * from './VenueBooking';
11
11
  export * from './UnifiedBookingSales';
12
+ export * from './OrderInvoicePreview';
@@ -8,4 +8,5 @@ export * from "./Sales";
8
8
  export * from "./ScanOrder";
9
9
  export * from "./BaseSales";
10
10
  export * from "./VenueBooking";
11
- export * from "./UnifiedBookingSales";
11
+ export * from "./UnifiedBookingSales";
12
+ export * from "./OrderInvoicePreview";
package/lib/index.d.ts CHANGED
@@ -10,3 +10,5 @@ export * from './model';
10
10
  export { PisellOSCore } from './core';
11
11
  import PisellOSCore from './core';
12
12
  export default PisellOSCore;
13
+ export * from './shared/receipt/small-ticket';
14
+ export { loadSalesOrderSnapshot } from './shared/sales/loadSalesOrderSnapshot';
package/lib/index.js CHANGED
@@ -4,7 +4,8 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  var _exportNames = {
7
- PisellOSCore: true
7
+ PisellOSCore: true,
8
+ loadSalesOrderSnapshot: true
8
9
  };
9
10
  Object.defineProperty(exports, "PisellOSCore", {
10
11
  enumerable: true,
@@ -13,6 +14,12 @@ Object.defineProperty(exports, "PisellOSCore", {
13
14
  }
14
15
  });
15
16
  exports.default = void 0;
17
+ Object.defineProperty(exports, "loadSalesOrderSnapshot", {
18
+ enumerable: true,
19
+ get: function () {
20
+ return _loadSalesOrderSnapshot.loadSalesOrderSnapshot;
21
+ }
22
+ });
16
23
  var _types = require("./types");
17
24
  Object.keys(_types).forEach(function (key) {
18
25
  if (key === "default" || key === "__esModule") return;
@@ -74,6 +81,19 @@ Object.keys(_model).forEach(function (key) {
74
81
  });
75
82
  });
76
83
  var _core = _interopRequireWildcard(require("./core"));
84
+ var _smallTicket = require("./shared/receipt/small-ticket");
85
+ Object.keys(_smallTicket).forEach(function (key) {
86
+ if (key === "default" || key === "__esModule") return;
87
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
88
+ if (key in exports && exports[key] === _smallTicket[key]) return;
89
+ Object.defineProperty(exports, key, {
90
+ enumerable: true,
91
+ get: function () {
92
+ return _smallTicket[key];
93
+ }
94
+ });
95
+ });
96
+ var _loadSalesOrderSnapshot = require("./shared/sales/loadSalesOrderSnapshot");
77
97
  function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
78
98
  function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
79
99
  /**
@@ -1 +1,46 @@
1
- "use strict";
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "BUY_X_GET_Y_FREE_STRATEGY", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _examples.BUY_X_GET_Y_FREE_STRATEGY;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "ITEM_REWARD_STRATEGY", {
13
+ enumerable: true,
14
+ get: function () {
15
+ return _examples.ITEM_REWARD_STRATEGY;
16
+ }
17
+ });
18
+ Object.defineProperty(exports, "PromotionAdapter", {
19
+ enumerable: true,
20
+ get: function () {
21
+ return _adapter.PromotionAdapter;
22
+ }
23
+ });
24
+ Object.defineProperty(exports, "PromotionEvaluator", {
25
+ enumerable: true,
26
+ get: function () {
27
+ return _evaluator.PromotionEvaluator;
28
+ }
29
+ });
30
+ Object.defineProperty(exports, "X_ITEMS_FOR_Y_PRICE_STRATEGY", {
31
+ enumerable: true,
32
+ get: function () {
33
+ return _examples.X_ITEMS_FOR_Y_PRICE_STRATEGY;
34
+ }
35
+ });
36
+ Object.defineProperty(exports, "default", {
37
+ enumerable: true,
38
+ get: function () {
39
+ return _adapter.default;
40
+ }
41
+ });
42
+ var _evaluator = require("./evaluator");
43
+ var _adapter = _interopRequireWildcard(require("./adapter"));
44
+ var _examples = require("./examples");
45
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
46
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
@@ -0,0 +1,30 @@
1
+ import type { MultiLangObject } from '../OpenData/types';
2
+ import type { ScheduleItem } from '../Schedule/types';
3
+ export type BusinessClosedBehavior = 'show_menu_disabled' | 'hide_all';
4
+ export interface BusinessAvailability {
5
+ status: 'open' | 'paused' | 'closed' | 'error';
6
+ behavior: BusinessClosedBehavior | null;
7
+ message: string | MultiLangObject | null;
8
+ /** Epoch milliseconds. Re-evaluate the cached configuration at this time. */
9
+ nextChangeAt: number;
10
+ requirePaymentOnSubmit: boolean;
11
+ error?: string;
12
+ }
13
+ export interface BusinessAvailabilityConfig {
14
+ paused: boolean;
15
+ pauseBehavior: BusinessClosedBehavior;
16
+ closedBehavior: BusinessClosedBehavior;
17
+ pauseMessage: BusinessAvailability['message'];
18
+ closedMessage: BusinessAvailability['message'];
19
+ scheduleIds: number[];
20
+ invalidScheduleIds: boolean;
21
+ requirePaymentOnSubmit: boolean;
22
+ }
23
+ export declare function normalizeBusinessAvailabilityConfig(data: Record<string, unknown>): BusinessAvailabilityConfig;
24
+ /** Business ordering is independent of reservation switches and Pickup slot availability. */
25
+ export declare function computeBusinessAvailability(input: {
26
+ config: BusinessAvailabilityConfig;
27
+ schedules: ScheduleItem[];
28
+ timezone: string;
29
+ now: Date;
30
+ }): BusinessAvailability;
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.computeBusinessAvailability = computeBusinessAvailability;
7
+ exports.normalizeBusinessAvailabilityConfig = normalizeBusinessAvailabilityConfig;
8
+ var _dayjs = _interopRequireDefault(require("dayjs"));
9
+ var _isSameOrAfter = _interopRequireDefault(require("dayjs/plugin/isSameOrAfter"));
10
+ var _isSameOrBefore = _interopRequireDefault(require("dayjs/plugin/isSameOrBefore"));
11
+ var _getDateIsInSchedule = require("../Schedule/getDateIsInSchedule");
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+ _dayjs.default.extend(_isSameOrAfter.default);
14
+ _dayjs.default.extend(_isSameOrBefore.default);
15
+ const DAY = 86_400_000;
16
+ const behavior = value => value === 'show_menu_disabled' ? value : 'hide_all';
17
+ const message = value => typeof value === 'string' || value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
18
+ function normalizeBusinessAvailabilityConfig(data) {
19
+ const rawIds = data['availability.operating_hours'];
20
+ const ids = Array.isArray(rawIds) ? rawIds.map(id => typeof id === 'number' || typeof id === 'string' ? Number(id) : NaN) : [];
21
+ const validIds = ids.filter(id => Number.isInteger(id) && id > 0);
22
+ const paused = data['availability.paused'];
23
+ return {
24
+ paused: paused === true || paused === 1 || paused === 'true' || paused === '1',
25
+ pauseBehavior: behavior(data['availability.pause_behavior']),
26
+ closedBehavior: behavior(data['availability.closed_behavior']),
27
+ pauseMessage: message(data['availability.pause_message']),
28
+ closedMessage: message(data['availability.closed_message']),
29
+ scheduleIds: [...new Set(validIds)],
30
+ invalidScheduleIds: rawIds != null && (!Array.isArray(rawIds) || validIds.length !== ids.length),
31
+ // Only an explicitly disabled setting changes the existing payment flow.
32
+ requirePaymentOnSubmit: data['sale.require_payment_on_submit'] !== false
33
+ };
34
+ }
35
+ function createClock(timezone) {
36
+ if (!timezone) throw new Error('Store timezone is unavailable.');
37
+ const formatter = new Intl.DateTimeFormat('en-GB', {
38
+ timeZone: timezone,
39
+ year: 'numeric',
40
+ month: '2-digit',
41
+ day: '2-digit',
42
+ hour: '2-digit',
43
+ minute: '2-digit',
44
+ second: '2-digit',
45
+ hourCycle: 'h23'
46
+ });
47
+ const local = timestamp => {
48
+ const parts = {};
49
+ formatter.formatToParts(timestamp).forEach(part => {
50
+ parts[part.type] = part.value;
51
+ });
52
+ const date = `${parts.year}-${parts.month}-${parts.day}`;
53
+ return {
54
+ date,
55
+ scalar: Date.parse(`${date}T${parts.hour}:${parts.minute}:${parts.second}Z`)
56
+ };
57
+ };
58
+ const offsets = new Set();
59
+ const instants = scalar => {
60
+ offsets.clear();
61
+ for (let hours = -36; hours <= 36; hours += 6) {
62
+ const sample = scalar + hours * 3_600_000;
63
+ offsets.add(local(sample).scalar - sample);
64
+ }
65
+ return [...offsets].map(offset => scalar - offset).filter(instant => local(instant).scalar === scalar).sort((a, b) => a - b);
66
+ };
67
+ return {
68
+ local,
69
+ instants
70
+ };
71
+ }
72
+
73
+ /** Business ordering is independent of reservation switches and Pickup slot availability. */
74
+ function computeBusinessAvailability(input) {
75
+ const {
76
+ config,
77
+ schedules,
78
+ timezone,
79
+ now
80
+ } = input;
81
+ const nowAt = now.getTime();
82
+ const base = {
83
+ requirePaymentOnSubmit: config.requirePaymentOnSubmit,
84
+ nextChangeAt: nowAt + DAY
85
+ };
86
+ if (config.paused) {
87
+ return {
88
+ ...base,
89
+ status: 'paused',
90
+ behavior: config.pauseBehavior,
91
+ message: config.pauseMessage
92
+ };
93
+ }
94
+ if (config.invalidScheduleIds) throw new Error('Business operating-hours configuration is invalid.');
95
+ if (!config.scheduleIds.length) return {
96
+ ...base,
97
+ status: 'open',
98
+ behavior: null,
99
+ message: null
100
+ };
101
+ const selected = schedules.filter(schedule => config.scheduleIds.includes(Number(schedule.id)));
102
+ if (config.scheduleIds.some(id => !selected.some(schedule => Number(schedule.id) === id))) {
103
+ throw new Error('A configured business operating-hours schedule is unavailable.');
104
+ }
105
+ const clock = createClock(timezone);
106
+ const current = clock.local(nowAt);
107
+ const today = Date.parse(`${current.date}T00:00:00Z`);
108
+ const nextMidnight = clock.instants(today + DAY).find(instant => instant > nowAt);
109
+ let nextChangeAt = nextMidnight ?? nowAt + 60_000;
110
+ let open = false;
111
+ // Yesterday contributes the tail of overnight windows; today supplies the next boundary.
112
+ for (const dateAt of [today - DAY, today]) {
113
+ const date = new Date(dateAt).toISOString().slice(0, 10);
114
+ // Schedule's resolver merges by time-of-day, so resolve each schedule independently.
115
+ for (const schedule of selected) {
116
+ for (const window of (0, _getDateIsInSchedule.getScheduleStartEndTimePoints)(date, [schedule])) {
117
+ const toMinutes = value => {
118
+ if (!/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value) && value !== '24:00') {
119
+ throw new Error('Business operating-hours schedule contains an invalid time.');
120
+ }
121
+ const [hours, minutes] = value.split(':').map(Number);
122
+ return hours * 60 + minutes;
123
+ };
124
+ const start = dateAt + toMinutes(window.start_time) * 60_000;
125
+ let end = dateAt + toMinutes(window.end_time) * 60_000;
126
+ if (end <= start) end += DAY;
127
+ if (current.scalar >= start && current.scalar < end) open = true;
128
+ for (const boundary of [start, end]) {
129
+ for (const instant of clock.instants(boundary)) {
130
+ if (instant > nowAt) nextChangeAt = Math.min(nextChangeAt, instant);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ // A timezone offset change can repeat/skip a wall-clock boundary. A local-only safety
137
+ // check also covers throttled timers; it does not fetch either configuration source.
138
+ nextChangeAt = Math.min(nextChangeAt, nowAt + 60_000);
139
+ return {
140
+ ...base,
141
+ nextChangeAt,
142
+ status: open ? 'open' : 'closed',
143
+ behavior: open ? null : config.closedBehavior,
144
+ message: open ? null : config.closedMessage
145
+ };
146
+ }
@@ -0,0 +1,11 @@
1
+ import type { PickupTimingAvailability, PickupTimingBookingTimes, PickupTimingClockInput, PickupTimingComputeInput, PickupTimingConfig, PickupTimingSelection, PickupTimingSlot, PickupTimingValidationResult } from './types';
2
+ export * from './types';
3
+ /** Consume effective OpenData values only; legacy switches never enable Pickup. */
4
+ export declare function normalizePickupTimingConfig(openData: Record<string, unknown>): PickupTimingConfig;
5
+ export declare function resolvePickupTimingDateTime(date: string, time: string, timezone: string, instant?: string): PickupTimingSlot | undefined;
6
+ export declare function getAsapPickupTiming({ config, timezone, now }: PickupTimingClockInput): PickupTimingSlot;
7
+ export declare function pickupTimingSlotToBookingTimes(slot: PickupTimingSlot): PickupTimingBookingTimes;
8
+ export declare function computePickupTimingAvailability(input: PickupTimingComputeInput): PickupTimingAvailability;
9
+ export declare function validatePickupTimingSelection(selection: PickupTimingSelection, input: PickupTimingComputeInput & {
10
+ allowManualOverride?: boolean;
11
+ }): PickupTimingValidationResult;
@@ -0,0 +1,359 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ normalizePickupTimingConfig: true,
8
+ resolvePickupTimingDateTime: true,
9
+ getAsapPickupTiming: true,
10
+ pickupTimingSlotToBookingTimes: true,
11
+ computePickupTimingAvailability: true,
12
+ validatePickupTimingSelection: true
13
+ };
14
+ exports.computePickupTimingAvailability = computePickupTimingAvailability;
15
+ exports.getAsapPickupTiming = getAsapPickupTiming;
16
+ exports.normalizePickupTimingConfig = normalizePickupTimingConfig;
17
+ exports.pickupTimingSlotToBookingTimes = pickupTimingSlotToBookingTimes;
18
+ exports.resolvePickupTimingDateTime = resolvePickupTimingDateTime;
19
+ exports.validatePickupTimingSelection = validatePickupTimingSelection;
20
+ var _dayjs = _interopRequireDefault(require("dayjs"));
21
+ var _isSameOrAfter = _interopRequireDefault(require("dayjs/plugin/isSameOrAfter"));
22
+ var _isSameOrBefore = _interopRequireDefault(require("dayjs/plugin/isSameOrBefore"));
23
+ var _getDateIsInSchedule = require("../Schedule/getDateIsInSchedule");
24
+ var _types = require("./types");
25
+ Object.keys(_types).forEach(function (key) {
26
+ if (key === "default" || key === "__esModule") return;
27
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
28
+ if (key in exports && exports[key] === _types[key]) return;
29
+ Object.defineProperty(exports, key, {
30
+ enumerable: true,
31
+ get: function () {
32
+ return _types[key];
33
+ }
34
+ });
35
+ });
36
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
37
+ // The shared Schedule resolver uses these comparisons without registering them.
38
+ _dayjs.default.extend(_isSameOrAfter.default);
39
+ _dayjs.default.extend(_isSameOrBefore.default);
40
+ const MINUTE = 60_000;
41
+ const DAY = 24 * 60 * MINUTE;
42
+ const integerSetting = (value, min, max, fallback) => typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max ? value : fallback;
43
+
44
+ /** Consume effective OpenData values only; legacy switches never enable Pickup. */
45
+ function normalizePickupTimingConfig(openData) {
46
+ const handovers = openData['fulfillment.handover_mode'];
47
+ const scheduleIds = openData['fulfillment.pickup.schedule'];
48
+ const operatingHoursScheduleIds = openData['availability.operating_hours'];
49
+ const mode = openData['fulfillment.pickup.timing_mode'];
50
+ return {
51
+ handoverModes: Array.isArray(handovers) ? [...new Set(handovers.filter(value => typeof value === 'string' && value.length > 0))] : [],
52
+ timingMode: mode === 'scheduled_only' || mode === 'asap_and_scheduled' ? mode : 'asap_only',
53
+ scheduleIds: Array.isArray(scheduleIds) ? [...new Set(scheduleIds.filter(value => typeof value === 'number' && Number.isInteger(value) && value > 0))] : [],
54
+ operatingHoursScheduleIds: Array.isArray(operatingHoursScheduleIds) ? [...new Set(operatingHoursScheduleIds.map(value => typeof value === 'number' || typeof value === 'string' ? Number(value) : NaN).filter(value => Number.isInteger(value) && value > 0))] : [],
55
+ slotIntervalMinutes: integerSetting(openData['fulfillment.pickup.slot_interval_minutes'], 1, 1440, 15),
56
+ preparationTimeMinutes: integerSetting(openData['fulfillment.pickup.preparation_time_minutes'], 0, 1440, 0),
57
+ advanceDays: integerSetting(openData['fulfillment.pickup.advance_days'], 0, 365, 7),
58
+ fulfillmentRefMode: typeof openData['fulfillment.fulfillment_ref_mode'] === 'string' ? openData['fulfillment.fulfillment_ref_mode'] : undefined,
59
+ manualInputType: typeof openData['fulfillment.manual_input_type'] === 'string' ? openData['fulfillment.manual_input_type'] : undefined
60
+ };
61
+ }
62
+ function dateStamp(date) {
63
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return NaN;
64
+ const value = Date.parse(`${date}T00:00:00Z`);
65
+ return Number.isFinite(value) && new Date(value).toISOString().slice(0, 10) === date ? value : NaN;
66
+ }
67
+ function addDays(date, days) {
68
+ return new Date(dateStamp(date) + days * DAY).toISOString().slice(0, 10);
69
+ }
70
+ function timeMinutes(time, allowDayEnd = false) {
71
+ if (!/^\d{2}:\d{2}(?::00)?$/.test(time)) return NaN;
72
+ const [hours, minutes] = time.split(':').map(Number);
73
+ if (allowDayEnd && hours === 24 && minutes === 0) return 1440;
74
+ return hours < 24 && minutes < 60 ? hours * 60 + minutes : NaN;
75
+ }
76
+ function instantStamp(value) {
77
+ // A local string would silently use the device timezone instead of the store.
78
+ if (typeof value === 'string' && !/(Z|[+-]\d{2}:?\d{2})$/i.test(value)) return NaN;
79
+ return value instanceof Date ? value.getTime() : new Date(value).getTime();
80
+ }
81
+
82
+ /** Per-query timezone adapter; no device-offset arithmetic or global time cache. */
83
+ function createClock(timezone) {
84
+ if (!timezone || typeof timezone !== 'string') throw new Error('Store timezone is unavailable.');
85
+ let formatter;
86
+ try {
87
+ formatter = new Intl.DateTimeFormat('en-GB', {
88
+ timeZone: timezone,
89
+ year: 'numeric',
90
+ month: '2-digit',
91
+ day: '2-digit',
92
+ hour: '2-digit',
93
+ minute: '2-digit',
94
+ second: '2-digit',
95
+ hourCycle: 'h23'
96
+ });
97
+ } catch {
98
+ throw new Error('Store timezone is invalid.');
99
+ }
100
+ const offsetsByDate = new Map();
101
+ const local = timestamp => {
102
+ const parts = {};
103
+ formatter.formatToParts(timestamp).forEach(part => {
104
+ parts[part.type] = part.value;
105
+ });
106
+ return {
107
+ date: `${parts.year}-${parts.month}-${parts.day}`,
108
+ time: `${parts.hour}:${parts.minute}`,
109
+ second: parts.second
110
+ };
111
+ };
112
+ const offsets = date => {
113
+ const cached = offsetsByDate.get(date);
114
+ if (cached) return cached;
115
+ const result = new Set();
116
+ const nominal = dateStamp(date);
117
+ // Sampling both sides of the target day discovers pre/post-transition offsets.
118
+ for (let hours = -36; hours <= 36; hours += 6) {
119
+ const sample = nominal + hours * 60 * MINUTE;
120
+ const wall = local(sample);
121
+ result.add(Date.parse(`${wall.date}T${wall.time}:${wall.second}Z`) - sample);
122
+ }
123
+ const values = [...result];
124
+ offsetsByDate.set(date, values);
125
+ return values;
126
+ };
127
+ const resolve = (date, time) => {
128
+ const day = dateStamp(date);
129
+ const minutes = timeMinutes(time);
130
+ if (!Number.isFinite(day) || !Number.isFinite(minutes)) return [];
131
+ const label = time.slice(0, 5);
132
+ const nominal = day + minutes * MINUTE;
133
+ return offsets(date).map(offset => nominal - offset).filter(timestamp => {
134
+ const wall = local(timestamp);
135
+ return wall.date === date && wall.time === label;
136
+ }).sort((a, b) => a - b);
137
+ };
138
+ const slot = timestamp => {
139
+ const {
140
+ date,
141
+ time
142
+ } = local(timestamp);
143
+ const instant = new Date(timestamp).toISOString();
144
+ return {
145
+ id: instant,
146
+ date,
147
+ time,
148
+ instant
149
+ };
150
+ };
151
+ return {
152
+ local,
153
+ resolve,
154
+ slot,
155
+ hasOffsetTransition: date => offsets(date).length > 1
156
+ };
157
+ }
158
+ function resolvePickupTimingDateTime(date, time, timezone, instant) {
159
+ const clock = createClock(timezone);
160
+ const matches = clock.resolve(date, time);
161
+ const selected = instant ? instantStamp(instant) : matches.length === 1 ? matches[0] : NaN;
162
+ return matches.includes(selected) ? clock.slot(selected) : undefined;
163
+ }
164
+ function getAsapPickupTiming({
165
+ config,
166
+ timezone,
167
+ now
168
+ }) {
169
+ const timestamp = instantStamp(now);
170
+ if (!Number.isFinite(timestamp)) throw new Error('Current time is invalid.');
171
+ return createClock(timezone).slot(timestamp + config.preparationTimeMinutes * MINUTE);
172
+ }
173
+ function pickupTimingSlotToBookingTimes(slot) {
174
+ return {
175
+ start_date: slot.date,
176
+ start_time: slot.time,
177
+ end_date: slot.date,
178
+ end_time: slot.time
179
+ };
180
+ }
181
+ function createEvaluation(input) {
182
+ const {
183
+ config,
184
+ timezone
185
+ } = input;
186
+ const clock = createClock(timezone);
187
+ const now = instantStamp(input.now);
188
+ if (!Number.isFinite(now)) throw new Error('Current time is invalid.');
189
+ const today = clock.local(now).date;
190
+ const maxDate = addDays(today, config.advanceDays);
191
+ const earliest = now + config.preparationTimeMinutes * MINUTE;
192
+ const schedules = input.schedules.filter(schedule => config.scheduleIds.includes(schedule.id));
193
+ const windowCache = new Map();
194
+ const windows = date => {
195
+ if (!windowCache.has(date)) {
196
+ windowCache.set(date, (0, _getDateIsInSchedule.getScheduleStartEndTimePoints)(date, schedules));
197
+ }
198
+ return windowCache.get(date);
199
+ };
200
+ const operatingIds = config.operatingHoursScheduleIds || [];
201
+ const operatingSchedules = input.schedules.filter(schedule => operatingIds.includes(schedule.id));
202
+ const operatingWindowCache = new Map();
203
+ const operatingWindows = date => {
204
+ if (!operatingWindowCache.has(date)) {
205
+ const ranges = [];
206
+ for (const offset of [-1, 0]) {
207
+ for (const window of (0, _getDateIsInSchedule.getScheduleStartEndTimePoints)(addDays(date, offset), operatingSchedules)) {
208
+ const start = timeMinutes(window.start_time);
209
+ let end = timeMinutes(window.end_time, true);
210
+ if (!Number.isFinite(start) || !Number.isFinite(end)) continue;
211
+ // Store hours use equal endpoints for a full operating day, while
212
+ // the Pickup Schedule may deliberately contain a single time point.
213
+ if (end <= start) end += 1440;
214
+ ranges.push({
215
+ start: start + offset * 1440,
216
+ end: end + offset * 1440
217
+ });
218
+ }
219
+ }
220
+ operatingWindowCache.set(date, ranges);
221
+ }
222
+ return operatingWindowCache.get(date);
223
+ };
224
+ const slotsForDate = (date, firstOnly = false) => {
225
+ if (!Number.isFinite(dateStamp(date)) || date < today || date > maxDate || !config.handoverModes.includes('pick_up') || config.timingMode === 'asap_only') return [];
226
+ const found = new Map();
227
+ // Missing hours configuration preserves the existing all-day convention.
228
+ // Referenced but missing schedules yield no windows, never an all-day fallback.
229
+ const businessWindows = operatingIds.length ? operatingWindows(date) : undefined;
230
+ // Include the prior day's windows so overnight tails belong to their actual date.
231
+ for (const windowDate of [addDays(date, -1), date]) {
232
+ for (const window of windows(windowDate)) {
233
+ const start = timeMinutes(window.start_time);
234
+ let end = timeMinutes(window.end_time, true);
235
+ if (!Number.isFinite(start) || !Number.isFinite(end)) continue;
236
+ if (end < start) end += 1440;
237
+ let firstFoundInWindow = false;
238
+ for (let minute = start; minute <= end; minute += config.slotIntervalMinutes) {
239
+ const targetDate = minute >= 1440 ? addDays(windowDate, 1) : windowDate;
240
+ if (targetDate !== date) continue;
241
+ const localMinute = minute % 1440;
242
+ // Filter the original Pickup grid rather than moving its anchor to
243
+ // the store opening time. A zero-duration pickup may be at closing.
244
+ if (businessWindows && !businessWindows.some(({
245
+ start,
246
+ end
247
+ }) => localMinute >= start && localMinute <= end)) continue;
248
+ const time = `${String(Math.floor(localMinute / 60)).padStart(2, '0')}:${String(localMinute % 60).padStart(2, '0')}`;
249
+ for (const timestamp of clock.resolve(date, time)) {
250
+ if (timestamp < earliest) continue;
251
+ found.set(timestamp, clock.slot(timestamp));
252
+ firstFoundInWindow = true;
253
+ }
254
+ // Summary needs only an available candidate, not a full year's slots.
255
+ // During a repeated hour, an earlier wall label's second occurrence can
256
+ // be later than a subsequent label's first occurrence. Sort them all.
257
+ if (firstOnly && firstFoundInWindow && !clock.hasOffsetTransition(date)) break;
258
+ }
259
+ }
260
+ }
261
+ const result = [...found.entries()].sort(([a], [b]) => a - b).map(([, slot]) => slot);
262
+ return firstOnly ? result.slice(0, 1) : result;
263
+ };
264
+ return {
265
+ clock,
266
+ now,
267
+ today,
268
+ maxDate,
269
+ slotsForDate
270
+ };
271
+ }
272
+ function computePickupTimingAvailability(input) {
273
+ if (!input.config.handoverModes.includes('pick_up')) {
274
+ const now = instantStamp(input.now);
275
+ if (!Number.isFinite(now)) throw new Error('Current time is invalid.');
276
+ return {
277
+ config: input.config,
278
+ timezone: input.timezone,
279
+ now: new Date(now).toISOString(),
280
+ today: '',
281
+ maxDate: '',
282
+ date: input.date || '',
283
+ dates: [],
284
+ slots: []
285
+ };
286
+ }
287
+ const evaluation = createEvaluation(input);
288
+ const {
289
+ today,
290
+ maxDate,
291
+ slotsForDate
292
+ } = evaluation;
293
+ const date = input.date || today;
294
+ if (!Number.isFinite(dateStamp(date))) throw new Error('Pickup date is invalid.');
295
+ const slots = slotsForDate(date);
296
+ const dates = [];
297
+ let firstSlot;
298
+ for (let day = today; day <= maxDate; day = addDays(day, 1)) {
299
+ const first = day === date ? slots[0] : slotsForDate(day, true)[0];
300
+ dates.push({
301
+ date: day,
302
+ status: first ? 'available' : 'unavailable'
303
+ });
304
+ if (!firstSlot && first) firstSlot = first;
305
+ }
306
+ return {
307
+ config: input.config,
308
+ timezone: input.timezone,
309
+ now: new Date(evaluation.now).toISOString(),
310
+ today,
311
+ maxDate,
312
+ date,
313
+ dates,
314
+ slots,
315
+ firstSlot
316
+ };
317
+ }
318
+ function validatePickupTimingSelection(selection, input) {
319
+ const fail = (code, message) => ({
320
+ valid: false,
321
+ code,
322
+ message
323
+ });
324
+ const {
325
+ config
326
+ } = input;
327
+ if (config.handoverModes.length === 0) return {
328
+ valid: true
329
+ };
330
+ if (!config.handoverModes.includes(selection.serviceType)) {
331
+ return fail('handover_unavailable', 'Choose an available handover method.');
332
+ }
333
+ if (selection.serviceType !== 'pick_up') return {
334
+ valid: true
335
+ };
336
+ if (selection.mode === 'asap') {
337
+ return config.timingMode === 'scheduled_only' ? fail('scheduled_required', 'Choose a pickup date and time.') : {
338
+ valid: true,
339
+ slot: getAsapPickupTiming(input)
340
+ };
341
+ }
342
+ if (selection.mode !== 'scheduled' || config.timingMode === 'asap_only') {
343
+ return fail('mode_unavailable', 'The selected pickup timing mode is unavailable.');
344
+ }
345
+ const slot = resolvePickupTimingDateTime(selection.date || '', selection.time || '', input.timezone, selection.instant);
346
+ if (!slot) return fail('invalid_time', 'Choose a valid pickup date and time.');
347
+ const now = instantStamp(input.now);
348
+ if (!Number.isFinite(now)) throw new Error('Current time is invalid.');
349
+ if (instantStamp(slot.instant) < now) return fail('time_in_past', 'Pickup time cannot be in the past.');
350
+ if (selection.source === 'pos_manual' && input.allowManualOverride) return {
351
+ valid: true,
352
+ slot
353
+ };
354
+ const legal = createEvaluation(input).slotsForDate(slot.date).some(candidate => candidate.instant === slot.instant);
355
+ return legal ? {
356
+ valid: true,
357
+ slot
358
+ } : fail('time_unavailable', 'This pickup time is no longer available. Choose another time.');
359
+ }