@pisell/pisellos 0.10.88 → 0.10.91

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 (227) hide show
  1. package/dist/model/strategy/adapter/itemRule/adapter.d.ts +3 -1
  2. package/dist/model/strategy/adapter/itemRule/adapter.js +74 -7
  3. package/dist/model/strategy/adapter/itemRule/evaluator.d.ts +3 -1
  4. package/dist/model/strategy/adapter/itemRule/evaluator.js +13 -0
  5. package/dist/model/strategy/adapter/itemRule/type.d.ts +40 -1
  6. package/dist/model/strategy/adapter/itemRule/type.js +10 -0
  7. package/dist/model/strategy/adapter/promotion/evaluator.d.ts +2 -1
  8. package/dist/model/strategy/adapter/promotion/evaluator.js +103 -112
  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 +21 -0
  14. package/dist/modules/BookingContext/utils/productExtend.js +132 -33
  15. package/dist/modules/BookingContext/utils/resources.js +1 -1
  16. package/dist/modules/Cart/index.js +4 -3
  17. package/dist/modules/Cart/types.d.ts +2 -0
  18. package/dist/modules/Cart/utils/cartProduct.d.ts +3 -1
  19. package/dist/modules/Cart/utils/cartProduct.js +59 -32
  20. package/dist/modules/Date/index.d.ts +1 -1
  21. package/dist/modules/Date/index.js +60 -14
  22. package/dist/modules/Date/types.d.ts +5 -0
  23. package/dist/modules/OpenData/salesSettings.js +1 -1
  24. package/dist/modules/OpenData/types.d.ts +9 -0
  25. package/dist/modules/OpenData/utils.d.ts +1 -1
  26. package/dist/modules/OpenData/utils.js +3 -2
  27. package/dist/modules/Order/index.d.ts +22 -7
  28. package/dist/modules/Order/index.js +1565 -1161
  29. package/dist/modules/Order/localEftposState.d.ts +13 -0
  30. package/dist/modules/Order/localEftposState.js +39 -0
  31. package/dist/modules/Order/types.d.ts +33 -11
  32. package/dist/modules/Order/types.js +2 -2
  33. package/dist/modules/Order/unpaidAmountGap.d.ts +6 -0
  34. package/dist/modules/Order/unpaidAmountGap.js +72 -0
  35. package/dist/modules/Order/utils.d.ts +4 -1
  36. package/dist/modules/Order/utils.js +185 -129
  37. package/dist/modules/Payment/walletpass.js +32 -6
  38. package/dist/modules/Product/types.d.ts +16 -0
  39. package/dist/modules/ProductList/index.js +1 -1
  40. package/dist/modules/ResourcePlanner/planner.d.ts +2 -0
  41. package/dist/modules/ResourcePlanner/planner.js +383 -24
  42. package/dist/modules/ResourcePlanner/types.d.ts +42 -0
  43. package/dist/modules/Rules/index.js +86 -54
  44. package/dist/modules/Schedule/index.d.ts +7 -1
  45. package/dist/modules/Schedule/index.js +155 -39
  46. package/dist/modules/Schedule/types.d.ts +2 -0
  47. package/dist/modules/bookingReadValidation.d.ts +6 -0
  48. package/dist/modules/bookingReadValidation.js +72 -0
  49. package/dist/plugins/request.d.ts +2 -0
  50. package/dist/server/index.d.ts +9 -0
  51. package/dist/server/index.js +1928 -1462
  52. package/dist/server/modules/form/index.d.ts +19 -0
  53. package/dist/server/modules/form/index.js +205 -0
  54. package/dist/server/modules/form/types.d.ts +13 -0
  55. package/dist/server/modules/form/types.js +3 -0
  56. package/dist/server/modules/index.d.ts +3 -0
  57. package/dist/server/modules/index.js +4 -0
  58. package/dist/server/modules/order/index.d.ts +21 -0
  59. package/dist/server/modules/order/index.js +1399 -831
  60. package/dist/server/modules/order/types.d.ts +3 -0
  61. package/dist/server/modules/order/utils/filterOrders.js +20 -0
  62. package/dist/server/modules/products/index.d.ts +28 -7
  63. package/dist/server/modules/products/index.js +1295 -769
  64. package/dist/server/modules/products/replication.d.ts +8 -0
  65. package/dist/server/modules/products/replication.js +69 -0
  66. package/dist/server/modules/products/types.d.ts +12 -1
  67. package/dist/server/modules/products/types.js +4 -0
  68. package/dist/shared/receipt/customerInvoiceLanguages.d.ts +1 -1
  69. package/dist/shared/receipt/customerInvoiceLanguages.js +5 -3
  70. package/dist/shared/receipt/small-ticket.d.ts +1 -0
  71. package/dist/shared/receipt/small-ticket.js +58 -26
  72. package/dist/shared/receipt/templateVisibility.d.ts +3 -0
  73. package/dist/shared/receipt/templateVisibility.js +6 -2
  74. package/dist/solution/BaseSales/fulfillmentItemRules.d.ts +27 -0
  75. package/dist/solution/BaseSales/fulfillmentItemRules.js +750 -0
  76. package/dist/solution/BaseSales/index.d.ts +22 -6
  77. package/dist/solution/BaseSales/index.js +1881 -1347
  78. package/dist/solution/BaseSales/pickupTiming.d.ts +4 -0
  79. package/dist/solution/BaseSales/pickupTiming.js +35 -8
  80. package/dist/solution/BaseSales/types.d.ts +4 -0
  81. package/dist/solution/BaseSales/types.js +1 -0
  82. package/dist/solution/BaseSales/utils/posDurationPricing.d.ts +21 -0
  83. package/dist/solution/BaseSales/utils/posDurationPricing.js +174 -0
  84. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +2 -0
  85. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +8 -8
  86. package/dist/solution/BookingByStep/index.d.ts +19 -3
  87. package/dist/solution/BookingByStep/index.js +681 -361
  88. package/dist/solution/BookingByStep/utils/resources.d.ts +10 -0
  89. package/dist/solution/BookingByStep/utils/resources.js +117 -76
  90. package/dist/solution/BookingTicket/index.d.ts +6 -0
  91. package/dist/solution/BookingTicket/index.js +666 -593
  92. package/dist/solution/BookingTicket/types.d.ts +1 -1
  93. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +2 -1
  94. package/dist/solution/BookingTicket/utils/addProductDecision.js +35 -8
  95. package/dist/solution/BookingTicket/utils/redeemArrival.d.ts +7 -7
  96. package/dist/solution/BookingTicket/utils/resolveUniqueCartDetail.d.ts +8 -0
  97. package/dist/solution/BookingTicket/utils/resolveUniqueCartDetail.js +188 -0
  98. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +58 -94
  99. package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +1 -3
  100. package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +33 -62
  101. package/dist/solution/OrderInvoicePreview/index.js +4 -3
  102. package/dist/solution/Sales/index.js +1 -1
  103. package/dist/solution/ScanOrder/index.d.ts +2 -0
  104. package/dist/solution/ScanOrder/index.js +230 -97
  105. package/dist/solution/ScanOrder/menuAvailability.d.ts +24 -0
  106. package/dist/solution/ScanOrder/menuAvailability.js +363 -0
  107. package/dist/solution/ScanOrder/types.d.ts +3 -0
  108. package/dist/solution/UnifiedBookingSales/index.d.ts +42 -10
  109. package/dist/solution/UnifiedBookingSales/index.js +2493 -1496
  110. package/dist/solution/UnifiedBookingSales/salesSettings.js +1 -1
  111. package/dist/solution/UnifiedBookingSales/types.d.ts +20 -5
  112. package/dist/utils/pos-receipt-auto-print.d.ts +4 -0
  113. package/dist/utils/pos-receipt-auto-print.js +14 -0
  114. package/lib/model/strategy/adapter/itemRule/adapter.d.ts +3 -1
  115. package/lib/model/strategy/adapter/itemRule/adapter.js +54 -4
  116. package/lib/model/strategy/adapter/itemRule/evaluator.d.ts +3 -1
  117. package/lib/model/strategy/adapter/itemRule/evaluator.js +9 -0
  118. package/lib/model/strategy/adapter/itemRule/type.d.ts +40 -1
  119. package/lib/model/strategy/adapter/itemRule/type.js +10 -0
  120. package/lib/model/strategy/adapter/promotion/evaluator.d.ts +2 -1
  121. package/lib/model/strategy/adapter/promotion/evaluator.js +22 -21
  122. package/lib/modules/BookingContext/utils/calendarBooking.d.ts +15 -0
  123. package/lib/modules/BookingContext/utils/calendarBooking.js +156 -0
  124. package/lib/modules/BookingContext/utils/index.d.ts +1 -0
  125. package/lib/modules/BookingContext/utils/index.js +11 -0
  126. package/lib/modules/BookingContext/utils/productExtend.d.ts +21 -0
  127. package/lib/modules/BookingContext/utils/productExtend.js +104 -5
  128. package/lib/modules/BookingContext/utils/resources.js +1 -1
  129. package/lib/modules/Cart/index.js +4 -2
  130. package/lib/modules/Cart/types.d.ts +2 -0
  131. package/lib/modules/Cart/utils/cartProduct.d.ts +3 -1
  132. package/lib/modules/Cart/utils/cartProduct.js +39 -20
  133. package/lib/modules/Date/index.d.ts +1 -1
  134. package/lib/modules/Date/index.js +28 -5
  135. package/lib/modules/Date/types.d.ts +5 -0
  136. package/lib/modules/OpenData/salesSettings.js +1 -1
  137. package/lib/modules/OpenData/types.d.ts +9 -0
  138. package/lib/modules/OpenData/utils.d.ts +1 -1
  139. package/lib/modules/OpenData/utils.js +3 -2
  140. package/lib/modules/Order/index.d.ts +22 -7
  141. package/lib/modules/Order/index.js +457 -174
  142. package/lib/modules/Order/localEftposState.d.ts +13 -0
  143. package/lib/modules/Order/localEftposState.js +44 -0
  144. package/lib/modules/Order/types.d.ts +33 -11
  145. package/lib/modules/Order/types.js +2 -2
  146. package/lib/modules/Order/unpaidAmountGap.d.ts +6 -0
  147. package/lib/modules/Order/unpaidAmountGap.js +60 -0
  148. package/lib/modules/Order/utils.d.ts +4 -1
  149. package/lib/modules/Order/utils.js +51 -3
  150. package/lib/modules/Payment/walletpass.js +23 -1
  151. package/lib/modules/Product/types.d.ts +16 -0
  152. package/lib/modules/ProductList/index.js +1 -1
  153. package/lib/modules/ResourcePlanner/planner.d.ts +2 -0
  154. package/lib/modules/ResourcePlanner/planner.js +299 -9
  155. package/lib/modules/ResourcePlanner/types.d.ts +42 -0
  156. package/lib/modules/Rules/index.js +32 -3
  157. package/lib/modules/Schedule/index.d.ts +7 -1
  158. package/lib/modules/Schedule/index.js +68 -4
  159. package/lib/modules/Schedule/types.d.ts +2 -0
  160. package/lib/modules/bookingReadValidation.d.ts +6 -0
  161. package/lib/modules/bookingReadValidation.js +56 -0
  162. package/lib/plugins/request.d.ts +2 -0
  163. package/lib/server/index.d.ts +9 -0
  164. package/lib/server/index.js +279 -30
  165. package/lib/server/modules/form/index.d.ts +19 -0
  166. package/lib/server/modules/form/index.js +73 -0
  167. package/lib/server/modules/form/types.d.ts +13 -0
  168. package/lib/server/modules/form/types.js +9 -0
  169. package/lib/server/modules/index.d.ts +3 -0
  170. package/lib/server/modules/index.js +15 -1
  171. package/lib/server/modules/order/index.d.ts +21 -0
  172. package/lib/server/modules/order/index.js +344 -35
  173. package/lib/server/modules/order/types.d.ts +3 -0
  174. package/lib/server/modules/order/utils/filterOrders.js +18 -0
  175. package/lib/server/modules/products/index.d.ts +28 -7
  176. package/lib/server/modules/products/index.js +224 -62
  177. package/lib/server/modules/products/replication.d.ts +8 -0
  178. package/lib/server/modules/products/replication.js +30 -0
  179. package/lib/server/modules/products/types.d.ts +12 -1
  180. package/lib/server/modules/products/types.js +3 -0
  181. package/lib/shared/receipt/customerInvoiceLanguages.d.ts +1 -1
  182. package/lib/shared/receipt/customerInvoiceLanguages.js +5 -3
  183. package/lib/shared/receipt/small-ticket.d.ts +1 -0
  184. package/lib/shared/receipt/small-ticket.js +53 -25
  185. package/lib/shared/receipt/templateVisibility.d.ts +3 -0
  186. package/lib/shared/receipt/templateVisibility.js +6 -2
  187. package/lib/solution/BaseSales/fulfillmentItemRules.d.ts +27 -0
  188. package/lib/solution/BaseSales/fulfillmentItemRules.js +259 -0
  189. package/lib/solution/BaseSales/index.d.ts +22 -6
  190. package/lib/solution/BaseSales/index.js +347 -59
  191. package/lib/solution/BaseSales/pickupTiming.d.ts +4 -0
  192. package/lib/solution/BaseSales/pickupTiming.js +24 -3
  193. package/lib/solution/BaseSales/types.d.ts +4 -0
  194. package/lib/solution/BaseSales/types.js +1 -0
  195. package/lib/solution/BaseSales/utils/posDurationPricing.d.ts +21 -0
  196. package/lib/solution/BaseSales/utils/posDurationPricing.js +133 -0
  197. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +2 -0
  198. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +1 -1
  199. package/lib/solution/BookingByStep/index.d.ts +19 -3
  200. package/lib/solution/BookingByStep/index.js +229 -17
  201. package/lib/solution/BookingByStep/utils/resources.d.ts +10 -0
  202. package/lib/solution/BookingByStep/utils/resources.js +25 -15
  203. package/lib/solution/BookingTicket/index.d.ts +6 -0
  204. package/lib/solution/BookingTicket/index.js +40 -5
  205. package/lib/solution/BookingTicket/types.d.ts +1 -1
  206. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +2 -1
  207. package/lib/solution/BookingTicket/utils/addProductDecision.js +34 -4
  208. package/lib/solution/BookingTicket/utils/redeemArrival.d.ts +7 -7
  209. package/lib/solution/BookingTicket/utils/resolveUniqueCartDetail.d.ts +8 -0
  210. package/lib/solution/BookingTicket/utils/resolveUniqueCartDetail.js +136 -0
  211. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +2 -14
  212. package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +1 -3
  213. package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +17 -34
  214. package/lib/solution/OrderInvoicePreview/index.js +1 -0
  215. package/lib/solution/Sales/index.js +1 -1
  216. package/lib/solution/ScanOrder/index.d.ts +2 -0
  217. package/lib/solution/ScanOrder/index.js +131 -22
  218. package/lib/solution/ScanOrder/menuAvailability.d.ts +24 -0
  219. package/lib/solution/ScanOrder/menuAvailability.js +203 -0
  220. package/lib/solution/ScanOrder/types.d.ts +3 -0
  221. package/lib/solution/UnifiedBookingSales/index.d.ts +42 -10
  222. package/lib/solution/UnifiedBookingSales/index.js +717 -144
  223. package/lib/solution/UnifiedBookingSales/salesSettings.js +1 -1
  224. package/lib/solution/UnifiedBookingSales/types.d.ts +20 -5
  225. package/lib/utils/pos-receipt-auto-print.d.ts +4 -0
  226. package/lib/utils/pos-receipt-auto-print.js +13 -0
  227. package/package.json +1 -1
@@ -33,6 +33,7 @@ var _dayjs = _interopRequireDefault(require("dayjs"));
33
33
  var _lodashEs = require("lodash-es");
34
34
  var _modules = require("../../modules");
35
35
  var _pickupTiming = require("../../modules/Order/pickupTiming");
36
+ var _cacheItemToBookingInput = require("../../modules/BookingContext/utils/cacheItemToBookingInput");
36
37
  var _utils = require("../../modules/BookingContext/utils");
37
38
  var _OpenData = require("../../modules/OpenData");
38
39
  var _salesSettings = require("./salesSettings");
@@ -70,6 +71,7 @@ var _venueCatalogSession = require("./venueCatalogSession");
70
71
  var _BookingTicket = require("../BookingTicket");
71
72
  var _localClock = require("../../modules/ResourcePlanner/localClock");
72
73
  var _platform = require("../../utils/platform");
74
+ var _posReceiptAutoPrint = require("../../utils/pos-receipt-auto-print");
73
75
  var _itemRule = require("../../model/strategy/adapter/itemRule");
74
76
  var _hostLogger = require("../../utils/hostLogger");
75
77
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
@@ -884,6 +886,20 @@ function collectAvailabilityResourceIds(products, explicitResourceIds = []) {
884
886
  function getProductLineUid(product) {
885
887
  return String(product?.metadata?.unique_identification_number ?? product?.unique_identification_number ?? '');
886
888
  }
889
+ function getVisibleCalendarDate(value) {
890
+ if (typeof value !== 'string') return null;
891
+ const raw = value.trim();
892
+ try {
893
+ if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) {
894
+ (0, _localClock.parseLocalDate)(raw);
895
+ } else {
896
+ (0, _localClock.parseLocalDateTime)(raw);
897
+ }
898
+ return raw.slice(0, 10);
899
+ } catch (_error) {
900
+ return null;
901
+ }
902
+ }
887
903
  function buildAvailabilityLineIdentity(product) {
888
904
  return {
889
905
  product_id: product.product_id,
@@ -1319,30 +1335,6 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1319
1335
  throw error;
1320
1336
  }
1321
1337
  }
1322
- async initializeUnifiedSalesRuntime(core, options) {
1323
- const initializationGeneration = ++this.runtimeInitializationGeneration;
1324
- this.resetRuntimeOpenData();
1325
- this.runtimeOpenDataDestroyed = false;
1326
- this.availabilityScheduleCatalog = null;
1327
- this.availabilityRuntimeOffsetMinutes = (0, _localClock.captureRuntimeOffsetMinutes)();
1328
- this.clearAvailabilityRemoteResourceState();
1329
- this.resetAllergyItemRuleState();
1330
- // BaseSales synchronously installs this runtime before its first await. Cache
1331
- // refreshes during that await are valid; they are not a new initialization.
1332
- const initialization = super.initialize(core, options);
1333
- const scope = this.getRuntimeOpenDataScope();
1334
- const openDataModule = this.store.openData;
1335
- await initialization;
1336
- if (this.runtimeOpenDataDestroyed || initializationGeneration !== this.runtimeInitializationGeneration) {
1337
- // A destroyed/reinitialized instance must not publish a ready snapshot.
1338
- return false;
1339
- }
1340
- if (core !== this.core || openDataModule !== this.store.openData || scope !== this.getRuntimeOpenDataScope()) {
1341
- throw new Error('Store settings changed. Please try again.');
1342
- }
1343
- this.captureAvailabilityScheduleCatalog();
1344
- return !this.runtimeOpenDataDestroyed && initializationGeneration === this.runtimeInitializationGeneration;
1345
- }
1346
1338
  getSubmitOrderSalesChannel() {
1347
1339
  const channel = String(this.otherParams?.channel ?? '').trim();
1348
1340
  return channel || super.getSubmitOrderSalesChannel();
@@ -1413,13 +1405,25 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1413
1405
  } : {})
1414
1406
  };
1415
1407
  }
1416
-
1417
- /** Kiosk keeps its device/channel semantics; only explicit Venue templates opt in. */
1418
- isVenueKioskPlatform(otherParams = this.otherParams || {}) {
1419
- return (0, _platform.normalizeRuntimePlatform)(otherParams.platform) === 'kiosk' && (otherParams.venueBookingMode === 'tickets' || otherParams.venueBookingMode === 'party');
1408
+ usesDurationTimeGrid(projection) {
1409
+ const platform = String(this.otherParams?.platform ?? '').trim().toLowerCase();
1410
+ return (platform === 'pos' || platform === 'kiosk') && (!projection || projection.products.some(product => product.kind === 'duration'));
1420
1411
  }
1421
- supportsVenueSelectionSnapshot() {
1422
- return (0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) || this.isVenueKioskPlatform();
1412
+ getCurrentAvailabilityBusinessDate(projection) {
1413
+ return (0, _ResourcePlanner.getDurationBusinessDate)(projection, this.getAvailabilityRuntimeDateTime());
1414
+ }
1415
+ getAvailabilityBusinessDateRange(projection) {
1416
+ const prepare = projection.meta.prepareParams;
1417
+ const range = prepare?.dateRange;
1418
+ if (!this.usesDurationTimeGrid(projection) || !range?.startDate || !range.endDate) {
1419
+ return projection.meta.coverage;
1420
+ }
1421
+ const businessDate = this.getCurrentAvailabilityBusinessDate(projection);
1422
+ const today = this.getAvailabilityRuntimeDateTime().slice(0, 10);
1423
+ return {
1424
+ startDate: range.startDate === today && businessDate < today ? businessDate : range.startDate,
1425
+ endDate: range.endDate
1426
+ };
1423
1427
  }
1424
1428
  normalizeAvailabilityIdList(values) {
1425
1429
  if (!Array.isArray(values) || values.length === 0) return undefined;
@@ -1464,6 +1468,180 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1464
1468
  mode
1465
1469
  });
1466
1470
  }
1471
+
1472
+ /**
1473
+ * 列表直加没有经过 SKU availability flow,legacy cacheItem 的灵活时长可能落到
1474
+ * 23:59。提交前用同一套营业排期补齐结束时间,保留已选开始时间、资源和 Holder。
1475
+ * 仅供直加调用;手动时间选择和 availability candidate 不经过此方法。
1476
+ */
1477
+ async prepareDirectAddFlexibleBooking(cacheItem) {
1478
+ if (!(0, _utils.isProductFlexibleDuration)(cacheItem?.duration) || (0, _utils.isSessionProduct)(cacheItem)) {
1479
+ return cacheItem;
1480
+ }
1481
+ const extend = cacheItem?._extend;
1482
+ const {
1483
+ startDate
1484
+ } = (0, _utils.getServiceTimes)(cacheItem);
1485
+ if (!extend?.start_date || !extend?.start_time || !startDate.isValid()) {
1486
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '灵活时长商品缺少有效开始时间');
1487
+ }
1488
+ const date = startDate.format('YYYY-MM-DD');
1489
+ // 带上前一天,覆盖凌晨仍处在前一营业时段内的情况。
1490
+ const dateRange = {
1491
+ startDate: startDate.subtract(1, 'day').format('YYYY-MM-DD'),
1492
+ endDate: date
1493
+ };
1494
+ const prepare = await this.resolveAvailabilityPrepareDefaults({
1495
+ dateRange
1496
+ });
1497
+ if (prepare._availabilityOperatingHours?.source !== 'open_data_schedule') {
1498
+ return cacheItem;
1499
+ }
1500
+ const operatingHours = this.buildAvailabilityOperatingHoursSnapshot({
1501
+ prepare,
1502
+ dateRange,
1503
+ scheduleList: this.getAvailabilityScheduleCatalog(),
1504
+ businessHours: DEFAULT_AVAILABILITY_BUSINESS_HOURS
1505
+ });
1506
+ if (operatingHours.missingScheduleIds.length > 0) {
1507
+ throw new _ResourcePlanner.AvailabilityError('OPERATING_HOURS_RESOLVE_FAILED', '店铺营业时间排期缺失,请重试', {
1508
+ missingScheduleIds: operatingHours.missingScheduleIds
1509
+ });
1510
+ }
1511
+ const start = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(startDate.format('YYYY-MM-DDTHH:mm:00')));
1512
+ const nextDay = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(`${startDate.add(1, 'day').format('YYYY-MM-DD')}T00:00:00`));
1513
+ const windows = operatingHours.windows.map(window => ({
1514
+ start: (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(window.startAt)),
1515
+ end: (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(window.endAt))
1516
+ })).filter(window => window.end > start && window.start < nextDay).sort((left, right) => left.start - right.start);
1517
+ const merged = [];
1518
+ for (const window of windows) {
1519
+ const previous = merged[merged.length - 1];
1520
+ if (previous && window.start <= previous.end) {
1521
+ previous.end = Math.max(previous.end, window.end);
1522
+ } else {
1523
+ merged.push({
1524
+ ...window
1525
+ });
1526
+ }
1527
+ }
1528
+ // POS 可以提前售票;保留开始分钟,结束取当前或当天下一段营业时间。
1529
+ // 不跨越午休,也不把闭店后的直加顺延到次日。
1530
+ let end = merged[0]?.end;
1531
+ const resourceEndAt = (0, _utils.getUsableTime)(cacheItem)?._extend?.usableTime?.end_at;
1532
+ if (resourceEndAt) {
1533
+ const resourceEnd = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)((0, _dayjs.default)(resourceEndAt).format('YYYY-MM-DDTHH:mm:00')));
1534
+ if (end !== undefined) end = Math.min(end, resourceEnd);
1535
+ }
1536
+ if (end === undefined || end <= start) {
1537
+ throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '当前时间没有可用营业时段,请选择预约时间');
1538
+ }
1539
+ const duration = Math.floor((end - start) / 60000);
1540
+ if (duration <= 0) {
1541
+ throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '灵活时长商品的结束时间必须晚于开始时间');
1542
+ }
1543
+ const endDate = (0, _dayjs.default)((0, _localClock.formatLocalDateTime)(start + duration * 60000));
1544
+ return {
1545
+ ...cacheItem,
1546
+ _extend: {
1547
+ ...extend,
1548
+ duration: _utils.flexibleObj.create(duration),
1549
+ endDate,
1550
+ end_date: endDate.format('YYYY-MM-DD'),
1551
+ end_time: endDate.format('HH:mm')
1552
+ }
1553
+ };
1554
+ }
1555
+
1556
+ /** Reuse an approved calendar cache; only the final commit may mutate the order. */
1557
+ async prepareDirectAddCalendarBooking(cacheItem, options = {}) {
1558
+ if ((0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform) !== 'pos' || cacheItem?._data?.calendarManualBooking || cacheItem?.duration?.type === 'days') return null;
1559
+ if (!cacheItem?._data?.calendarBookingPreparationKey || (0, _utils.calendarBookingNeedsInput)(cacheItem)) {
1560
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Calendar booking still requires product input.');
1561
+ }
1562
+ const productId = Number(cacheItem.product_id ?? cacheItem.id);
1563
+ const bookingCount = Number(options.bookingCount ?? cacheItem._extend?.quantity ?? 1);
1564
+ const capacity = cacheItem._extend?.capacity || [];
1565
+ const partySize = Array.isArray(capacity) ? Math.max(1, capacity.reduce((sum, item) => sum + Number(item.value), 0)) : NaN;
1566
+ if (!Number.isSafeInteger(productId) || productId <= 0 || !Number.isInteger(bookingCount) || bookingCount <= 0 || !Array.isArray(capacity) || !capacity.every(item => Number.isInteger(Number(item.value)) && Number(item.value) >= 0) || !Number.isInteger(partySize)) throw new _ResourcePlanner.AvailabilityError('INVALID_RESERVATION_QUANTITY', 'Invalid calendar booking quantity.');
1567
+ const product = normalizeProductForAvailability(cacheItem, this.getAvailabilityScheduleCatalog(), this.getAvailabilityRuntimeOffsetMinutes());
1568
+ if (product.kind !== 'duration' && product.kind !== 'session') return null;
1569
+ const range = {
1570
+ startAt: `${(0, _dayjs.default)(cacheItem._extend.start_date).format('YYYY-MM-DD')}T${cacheItem._extend.start_time}:00${(0, _localClock.formatFixedOffset)(this.getAvailabilityRuntimeOffsetMinutes())}`,
1571
+ endAt: `${(0, _dayjs.default)(cacheItem._extend.end_date).format('YYYY-MM-DD')}T${cacheItem._extend.end_time}:00${(0, _localClock.formatFixedOffset)(this.getAvailabilityRuntimeOffsetMinutes())}`
1572
+ };
1573
+ const requirementSelections = [];
1574
+ for (const [formId, rows] of Object.entries(cacheItem._extend?.resource || {})) {
1575
+ if (!Array.isArray(rows)) throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Invalid selected calendar resources.');
1576
+ if (!rows.length) continue;
1577
+ const groups = (product.requirementGroups || []).filter(group => String(group.formId) === formId);
1578
+ if (groups.length !== 1 || rows.some(row => row.form_id != null && String(row.form_id) !== formId)) {
1579
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Calendar resource group does not belong to this product.');
1580
+ }
1581
+ requirementSelections.push({
1582
+ requirementGroupId: groups[0].id,
1583
+ formId: groups[0].formId,
1584
+ resourceIds: rows.map(row => row.relation_id ?? row.resource_id)
1585
+ });
1586
+ }
1587
+ const order = this.getTempOrder();
1588
+ const calendarOrderSessionId = this.getOrderSessionId();
1589
+ const scope = JSON.stringify(this.getAvailabilityScopeDescriptor());
1590
+ const assertCurrent = () => {
1591
+ options.availabilityCommitGuard?.();
1592
+ if (calendarOrderSessionId && !this.isOrderSessionCurrent(calendarOrderSessionId) || this.getTempOrder() !== order || JSON.stringify(this.getAvailabilityScopeDescriptor()) !== scope) {
1593
+ throw new _ResourcePlanner.AvailabilityError('AVAILABILITY_SELECTION_STALE', 'Calendar booking order changed.');
1594
+ }
1595
+ };
1596
+ let contextId;
1597
+ try {
1598
+ assertCurrent();
1599
+ const context = await this.prepareAvailabilityProjection({
1600
+ productIds: [productId],
1601
+ dateRange: {
1602
+ startDate: range.startAt.slice(0, 10),
1603
+ endDate: range.endAt.slice(0, 10)
1604
+ },
1605
+ rawProducts: [...this.unifiedProductCatalog.filter(item => String(item.id) !== String(productId)), cacheItem]
1606
+ });
1607
+ contextId = context.contextId;
1608
+ assertCurrent();
1609
+ const groups = await this.getProductTimeRanges(contextId, {
1610
+ productIds: [productId],
1611
+ requestedRangesByProductId: {
1612
+ [String(productId)]: range
1613
+ }
1614
+ });
1615
+ assertCurrent();
1616
+ const ranges = groups.find(group => String(group.productId) === String(productId))?.ranges || [];
1617
+ if (ranges.length !== 1) throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', 'Calendar booking requires one exact interval.');
1618
+ const candidate = ranges[0];
1619
+ const contextEntry = this.getAvailabilityContextEntry(contextId);
1620
+ contextEntry.calendarOrderSessionId = calendarOrderSessionId ?? undefined;
1621
+ const projection = this.getActiveAvailabilityProjectionEntry(contextEntry).projection;
1622
+ const forced = buildPosForcedAvailabilityAssignments({
1623
+ product,
1624
+ resources: projection.resources,
1625
+ candidate,
1626
+ requirementSelections,
1627
+ partySize
1628
+ });
1629
+ if (forced.conflicts.length) throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', 'Invalid calendar resource selection.', {
1630
+ validation: forced
1631
+ });
1632
+ return {
1633
+ cacheItem,
1634
+ contextId,
1635
+ candidate,
1636
+ requirementSelections,
1637
+ partySize,
1638
+ bookingCount
1639
+ };
1640
+ } catch (error) {
1641
+ if (contextId) this.releaseAvailabilityContext(contextId);
1642
+ throw error;
1643
+ }
1644
+ }
1467
1645
  async resolveAvailabilityPrepareDefaults(params) {
1468
1646
  const needsOperatingHours = params.businessHours === undefined;
1469
1647
  const needsTimeSlice = params.slotStepMinutes === undefined;
@@ -1634,63 +1812,51 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1634
1812
  return typeof value === 'string' && value.trim() ? value : undefined;
1635
1813
  }
1636
1814
  createAvailabilityContextRef(context) {
1815
+ const projection = this.getActiveAvailabilityProjectionEntry(context)?.projection;
1637
1816
  return {
1638
- contextId: context.contextId
1817
+ contextId: context.contextId,
1818
+ ...(projection && this.usesDurationTimeGrid(projection) ? {
1819
+ durationTimeSelection: {
1820
+ version: 2,
1821
+ currentBusinessDate: this.getCurrentAvailabilityBusinessDate(projection),
1822
+ orderSessionId: this.getOrderSessionId()
1823
+ }
1824
+ } : {})
1639
1825
  };
1640
1826
  }
1641
- getSolutionLogContext() {
1642
- const context = {};
1643
- try {
1644
- Object.assign(context, {
1645
- solutionName: this.name,
1646
- moduleName: this.defaultName,
1647
- module: 'unifiedBookingSales',
1648
- cacheId: this.cacheId,
1649
- businessCode: this.otherParams?.businessCode ?? this.otherParams?.business_code,
1650
- platform: this.otherParams?.platform,
1651
- channel: this.otherParams?.channel
1652
- });
1653
- try {
1654
- const order = this.getTempOrder();
1655
- Object.assign(context, {
1656
- orderId: order?.order_id,
1657
- externalSaleNumber: order?.external_sale_number,
1658
- shopOrderNumber: order?.shop_order_number
1659
- });
1660
- } catch {/* A partially initialized order must not hide the failure log. */}
1827
+
1828
+ /** Accept the v2 interval only within the POS order that recorded it. */
1829
+ resolveOrderRememberedTimes(context, projection, ranges, orderSessionId) {
1830
+ if (ranges === undefined) return undefined;
1831
+ if (String(this.otherParams?.platform ?? '').trim().toLowerCase() !== 'pos' || context.prepareParams.editingProductLineUids?.length || !this.usesDurationTimeGrid(projection)) return undefined;
1832
+ this.assertRememberedOrderSession(orderSessionId);
1833
+ if (!isRecord(ranges) || !Object.keys(ranges).length) {
1834
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间区间不能为空');
1835
+ }
1836
+ const offset = (0, _localClock.extractFixedOffsetMinutes)(projection.meta.now) ?? this.getAvailabilityRuntimeOffsetMinutes();
1837
+ return Object.fromEntries(Object.entries(ranges).map(([productId, range]) => {
1661
1838
  try {
1662
- const order = this.store.order;
1663
- context.orderSessionId = order?.getOrderSessionId?.() ?? null;
1664
- } catch {/* Session context is optional during initialization and teardown. */}
1665
- } catch {/* Basic context remains useful even when some runtime fields cannot be read. */}
1666
- return context;
1667
- }
1668
- writeSolutionLog(type, title, metadata = {}, context = this.getSolutionLogContext()) {
1669
- try {
1670
- (0, _hostLogger.writeHostLog)(this.core, {
1671
- type,
1672
- title: `[UnifiedBookingSales] ${title}`,
1673
- metadata: {
1674
- ...context,
1675
- ...metadata
1676
- }
1677
- });
1678
- } catch {
1679
- // Reading diagnostic context must not change the sales result.
1680
- }
1839
+ const normalize = value => {
1840
+ if (typeof value !== 'string') throw new Error('Missing interval boundary');
1841
+ const scalar = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(value));
1842
+ const inputOffset = (0, _localClock.extractFixedOffsetMinutes)(value) ?? offset;
1843
+ return (0, _localClock.formatLocalDateTime)(scalar + (offset - inputOffset) * 60000, offset);
1844
+ };
1845
+ const startAt = normalize(range.startAt);
1846
+ const endAt = normalize(range.endAt);
1847
+ if (endAt <= startAt) throw new Error('Invalid interval');
1848
+ return [productId, {
1849
+ startAt,
1850
+ endAt
1851
+ }];
1852
+ } catch {
1853
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间必须包含有效且递增的开始和结束时间');
1854
+ }
1855
+ }));
1681
1856
  }
1682
- logSolutionFailure(method, error, metadata = {}, context, type) {
1683
- try {
1684
- const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : undefined;
1685
- const isBusinessFailure = error instanceof _ResourcePlanner.AvailabilityError && code !== 'OPERATING_HOURS_RESOLVE_FAILED' && code !== 'SELF_EXCLUSION_RESOLVE_FAILED';
1686
- this.writeSolutionLog(type ?? (code === 'AVAILABILITY_COMMIT_IN_PROGRESS' ? 'debug' : isBusinessFailure || code === 'REQUIRED_PRODUCT_MISSING' ? 'warning' : 'error'), `${method} failed`, {
1687
- ...metadata,
1688
- action: method,
1689
- errorCode: code,
1690
- errorMessage: (error instanceof Error ? error.message : String(error)).slice(0, 500)
1691
- }, context);
1692
- } catch {
1693
- // Error serialization is observational only.
1857
+ assertRememberedOrderSession(orderSessionId) {
1858
+ if (!orderSessionId || !this.isOrderSessionCurrent(orderSessionId)) {
1859
+ throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '记忆时间所属订单已变化,请重新选择');
1694
1860
  }
1695
1861
  }
1696
1862
  async emitAvailabilityDiagnostic(payload) {
@@ -1849,6 +2015,42 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1849
2015
  this.store.order?.clearSessionStoragePersistedTempOrder?.();
1850
2016
  }
1851
2017
 
2018
+ /** 在 Kiosk 拉起支付设备前补齐订单号,同一订单重试复用已分配的号码。 */
2019
+ async ensureLocalOrderNumbersForCheckout() {
2020
+ if ((0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform) !== 'kiosk') return;
2021
+ const order = this.store.order;
2022
+ const tempOrder = order?.getTempOrder();
2023
+ if (!tempOrder) throw new Error('当前订单不存在,无法生成订单编号');
2024
+ if (tempOrder.shop_order_number && tempOrder.shop_full_order_number) return;
2025
+ const biz = this.getBookingTicketBusinessCode();
2026
+ if (!biz) throw new Error('当前订单缺少业务类型,无法生成订单编号');
2027
+ const idGenerator = this.appPlugin?.getApp?.()?.getPlugin?.('idGenerator');
2028
+ if (!tempOrder.shop_order_number && typeof idGenerator?.generateShopOrderNumber !== 'function' || !tempOrder.shop_full_order_number && typeof idGenerator?.generateReceiptId !== 'function') {
2029
+ throw new Error('订单编号生成器不可用,请重启应用后重试');
2030
+ }
2031
+ try {
2032
+ if (!tempOrder.shop_order_number) {
2033
+ tempOrder.shop_order_number = await idGenerator.generateShopOrderNumber({
2034
+ biz
2035
+ });
2036
+ }
2037
+ if (!tempOrder.shop_full_order_number) {
2038
+ tempOrder.shop_full_order_number = await idGenerator.generateReceiptId({
2039
+ biz
2040
+ });
2041
+ }
2042
+ if (order.getTempOrder() !== tempOrder) {
2043
+ throw new Error('当前订单已切换,请重新发起支付');
2044
+ }
2045
+ if (!tempOrder.shop_order_number || !tempOrder.shop_full_order_number) {
2046
+ throw new Error('订单编号生成失败,请重试');
2047
+ }
2048
+ } finally {
2049
+ // 部分生成成功时也保留号码,后续只补仍然缺失的字段。
2050
+ if (order.getTempOrder() === tempOrder) order.persistTempOrder();
2051
+ }
2052
+ }
2053
+
1852
2054
  /**
1853
2055
  * PC/H5 及自助终端结账默认直接等待云端 checkout;POS/WebPOS 仍保持本地待同步。
1854
2056
  * 显式传 checkoutSyncTaskEnabled: true 时仍可回退到本地同步模式。
@@ -1991,13 +2193,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1991
2193
  this.otherParams.openData = injectedOpenData;
1992
2194
  this.openDataTarget = `${businessCode}+${this.getSubmitOrderSalesChannel()}`;
1993
2195
  }
1994
- const logContext = this.getSolutionLogContext();
1995
2196
  try {
1996
2197
  await this.loadOpenDataConfig();
1997
2198
  } catch (error) {
1998
- this.logSolutionFailure('prepareInvoiceTemplateAtSolutionReady', error, {
1999
- fallback: 'default'
2000
- }, logContext, 'warning');
2199
+ console.warn('[UnifiedBookingSales] Invoice 模板预加载失败,使用默认配置', error);
2001
2200
  }
2002
2201
  }
2003
2202
  async loadOpenDataConfig() {
@@ -2129,13 +2328,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2129
2328
  buildBookingCalcContext(extra) {
2130
2329
  return {
2131
2330
  ...super.buildBookingCalcContext(extra),
2132
- resolveDefaultBookingStart: (cacheItem, fallback) => this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
2331
+ resolveDefaultBookingStart: (cacheItem, fallback) => extra?.useCurrentTimeAfterRememberedExpiry ? (0, _salesSettings.normalizeBookingDateTime)(fallback) : this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
2133
2332
  };
2134
2333
  }
2135
2334
  buildAddProductCtx(extra) {
2136
2335
  return {
2137
2336
  ...super.buildAddProductCtx(extra),
2138
- resolveDefaultBookingStart: (cacheItem, fallback) => this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
2337
+ resolveDefaultBookingStart: (cacheItem, fallback) => extra?.useCurrentTimeAfterRememberedExpiry ? (0, _salesSettings.normalizeBookingDateTime)(fallback) : this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
2139
2338
  };
2140
2339
  }
2141
2340
 
@@ -2234,6 +2433,82 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2234
2433
  throw error;
2235
2434
  }
2236
2435
  }
2436
+
2437
+ /** Required products currently apply only to the online venue-ticket entry. */
2438
+ async validateRequiredProducts() {
2439
+ const businessCode = String(this.otherParams?.businessCode ?? this.otherParams?.business_code ?? '').trim();
2440
+ const channel = String(this.otherParams?.channel ?? '').trim();
2441
+ if (businessCode !== 'venue_ticket' || channel !== 'online_ordering') return;
2442
+ const scope = this.getPickupTimingScope();
2443
+ const order = this.getTempOrder();
2444
+ const runtimeConfig = this.otherParams?.itemRule || {};
2445
+ let configs = normalizeItemRuleStrategyConfigs(runtimeConfig.strategyConfigs);
2446
+ if (!configs.length) {
2447
+ const openData = await this.getOpenData();
2448
+ if (!toConfiguredBoolean(openData?.['sale.enable_item_rules'])) return;
2449
+ const ids = normalizePositiveIntegerList(openData?.['sale.enabled_item_rules']);
2450
+ if (!ids.length) return;
2451
+
2452
+ // Checkout must not use the allergy loader's fail-open fallback.
2453
+ const response = await this.request.get('/promotion', {
2454
+ skip: 1,
2455
+ num: 99,
2456
+ status: 'active',
2457
+ ids
2458
+ });
2459
+ if (response?.code !== 200 || !Array.isArray(response?.data?.list)) {
2460
+ throw new Error('Unable to load required product rules. Please try again.');
2461
+ }
2462
+ // Configured IDs can include disabled or deleted rules; only active results participate.
2463
+ configs = normalizeItemRuleStrategyConfigs(response.data.list.filter(item => ids.includes(Number(item?.id))).map(item => item?.metadata));
2464
+ }
2465
+ if (scope !== this.getPickupTimingScope() || order !== this.getTempOrder()) {
2466
+ throw new Error('The order changed. Please try again.');
2467
+ }
2468
+ const strategyConfigs = configs.filter(config => Array.isArray(config.actions)).map(config => ({
2469
+ ...config,
2470
+ actions: config.actions.filter(action => {
2471
+ const rules = action.config?.quantityRules;
2472
+ return action.type === 'QUANTITY_CHECK' && action.config?.targetType === 'product' && Array.isArray(rules) && rules.length > 0 && rules.every(rule => rule.source === 'fixed' && (rule.comparison === 'minimum' || rule.comparison === 'must_include'));
2473
+ })
2474
+ })).filter(config => config.actions.length > 0);
2475
+ if (!strategyConfigs.length) return;
2476
+ const cartItems = this.getOrderProducts().map(item => ({
2477
+ product_id: Number(item.product_id),
2478
+ quantity: Number(item.num)
2479
+ })).filter(item => Number.isFinite(item.product_id) && item.product_id > 0 && Number.isFinite(item.quantity) && item.quantity > 0);
2480
+ const result = new _itemRule.ItemRuleEvaluator().evaluate({
2481
+ strategyConfigs,
2482
+ cartItems,
2483
+ // Fixed-quantity rules do not consume pax; no customer headcount is collected.
2484
+ pax: {
2485
+ total: 0,
2486
+ adult: 0,
2487
+ child: 0
2488
+ },
2489
+ channel,
2490
+ submissionIndex: 0,
2491
+ custom: {
2492
+ ...runtimeConfig.custom,
2493
+ businessCode
2494
+ }
2495
+ });
2496
+ if (result.rawResults.some(evaluation => !evaluation.success)) {
2497
+ throw new Error('Unable to validate required product rules. Please try again.');
2498
+ }
2499
+ if (!result.allPassed) {
2500
+ const error = new Error(result.failedChecks[0]?.validationMessage || 'Please select the required product before checkout.');
2501
+ Object.assign(error, {
2502
+ code: 'REQUIRED_PRODUCT_MISSING',
2503
+ failures: result.failedChecks
2504
+ });
2505
+ throw error;
2506
+ }
2507
+ }
2508
+ async submitSalesOrder(params) {
2509
+ await this.validateRequiredProducts();
2510
+ return super.submitSalesOrder(params);
2511
+ }
2237
2512
  async ensureAllergyItemRuleConfigsLoaded() {
2238
2513
  if (this.allergyItemRuleConfigs.length > 0) {
2239
2514
  return this.allergyItemRuleConfigs;
@@ -2259,7 +2534,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2259
2534
  this.allergyItemRuleConfigs = loaded;
2260
2535
  this.allergyItemRuleEvaluator.setStrategyConfigs(loaded);
2261
2536
  return loaded;
2262
- })();
2537
+ })().catch(() => []);
2263
2538
  return this.allergyItemRuleConfigsPromise;
2264
2539
  }
2265
2540
 
@@ -2318,6 +2593,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2318
2593
  }
2319
2594
  return this.store.openData.getInvoiceTemplateSettings();
2320
2595
  }
2596
+ getPosReceiptAutoPrintPaymentStatuses() {
2597
+ const platform = (0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform);
2598
+ if (platform !== 'pos' && platform !== 'webpos') return undefined;
2599
+ if (!this.isInvoiceOpenDataCacheCurrent() || this.runtimeOpenDataModule !== this.store.openData || this.runtimeOpenDataCore !== this.core) return undefined;
2600
+ return (0, _posReceiptAutoPrint.normalizePosReceiptAutoPrintPaymentStatuses)(this.runtimeOpenDataSnapshot?.['documents.pos_receipt_auto_print_payment_statuses']);
2601
+ }
2321
2602
  isInvoiceOpenDataCacheCurrent() {
2322
2603
  const businessCode = String(this.otherParams?.businessCode || '').trim();
2323
2604
  const channel = String(this.otherParams?.channel || '').trim();
@@ -2345,13 +2626,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2345
2626
  * product because session products carry their fixed intervals there.
2346
2627
  */
2347
2628
  async loadProducts(params = {}, options) {
2348
- const catalogScope = this.otherParams.catalogScopeKey;
2349
2629
  const result = await this.loadCatalogProducts(params, options);
2350
- if (catalogScope !== this.otherParams.catalogScopeKey) {
2351
- throw Object.assign(new Error('Product scope changed'), {
2352
- name: 'AbortError'
2353
- });
2354
- }
2355
2630
  this.unifiedProductCatalog = Array.isArray(result) ? [...result] : [];
2356
2631
  await this.core.effects.emit(`${this.name}:onProductsLoaded`, result);
2357
2632
  return result;
@@ -3076,6 +3351,17 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3076
3351
  }
3077
3352
  buildUnifiedOrderProduct(sourceProduct, ownershipKey, product) {
3078
3353
  const normalizedProductRaw = product?.raw || {};
3354
+ const bookingQuote = sourceProduct._extend?.bookingPriceQuote;
3355
+ const isPos = (0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform) === 'pos';
3356
+ const quoteMethod = isPos ? bookingQuote?.pricing_method?.type : undefined;
3357
+ const hasDurationQuote = quoteMethod === 'duration_based';
3358
+ const quoteSourcePrice = bookingQuote?.sourceUnitPrice;
3359
+ const quoteDuration = bookingQuote?.duration;
3360
+ if (hasDurationQuote && (quoteSourcePrice === undefined || quoteSourcePrice === null || quoteSourcePrice === '' || !Number.isFinite(Number(quoteSourcePrice)) || Number(quoteSourcePrice) < 0 || quoteDuration?.type !== 'minutes' || !Number.isFinite(Number(quoteDuration.value)) || Number(quoteDuration.value) <= 0)) {
3361
+ throw Object.assign(new Error('按时长计价结果无效,请重新选择预约时间。'), {
3362
+ code: 'DURATION_PRICING_UNAVAILABLE'
3363
+ });
3364
+ }
3079
3365
  const quotationShelfId = sourceProduct._extend?.quotation_shelf_id ?? sourceProduct.quotation_shelf_id ?? sourceProduct.metadata?.quotation_shelf_id;
3080
3366
  const orderProduct = this.transformBaseProductToOrderProduct({
3081
3367
  payload: {
@@ -3090,7 +3376,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3090
3376
  [ownershipKey]: true
3091
3377
  }
3092
3378
  },
3093
- sourceProduct
3379
+ sourceProduct,
3380
+ ...(hasDurationQuote ? {
3381
+ quotedSourceProductPrice: quoteSourcePrice
3382
+ } : {})
3094
3383
  });
3095
3384
  if (orderProduct && typeof orderProduct === 'object') {
3096
3385
  const venueMetadata = Object.fromEntries(['venue_booking_role', 'venue_booking_parent_uid', 'venue_booking_service_datetime', 'venue_booking_scope_key'].filter(key => sourceProduct.metadata?.[key] !== undefined).map(key => [key, sourceProduct.metadata[key]]));
@@ -3108,6 +3397,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3108
3397
  ...(orderProduct.metadata || {}),
3109
3398
  ...venueMetadata,
3110
3399
  [ownershipKey]: true,
3400
+ ...(hasDurationQuote || quoteMethod === 'fixed_price' ? {
3401
+ pricing_method: {
3402
+ type: quoteMethod
3403
+ },
3404
+ duration: hasDurationQuote ? {
3405
+ ...quoteDuration
3406
+ } : undefined
3407
+ } : {}),
3111
3408
  ...(quotationShelfId !== undefined ? {
3112
3409
  quotation_shelf_id: quotationShelfId
3113
3410
  } : {})
@@ -3366,7 +3663,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3366
3663
  return range ? [{
3367
3664
  startAt: range.startAt,
3368
3665
  endAt: range.endAt,
3369
- source: descriptor.source
3666
+ source: descriptor.source,
3667
+ businessDate: date,
3668
+ openingAnchorAt: range.startAt
3370
3669
  }] : [];
3371
3670
  });
3372
3671
  return {
@@ -3390,7 +3689,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3390
3689
  return range ? [{
3391
3690
  startAt: range.startAt,
3392
3691
  endAt: range.endAt,
3393
- source: `operating_schedule:${descriptor.scheduleIds.map(String).join(',')}`
3692
+ source: `operating_schedule:${descriptor.scheduleIds.map(String).join(',')}`,
3693
+ businessDate: date
3394
3694
  }] : [];
3395
3695
  }));
3396
3696
  const excludedWindows = dateRangeDays(params.dateRange).flatMap(date => schedules.flatMap(schedule => getExcludedScheduleDateOverrideTimePoints(date, schedule).flatMap(slot => {
@@ -3404,12 +3704,23 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3404
3704
  startAt: range.startAt,
3405
3705
  endAt: range.endAt,
3406
3706
  source: `operating_schedule_excluded:${schedule.id}`,
3707
+ businessDate: date,
3407
3708
  raw: {
3408
3709
  scheduleId: schedule.id,
3409
3710
  excludedDate: date
3410
3711
  }
3411
3712
  }] : [];
3412
3713
  })));
3714
+ // All lunch-break windows share the first opening of their business day.
3715
+ const openings = new Map();
3716
+ [...windows, ...excludedWindows].forEach(window => {
3717
+ const date = window.businessDate || window.startAt.slice(0, 10);
3718
+ const previous = openings.get(date);
3719
+ if (!previous || window.startAt < previous) openings.set(date, window.startAt);
3720
+ });
3721
+ [...windows, ...excludedWindows].forEach(window => {
3722
+ window.openingAnchorAt = openings.get(window.businessDate || window.startAt.slice(0, 10));
3723
+ });
3413
3724
  return {
3414
3725
  source: descriptor.source,
3415
3726
  scheduleIds: [...descriptor.scheduleIds],
@@ -3463,12 +3774,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3463
3774
  schedule_date: prepare.catalogScope.params.schedule_date || dateRange.startDate
3464
3775
  });
3465
3776
  }
3466
- const normalized = rawProducts.map(product => normalizeProductForAvailability(product, params.scheduleList, this.getAvailabilityRuntimeOffsetMinutes()));
3777
+ const productIdSet = explicitProductIds.length ? new Set(explicitProductIds.map(String)) : null;
3778
+ const normalized = (productIdSet ? rawProducts.filter(product => productIdSet.has(String(product.id ?? product.product_id))) : rawProducts).map(product => normalizeProductForAvailability(product, params.scheduleList, this.getAvailabilityRuntimeOffsetMinutes()));
3467
3779
  if (!explicitProductIds.length && prepare.resourceIds?.length) {
3468
3780
  return normalized.filter(product => product.requirementGroups?.some(group => group.resourceIds?.some(resourceId => prepare.resourceIds.some(id => sameAvailabilityId(id, resourceId)))));
3469
3781
  }
3470
- const productIdSet = explicitProductIds.length ? new Set(explicitProductIds.map(String)) : null;
3471
- return productIdSet ? normalized.filter(product => productIdSet.has(String(product.id))) : normalized;
3782
+ return normalized;
3472
3783
  }
3473
3784
 
3474
3785
  /**
@@ -3907,6 +4218,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3907
4218
  lastPreparedAt: params.projection.meta.preparedAt,
3908
4219
  lastSnapshotId: params.projection.meta.snapshotId,
3909
4220
  durationCandidateAnchorAt: previousContext?.durationCandidateAnchorAt ?? this.getAvailabilityDurationCandidateAnchorAt(params.projection),
4221
+ calendarOrderSessionId: previousContext?.calendarOrderSessionId,
3910
4222
  refreshNonce: previousContext?.refreshNonce ?? 0,
3911
4223
  lifecycleGeneration: this.availabilityLifecycleGeneration
3912
4224
  };
@@ -3918,24 +4230,34 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3918
4230
  const normalizedPrepareParams = this.normalizeAvailabilityPrepareDescriptor(params);
3919
4231
  const timezoneLabel = String(normalizedPrepareParams.timezone);
3920
4232
  const dateRange = normalizedPrepareParams.dateRange;
4233
+ const scheduleList = this.getAvailabilityScheduleCatalog();
4234
+ const products = await this.loadAvailabilityProducts({
4235
+ prepare: normalizedPrepareParams,
4236
+ dateRange,
4237
+ scheduleList
4238
+ });
4239
+ // Coverage is physical local time; the caller's date range remains business
4240
+ // dates. Keep yesterday's opening and the last business day's overnight tail.
4241
+ const useDurationTimeGrid = this.usesDurationTimeGrid() && products.some(product => product.kind === 'duration');
4242
+ const coverageDateRange = useDurationTimeGrid ? {
4243
+ startDate: (0, _localClock.formatLocalDate)((0, _localClock.addLocalCalendarDays)((0, _localClock.localDateToScalarStart)((0, _localClock.parseLocalDate)(dateRange.startDate)), -1)),
4244
+ endDate: (0, _localClock.formatLocalDate)((0, _localClock.addLocalCalendarDays)((0, _localClock.localDateToScalarStart)((0, _localClock.parseLocalDate)(dateRange.endDate)), 1))
4245
+ } : dateRange;
3921
4246
  const slotStepMinutes = normalizedPrepareParams.slotStepMinutes || DEFAULT_AVAILABILITY_SLOT_STEP_MINUTES;
3922
4247
  const businessHours = normalizedPrepareParams.businessHours || DEFAULT_AVAILABILITY_BUSINESS_HOURS;
3923
4248
  const mode = normalizedPrepareParams.mode || 'appointment';
3924
- const scheduleList = this.getAvailabilityScheduleCatalog();
3925
4249
  const operatingHours = this.buildAvailabilityOperatingHoursSnapshot({
3926
4250
  prepare: normalizedPrepareParams,
3927
- dateRange,
4251
+ dateRange: useDurationTimeGrid ? {
4252
+ startDate: coverageDateRange.startDate,
4253
+ endDate: dateRange.endDate
4254
+ } : dateRange,
3928
4255
  scheduleList,
3929
4256
  businessHours
3930
4257
  });
3931
- const products = await this.loadAvailabilityProducts({
3932
- prepare: normalizedPrepareParams,
3933
- dateRange,
3934
- scheduleList
3935
- });
3936
4258
  const loadedResources = await this.loadAvailabilityResources({
3937
4259
  timezone: timezoneLabel,
3938
- dateRange,
4260
+ dateRange: coverageDateRange,
3939
4261
  resourceIds: normalizedPrepareParams.resourceIds,
3940
4262
  products,
3941
4263
  rawResources: normalizedPrepareParams.rawResources,
@@ -3973,7 +4295,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3973
4295
  resourceOccupancies: [...remoteOccupancies, ...cartOccupancies],
3974
4296
  mode,
3975
4297
  timezone: timezoneLabel,
3976
- coverage: dateRange,
4298
+ coverage: coverageDateRange,
3977
4299
  slotStepMinutes,
3978
4300
  businessHours,
3979
4301
  operatingHours,
@@ -4253,9 +4575,64 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4253
4575
  const contextVersion = context.activeVersion;
4254
4576
  const strictAvailability = context.prepareParams.strictAvailability === true;
4255
4577
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
4256
- const allowOutsideOperatingHoursForRequestedStartTimes = isPosAvailabilityRequest && !strictAvailability && Object.values(request.durationStartTimesByProductId || {}).some(startTimes => Array.isArray(startTimes) && startTimes.length > 0);
4578
+ const isEditingContext = Boolean(context.prepareParams.editingProductLineUids?.length);
4579
+ const editingOffset = (0, _localClock.extractFixedOffsetMinutes)(projectionEntry.projection.meta.now) ?? this.getAvailabilityRuntimeOffsetMinutes();
4580
+ const hasRequestedRanges = Object.keys(request.requestedRangesByProductId || {}).length > 0;
4581
+ if (hasRequestedRanges && (!isPosAvailabilityRequest || strictAvailability || request.rememberedStartAtByProductId || request.rememberedTimeByProductId)) {
4582
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '明确预约范围仅支持 POS 手工选择');
4583
+ }
4584
+ // Calendar entry carries absolute instants. Convert both endpoints once to
4585
+ // the projection clock; never reinterpret their HH:mm as a business date.
4586
+ const requestedRangesByProductId = hasRequestedRanges ? Object.fromEntries(Object.entries(request.requestedRangesByProductId).map(([productId, range]) => {
4587
+ try {
4588
+ const normalizeEndpoint = value => {
4589
+ const scalar = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(value));
4590
+ const inputOffset = (0, _localClock.extractFixedOffsetMinutes)(value) ?? editingOffset;
4591
+ return (0, _localClock.formatLocalDateTime)(scalar + (editingOffset - inputOffset) * 60000, editingOffset);
4592
+ };
4593
+ return [productId, {
4594
+ startAt: normalizeEndpoint(range.startAt),
4595
+ endAt: normalizeEndpoint(range.endAt)
4596
+ }];
4597
+ } catch {
4598
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '手工预约范围必须包含完整有效起止日期时间');
4599
+ }
4600
+ })) : undefined;
4601
+ // This new editing input represents an absolute instant. Normalize it once
4602
+ // to the projection's fixed business clock before the wall-clock planner.
4603
+ const editingStartAtByProductId = isEditingContext && request.editingStartAtByProductId ? Object.fromEntries(Object.entries(request.editingStartAtByProductId).map(([productId, startAt]) => {
4604
+ try {
4605
+ const scalar = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(startAt));
4606
+ const inputOffset = (0, _localClock.extractFixedOffsetMinutes)(startAt) ?? editingOffset;
4607
+ return [productId, (0, _localClock.formatLocalDateTime)(scalar + (editingOffset - inputOffset) * 60000, editingOffset)];
4608
+ } catch {
4609
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '编辑开始时间必须是完整有效日期时间');
4610
+ }
4611
+ })) : undefined;
4612
+ let dateRange = request.dateRange || this.getAvailabilityBusinessDateRange(projectionEntry.projection);
4613
+ // Older edit drafts carry the real calendar date, not a business-date label.
4614
+ // The explicit absolute start disambiguates the previous day's overnight tail.
4615
+ const editingStarts = Object.values(editingStartAtByProductId || {});
4616
+ if (this.usesDurationTimeGrid(projectionEntry.projection) && editingStarts.length === 1 && dateRange.startDate === dateRange.endDate && dateRange.startDate === (0, _localClock.formatLocalDate)((0, _localClock.parseLocalDateTime)(editingStarts[0]))) {
4617
+ const businessDate = (0, _ResourcePlanner.getDurationBusinessDate)(projectionEntry.projection, editingStarts[0]);
4618
+ dateRange = {
4619
+ startDate: businessDate,
4620
+ endDate: businessDate
4621
+ };
4622
+ }
4623
+ const rememberedTimeByProductId = this.resolveOrderRememberedTimes(context, projectionEntry.projection, request.rememberedTimeByProductId, request.orderSessionId);
4624
+ const rememberedStartAtByProductId = !rememberedTimeByProductId && isPosAvailabilityRequest && !isEditingContext ? request.rememberedStartAtByProductId : undefined;
4625
+ const allowOutsideOperatingHoursForRequestedStartTimes = isPosAvailabilityRequest && !strictAvailability && !rememberedStartAtByProductId && !rememberedTimeByProductId && (editingStarts.length > 0 || Object.values(request.durationStartTimesByProductId || {}).some(startTimes => Array.isArray(startTimes) && startTimes.length > 0));
4257
4626
  return (0, _ResourcePlanner.getProductTimeRanges)(projectionEntry.projection, {
4258
4627
  ...request,
4628
+ dateRange,
4629
+ editingStartAtByProductId,
4630
+ requestedRangesByProductId,
4631
+ rememberedStartAtByProductId,
4632
+ rememberedTimeByProductId,
4633
+ ...(rememberedStartAtByProductId || rememberedTimeByProductId ? {
4634
+ allowOutsideOperatingHoursForRequestedStartTimes: false
4635
+ } : {}),
4259
4636
  ...(allowOutsideOperatingHoursForRequestedStartTimes ? {
4260
4637
  allowOutsideOperatingHoursForRequestedStartTimes: true
4261
4638
  } : {}),
@@ -4264,8 +4641,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4264
4641
  } : {})
4265
4642
  }, {
4266
4643
  evaluatedAt: this.getAvailabilityRuntimeDateTime(),
4644
+ useDurationTimeGrid: this.usesDurationTimeGrid(projectionEntry.projection),
4645
+ enforceSaleCutoff: strictAvailability || Boolean(rememberedStartAtByProductId || rememberedTimeByProductId),
4646
+ rememberedTimeByProductId,
4267
4647
  useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
4268
4648
  allowSessionCustomRanges: isPosAvailabilityRequest && !strictAvailability,
4649
+ allowRequestedRanges: isPosAvailabilityRequest && !strictAvailability && !rememberedStartAtByProductId && !rememberedTimeByProductId,
4269
4650
  allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
4270
4651
  }).map(group => ({
4271
4652
  ...group,
@@ -4284,10 +4665,18 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4284
4665
  this.assertContextualQueryFreshness(context, request);
4285
4666
  const strictAvailability = context.prepareParams.strictAvailability === true;
4286
4667
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
4287
- const result = (0, _ResourcePlanner.queryAvailabilityProjection)(projectionEntry.projection, request, {
4668
+ const rememberedTimeByProductId = request.selectionIntent === 'remembered' ? this.resolveOrderRememberedTimes(context, projectionEntry.projection, request.rememberedTimeByProductId, request.orderSessionId) : undefined;
4669
+ const queryRequest = request.target === 'date' || request.target === 'product' ? {
4670
+ ...request,
4671
+ dateRange: request.dateRange || this.getAvailabilityBusinessDateRange(projectionEntry.projection)
4672
+ } : request;
4673
+ const result = (0, _ResourcePlanner.queryAvailabilityProjection)(projectionEntry.projection, queryRequest, {
4288
4674
  ...(customerSelectionSnapshot ? {
4289
4675
  evaluatedAt: projectionEntry.projection.meta.now
4290
4676
  } : {}),
4677
+ useDurationTimeGrid: this.usesDurationTimeGrid(projectionEntry.projection),
4678
+ enforceSaleCutoff: strictAvailability || isPosAvailabilityRequest && !context.prepareParams.editingProductLineUids?.length && request.selectionIntent === 'remembered',
4679
+ rememberedTimeByProductId,
4291
4680
  useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
4292
4681
  allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
4293
4682
  });
@@ -4381,8 +4770,26 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4381
4770
  const bookingUid = String(product.booking_uid ?? product.metadata?.booking_uid ?? '');
4382
4771
  return (this.getTempOrder()?.bookings || []).find(booking => bookingUid && getBookingUid(booking) === bookingUid || productUid && String(booking.product_uid ?? '') === productUid);
4383
4772
  }
4773
+ async removeBookingProductsOutsideStartDate(startDate) {
4774
+ const products = this.getTempOrder()?.products || [];
4775
+ if (this.otherParams?.enforceSingleBookingStartDate !== true) {
4776
+ return products;
4777
+ }
4778
+ const targetDate = getVisibleCalendarDate(startDate);
4779
+ if (!targetDate) return products;
4780
+ const identities = products.flatMap(product => {
4781
+ if (!getProductLineUid(product) || product?.metadata?.product_add_schedule_time != null) {
4782
+ return [];
4783
+ }
4784
+ const booking = this.findLinkedBooking(product);
4785
+ if (!booking || (0, _pickupTiming.isFulfillmentTimingBooking)(booking)) return [];
4786
+ const bookingDate = getVisibleCalendarDate(booking.start_date);
4787
+ return bookingDate && bookingDate !== targetDate ? [buildAvailabilityLineIdentity(product)] : [];
4788
+ });
4789
+ return identities.length ? this.removeProductsFromOrder(identities) : products;
4790
+ }
4384
4791
 
4385
- /** Customer snapshot writes defer availability to checkout; other callers retain cache revalidation. */
4792
+ /** Revalidates against the latest landed occupancy cache, then mutates exactly one product line. */
4386
4793
  async commitAvailabilitySelection(contextId, params) {
4387
4794
  const logContext = this.getSolutionLogContext();
4388
4795
  try {
@@ -4402,27 +4809,49 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4402
4809
  candidate: params.candidate
4403
4810
  });
4404
4811
  }
4812
+ const calendarOrderSessionId = this.availabilityContextRegistry.get(normalizedContextId)?.calendarOrderSessionId;
4813
+ if (calendarOrderSessionId) {
4814
+ const callerGuard = params.availabilityCommitGuard;
4815
+ params = {
4816
+ ...params,
4817
+ availabilityCommitGuard: () => {
4818
+ callerGuard?.();
4819
+ if (!this.isOrderSessionCurrent(calendarOrderSessionId)) {
4820
+ throw new _ResourcePlanner.AvailabilityError('AVAILABILITY_SELECTION_STALE', 'Calendar booking order session changed.');
4821
+ }
4822
+ }
4823
+ };
4824
+ }
4405
4825
  const isEditingSelection = params.mode === 'edit' || params.mode === 'replace';
4406
4826
  const isPartyReplacement = params.mode === 'replace' || params.relatedRetailProducts !== undefined;
4407
4827
  if (isPartyReplacement && (!isEditingSelection || !Array.isArray(params.relatedRetailProducts))) {
4408
4828
  throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Party replacement requires edit/replace mode and the confirmed complete extras array');
4409
4829
  }
4410
4830
  const customerSelectionSnapshot = params.customerSelectionSnapshot === true && this.supportsVenueSelectionSnapshot();
4831
+ const isRememberedSelection = params.selectionIntent === 'remembered';
4832
+ const isOrderRememberedSelection = isRememberedSelection && params.orderSessionId !== undefined;
4833
+ if (isRememberedSelection && (String(this.otherParams?.platform ?? '').trim().toLowerCase() !== 'pos' || params.mode !== 'add')) {
4834
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间自动提交仅支持 POS 新增 duration 商品');
4835
+ }
4411
4836
  const strictAvailability = this.availabilityContextRegistry.get(normalizedContextId)?.prepareParams.strictAvailability === true;
4412
- const hasCommitGuard = customerSelectionSnapshot || strictAvailability || isPartyReplacement || Boolean(params.availabilityCommitGuard);
4837
+ const hasCommitGuard = customerSelectionSnapshot || strictAvailability || isRememberedSelection || isPartyReplacement || Boolean(params.availabilityCommitGuard);
4413
4838
  params.availabilityCommitGuard?.();
4414
- // Stabilize the locally generated sale identity before taking the guard snapshot.
4415
4839
  if (hasCommitGuard) this.store.order?.ensureTempOrder?.();
4416
- const guardedOrder = hasCommitGuard ? this.getTempOrder() : null;
4417
- const getGuardedCommitIdentity = () => JSON.stringify(stableValue({
4840
+ if (isOrderRememberedSelection) this.assertRememberedOrderSession(params.orderSessionId);
4841
+ let rememberedOrder = hasCommitGuard ? this.getTempOrder() : null;
4842
+ const getRememberedCommitIdentity = () => JSON.stringify(stableValue({
4418
4843
  scope: this.getAvailabilityScopeDescriptor(),
4419
4844
  shopId: this.otherParams?.shop_id ?? this.otherParams?.shopId,
4420
4845
  contextShopId: this.core?.context?.shop_id,
4421
- orderId: this.getTempOrder()?.order_id,
4422
- externalSaleNumber: this.getTempOrder()?.external_sale_number
4846
+ ...(isOrderRememberedSelection ? {
4847
+ orderSessionId: this.getOrderSessionId()
4848
+ } : {
4849
+ orderId: this.getTempOrder()?.order_id,
4850
+ externalSaleNumber: this.getTempOrder()?.external_sale_number
4851
+ })
4423
4852
  }));
4424
- const guardedCommitIdentity = hasCommitGuard ? getGuardedCommitIdentity() : '';
4425
- const availabilityCommitTargetGuard = () => this.getTempOrder() === guardedOrder && getGuardedCommitIdentity() === guardedCommitIdentity;
4853
+ const rememberedCommitIdentity = hasCommitGuard ? getRememberedCommitIdentity() : '';
4854
+ const availabilityCommitTargetGuard = () => (isOrderRememberedSelection ? this.isOrderSessionCurrent(params.orderSessionId) : this.getTempOrder() === rememberedOrder) && getRememberedCommitIdentity() === rememberedCommitIdentity;
4426
4855
  let guardedCommitPublished = false;
4427
4856
  await this.tryAcquireAvailabilityCommitLock(normalizedContextId);
4428
4857
  try {
@@ -4529,6 +4958,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4529
4958
  });
4530
4959
  }
4531
4960
  const baseProjection = projectionEntry.projection;
4961
+ const selectedProduct = baseProjection.products.find(item => sameAvailabilityId(item.id, params.candidate.productId));
4962
+ if (isRememberedSelection && (String(this.otherParams?.platform ?? '').trim().toLowerCase() !== 'pos' || params.mode !== 'add' || selectedProduct?.kind !== 'duration')) {
4963
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间自动提交仅支持 POS 新增 duration 商品');
4964
+ }
4532
4965
  let commitWriteGuard = {
4533
4966
  contextId: normalizedContextId,
4534
4967
  expectedVersion: context.activeVersion,
@@ -4578,17 +5011,48 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4578
5011
  this.assertAvailabilityCommitWriteCAS(commitWriteGuard);
4579
5012
  const candidateDurationMinutes = getCandidateDurationMinutes(params.candidate);
4580
5013
  const candidateStartTime = getCandidateStartTime(params.candidate);
4581
- const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !strictAvailability;
4582
- const refreshedRanges = customerSelectionSnapshot ? [params.candidate] : (0, _ResourcePlanner.getProductTimeRanges)(refreshedProjection, {
5014
+ const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !isRememberedSelection && !strictAvailability;
5015
+ const candidateBusinessDate = params.candidate.businessDate || (selectedProduct?.kind === 'duration' && this.usesDurationTimeGrid(refreshedProjection) ? (0, _ResourcePlanner.getDurationBusinessDate)(refreshedProjection, params.candidate.startAt) : params.candidate.startAt.slice(0, 10));
5016
+ const rememberedTimeByProductId = isOrderRememberedSelection ? this.resolveOrderRememberedTimes(context, refreshedProjection, {
5017
+ [String(params.candidate.productId)]: {
5018
+ startAt: params.candidate.bookingStartAt,
5019
+ endAt: params.candidate.bookingEndAt
5020
+ }
5021
+ }, params.orderSessionId) : undefined;
5022
+ const refreshedRanges = (0, _ResourcePlanner.getProductTimeRanges)(refreshedProjection, {
4583
5023
  productIds: [params.candidate.productId],
4584
5024
  dateRange: {
4585
- startDate: params.candidate.startAt.slice(0, 10),
4586
- endDate: params.candidate.startAt.slice(0, 10)
5025
+ startDate: candidateBusinessDate,
5026
+ endDate: candidateBusinessDate
4587
5027
  },
4588
- ...(candidateDurationMinutes ? {
5028
+ ...(allowPosAvailabilityOverride && params.candidate.source === 'duration_window' ? {
5029
+ requestedRangesByProductId: {
5030
+ [String(params.candidate.productId)]: {
5031
+ startAt: params.candidate.bookingStartAt,
5032
+ endAt: params.candidate.bookingEndAt
5033
+ }
5034
+ }
5035
+ } : {}),
5036
+ ...(rememberedTimeByProductId ? {
5037
+ rememberedTimeByProductId
5038
+ } : isRememberedSelection ? {
5039
+ rememberedStartAtByProductId: {
5040
+ [String(params.candidate.productId)]: params.candidate.bookingStartAt
5041
+ },
5042
+ ...(!selectedProduct?.isFlexibleDuration && candidateDurationMinutes ? {
5043
+ durationMinutesByProductId: {
5044
+ [String(params.candidate.productId)]: candidateDurationMinutes
5045
+ }
5046
+ } : {})
5047
+ } : candidateDurationMinutes ? {
4589
5048
  durationMinutesByProductId: {
4590
5049
  [String(params.candidate.productId)]: candidateDurationMinutes
4591
5050
  },
5051
+ ...(isEditingSelection && selectedProduct?.kind === 'duration' ? {
5052
+ editingStartAtByProductId: {
5053
+ [String(params.candidate.productId)]: params.candidate.bookingStartAt
5054
+ }
5055
+ } : {}),
4592
5056
  ...(candidateStartTime ? {
4593
5057
  durationStartTimesByProductId: {
4594
5058
  [String(params.candidate.productId)]: [candidateStartTime]
@@ -4599,11 +5063,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4599
5063
  } : {})
4600
5064
  } : {})
4601
5065
  }, {
4602
- ...(strictAvailability ? {
4603
- evaluatedAt: this.getAvailabilityRuntimeDateTime()
4604
- } : {}),
5066
+ evaluatedAt: this.getAvailabilityRuntimeDateTime(),
5067
+ useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
5068
+ enforceSaleCutoff: strictAvailability || isRememberedSelection,
5069
+ rememberedTimeByProductId,
4605
5070
  useExactDurationCandidateMinute: allowPosAvailabilityOverride,
4606
5071
  allowSessionCustomRanges: allowPosAvailabilityOverride,
5072
+ allowRequestedRanges: allowPosAvailabilityOverride,
4607
5073
  allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
4608
5074
  }).flatMap(group => group.ranges);
4609
5075
  const refreshedCandidateBase = refreshedRanges.find(candidate => candidate.startAt === params.candidate.startAt && candidate.endAt === params.candidate.endAt && candidate.bookingStartAt === params.candidate.bookingStartAt && candidate.bookingEndAt === params.candidate.bookingEndAt);
@@ -4632,6 +5098,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4632
5098
  partySize,
4633
5099
  bookingCount
4634
5100
  }, {
5101
+ useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
5102
+ enforceSaleCutoff: strictAvailability || isRememberedSelection,
5103
+ rememberedTimeByProductId,
4635
5104
  useExactDurationCandidateMinute: allowPosAvailabilityOverride,
4636
5105
  allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
4637
5106
  });
@@ -4662,9 +5131,6 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4662
5131
  refreshedSnapshotId: refreshedProjection.meta.snapshotId
4663
5132
  });
4664
5133
  }
4665
- // Revalidation failure must leave the caller's candidate reusable. Only publish the
4666
- // refreshed projection/version after candidate and resource validation has passed;
4667
- // otherwise a second Confirm from the still-open modal would incorrectly become stale.
4668
5134
  const revalidationEntry = customerSelectionSnapshot ? projectionEntry : this.storeAvailabilityProjectionEntry({
4669
5135
  contextId: normalizedContextId,
4670
5136
  prepareParams: commitSnapshot.prepareParams,
@@ -4692,20 +5158,23 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4692
5158
  expectedOrderRevision: customerSelectionSnapshot ? commitWriteGuard.expectedOrderRevision : revalidationEntry.orderRevision
4693
5159
  };
4694
5160
  const refreshedCandidate = this.decorateAvailabilityCandidate(normalizedContextId, revalidatedContext.activeVersion, refreshedCandidateBase);
4695
- // Order may await line/runtime setup. Its guarded transaction invokes this
4696
- // again immediately before publishing, while the live cart is unchanged.
4697
5161
  const availabilityCommitGuard = hasCommitGuard ? () => {
4698
5162
  params.availabilityCommitGuard?.();
4699
5163
  this.assertAvailabilityCommitWriteCAS(commitWriteGuard);
4700
5164
  if (!availabilityCommitTargetGuard()) {
4701
- throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '预约加购期间订单或业务已变化');
5165
+ throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '记忆时间加购期间订单或业务已变化');
4702
5166
  }
4703
- if (customerSelectionSnapshot || !strictAvailability) return;
5167
+ if (isOrderRememberedSelection) rememberedOrder = this.getTempOrder();
5168
+ if (customerSelectionSnapshot || !isRememberedSelection && !strictAvailability) return;
4704
5169
  const currentValidation = (0, _ResourcePlanner.validateAvailabilitySelection)(refreshedProjection, {
4705
5170
  candidate: refreshedCandidateBase,
4706
5171
  requirementSelections: params.requirementSelections,
4707
5172
  partySize,
4708
5173
  bookingCount
5174
+ }, {
5175
+ useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
5176
+ enforceSaleCutoff: true,
5177
+ rememberedTimeByProductId
4709
5178
  });
4710
5179
  if (!currentValidation.ok) {
4711
5180
  throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '所选时间在加购前已不可用,请重新选择', {
@@ -4731,10 +5200,24 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4731
5200
  holderIds: params.orderProduct?._extend?.holder_id ?? params.orderProduct?._extend?.holder?.form_record ?? (params.mode === 'replace' ? undefined : existingBooking?.metadata?.holder_id ?? existingBooking?.holder?.form_record)
4732
5201
  });
4733
5202
  if (params.mode === 'replace') {
4734
- // A different product must not inherit the previous product/resource's completed forms.
4735
5203
  booking.holder = booking.holder || null;
4736
5204
  booking.relation_forms = [];
4737
5205
  }
5206
+ if (isRememberedSelection && params.orderProduct?._extend?.resource) {
5207
+ const legacyBooking = (0, _cacheItemToBookingInput.cacheItemToBookingInput)(params.orderProduct);
5208
+ const legacyResources = legacyBooking.resources || [];
5209
+ const selectedResources = legacyResources.filter(resource => Number(resource.relation_id) !== 0);
5210
+ const resourceKeys = resources => resources.map(resource => JSON.stringify([String(resource.form_id), String(resource.relation_id), resource.relation_type, Number(resource.capacity)])).sort();
5211
+ if (JSON.stringify(resourceKeys(selectedResources)) !== JSON.stringify(resourceKeys(booking.resources)) || legacyResources.some(resource => Number(resource.relation_id) === 0 && !selectedResources.some(selected => sameAvailabilityId(selected.form_id, resource.form_id)))) {
5212
+ throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '记忆时间的资源与本次校验结果不一致');
5213
+ }
5214
+ Object.assign(booking, {
5215
+ relation_id: legacyBooking.relation_id,
5216
+ form_id: legacyBooking.form_id,
5217
+ relation_type: legacyBooking.relation_type,
5218
+ resources: (0, _lodashEs.cloneDeep)(legacyResources)
5219
+ });
5220
+ }
4738
5221
  const transformed = this.buildUnifiedOrderProduct({
4739
5222
  ...params.orderProduct,
4740
5223
  num: bookingCount,
@@ -4764,7 +5247,6 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4764
5247
  const relatedRetailProducts = params.relatedRetailProducts.map(source => {
4765
5248
  const line = this.buildUnifiedOrderProduct(source, 'unified_booking_sales_retail');
4766
5249
  if (!line) throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '无法生成附加商品订单行');
4767
- // This is the only replacement-specific UID restore. Order checks ownership/collisions.
4768
5250
  const sourceUid = getProductLineUid(source);
4769
5251
  if (sourceUid) {
4770
5252
  line.metadata = {
@@ -4816,7 +5298,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4816
5298
  isCurrentOrder: availabilityCommitTargetGuard
4817
5299
  });
4818
5300
  guardedCommitPublished = true;
4819
- } else await this.updateOrderProduct(update);
5301
+ } else {
5302
+ await this.updateOrderProduct(update);
5303
+ }
5304
+ await this.removeBookingProductsOutsideStartDate(booking.start_date);
4820
5305
  productLineUid = params.productLineUid;
4821
5306
  bookingUid = existingBookingUid;
4822
5307
  productLineUids = [productLineUid];
@@ -4825,7 +5310,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4825
5310
  const beforeProductLineUids = new Set((this.getTempOrder()?.products || []).map(line => getProductLineUid(line)).filter(Boolean));
4826
5311
  const beforeBookingUids = new Set((this.getTempOrder()?.bookings || []).map(item => getBookingUid(item)).filter(Boolean));
4827
5312
  availabilityCommitGuard?.();
4828
- const products = await this.addProductToOrder(transformed, booking, params.salesNotes?.length || availabilityCommitGuard ? {
5313
+ let products = await this.addProductToOrder(transformed, booking, params.salesNotes?.length || availabilityCommitGuard ? {
4829
5314
  ...(params.salesNotes?.length ? {
4830
5315
  salesNotes: params.salesNotes
4831
5316
  } : {}),
@@ -4835,9 +5320,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4835
5320
  } : {})
4836
5321
  } : undefined);
4837
5322
  guardedCommitPublished = hasCommitGuard;
5323
+ if (!hasCommitGuard || availabilityCommitTargetGuard()) {
5324
+ products = await this.removeBookingProductsOutsideStartDate(booking.start_date);
5325
+ }
4838
5326
  const addedLines = products.filter(line => sameAvailabilityId(line.product_id ?? line.id, refreshedCandidate.productId) && line.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeProductLineUids.has(getProductLineUid(line)));
4839
5327
  productLineUids = addedLines.map(line => getProductLineUid(line)).filter(Boolean);
4840
- const addedBookings = ((hasCommitGuard ? guardedOrder : this.getTempOrder())?.bookings || []).filter(item => item.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeBookingUids.has(getBookingUid(item)));
5328
+ const addedBookings = ((hasCommitGuard ? rememberedOrder : this.getTempOrder())?.bookings || []).filter(item => item.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeBookingUids.has(getBookingUid(item)));
4841
5329
  bookingUids = addedBookings.map(item => getBookingUid(item)).filter(Boolean);
4842
5330
  if (bookingUids.length === 0) {
4843
5331
  bookingUids = addedLines.map(line => String(line.booking_uid ?? line.metadata?.booking_uid ?? '')).filter(Boolean);
@@ -4851,7 +5339,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4851
5339
  const result = {
4852
5340
  contextId: normalizedContextId,
4853
5341
  contextVersion: nextContext?.activeVersion ?? refreshedCandidate.availabilityContextVersion,
4854
- tempOrder: hasCommitGuard ? guardedOrder : this.getTempOrder(),
5342
+ tempOrder: hasCommitGuard ? rememberedOrder : this.getTempOrder(),
4855
5343
  validation,
4856
5344
  candidate: refreshedCandidate,
4857
5345
  productLineUid,
@@ -4860,12 +5348,11 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4860
5348
  bookingUids
4861
5349
  };
4862
5350
  if (targetStillCurrent) {
4863
- // A notification failure after publication must not invite a duplicate add.
4864
5351
  const emit = () => this.core.effects.emit(`${this.name}:${_types.UnifiedBookingSalesHooks.onAvailabilitySelectionCommitted}`, result);
4865
5352
  if (guardedCommitPublished) {
4866
5353
  try {
4867
5354
  await emit();
4868
- } catch {/* The cart mutation has already succeeded. */}
5355
+ } catch {}
4869
5356
  } else await emit();
4870
5357
  }
4871
5358
  return result;
@@ -4874,6 +5361,92 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4874
5361
  if (guardedCommitPublished) await release.catch(() => undefined);else await release;
4875
5362
  }
4876
5363
  }
5364
+ async initializeUnifiedSalesRuntime(core, options) {
5365
+ const initializationGeneration = ++this.runtimeInitializationGeneration;
5366
+ this.resetRuntimeOpenData();
5367
+ this.runtimeOpenDataDestroyed = false;
5368
+ this.availabilityScheduleCatalog = null;
5369
+ this.availabilityRuntimeOffsetMinutes = (0, _localClock.captureRuntimeOffsetMinutes)();
5370
+ this.clearAvailabilityRemoteResourceState();
5371
+ this.resetAllergyItemRuleState();
5372
+ // BaseSales synchronously installs this runtime before its first await. Cache
5373
+ // refreshes during that await are valid; they are not a new initialization.
5374
+ const initialization = super.initialize(core, options);
5375
+ const scope = this.getRuntimeOpenDataScope();
5376
+ const openDataModule = this.store.openData;
5377
+ await initialization;
5378
+ if (this.runtimeOpenDataDestroyed || initializationGeneration !== this.runtimeInitializationGeneration) {
5379
+ // A destroyed/reinitialized instance must not publish a ready snapshot.
5380
+ return false;
5381
+ }
5382
+ if (core !== this.core || openDataModule !== this.store.openData || scope !== this.getRuntimeOpenDataScope()) {
5383
+ throw new Error('Store settings changed. Please try again.');
5384
+ }
5385
+ this.captureAvailabilityScheduleCatalog();
5386
+ await this.ensureAllergyItemRuleConfigsLoaded();
5387
+ return !this.runtimeOpenDataDestroyed && initializationGeneration === this.runtimeInitializationGeneration;
5388
+ }
5389
+ isVenueKioskPlatform(otherParams = this.otherParams || {}) {
5390
+ return (0, _platform.normalizeRuntimePlatform)(otherParams.platform) === 'kiosk' && (otherParams.venueBookingMode === 'tickets' || otherParams.venueBookingMode === 'party');
5391
+ }
5392
+ supportsVenueSelectionSnapshot() {
5393
+ return (0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) || this.isVenueKioskPlatform();
5394
+ }
5395
+ getSolutionLogContext() {
5396
+ const context = {};
5397
+ try {
5398
+ Object.assign(context, {
5399
+ solutionName: this.name,
5400
+ moduleName: this.defaultName,
5401
+ module: 'unifiedBookingSales',
5402
+ cacheId: this.cacheId,
5403
+ businessCode: this.otherParams?.businessCode ?? this.otherParams?.business_code,
5404
+ platform: this.otherParams?.platform,
5405
+ channel: this.otherParams?.channel
5406
+ });
5407
+ try {
5408
+ const order = this.getTempOrder();
5409
+ Object.assign(context, {
5410
+ orderId: order?.order_id,
5411
+ externalSaleNumber: order?.external_sale_number,
5412
+ shopOrderNumber: order?.shop_order_number
5413
+ });
5414
+ } catch {/* A partially initialized order must not hide the failure log. */}
5415
+ try {
5416
+ const order = this.store.order;
5417
+ context.orderSessionId = order?.getOrderSessionId?.() ?? null;
5418
+ } catch {/* Session context is optional during initialization and teardown. */}
5419
+ } catch {/* Basic context remains useful even when some runtime fields cannot be read. */}
5420
+ return context;
5421
+ }
5422
+ writeSolutionLog(type, title, metadata = {}, context = this.getSolutionLogContext()) {
5423
+ try {
5424
+ (0, _hostLogger.writeHostLog)(this.core, {
5425
+ type,
5426
+ title: `[UnifiedBookingSales] ${title}`,
5427
+ metadata: {
5428
+ ...context,
5429
+ ...metadata
5430
+ }
5431
+ });
5432
+ } catch {
5433
+ // Reading diagnostic context must not change the sales result.
5434
+ }
5435
+ }
5436
+ logSolutionFailure(method, error, metadata = {}, context, type) {
5437
+ try {
5438
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : undefined;
5439
+ const isBusinessFailure = error instanceof _ResourcePlanner.AvailabilityError && code !== 'OPERATING_HOURS_RESOLVE_FAILED' && code !== 'SELF_EXCLUSION_RESOLVE_FAILED';
5440
+ this.writeSolutionLog(type ?? (code === 'AVAILABILITY_COMMIT_IN_PROGRESS' ? 'debug' : isBusinessFailure || code === 'REQUIRED_PRODUCT_MISSING' ? 'warning' : 'error'), `${method} failed`, {
5441
+ ...metadata,
5442
+ action: method,
5443
+ errorCode: code,
5444
+ errorMessage: (error instanceof Error ? error.message : String(error)).slice(0, 500)
5445
+ }, context);
5446
+ } catch {
5447
+ // Error serialization is observational only.
5448
+ }
5449
+ }
4877
5450
  }
4878
5451
  exports.UnifiedBookingSalesImpl = UnifiedBookingSalesImpl;
4879
5452
  const UnifiedBookingSales = exports.UnifiedBookingSales = UnifiedBookingSalesImpl;