@pisell/pisellos 2.2.322 → 2.2.324

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 (209) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.js +1 -0
  3. package/dist/inventory/index.d.ts +92 -0
  4. package/dist/inventory/index.js +509 -0
  5. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  6. package/dist/modules/BookingContext/index.d.ts +2 -2
  7. package/dist/modules/BookingContext/index.js +55 -25
  8. package/dist/modules/BookingContext/types.d.ts +2 -0
  9. package/dist/modules/BookingContext/utils/calendarBooking.d.ts +15 -0
  10. package/dist/modules/BookingContext/utils/calendarBooking.js +207 -0
  11. package/dist/modules/BookingContext/utils/index.d.ts +1 -0
  12. package/dist/modules/BookingContext/utils/index.js +1 -0
  13. package/dist/modules/BookingContext/utils/productExtend.d.ts +20 -1
  14. package/dist/modules/BookingContext/utils/productExtend.js +122 -29
  15. package/dist/modules/Date/index.d.ts +1 -1
  16. package/dist/modules/Date/index.js +60 -14
  17. package/dist/modules/Date/types.d.ts +5 -0
  18. package/dist/modules/Discount/index.js +1 -0
  19. package/dist/modules/OpenData/index.d.ts +1 -0
  20. package/dist/modules/OpenData/index.js +1 -0
  21. package/dist/modules/OpenData/salesSettings.d.ts +32 -0
  22. package/dist/modules/OpenData/salesSettings.js +80 -0
  23. package/dist/modules/OpenData/types.d.ts +16 -0
  24. package/dist/modules/OpenData/utils.d.ts +1 -1
  25. package/dist/modules/OpenData/utils.js +3 -2
  26. package/dist/modules/Order/index.d.ts +54 -11
  27. package/dist/modules/Order/index.js +2699 -1411
  28. package/dist/modules/Order/types.d.ts +43 -5
  29. package/dist/modules/Order/types.js +4 -0
  30. package/dist/modules/Order/unpaidAmountGap.d.ts +6 -0
  31. package/dist/modules/Order/unpaidAmountGap.js +72 -0
  32. package/dist/modules/Order/utils/discountProductLineIdentity.js +2 -2
  33. package/dist/modules/Order/utils/productVoucherGroups.d.ts +15 -0
  34. package/dist/modules/Order/utils/productVoucherGroups.js +115 -0
  35. package/dist/modules/Order/utils.d.ts +3 -1
  36. package/dist/modules/Order/utils.js +18 -3
  37. package/dist/modules/Product/index.d.ts +1 -1
  38. package/dist/modules/Product/types.d.ts +5 -0
  39. package/dist/modules/ProductList/clientDataVariants.js +6 -2
  40. package/dist/modules/ProductList/index.d.ts +2 -0
  41. package/dist/modules/ProductList/index.js +161 -51
  42. package/dist/modules/ResourcePlanner/planner.js +58 -2
  43. package/dist/modules/ResourcePlanner/types.d.ts +13 -0
  44. package/dist/modules/Rules/index.d.ts +2 -0
  45. package/dist/modules/Rules/index.js +58 -39
  46. package/dist/modules/Schedule/index.d.ts +7 -1
  47. package/dist/modules/Schedule/index.js +155 -39
  48. package/dist/modules/Schedule/types.d.ts +2 -0
  49. package/dist/modules/bookingReadValidation.d.ts +6 -0
  50. package/dist/modules/bookingReadValidation.js +72 -0
  51. package/dist/plugins/request.d.ts +2 -0
  52. package/dist/server/index.d.ts +5 -0
  53. package/dist/server/index.js +1312 -1154
  54. package/dist/server/modules/order/index.js +2 -1
  55. package/dist/shared/receipt/customerInvoiceLanguages.d.ts +1 -1
  56. package/dist/shared/receipt/customerInvoiceLanguages.js +5 -3
  57. package/dist/shared/receipt/small-ticket.d.ts +4 -0
  58. package/dist/shared/receipt/small-ticket.js +70 -12
  59. package/dist/solution/BaseSales/index.d.ts +40 -5
  60. package/dist/solution/BaseSales/index.js +1939 -1484
  61. package/dist/solution/BaseSales/types.d.ts +4 -0
  62. package/dist/solution/BaseSales/types.js +1 -0
  63. package/dist/solution/BaseSales/utils/posDurationPricing.d.ts +21 -0
  64. package/dist/solution/BaseSales/utils/posDurationPricing.js +174 -0
  65. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +2 -0
  66. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +8 -8
  67. package/dist/solution/BookingByStep/index.d.ts +16 -2
  68. package/dist/solution/BookingByStep/index.js +676 -361
  69. package/dist/solution/BookingByStep/utils/resources.d.ts +10 -0
  70. package/dist/solution/BookingByStep/utils/resources.js +117 -76
  71. package/dist/solution/BookingTicket/index.d.ts +2 -2
  72. package/dist/solution/BookingTicket/index.js +249 -135
  73. package/dist/solution/BookingTicket/types.d.ts +14 -2
  74. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +3 -1
  75. package/dist/solution/BookingTicket/utils/addProductDecision.js +39 -11
  76. package/dist/solution/BookingTicket/utils/resolveUniqueCartDetail.d.ts +8 -0
  77. package/dist/solution/BookingTicket/utils/resolveUniqueCartDetail.js +188 -0
  78. package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +8 -0
  79. package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +88 -0
  80. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +1 -0
  81. package/dist/solution/BookingTicket/utils/scan/handleScan.js +2 -1
  82. package/dist/solution/OrderInvoicePreview/index.js +14 -8
  83. package/dist/solution/ScanOrder/index.d.ts +2 -0
  84. package/dist/solution/ScanOrder/index.js +166 -67
  85. package/dist/solution/ScanOrder/menuAvailability.d.ts +24 -0
  86. package/dist/solution/ScanOrder/menuAvailability.js +363 -0
  87. package/dist/solution/UnifiedBookingSales/catalogQueryBatch.d.ts +21 -0
  88. package/dist/solution/UnifiedBookingSales/catalogQueryBatch.js +202 -0
  89. package/dist/solution/UnifiedBookingSales/index.d.ts +96 -4
  90. package/dist/solution/UnifiedBookingSales/index.js +3391 -1176
  91. package/dist/solution/UnifiedBookingSales/remoteOccupancyCache.d.ts +2 -0
  92. package/dist/solution/UnifiedBookingSales/remoteOccupancyCache.js +4 -0
  93. package/dist/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
  94. package/dist/solution/UnifiedBookingSales/salesSettings.js +81 -0
  95. package/dist/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
  96. package/dist/solution/UnifiedBookingSales/sessionResourceCache.js +271 -0
  97. package/dist/solution/UnifiedBookingSales/types.d.ts +71 -2
  98. package/dist/solution/UnifiedBookingSales/types.js +7 -1
  99. package/dist/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
  100. package/dist/solution/UnifiedBookingSales/venueCatalogSession.js +283 -0
  101. package/dist/utils/platform.d.ts +2 -0
  102. package/dist/utils/platform.js +6 -0
  103. package/dist/utils/pos-receipt-auto-print.d.ts +4 -0
  104. package/dist/utils/pos-receipt-auto-print.js +14 -0
  105. package/lib/index.d.ts +1 -0
  106. package/lib/index.js +12 -0
  107. package/lib/inventory/index.d.ts +92 -0
  108. package/lib/inventory/index.js +287 -0
  109. package/lib/model/strategy/adapter/promotion/index.js +1 -46
  110. package/lib/modules/BookingContext/index.d.ts +2 -2
  111. package/lib/modules/BookingContext/index.js +42 -10
  112. package/lib/modules/BookingContext/types.d.ts +2 -0
  113. package/lib/modules/BookingContext/utils/calendarBooking.d.ts +15 -0
  114. package/lib/modules/BookingContext/utils/calendarBooking.js +156 -0
  115. package/lib/modules/BookingContext/utils/index.d.ts +1 -0
  116. package/lib/modules/BookingContext/utils/index.js +11 -0
  117. package/lib/modules/BookingContext/utils/productExtend.d.ts +20 -1
  118. package/lib/modules/BookingContext/utils/productExtend.js +96 -7
  119. package/lib/modules/Date/index.d.ts +1 -1
  120. package/lib/modules/Date/index.js +28 -5
  121. package/lib/modules/Date/types.d.ts +5 -0
  122. package/lib/modules/Discount/index.js +1 -0
  123. package/lib/modules/OpenData/index.d.ts +1 -0
  124. package/lib/modules/OpenData/index.js +12 -0
  125. package/lib/modules/OpenData/salesSettings.d.ts +32 -0
  126. package/lib/modules/OpenData/salesSettings.js +70 -0
  127. package/lib/modules/OpenData/types.d.ts +16 -0
  128. package/lib/modules/OpenData/utils.d.ts +1 -1
  129. package/lib/modules/OpenData/utils.js +3 -2
  130. package/lib/modules/Order/index.d.ts +54 -11
  131. package/lib/modules/Order/index.js +659 -80
  132. package/lib/modules/Order/types.d.ts +43 -5
  133. package/lib/modules/Order/types.js +2 -0
  134. package/lib/modules/Order/unpaidAmountGap.d.ts +6 -0
  135. package/lib/modules/Order/unpaidAmountGap.js +60 -0
  136. package/lib/modules/Order/utils/discountProductLineIdentity.js +1 -1
  137. package/lib/modules/Order/utils/productVoucherGroups.d.ts +15 -0
  138. package/lib/modules/Order/utils/productVoucherGroups.js +64 -0
  139. package/lib/modules/Order/utils.d.ts +3 -1
  140. package/lib/modules/Order/utils.js +19 -2
  141. package/lib/modules/Product/index.d.ts +1 -1
  142. package/lib/modules/Product/types.d.ts +5 -0
  143. package/lib/modules/ProductList/clientDataVariants.js +6 -2
  144. package/lib/modules/ProductList/index.d.ts +2 -0
  145. package/lib/modules/ProductList/index.js +74 -0
  146. package/lib/modules/ResourcePlanner/planner.js +52 -1
  147. package/lib/modules/ResourcePlanner/types.d.ts +13 -0
  148. package/lib/modules/Rules/index.d.ts +2 -0
  149. package/lib/modules/Rules/index.js +25 -9
  150. package/lib/modules/Schedule/index.d.ts +7 -1
  151. package/lib/modules/Schedule/index.js +68 -4
  152. package/lib/modules/Schedule/types.d.ts +2 -0
  153. package/lib/modules/bookingReadValidation.d.ts +6 -0
  154. package/lib/modules/bookingReadValidation.js +56 -0
  155. package/lib/plugins/request.d.ts +2 -0
  156. package/lib/server/index.d.ts +5 -0
  157. package/lib/server/index.js +124 -16
  158. package/lib/server/modules/order/index.js +2 -1
  159. package/lib/shared/receipt/customerInvoiceLanguages.d.ts +1 -1
  160. package/lib/shared/receipt/customerInvoiceLanguages.js +5 -3
  161. package/lib/shared/receipt/small-ticket.d.ts +4 -0
  162. package/lib/shared/receipt/small-ticket.js +63 -8
  163. package/lib/solution/BaseSales/index.d.ts +40 -5
  164. package/lib/solution/BaseSales/index.js +296 -43
  165. package/lib/solution/BaseSales/types.d.ts +4 -0
  166. package/lib/solution/BaseSales/types.js +1 -0
  167. package/lib/solution/BaseSales/utils/posDurationPricing.d.ts +21 -0
  168. package/lib/solution/BaseSales/utils/posDurationPricing.js +133 -0
  169. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +2 -0
  170. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +1 -1
  171. package/lib/solution/BookingByStep/index.d.ts +16 -2
  172. package/lib/solution/BookingByStep/index.js +222 -14
  173. package/lib/solution/BookingByStep/utils/resources.d.ts +10 -0
  174. package/lib/solution/BookingByStep/utils/resources.js +25 -15
  175. package/lib/solution/BookingTicket/index.d.ts +2 -2
  176. package/lib/solution/BookingTicket/index.js +47 -4
  177. package/lib/solution/BookingTicket/types.d.ts +14 -2
  178. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +3 -1
  179. package/lib/solution/BookingTicket/utils/addProductDecision.js +37 -6
  180. package/lib/solution/BookingTicket/utils/resolveUniqueCartDetail.d.ts +8 -0
  181. package/lib/solution/BookingTicket/utils/resolveUniqueCartDetail.js +136 -0
  182. package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +8 -0
  183. package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +54 -0
  184. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +1 -0
  185. package/lib/solution/BookingTicket/utils/scan/handleScan.js +2 -1
  186. package/lib/solution/OrderInvoicePreview/index.js +7 -1
  187. package/lib/solution/ScanOrder/index.d.ts +2 -0
  188. package/lib/solution/ScanOrder/index.js +72 -2
  189. package/lib/solution/ScanOrder/menuAvailability.d.ts +24 -0
  190. package/lib/solution/ScanOrder/menuAvailability.js +203 -0
  191. package/lib/solution/UnifiedBookingSales/catalogQueryBatch.d.ts +21 -0
  192. package/lib/solution/UnifiedBookingSales/catalogQueryBatch.js +109 -0
  193. package/lib/solution/UnifiedBookingSales/index.d.ts +96 -4
  194. package/lib/solution/UnifiedBookingSales/index.js +1339 -74
  195. package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.d.ts +2 -0
  196. package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.js +2 -0
  197. package/lib/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
  198. package/lib/solution/UnifiedBookingSales/salesSettings.js +72 -0
  199. package/lib/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
  200. package/lib/solution/UnifiedBookingSales/sessionResourceCache.js +199 -0
  201. package/lib/solution/UnifiedBookingSales/types.d.ts +71 -2
  202. package/lib/solution/UnifiedBookingSales/types.js +4 -1
  203. package/lib/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
  204. package/lib/solution/UnifiedBookingSales/venueCatalogSession.js +155 -0
  205. package/lib/utils/platform.d.ts +2 -0
  206. package/lib/utils/platform.js +7 -0
  207. package/lib/utils/pos-receipt-auto-print.d.ts +4 -0
  208. package/lib/utils/pos-receipt-auto-print.js +13 -0
  209. package/package.json +1 -1
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.buildPosDurationPricingPlan = buildPosDurationPricingPlan;
7
+ exports.combinePosDurationPrices = combinePosDurationPrices;
8
+ exports.durationPricingUnavailable = durationPricingUnavailable;
9
+ exports.forEachPriceQueryGroup = forEachPriceQueryGroup;
10
+ exports.hasAppliedPosDurationPricing = hasAppliedPosDurationPricing;
11
+ exports.hasDurationBasedPricing = hasDurationBasedPricing;
12
+ exports.resolveDurationPricingProduct = resolveDurationPricingProduct;
13
+ exports.usesPosDurationPricing = usesPosDurationPricing;
14
+ var _dayjs = _interopRequireDefault(require("dayjs"));
15
+ var _decimal = _interopRequireDefault(require("decimal.js"));
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+ function durationPricingUnavailable(message) {
18
+ return Object.assign(new Error(message), {
19
+ code: 'DURATION_PRICING_UNAVAILABLE'
20
+ });
21
+ }
22
+ function hasDurationBasedPricing(product) {
23
+ return product?.pricing_method?.type === 'duration_based';
24
+ }
25
+
26
+ /** Days/Flexible retain their existing quotation behavior. */
27
+ function usesPosDurationPricing(product) {
28
+ const type = String(product?.duration?.type || '').trim().toLowerCase();
29
+ return hasDurationBasedPricing(product) && !['day', 'days', 'flexible'].includes(type);
30
+ }
31
+
32
+ /** A hydrated catalog can already be fixed while its order/quote still contains an applied duration price. */
33
+ function hasAppliedPosDurationPricing(product) {
34
+ return usesPosDurationPricing(product?._extend?.bookingPriceQuote) || usesPosDurationPricing(product?._extend?.bookingPrice?.quote) || usesPosDurationPricing(product?.metadata);
35
+ }
36
+ function bookingDateTime(date, time) {
37
+ const dateText = typeof date === 'string' ? date.trim() : '';
38
+ const timeText = typeof time === 'string' ? time.trim() : '';
39
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(dateText) || !/^\d{2}:\d{2}(?::\d{2})?$/.test(timeText)) {
40
+ throw durationPricingUnavailable('A valid booking start and end are required for duration pricing.');
41
+ }
42
+ const text = `${dateText} ${timeText.length === 5 ? `${timeText}:00` : timeText}`;
43
+ const value = (0, _dayjs.default)(text);
44
+ if (!value.isValid() || value.format('YYYY-MM-DD HH:mm:ss') !== text) {
45
+ throw durationPricingUnavailable('The booking time is invalid for duration pricing.');
46
+ }
47
+ return value;
48
+ }
49
+ function buildPosDurationPricingPlan(params, product) {
50
+ const type = String(product.duration?.type || '').trim().toLowerCase();
51
+ const value = Number(product.duration?.value);
52
+ const minutes = ['hour', 'hours'].includes(type) ? value * 60 : value;
53
+ if (!['minute', 'minutes', 'hour', 'hours'].includes(type) || !Number.isFinite(minutes) || minutes <= 0) {
54
+ throw durationPricingUnavailable('A positive fixed billing duration is required.');
55
+ }
56
+ const start = bookingDateTime(params.booking?.start_date, params.booking?.start_time);
57
+ const end = bookingDateTime(params.booking?.end_date, params.booking?.end_time);
58
+ const count = end.diff(start) / (minutes * 60_000);
59
+ if (!Number.isInteger(count) || count < 1 || count > 10_000) {
60
+ throw durationPricingUnavailable('The booking duration must be a whole multiple of its billing duration.');
61
+ }
62
+ return {
63
+ duration: {
64
+ type: 'minutes',
65
+ value: minutes
66
+ },
67
+ segments: Array.from({
68
+ length: count
69
+ }, (_, index) => ({
70
+ start: start.add(index * minutes, 'minute').format('YYYY-MM-DD HH:mm:ss'),
71
+ end: start.add((index + 1) * minutes, 'minute').format('YYYY-MM-DD HH:mm:ss')
72
+ }))
73
+ };
74
+ }
75
+
76
+ /** Never use a previously accumulated order price as one unit's fallback. */
77
+ function resolveDurationPricingProduct(product, selected) {
78
+ const variantId = Number(selected.product_variant_id ?? selected.variant_id ?? 0);
79
+ const authoritativeVariantId = Number(product.product_variant_id ?? product.variant_id ?? 0);
80
+ const variant = variantId > 0 && Array.isArray(product.variant) ? product.variant.find(item => Number(item?.id) === variantId) : undefined;
81
+ if (variantId > 0 && !variant && authoritativeVariantId !== variantId) {
82
+ throw durationPricingUnavailable('The selected SKU is missing from the authoritative price response.');
83
+ }
84
+ const appliedFields = product._dataVariant?.appliedFields;
85
+ const hasAppliedPrice = Array.isArray(appliedFields) && ['price', 'selling_price', 'original_price', 'base_price'].some(field => appliedFields.includes(field));
86
+ const priceSource = variantId > 0 && authoritativeVariantId !== variantId && !hasAppliedPrice ? variant : product;
87
+ const price = priceSource?.price ?? priceSource?.selling_price ?? priceSource?.base_price ?? priceSource?.original_price;
88
+ if (!(typeof price === 'number' || typeof price === 'string' && price.trim() !== '') || !Number.isFinite(Number(price)) || Number(price) < 0) {
89
+ throw durationPricingUnavailable('An authoritative price is required for every billing unit.');
90
+ }
91
+ return {
92
+ ...product,
93
+ price
94
+ };
95
+ }
96
+ function combinePosDurationPrices(plan, prices) {
97
+ if (prices.length !== plan.segments.length || prices.length === 0) {
98
+ throw durationPricingUnavailable('The duration price is incomplete.');
99
+ }
100
+ const unitPrice = prices.reduce((sum, price) => sum.plus(price.unit_price), new _decimal.default(0));
101
+ return {
102
+ ...prices[0],
103
+ pricing_method: {
104
+ type: 'duration_based'
105
+ },
106
+ duration: plan.duration,
107
+ unit_price: unitPrice.toFixed(2),
108
+ total_price: unitPrice.times(prices[0].quantity).toFixed(2),
109
+ quotation_shelf_id: prices.find(price => price.quotation_shelf_id)?.quotation_shelf_id || 0,
110
+ segments: prices.map((price, index) => ({
111
+ ...price.segments[0],
112
+ start_datetime: plan.segments[index].start,
113
+ end_datetime: plan.segments[index].end,
114
+ time_point: plan.segments[index].start,
115
+ unit_price: price.unit_price,
116
+ total_price: price.unit_price,
117
+ quantity: 1
118
+ })),
119
+ // Options are composed by the caller; bundle pricing belongs to the first unit only.
120
+ product_bundle: prices[0].product_bundle
121
+ };
122
+ }
123
+ async function forEachPriceQueryGroup(groups, resolve, concurrency) {
124
+ let next = 0;
125
+ await Promise.all(Array.from({
126
+ length: Math.min(groups.length, concurrency)
127
+ }, async () => {
128
+ while (next < groups.length) {
129
+ const group = groups[next++];
130
+ await resolve(group);
131
+ }
132
+ }));
133
+ }
@@ -55,6 +55,8 @@ export interface TransformBaseProductToOrderProductParams {
55
55
  fallbackProductId?: number | string | null;
56
56
  sourceProduct?: ProductData | Record<string, any> | null;
57
57
  sourceItem?: ProductData | Record<string, any> | null;
58
+ /** Validated booking quote's pre-discount main price, excluding options/bundles. */
59
+ quotedSourceProductPrice?: number | string;
58
60
  }
59
61
  export type BaseProductOrderProductInput = Partial<OrderProduct> & OrderProductIdentity & {
60
62
  _origin?: Record<string, any>;
@@ -156,7 +156,7 @@ function transformBaseProductToOrderProduct(params) {
156
156
  // 售价仍由 line_total - bundle 推导。
157
157
  const catalogSourcePrice = matchedVariant?.price ?? matchedVariant?.base_price ?? origin?.price ?? origin?.base_price ?? sourceProduct?.price ?? sourceProduct?.selling_price ?? sourceProduct?.base_price;
158
158
  const weighedSourcePrice = (0, _weighedProduct.resolveWeighedSourcePrice)(payload.product_sku ?? origin.product_sku, payload._extend?.weighing ?? origin._extend?.weighing);
159
- const sourceProductPrice = toPriceString(weighedSourcePrice ?? (hasPriceOverride ? catalogSourcePrice ?? payload.price ?? payload.selling_price : payload.price ?? payload.selling_price ?? catalogSourcePrice), '0.00');
159
+ const sourceProductPrice = toPriceString(params.quotedSourceProductPrice ?? weighedSourcePrice ?? (hasPriceOverride ? catalogSourcePrice ?? payload.price ?? payload.selling_price : payload.price ?? payload.selling_price ?? catalogSourcePrice), '0.00');
160
160
  const explicitLineTotal = payload.line_total ?? payload.total ?? payload._extend?.total;
161
161
  const hasExplicitLineTotal = Number.isFinite(Number(explicitLineTotal));
162
162
  const lineCompositeTotal = toPriceString(explicitLineTotal, sourceProductPrice);
@@ -20,9 +20,20 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
20
20
  private shopStore;
21
21
  private store;
22
22
  private otherParams;
23
+ private scheduleRuntimeParams;
23
24
  private cacheId;
24
25
  private otherData;
25
26
  private platform;
27
+ private productDetailGeneration;
28
+ private sessionAvailabilityRequestVersion;
29
+ private lifecycleGeneration;
30
+ private disposed;
31
+ private resourcePreparation?;
32
+ private staleSelection;
33
+ private resourceSelectionKey;
34
+ /** Semantic selection token for async UI transitions. */
35
+ getBookingSelectionKey(): string;
36
+ private refreshCurrentProductSchedule;
26
37
  initialize(core: PisellCore, options: any): Promise<void>;
27
38
  initStep(stepList: (keyof BookingByStepState)[]): void;
28
39
  getCurrentStep(): {
@@ -108,7 +119,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
108
119
  * }
109
120
  * @memberof BookingByStepImpl
110
121
  */
111
- loadScheduleAvailableDate({ startDate, endDate, custom_page_id, channel, }: LoadScheduleAvailableDateParams): Promise<ITime[]>;
122
+ loadScheduleAvailableDate({ startDate, endDate, custom_page_id, channel, assertCurrent, }: LoadScheduleAvailableDateParams): Promise<ITime[]>;
112
123
  addAccount(account: Account | IHolder, extra?: {
113
124
  type: 'account' | 'holder';
114
125
  customerId: number;
@@ -152,7 +163,10 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
152
163
  startDate?: string;
153
164
  endDate?: string;
154
165
  type?: 'month' | 'day';
166
+ assertCurrent?: () => void;
155
167
  }): Promise<ITime[]>;
168
+ /** Prepare the exact cart/date selection before synchronous resource checks. */
169
+ prepareResourcesForCurrentSelection(): Promise<void>;
156
170
  /**
157
171
  * 获取购物车汇总信息
158
172
  */
@@ -328,7 +342,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
328
342
  date: string;
329
343
  status: string;
330
344
  week: string;
331
- weekNum: 0 | 2 | 1 | 6 | 4 | 5 | 3;
345
+ weekNum: 0 | 2 | 1 | 3 | 5 | 4 | 6;
332
346
  }[]>;
333
347
  submitTimeSlot(timeSlots: TimeSliceItem): void;
334
348
  private getScheduleDataByIds;
@@ -33,14 +33,90 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
33
33
  shopStore;
34
34
  store;
35
35
  otherParams = {};
36
+ scheduleRuntimeParams = {};
36
37
  cacheId;
37
38
  otherData = {}; // 提供给 UI 层的临时数据存储,会进缓存
38
39
  platform; // 平台类型,用于判断是 PC / H5
40
+ productDetailGeneration = 0;
41
+ sessionAvailabilityRequestVersion = 0;
42
+ lifecycleGeneration = 0;
43
+ disposed = false;
44
+ resourcePreparation;
45
+ staleSelection() {
46
+ return Object.assign(new Error('Booking selection changed'), {
47
+ name: 'AbortError'
48
+ });
49
+ }
50
+ resourceSelectionKey() {
51
+ const items = this.store.cart.getItems();
52
+ const sessionDates = items.filter(item => (0, _products.isSessionProduct)(item._productOrigin)).flatMap(item => [item.start_date, item.end_date]).filter(Boolean);
53
+ return JSON.stringify({
54
+ lifecycle: this.lifecycleGeneration,
55
+ dates: sessionDates.length ? [...new Set(sessionDates)].sort() : (this.store.date.getDateRange() || []).map(date => date.date).sort(),
56
+ cart: items.map(item => ({
57
+ id: item._id,
58
+ num: item.num,
59
+ holder: item.holder_id,
60
+ start: [item.start_date, item.start_time],
61
+ end: [item.end_date, item.end_time],
62
+ resources: item._origin?.resources,
63
+ capacity: (0, _capacity.getCapacityInfoByCartItem)(item).currentCapacity,
64
+ product: {
65
+ id: item._productOrigin?.id,
66
+ schedules: item._productOrigin?.['schedule.ids'],
67
+ resources: item._productOrigin?.product_resource?.resources?.map(resource => ({
68
+ id: resource.id,
69
+ resource_type_id: resource.resource_type_id,
70
+ status: resource.status,
71
+ code: resource.code,
72
+ type: resource.type,
73
+ default_resource: resource.default_resource || [],
74
+ // Resource rendering removes required IDs from the optional list in place.
75
+ // Compare the same effective inputs before and after that normalization.
76
+ optional_resource: (resource.optional_resource || []).filter(id => !(resource.default_resource || []).includes(id)),
77
+ select_type: resource.select_type && {
78
+ type: resource.select_type.type,
79
+ min: resource.select_type.min,
80
+ max: resource.select_type.max
81
+ }
82
+ })),
83
+ duration: item._productOrigin?.duration,
84
+ cutoff: item._productOrigin?.cut_off_time
85
+ },
86
+ bundle: item._bundleOrigin,
87
+ options: item._optionsOrigin
88
+ }))
89
+ });
90
+ }
39
91
 
92
+ /** Semantic selection token for async UI transitions. */
93
+ getBookingSelectionKey() {
94
+ return this.resourceSelectionKey();
95
+ }
96
+ refreshCurrentProductSchedule() {
97
+ const product = this.store.currentProduct;
98
+ if (!product?.['schedule.ids'] || !this.store.schedule.isScheduleListLoaded()) return;
99
+ const version = this.store.schedule.getScheduleCatalogVersion();
100
+ const meta = this.store.currentProductMeta || {};
101
+ if (meta.scheduleCatalogVersion !== version) {
102
+ this.store.currentProductMeta = {
103
+ ...meta,
104
+ schedule: this.getScheduleDataByIds(product['schedule.ids']),
105
+ scheduleCatalogVersion: version,
106
+ timeSlotBySchedule: undefined
107
+ };
108
+ }
109
+ }
40
110
  async initialize(core, options) {
111
+ this.disposed = false;
112
+ this.lifecycleGeneration += 1;
113
+ this.productDetailGeneration += 1;
41
114
  this.core = core;
42
115
  this.store = options.store || {};
43
116
  this.otherParams = options.otherParams || {};
117
+ this.scheduleRuntimeParams = {
118
+ ...this.otherParams
119
+ };
44
120
  // 获取依赖的插件
45
121
  this.request = core.getPlugin('request');
46
122
  this.window = core.getPlugin('window');
@@ -78,14 +154,20 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
78
154
  ...this.otherParams,
79
155
  fatherModule: this.name,
80
156
  openCache: this.otherParams?.cacheId ? true : false,
81
- cacheId: this.otherParams?.cacheId
157
+ cacheId: this.otherParams?.cacheId,
158
+ ...(step === 'schedule' ? {
159
+ scheduleCatalogCache: 'memory',
160
+ bookingRead: true
161
+ } : {})
82
162
  }
83
163
  });
84
164
  } else {
85
165
  throw new Error(`模块 ${step} 不存在`);
86
166
  }
87
167
  });
88
- this.store.schedule.loadAllSchedule();
168
+ this.store.schedule.ensureScheduleReady().catch(error => {
169
+ if (error?.name !== 'AbortError') console.error('[BookingByStep] Schedule preload failed', error);
170
+ });
89
171
  this.core.effects.emit(`${this.name}:onInited`, {});
90
172
  }
91
173
  // 初始化step
@@ -174,6 +256,8 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
174
256
  startDate: schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD'),
175
257
  endDate: schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD'),
176
258
  products: [...res]
259
+ }).catch(error => {
260
+ if (error?.name !== 'AbortError') console.error('[BookingByStep] Resource preload failed', error);
177
261
  });
178
262
  return res;
179
263
  }
@@ -283,13 +367,15 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
283
367
  startDate,
284
368
  endDate,
285
369
  custom_page_id,
286
- channel
370
+ channel,
371
+ assertCurrent
287
372
  }) {
288
373
  return await this.store.schedule.loadScheduleAvailableDate({
289
374
  startDate,
290
375
  endDate,
291
376
  custom_page_id,
292
- channel
377
+ channel,
378
+ assertCurrent
293
379
  });
294
380
  }
295
381
 
@@ -431,6 +517,24 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
431
517
  startDate = (0, _dayjs.default)().format('YYYY-MM-DD');
432
518
  }
433
519
  let tempProducts = products || this.store.cart.getItems().map(p => p._productOrigin);
520
+ const generation = this.productDetailGeneration;
521
+ const lifecycle = this.lifecycleGeneration;
522
+ const selectionKey = products ? undefined : this.resourceSelectionKey();
523
+ const assertCurrent = () => {
524
+ if (this.disposed || lifecycle !== this.lifecycleGeneration || (!products || !params.assertCurrent) && generation !== this.productDetailGeneration || selectionKey !== undefined && selectionKey !== this.resourceSelectionKey()) throw this.staleSelection();
525
+ params.assertCurrent?.();
526
+ };
527
+ const requiresSchedule = tempProducts.some(product => product?.['schedule.ids']?.length) || !products && !!this.store.currentProduct?.['schedule.ids']?.length;
528
+ if (requiresSchedule) {
529
+ try {
530
+ await this.store.schedule.ensureScheduleReady();
531
+ } catch (error) {
532
+ assertCurrent();
533
+ throw error;
534
+ }
535
+ assertCurrent();
536
+ this.refreshCurrentProductSchedule();
537
+ }
434
538
  if (tempProducts.length) {
435
539
  tempProducts.forEach(p => {
436
540
  if (p?.['schedule.ids']) {
@@ -440,7 +544,7 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
440
544
  });
441
545
  }
442
546
  // 如果当前打开了某个的商品详情弹窗,则应该默认用这个商品
443
- if (this.store.currentProduct) {
547
+ if (!products && this.store.currentProduct) {
444
548
  tempProducts = [{
445
549
  ...this.store.currentProduct,
446
550
  _schedule: this.store.currentProductMeta?.['schedule']
@@ -460,6 +564,7 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
460
564
  resourcesMap
461
565
  } = (0, _products.getAvailableProductResources)(tempProducts) || {};
462
566
  this.otherParams.currentResourcesMap = resourcesMap;
567
+ const catalogVersion = this.store.schedule.getScheduleCatalogVersion();
463
568
  const res = await this.store.date.getResourceDates({
464
569
  url: params.url,
465
570
  query: {
@@ -469,11 +574,56 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
469
574
  },
470
575
  rules,
471
576
  type,
472
- useCache
577
+ useCache,
578
+ bookingRead: true,
579
+ errorMode: 'throw',
580
+ assertCurrent: () => {
581
+ assertCurrent();
582
+ if (requiresSchedule && catalogVersion !== this.store.schedule.getScheduleCatalogVersion()) throw this.staleSelection();
583
+ }
473
584
  });
474
585
  return res;
475
586
  }
476
587
 
588
+ /** Prepare the exact cart/date selection before synchronous resource checks. */
589
+ prepareResourcesForCurrentSelection() {
590
+ const key = this.resourceSelectionKey();
591
+ if (this.resourcePreparation?.key === key) return this.resourcePreparation.promise;
592
+ const selected = (0, _lodashEs.cloneDeep)(this.store.date.getDateRange() || []);
593
+ const cart = this.store.cart.getItems().filter(item => !(0, _utils5.isNormalProduct)(item._productOrigin));
594
+ const sessionDates = cart.filter(item => (0, _products.isSessionProduct)(item._productOrigin)).flatMap(item => [item.start_date, item.end_date]).filter(Boolean);
595
+ const selectedDates = sessionDates.length ? [...new Set(sessionDates)].sort() : selected.map(date => date.date).sort();
596
+ const dates = selectedDates;
597
+ if (!cart.length || !dates.length) return Promise.resolve();
598
+ const assertCurrent = () => {
599
+ if (this.disposed || key !== this.resourceSelectionKey()) throw this.staleSelection();
600
+ };
601
+ const promise = (async () => {
602
+ const available = await this.getAvailableDate({
603
+ startDate: dates[0],
604
+ endDate: dates[dates.length - 1],
605
+ products: cart.map(item => item._productOrigin),
606
+ assertCurrent
607
+ });
608
+ assertCurrent();
609
+ this.store.date.setDateRange(selectedDates.map(date => available.find(item => item.date === date) || {
610
+ date,
611
+ week: (0, _dayjs.default)(date).format('ddd'),
612
+ weekNum: (0, _dayjs.default)(date).day(),
613
+ status: 'unavailable',
614
+ resource: []
615
+ }));
616
+ })();
617
+ this.resourcePreparation = {
618
+ key,
619
+ promise
620
+ };
621
+ void promise.finally(() => {
622
+ if (this.resourcePreparation?.promise === promise) this.resourcePreparation = undefined;
623
+ }).catch(() => {});
624
+ return promise;
625
+ }
626
+
477
627
  /**
478
628
  * 获取购物车汇总信息
479
629
  */
@@ -610,6 +760,10 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
610
760
  async setOtherParams(params, {
611
761
  cover = false
612
762
  } = {}) {
763
+ this.scheduleRuntimeParams = {
764
+ ...this.scheduleRuntimeParams,
765
+ ...params
766
+ };
613
767
  if (cover) {
614
768
  this.otherParams = params;
615
769
  } else {
@@ -618,6 +772,13 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
618
772
  ...params
619
773
  };
620
774
  }
775
+ this.store.schedule?.updateOtherParams({
776
+ ...this.scheduleRuntimeParams,
777
+ fatherModule: this.name,
778
+ openCache: !!this.scheduleRuntimeParams.cacheId,
779
+ scheduleCatalogCache: 'memory',
780
+ bookingRead: true
781
+ });
621
782
  }
622
783
  async getOtherParams() {
623
784
  return this.otherParams;
@@ -948,6 +1109,11 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
948
1109
  return errorCartItemIds;
949
1110
  }
950
1111
  destroy() {
1112
+ this.disposed = true;
1113
+ this.lifecycleGeneration += 1;
1114
+ this.productDetailGeneration += 1;
1115
+ this.resourcePreparation = undefined;
1116
+ this.store.schedule?.destroy();
951
1117
  this.store.cart?.destroy();
952
1118
  this.store.step?.destroy();
953
1119
  this.store.products?.destroy();
@@ -1955,7 +2121,17 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
1955
2121
  }
1956
2122
  // 打开某个商品详情的弹窗,OS 层这边会记录当前选中的商品,适用于 session 类商品预约
1957
2123
  async openProductDetail(productId) {
1958
- const targetProductData = await this.store.products.getProduct(productId);
2124
+ const generation = ++this.productDetailGeneration;
2125
+ let targetProductData;
2126
+ try {
2127
+ targetProductData = await this.store.products.getProduct(productId);
2128
+ if (targetProductData?.['schedule.ids']?.length) await this.store.schedule.ensureScheduleReady();
2129
+ } catch (error) {
2130
+ if (this.disposed || generation !== this.productDetailGeneration) throw this.staleSelection();
2131
+ throw error;
2132
+ }
2133
+ if (this.disposed || generation !== this.productDetailGeneration) throw this.staleSelection();
2134
+ if (!targetProductData) throw new Error('Booking product is unavailable');
1959
2135
  if (targetProductData) {
1960
2136
  this.store.currentProduct = targetProductData;
1961
2137
  this.store.currentProductMeta = {};
@@ -1964,6 +2140,7 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
1964
2140
  const newScheduleArr = this.getScheduleDataByIds(targetProductData['schedule.ids']);
1965
2141
  if (!this.store.currentProductMeta) this.store.currentProductMeta = {};
1966
2142
  this.store.currentProductMeta.schedule = newScheduleArr;
2143
+ this.store.currentProductMeta.scheduleCatalogVersion = this.store.schedule.getScheduleCatalogVersion();
1967
2144
  } else if (targetProductData.duration) {
1968
2145
  const dateRange = this.store.date.getDateRange();
1969
2146
  // 如果不是先选日期的流程 duration 商品就啥也不做
@@ -1979,14 +2156,15 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
1979
2156
  startDate: dateRange[0].date,
1980
2157
  endDate: dateRange[dateRange.length - 1].date,
1981
2158
  products: [targetProductData]
2159
+ }).catch(error => {
2160
+ if (error?.name !== 'AbortError') console.error('[BookingByStep] Product resource preload failed', error);
1982
2161
  });
1983
2162
  }
1984
2163
  }
1985
2164
  }
1986
2165
  closeProductDetail() {
1987
- if (this.store.currentProductMeta) {
1988
- this.store.currentProductMeta.schedule = [];
1989
- }
2166
+ this.productDetailGeneration += 1;
2167
+ this.store.currentProductMeta = {};
1990
2168
  this.store.currentProduct = undefined;
1991
2169
  }
1992
2170
 
@@ -2222,11 +2400,19 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
2222
2400
  start_at: (0, _dayjs.default)(item.start),
2223
2401
  end_at: (0, _dayjs.default)(item.end)
2224
2402
  })) {
2225
- mSet.set(m.id, m.pax ?? 1);
2403
+ mSet.set(m.id, {
2404
+ ...m,
2405
+ pax: m.pax ?? 1
2406
+ });
2226
2407
  }
2227
2408
  });
2228
2409
  });
2229
- acc += Array.from(mSet.values()).reduce((acc, curr) => acc + curr, 0);
2410
+ const peakUsedCapacity = (0, _resources.getPeakConcurrentPax)(Array.from(mSet.values()), {
2411
+ start_at: (0, _dayjs.default)(item.start),
2412
+ end_at: (0, _dayjs.default)(item.end)
2413
+ });
2414
+ // 单个资源的超额占用不能扣减其他资源的可用容量。
2415
+ acc += Math.min(curr.capacity, peakUsedCapacity);
2230
2416
  return acc;
2231
2417
  }, 0);
2232
2418
  // 如果已使用容量超过了当前类型资源的容量,则不可用
@@ -3128,6 +3314,20 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
3128
3314
  return results;
3129
3315
  }
3130
3316
  async getAvailableDateForSessionOptimize(params = {}) {
3317
+ const requestVersion = ++this.sessionAvailabilityRequestVersion;
3318
+ const generation = this.productDetailGeneration;
3319
+ try {
3320
+ await this.store.schedule.ensureScheduleReady();
3321
+ } catch (error) {
3322
+ if (this.disposed || generation !== this.productDetailGeneration || requestVersion !== this.sessionAvailabilityRequestVersion) throw this.staleSelection();
3323
+ throw error;
3324
+ }
3325
+ if (this.disposed || generation !== this.productDetailGeneration || requestVersion !== this.sessionAvailabilityRequestVersion || !this.store.currentProduct) throw this.staleSelection();
3326
+ this.refreshCurrentProductSchedule();
3327
+ const catalogVersion = this.store.schedule.getScheduleCatalogVersion();
3328
+ const assertCurrent = () => {
3329
+ if (this.disposed || generation !== this.productDetailGeneration || requestVersion !== this.sessionAvailabilityRequestVersion || catalogVersion !== this.store.schedule.getScheduleCatalogVersion()) throw this.staleSelection();
3330
+ };
3131
3331
  // 开始日期如果小于今天,直接以今天当做开始日期
3132
3332
  let {
3133
3333
  startDate,
@@ -3158,7 +3358,8 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
3158
3358
  if (cache) {
3159
3359
  // 开始日期大于等于缓存的开始日期,且结束日期小于等于缓存的结束日期,则直接返回缓存结果
3160
3360
  if ((0, _dayjs.default)(params.startDate).isSameOrAfter((0, _dayjs.default)(cache.startDate), 'day') && (0, _dayjs.default)(params.endDate).isSameOrBefore((0, _dayjs.default)(cache.endDate), 'day')) {
3161
- this.store.date.setDateList(cache.dateList);
3361
+ assertCurrent();
3362
+ this.store.date.setDateList(cache.dateList, true);
3162
3363
  return {
3163
3364
  dateList: cache.dateList,
3164
3365
  firstAvailableDate: cache.firstAvailableDate
@@ -3173,12 +3374,18 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
3173
3374
  // 1.后端返回的数据,确定资源在每一天的可用和使用情况
3174
3375
  const tempResourceIds = (0, _capacity.getResourcesIdsByProduct)(tempProducts);
3175
3376
  const res = await this.store.date.fetchResourceDates({
3377
+ errorMode: 'throw',
3378
+ bookingRead: true,
3176
3379
  query: {
3177
3380
  start_date: startDate || '',
3178
3381
  end_date: endDate || '',
3179
3382
  resource_ids: tempResourceIds
3180
3383
  }
3384
+ }).catch(error => {
3385
+ assertCurrent();
3386
+ throw error;
3181
3387
  });
3388
+ assertCurrent();
3182
3389
  // 2. 商品 schedule 数据,确定日程在每一天的时间片
3183
3390
  // 3. 把后端返回的和 schedule 的数据进行合并,确定每一天的可用和使用情况
3184
3391
  let dates = [];
@@ -3358,7 +3565,8 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
3358
3565
  }
3359
3566
  // 最终把资源数据也加到日期内
3360
3567
  dates = (0, _utils4.handleAvailableDateByResource)(res.data, dates);
3361
- this.store.date.setDateList(dates);
3568
+ assertCurrent();
3569
+ this.store.date.setDateList(dates, true);
3362
3570
 
3363
3571
  // 缓存这次结果,以防后面他小幅度范围内去修改天数
3364
3572
  if (!this.store.currentProductMeta) this.store.currentProductMeta = {};
@@ -7,6 +7,11 @@ import { CartItem, ProductData } from '../../../modules';
7
7
  *
8
8
  */
9
9
  type DateType = Dayjs;
10
+ interface EventItem {
11
+ pax: number;
12
+ start_at: DateType;
13
+ end_at: DateType;
14
+ }
10
15
  export interface TimeSliceItem {
11
16
  start_time: string;
12
17
  end_time: string;
@@ -20,6 +25,11 @@ export interface ResourceItem {
20
25
  interface BookingItem {
21
26
  [key: string]: any;
22
27
  }
28
+ /** 计算目标区间内的最大同时占用人数;事件去重由调用方负责。 */
29
+ export declare const getPeakConcurrentPax: (eventList: EventItem[], timeSlice: {
30
+ start_at: DateType;
31
+ end_at: DateType;
32
+ }) => number;
23
33
  /**
24
34
  * @title: 判断两个时间段是否有重叠
25
35
  * @description: