@pisell/pisellos 2.3.128 → 2.3.130

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 (160) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +3 -1
  3. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  4. package/dist/model/strategy/adapter/walletPass/evaluator.d.ts +2 -0
  5. package/dist/model/strategy/adapter/walletPass/evaluator.js +4 -2
  6. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +58 -19
  7. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +24 -12
  8. package/dist/modules/Customer/index.js +6 -3
  9. package/dist/modules/Customer/types.d.ts +2 -0
  10. package/dist/modules/Discount/availability.d.ts +7 -0
  11. package/dist/modules/Discount/availability.js +49 -0
  12. package/dist/modules/Discount/entitlementPass.d.ts +34 -0
  13. package/dist/modules/Discount/entitlementPass.js +147 -0
  14. package/dist/modules/Discount/index.d.ts +2 -2
  15. package/dist/modules/Discount/index.js +37 -151
  16. package/dist/modules/Discount/types.d.ts +36 -5
  17. package/dist/modules/FulfillmentTiming/index.d.ts +11 -0
  18. package/dist/modules/FulfillmentTiming/index.js +407 -0
  19. package/dist/modules/FulfillmentTiming/types.d.ts +67 -0
  20. package/dist/modules/FulfillmentTiming/types.js +1 -0
  21. package/dist/modules/OpenData/types.d.ts +6 -0
  22. package/dist/modules/Order/index.d.ts +12 -0
  23. package/dist/modules/Order/index.js +498 -247
  24. package/dist/modules/Order/pickupTiming.d.ts +46 -0
  25. package/dist/modules/Order/pickupTiming.js +53 -0
  26. package/dist/modules/Order/types.d.ts +5 -1
  27. package/dist/modules/Order/utils/orderCollectionIdentity.js +16 -12
  28. package/dist/modules/Order/utils.d.ts +1 -1
  29. package/dist/modules/Order/utils.js +117 -66
  30. package/dist/modules/Payment/index.js +9 -10
  31. package/dist/modules/Payment/types.d.ts +21 -1
  32. package/dist/modules/Payment/types.js +2 -0
  33. package/dist/modules/Payment/walletpass.d.ts +1 -1
  34. package/dist/modules/Payment/walletpass.js +80 -47
  35. package/dist/modules/Rules/index.d.ts +2 -2
  36. package/dist/modules/Rules/index.js +480 -186
  37. package/dist/modules/Rules/types.d.ts +4 -0
  38. package/dist/modules/Schedule/index.d.ts +8 -0
  39. package/dist/modules/Schedule/index.js +141 -39
  40. package/dist/modules/index.d.ts +1 -0
  41. package/dist/modules/index.js +1 -0
  42. package/dist/plugins/request.d.ts +7 -0
  43. package/dist/server/modules/order/types.d.ts +2 -0
  44. package/dist/server/utils/small-ticket.d.ts +1 -85
  45. package/dist/server/utils/small-ticket.js +2 -2542
  46. package/dist/shared/payment/loadPaymentMethods.d.ts +9 -0
  47. package/dist/shared/payment/loadPaymentMethods.js +66 -0
  48. package/dist/shared/receipt/loadCustomerInvoiceLayout.d.ts +22 -0
  49. package/dist/shared/receipt/loadCustomerInvoiceLayout.js +142 -0
  50. package/dist/shared/receipt/small-ticket.d.ts +85 -0
  51. package/dist/shared/receipt/small-ticket.js +2576 -0
  52. package/dist/shared/sales/loadSalesOrderSnapshot.d.ts +9 -0
  53. package/dist/shared/sales/loadSalesOrderSnapshot.js +21 -0
  54. package/dist/solution/BaseSales/index.d.ts +25 -0
  55. package/dist/solution/BaseSales/index.js +1226 -1040
  56. package/dist/solution/BaseSales/pickupTiming.d.ts +43 -0
  57. package/dist/solution/BaseSales/pickupTiming.js +589 -0
  58. package/dist/solution/BaseSales/types.d.ts +2 -2
  59. package/dist/solution/BaseSales/utils/cartPromotion.js +141 -126
  60. package/dist/solution/BaseSales/utils/parseSalesResponse.js +3 -0
  61. package/dist/solution/BookingByStep/index.d.ts +1 -1
  62. package/dist/solution/BookingTicket/index.d.ts +4 -5
  63. package/dist/solution/BookingTicket/index.js +60 -63
  64. package/dist/solution/BookingTicket/types.d.ts +5 -1
  65. package/dist/solution/BookingTicket/utils/cartView.js +3 -1
  66. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +2 -0
  67. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +338 -147
  68. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +8 -4
  69. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +6 -0
  70. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.js +19 -6
  71. package/dist/solution/OrderInvoicePreview/index.d.ts +56 -0
  72. package/dist/solution/OrderInvoicePreview/index.js +269 -0
  73. package/dist/solution/ShopDiscount/index.d.ts +2 -0
  74. package/dist/solution/ShopDiscount/index.js +99 -42
  75. package/dist/solution/ShopDiscount/utils.d.ts +4 -2
  76. package/dist/solution/ShopDiscount/utils.js +43 -23
  77. package/dist/solution/UnifiedBookingSales/index.d.ts +13 -4
  78. package/dist/solution/UnifiedBookingSales/index.js +874 -709
  79. package/dist/solution/index.d.ts +1 -0
  80. package/dist/solution/index.js +2 -1
  81. package/lib/index.d.ts +2 -0
  82. package/lib/index.js +21 -1
  83. package/lib/model/strategy/adapter/walletPass/evaluator.d.ts +2 -0
  84. package/lib/model/strategy/adapter/walletPass/evaluator.js +2 -0
  85. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +35 -6
  86. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +13 -6
  87. package/lib/modules/Customer/index.js +5 -1
  88. package/lib/modules/Customer/types.d.ts +2 -0
  89. package/lib/modules/Discount/availability.d.ts +7 -0
  90. package/lib/modules/Discount/availability.js +43 -0
  91. package/lib/modules/Discount/entitlementPass.d.ts +34 -0
  92. package/lib/modules/Discount/entitlementPass.js +141 -0
  93. package/lib/modules/Discount/index.d.ts +2 -2
  94. package/lib/modules/Discount/index.js +23 -129
  95. package/lib/modules/Discount/types.d.ts +36 -5
  96. package/lib/modules/FulfillmentTiming/index.d.ts +11 -0
  97. package/lib/modules/FulfillmentTiming/index.js +359 -0
  98. package/lib/modules/FulfillmentTiming/types.d.ts +67 -0
  99. package/lib/modules/FulfillmentTiming/types.js +5 -0
  100. package/lib/modules/OpenData/types.d.ts +6 -0
  101. package/lib/modules/Order/index.d.ts +12 -0
  102. package/lib/modules/Order/index.js +252 -48
  103. package/lib/modules/Order/pickupTiming.d.ts +46 -0
  104. package/lib/modules/Order/pickupTiming.js +61 -0
  105. package/lib/modules/Order/types.d.ts +5 -1
  106. package/lib/modules/Order/utils/orderCollectionIdentity.js +14 -11
  107. package/lib/modules/Order/utils.d.ts +1 -1
  108. package/lib/modules/Order/utils.js +51 -7
  109. package/lib/modules/Payment/index.js +3 -4
  110. package/lib/modules/Payment/types.d.ts +21 -1
  111. package/lib/modules/Payment/types.js +1 -0
  112. package/lib/modules/Payment/walletpass.d.ts +1 -1
  113. package/lib/modules/Payment/walletpass.js +29 -9
  114. package/lib/modules/Rules/index.d.ts +2 -2
  115. package/lib/modules/Rules/index.js +357 -110
  116. package/lib/modules/Rules/types.d.ts +4 -0
  117. package/lib/modules/Schedule/index.d.ts +8 -0
  118. package/lib/modules/Schedule/index.js +68 -12
  119. package/lib/modules/index.d.ts +1 -0
  120. package/lib/modules/index.js +11 -0
  121. package/lib/plugins/request.d.ts +7 -0
  122. package/lib/server/modules/order/types.d.ts +2 -0
  123. package/lib/server/utils/small-ticket.d.ts +1 -85
  124. package/lib/server/utils/small-ticket.js +9 -2305
  125. package/lib/shared/payment/loadPaymentMethods.d.ts +9 -0
  126. package/lib/shared/payment/loadPaymentMethods.js +40 -0
  127. package/lib/shared/receipt/loadCustomerInvoiceLayout.d.ts +22 -0
  128. package/lib/shared/receipt/loadCustomerInvoiceLayout.js +86 -0
  129. package/lib/shared/receipt/small-ticket.d.ts +85 -0
  130. package/lib/shared/receipt/small-ticket.js +2342 -0
  131. package/lib/shared/sales/loadSalesOrderSnapshot.d.ts +9 -0
  132. package/lib/shared/sales/loadSalesOrderSnapshot.js +22 -0
  133. package/lib/solution/BaseSales/index.d.ts +25 -0
  134. package/lib/solution/BaseSales/index.js +102 -3
  135. package/lib/solution/BaseSales/pickupTiming.d.ts +43 -0
  136. package/lib/solution/BaseSales/pickupTiming.js +269 -0
  137. package/lib/solution/BaseSales/types.d.ts +2 -2
  138. package/lib/solution/BaseSales/utils/cartPromotion.js +12 -4
  139. package/lib/solution/BaseSales/utils/parseSalesResponse.js +3 -0
  140. package/lib/solution/BookingByStep/index.d.ts +1 -1
  141. package/lib/solution/BookingTicket/index.d.ts +4 -5
  142. package/lib/solution/BookingTicket/index.js +36 -33
  143. package/lib/solution/BookingTicket/types.d.ts +5 -1
  144. package/lib/solution/BookingTicket/utils/cartView.js +3 -1
  145. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +2 -0
  146. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +174 -42
  147. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +8 -4
  148. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +6 -0
  149. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.js +11 -3
  150. package/lib/solution/OrderInvoicePreview/index.d.ts +56 -0
  151. package/lib/solution/OrderInvoicePreview/index.js +192 -0
  152. package/lib/solution/ShopDiscount/index.d.ts +2 -0
  153. package/lib/solution/ShopDiscount/index.js +55 -9
  154. package/lib/solution/ShopDiscount/utils.d.ts +4 -2
  155. package/lib/solution/ShopDiscount/utils.js +42 -25
  156. package/lib/solution/UnifiedBookingSales/index.d.ts +13 -4
  157. package/lib/solution/UnifiedBookingSales/index.js +132 -48
  158. package/lib/solution/index.d.ts +1 -0
  159. package/lib/solution/index.js +11 -0
  160. package/package.json +1 -1
@@ -8,6 +8,7 @@ var _utils = require("../../solution/ShopDiscount/utils");
8
8
  var _BaseModule = require("../BaseModule");
9
9
  var _types = require("./types");
10
10
  var _decimal = _interopRequireDefault(require("decimal.js"));
11
+ var _availability = require("./availability");
11
12
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
13
  class DiscountModule extends _BaseModule.BaseModule {
13
14
  defaultName = 'discount';
@@ -83,7 +84,13 @@ class DiscountModule extends _BaseModule.BaseModule {
83
84
  with_available_wallet_pass_flag: params.with_available_wallet_pass_flag ?? 1,
84
85
  with_virtual_currency: params.with_virtual_currency ?? 1
85
86
  });
86
- const rawDiscountList = [...(prepareConfig?.data?.good_pass_list || []), ...(prepareConfig?.data?.discount_card_list || [])];
87
+ const entitlementPassList = prepareConfig?.data?.entitlement_pass_list || [];
88
+ const entitlementPassIds = new Set(entitlementPassList.map(discount => discount?.id).filter(id => id !== undefined && id !== null).map(id => String(id)));
89
+ const excludeEntitlementDuplicates = discount => {
90
+ const id = discount?.id;
91
+ return id === undefined || id === null || !entitlementPassIds.has(String(id));
92
+ };
93
+ const rawDiscountList = [...entitlementPassList, ...(prepareConfig?.data?.good_pass_list || []).filter(excludeEntitlementDuplicates), ...(prepareConfig?.data?.discount_card_list || []).filter(excludeEntitlementDuplicates)];
87
94
  const availableWalletList = [...(prepareConfig?.data?.avaiable_wallet_list || []), ...(prepareConfig?.data?.available_wallet_list || [])];
88
95
  const availableWalletPassList = prepareConfig?.data?.available_wallet_pass_list || [];
89
96
  const availableWalletIds = this.normalizePositiveNumberIds([...availableWalletList.map(item => item?.wallet_id), ...availableWalletPassList.map(item => item?.product_id)]);
@@ -135,7 +142,7 @@ class DiscountModule extends _BaseModule.BaseModule {
135
142
  const result = await this.request.get(`/machinecode/batch-search`, {
136
143
  code,
137
144
  translate_flag: 1,
138
- tags: ['good_pass', 'product_discount_card'],
145
+ tags: ['entitlement_pass', 'good_pass', 'product_discount_card'],
139
146
  // available: 1,
140
147
  relation_product: 1,
141
148
  with: ['extensionData', 'customScheduleSnapshot', 'holder.detail'],
@@ -154,143 +161,30 @@ class DiscountModule extends _BaseModule.BaseModule {
154
161
  const result = await this.request.get(`/machinecode/batch-search`, {
155
162
  ids: productIds,
156
163
  translate_flag: 1,
157
- tags: ['good_pass', 'product_discount_card'],
158
- relation_product: 1
164
+ tags: ['entitlement_pass', 'good_pass', 'product_discount_card'],
165
+ relation_product: 1,
166
+ with: ['extensionData', 'customScheduleSnapshot', 'holder.detail'],
167
+ unified_status_info_flag: 1,
168
+ request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
159
169
  });
160
170
  return result?.data || [];
161
171
  }
162
- filterEnabledDiscountList(discountList) {
163
- return discountList.filter(discount => discount.limit_status === 'enable' && new _decimal.default(discount?.par_value || 0).minus(new _decimal.default(discount?.used_par_value || 0)).greaterThan(0) && this.checkUsageCreditsLimit(discount));
164
- }
165
-
166
- // 检查使用次数限制
167
- checkUsageCreditsLimit(discount) {
168
- // 如果没有 extension_data,则不需要限制
169
- if (!discount.extension_data || discount.extension_data.length === 0) {
170
- return true;
171
- }
172
-
173
- // 查找 field_key 为 usage_credits 的数据
174
- const usageCreditsData = discount.extension_data.find(data => data.field_key === 'usage_credits');
175
-
176
- // 如果没有找到 usage_credits 数据,则不需要限制
177
- if (!usageCreditsData) {
178
- return true;
179
- }
180
- const value = usageCreditsData.value;
181
-
182
- // 检查总次数限制
183
- if (value.total_credits && value.total_credits > 0) {
184
- if ((discount.total_order_behavior_count || 0) >= value.total_credits) {
185
- return false;
186
- }
187
- }
188
172
 
189
- // 检查单用户限制
190
- if (value.per_user_limit && value.per_user_limit > 0) {
191
- if ((discount.customer_order_behavior_count || 0) >= value.per_user_limit) {
192
- return false;
193
- }
194
- }
195
-
196
- // 检查单日限制
197
- if (value.max_per_day && value.max_per_day > 0) {
198
- if ((discount.today_order_behavior_count || 0) >= value.max_per_day) {
199
- return false;
200
- }
201
- }
202
-
203
- // 检查单周限制
204
- if (value.max_per_week && value.max_per_week > 0) {
205
- if ((discount.week_order_behavior_count || 0) >= value.max_per_week) {
206
- return false;
207
- }
208
- }
209
-
210
- // 检查单月限制
211
- if (value.max_per_month && value.max_per_month > 0) {
212
- if ((discount.month_order_behavior_count || 0) >= value.max_per_month) {
213
- return false;
214
- }
215
- }
216
-
217
- // 所有检查都通过
218
- return true;
173
+ // 展示列表只剔除已失效项,当前不可用项保留并携带原因。
174
+ filterEnabledDiscountList(discountList) {
175
+ return discountList.filter(discount => discount.limit_status === 'enable' && (0, _availability.hasAvailableDiscountBalance)(discount) && !(0, _availability.getDiscountLifecycleReason)(discount)).map(discount => ({
176
+ ...discount,
177
+ usageLimitFailKey: (0, _availability.getDiscountUsageLimitFailKey)(discount),
178
+ reasonCode: (0, _availability.getDiscountUsageBlockReason)(discount)
179
+ }));
219
180
  }
220
-
221
- // 过滤启用且可用的优惠券,并返回校验失败原因
222
181
  filterEnabledDiscountListWithReason(discountList) {
223
- let lists = discountList.filter(discount => discount.limit_status === 'enable').filter(discount => {
224
- const remaining = new _decimal.default(discount?.par_value || 0).minus(new _decimal.default(discount?.used_par_value || 0)).greaterThan(0);
225
- return remaining;
226
- }).map(discount => {
227
- const limitFailKey = this.checkUsageCreditsLimitWithFailKey(discount);
228
- return {
229
- ...discount,
230
- usageLimitFailKey: limitFailKey
231
- };
232
- });
233
-
234
- // 可用的列表
235
- const availableLists = lists.filter(item => !item.usageLimitFailKey && item.unified_available_status !== 0);
236
- // 不可用数据
237
- const currentFailDiscount = lists.find(item => item.usageLimitFailKey);
238
182
  return {
239
- discountList: availableLists,
240
- unavailableReasonKey: currentFailDiscount?.usageLimitFailKey
183
+ discountList: this.filterEnabledDiscountList(discountList),
184
+ unavailableReasonKey: discountList.map(_availability.getDiscountUsageLimitFailKey).find(key => key !== null) || null
241
185
  };
242
186
  }
243
187
 
244
- // 检查使用次数限制,并返回校验失败原因
245
- checkUsageCreditsLimitWithFailKey(discount) {
246
- if (!discount.extension_data || discount.extension_data.length === 0) {
247
- return null;
248
- }
249
- const usageCreditsData = discount.extension_data.find(data => data.field_key === 'usage_credits');
250
- if (!usageCreditsData) {
251
- return null;
252
- }
253
- const value = usageCreditsData.value;
254
-
255
- // 总次数限制
256
- if (value.total_credits && value.total_credits > 0) {
257
- if ((discount.total_order_behavior_count || 0) >= value.total_credits) {
258
- return 'total_credits';
259
- }
260
- }
261
-
262
- // 单用户限制
263
- if (value.per_user_limit && value.per_user_limit > 0) {
264
- if ((discount.customer_order_behavior_count || 0) >= value.per_user_limit) {
265
- return 'per_user_limit';
266
- }
267
- }
268
-
269
- // 单日限制
270
- if (value.max_per_day && value.max_per_day > 0) {
271
- if ((discount.today_order_behavior_count || 0) >= value.max_per_day) {
272
- return 'max_per_day';
273
- }
274
- }
275
-
276
- // 单周限制
277
- if (value.max_per_week && value.max_per_week > 0) {
278
- if ((discount.week_order_behavior_count || 0) >= value.max_per_week) {
279
- return 'max_per_week';
280
- }
281
- }
282
-
283
- // 单月限制
284
- if (value.max_per_month && value.max_per_month > 0) {
285
- if ((discount.month_order_behavior_count || 0) >= value.max_per_month) {
286
- return 'max_per_month';
287
- }
288
- }
289
-
290
- // 全部通过
291
- return null;
292
- }
293
-
294
188
  // 根据productIds去重
295
189
  uniqueByProductId(discountList) {
296
190
  return (0, _utils.uniqueById)(discountList, 'product_id');
@@ -44,7 +44,10 @@ interface ApplicableProductDetails {
44
44
  original_amount: string;
45
45
  num: number;
46
46
  metadata?: {
47
+ encoded?: string;
47
48
  product_discount_difference?: number;
49
+ /** 月卡扣除本单新增使用后的剩余次数;不限次数时为 null。 */
50
+ balance?: number | null;
48
51
  };
49
52
  discount?: {
50
53
  fixed_amount?: number;
@@ -63,6 +66,13 @@ interface UsageCreditsValue {
63
66
  max_per_week: number;
64
67
  max_per_month: number;
65
68
  }
69
+ export type IncludedUses = {
70
+ type: 'limited';
71
+ value: number;
72
+ } | {
73
+ type: 'unlimited';
74
+ value: null;
75
+ };
66
76
  export type DiscountFilterRejectKey = 'total_credits' | 'per_user_limit' | 'max_per_day' | 'max_per_week' | 'max_per_month';
67
77
  export interface DiscountWithReason {
68
78
  discountList: Discount[];
@@ -107,30 +117,37 @@ interface ExtensionData {
107
117
  }
108
118
  export interface Discount {
109
119
  id: number;
120
+ shop_id?: number;
110
121
  product_name: string;
111
122
  encoded: string;
112
123
  code: string;
113
124
  tag: string;
114
- expire_time?: string;
125
+ expire_time?: string | null;
126
+ expire_date?: string | null;
127
+ end_time?: string | null;
115
128
  product_id: number;
116
129
  relation_type: string;
117
130
  par_value: string;
118
131
  used_par_value: string;
119
132
  limit_status: string;
120
133
  limited_relation_product_data: Limitedrelationproductdata;
121
- balance: string;
134
+ balance?: string | number | null;
135
+ available_num?: number;
136
+ available_products_info?: any[];
122
137
  format_title: Formattitle;
123
138
  metadata?: {
139
+ encoded?: string;
124
140
  discount_card_type?: 'fixed_amount' | 'percent';
125
141
  custom_product_bundle_map_id?: string;
126
142
  validity_type?: "custom_schedule_validity" | "fixed_validity";
127
- discount_calculation_mode: 'item_level' | 'order_level';
128
- holder: {
143
+ included_uses?: IncludedUses;
144
+ discount_calculation_mode?: 'item_level' | 'order_level';
145
+ holder?: {
129
146
  type: "customer" | "custom";
130
147
  };
131
148
  };
132
149
  product: Product;
133
- type: "product" | 'good_pass';
150
+ type?: "product" | 'good_pass' | 'entitlement_pass' | 'discount_card' | 'product_discount_card';
134
151
  resource_id?: number;
135
152
  savedAmount?: number;
136
153
  isEditMode?: boolean;
@@ -163,9 +180,17 @@ export interface Discount {
163
180
  applicableProductIds?: number[];
164
181
  applicableProductDetails: ApplicableProductDetails[];
165
182
  appliedProductDetails: ApplicableProductDetails[];
183
+ /** Entitlement Pass 编辑订单时已经提交的使用明细。 */
184
+ committedAppliedProductDetails?: ApplicableProductDetails[];
166
185
  isDisabledForProductUsed?: boolean;
167
186
  amount?: number;
168
187
  customer_id?: number | string | null;
188
+ holder?: {
189
+ holder_type?: 'customer' | 'form' | string;
190
+ holder_id?: number | string | Array<number | string>;
191
+ created_at?: string | null;
192
+ [key: string]: any;
193
+ };
169
194
  extension_data?: ExtensionData[];
170
195
  total_order_behavior_count?: number;
171
196
  today_order_behavior_count?: number;
@@ -180,6 +205,12 @@ export interface Discount {
180
205
  start_time?: string;
181
206
  discount_rule_uncheck_flag?: boolean;
182
207
  usageLimitFailKey?: string | null;
208
+ /** 本次规则计算的不可用原因;可用性恢复后清除。 */
209
+ reason?: string;
210
+ reasonCode?: string;
211
+ unified_messages?: {
212
+ title?: string | Record<string, string>;
213
+ };
183
214
  unified_available_status?: number | undefined | null;
184
215
  }
185
216
  export interface DiscountState {
@@ -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
+ }