@pisell/pisellos 2.2.323 → 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 (195) 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/modules/BookingContext/index.d.ts +2 -2
  6. package/dist/modules/BookingContext/index.js +55 -25
  7. package/dist/modules/BookingContext/types.d.ts +2 -0
  8. package/dist/modules/BookingContext/utils/calendarBooking.d.ts +15 -0
  9. package/dist/modules/BookingContext/utils/calendarBooking.js +207 -0
  10. package/dist/modules/BookingContext/utils/index.d.ts +1 -0
  11. package/dist/modules/BookingContext/utils/index.js +1 -0
  12. package/dist/modules/BookingContext/utils/productExtend.d.ts +20 -1
  13. package/dist/modules/BookingContext/utils/productExtend.js +122 -29
  14. package/dist/modules/Date/index.d.ts +1 -1
  15. package/dist/modules/Date/index.js +60 -14
  16. package/dist/modules/Date/types.d.ts +5 -0
  17. package/dist/modules/Discount/index.js +1 -0
  18. package/dist/modules/OpenData/index.d.ts +1 -0
  19. package/dist/modules/OpenData/index.js +1 -0
  20. package/dist/modules/OpenData/salesSettings.d.ts +32 -0
  21. package/dist/modules/OpenData/salesSettings.js +80 -0
  22. package/dist/modules/OpenData/types.d.ts +16 -0
  23. package/dist/modules/OpenData/utils.d.ts +1 -1
  24. package/dist/modules/OpenData/utils.js +3 -2
  25. package/dist/modules/Order/index.d.ts +54 -11
  26. package/dist/modules/Order/index.js +2699 -1411
  27. package/dist/modules/Order/types.d.ts +43 -5
  28. package/dist/modules/Order/types.js +4 -0
  29. package/dist/modules/Order/unpaidAmountGap.d.ts +6 -0
  30. package/dist/modules/Order/unpaidAmountGap.js +72 -0
  31. package/dist/modules/Order/utils/discountProductLineIdentity.js +2 -2
  32. package/dist/modules/Order/utils/productVoucherGroups.d.ts +15 -0
  33. package/dist/modules/Order/utils/productVoucherGroups.js +115 -0
  34. package/dist/modules/Order/utils.d.ts +3 -1
  35. package/dist/modules/Order/utils.js +6 -2
  36. package/dist/modules/ProductList/clientDataVariants.js +6 -2
  37. package/dist/modules/ProductList/index.d.ts +2 -0
  38. package/dist/modules/ProductList/index.js +161 -51
  39. package/dist/modules/ResourcePlanner/planner.js +58 -2
  40. package/dist/modules/ResourcePlanner/types.d.ts +13 -0
  41. package/dist/modules/Rules/index.d.ts +2 -0
  42. package/dist/modules/Rules/index.js +58 -39
  43. package/dist/modules/Schedule/index.d.ts +7 -1
  44. package/dist/modules/Schedule/index.js +155 -39
  45. package/dist/modules/Schedule/types.d.ts +2 -0
  46. package/dist/modules/bookingReadValidation.d.ts +6 -0
  47. package/dist/modules/bookingReadValidation.js +72 -0
  48. package/dist/plugins/request.d.ts +2 -0
  49. package/dist/server/index.d.ts +5 -0
  50. package/dist/server/index.js +1312 -1154
  51. package/dist/server/modules/order/index.js +2 -1
  52. package/dist/shared/receipt/customerInvoiceLanguages.d.ts +1 -1
  53. package/dist/shared/receipt/customerInvoiceLanguages.js +5 -3
  54. package/dist/shared/receipt/small-ticket.d.ts +4 -0
  55. package/dist/shared/receipt/small-ticket.js +70 -12
  56. package/dist/solution/BaseSales/index.d.ts +39 -5
  57. package/dist/solution/BaseSales/index.js +1828 -1462
  58. package/dist/solution/BaseSales/types.d.ts +1 -0
  59. package/dist/solution/BaseSales/types.js +1 -0
  60. package/dist/solution/BookingByStep/index.d.ts +17 -3
  61. package/dist/solution/BookingByStep/index.js +676 -361
  62. package/dist/solution/BookingByStep/utils/resources.d.ts +10 -0
  63. package/dist/solution/BookingByStep/utils/resources.js +117 -76
  64. package/dist/solution/BookingTicket/index.d.ts +15 -3
  65. package/dist/solution/BookingTicket/index.js +249 -135
  66. package/dist/solution/BookingTicket/types.d.ts +14 -2
  67. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +3 -1
  68. package/dist/solution/BookingTicket/utils/addProductDecision.js +39 -11
  69. package/dist/solution/BookingTicket/utils/resolveUniqueCartDetail.d.ts +8 -0
  70. package/dist/solution/BookingTicket/utils/resolveUniqueCartDetail.js +188 -0
  71. package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +8 -0
  72. package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +88 -0
  73. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +1 -0
  74. package/dist/solution/BookingTicket/utils/scan/handleScan.js +2 -1
  75. package/dist/solution/OrderInvoicePreview/index.js +14 -8
  76. package/dist/solution/ScanOrder/index.d.ts +2 -0
  77. package/dist/solution/ScanOrder/index.js +166 -67
  78. package/dist/solution/ScanOrder/menuAvailability.d.ts +24 -0
  79. package/dist/solution/ScanOrder/menuAvailability.js +363 -0
  80. package/dist/solution/UnifiedBookingSales/catalogQueryBatch.d.ts +21 -0
  81. package/dist/solution/UnifiedBookingSales/catalogQueryBatch.js +202 -0
  82. package/dist/solution/UnifiedBookingSales/index.d.ts +96 -4
  83. package/dist/solution/UnifiedBookingSales/index.js +3374 -1177
  84. package/dist/solution/UnifiedBookingSales/remoteOccupancyCache.d.ts +2 -0
  85. package/dist/solution/UnifiedBookingSales/remoteOccupancyCache.js +4 -0
  86. package/dist/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
  87. package/dist/solution/UnifiedBookingSales/salesSettings.js +81 -0
  88. package/dist/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
  89. package/dist/solution/UnifiedBookingSales/sessionResourceCache.js +271 -0
  90. package/dist/solution/UnifiedBookingSales/types.d.ts +71 -2
  91. package/dist/solution/UnifiedBookingSales/types.js +7 -1
  92. package/dist/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
  93. package/dist/solution/UnifiedBookingSales/venueCatalogSession.js +283 -0
  94. package/dist/utils/platform.d.ts +2 -0
  95. package/dist/utils/platform.js +6 -0
  96. package/dist/utils/pos-receipt-auto-print.d.ts +4 -0
  97. package/dist/utils/pos-receipt-auto-print.js +14 -0
  98. package/lib/index.d.ts +1 -0
  99. package/lib/index.js +12 -0
  100. package/lib/inventory/index.d.ts +92 -0
  101. package/lib/inventory/index.js +287 -0
  102. package/lib/modules/BookingContext/index.d.ts +2 -2
  103. package/lib/modules/BookingContext/index.js +42 -10
  104. package/lib/modules/BookingContext/types.d.ts +2 -0
  105. package/lib/modules/BookingContext/utils/calendarBooking.d.ts +15 -0
  106. package/lib/modules/BookingContext/utils/calendarBooking.js +156 -0
  107. package/lib/modules/BookingContext/utils/index.d.ts +1 -0
  108. package/lib/modules/BookingContext/utils/index.js +11 -0
  109. package/lib/modules/BookingContext/utils/productExtend.d.ts +20 -1
  110. package/lib/modules/BookingContext/utils/productExtend.js +96 -7
  111. package/lib/modules/Date/index.d.ts +1 -1
  112. package/lib/modules/Date/index.js +28 -5
  113. package/lib/modules/Date/types.d.ts +5 -0
  114. package/lib/modules/Discount/index.js +1 -0
  115. package/lib/modules/OpenData/index.d.ts +1 -0
  116. package/lib/modules/OpenData/index.js +12 -0
  117. package/lib/modules/OpenData/salesSettings.d.ts +32 -0
  118. package/lib/modules/OpenData/salesSettings.js +70 -0
  119. package/lib/modules/OpenData/types.d.ts +16 -0
  120. package/lib/modules/OpenData/utils.d.ts +1 -1
  121. package/lib/modules/OpenData/utils.js +3 -2
  122. package/lib/modules/Order/index.d.ts +54 -11
  123. package/lib/modules/Order/index.js +659 -80
  124. package/lib/modules/Order/types.d.ts +43 -5
  125. package/lib/modules/Order/types.js +2 -0
  126. package/lib/modules/Order/unpaidAmountGap.d.ts +6 -0
  127. package/lib/modules/Order/unpaidAmountGap.js +60 -0
  128. package/lib/modules/Order/utils/discountProductLineIdentity.js +1 -1
  129. package/lib/modules/Order/utils/productVoucherGroups.d.ts +15 -0
  130. package/lib/modules/Order/utils/productVoucherGroups.js +64 -0
  131. package/lib/modules/Order/utils.d.ts +3 -1
  132. package/lib/modules/Order/utils.js +6 -2
  133. package/lib/modules/ProductList/clientDataVariants.js +6 -2
  134. package/lib/modules/ProductList/index.d.ts +2 -0
  135. package/lib/modules/ProductList/index.js +74 -0
  136. package/lib/modules/ResourcePlanner/planner.js +52 -1
  137. package/lib/modules/ResourcePlanner/types.d.ts +13 -0
  138. package/lib/modules/Rules/index.d.ts +2 -0
  139. package/lib/modules/Rules/index.js +25 -9
  140. package/lib/modules/Schedule/index.d.ts +7 -1
  141. package/lib/modules/Schedule/index.js +68 -4
  142. package/lib/modules/Schedule/types.d.ts +2 -0
  143. package/lib/modules/bookingReadValidation.d.ts +6 -0
  144. package/lib/modules/bookingReadValidation.js +56 -0
  145. package/lib/plugins/request.d.ts +2 -0
  146. package/lib/server/index.d.ts +5 -0
  147. package/lib/server/index.js +124 -16
  148. package/lib/server/modules/order/index.js +2 -1
  149. package/lib/shared/receipt/customerInvoiceLanguages.d.ts +1 -1
  150. package/lib/shared/receipt/customerInvoiceLanguages.js +5 -3
  151. package/lib/shared/receipt/small-ticket.d.ts +4 -0
  152. package/lib/shared/receipt/small-ticket.js +63 -8
  153. package/lib/solution/BaseSales/index.d.ts +39 -5
  154. package/lib/solution/BaseSales/index.js +212 -18
  155. package/lib/solution/BaseSales/types.d.ts +1 -0
  156. package/lib/solution/BaseSales/types.js +1 -0
  157. package/lib/solution/BookingByStep/index.d.ts +17 -3
  158. package/lib/solution/BookingByStep/index.js +222 -14
  159. package/lib/solution/BookingByStep/utils/resources.d.ts +10 -0
  160. package/lib/solution/BookingByStep/utils/resources.js +25 -15
  161. package/lib/solution/BookingTicket/index.d.ts +15 -3
  162. package/lib/solution/BookingTicket/index.js +47 -4
  163. package/lib/solution/BookingTicket/types.d.ts +14 -2
  164. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +3 -1
  165. package/lib/solution/BookingTicket/utils/addProductDecision.js +37 -6
  166. package/lib/solution/BookingTicket/utils/resolveUniqueCartDetail.d.ts +8 -0
  167. package/lib/solution/BookingTicket/utils/resolveUniqueCartDetail.js +136 -0
  168. package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +8 -0
  169. package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +54 -0
  170. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +1 -0
  171. package/lib/solution/BookingTicket/utils/scan/handleScan.js +2 -1
  172. package/lib/solution/OrderInvoicePreview/index.js +7 -1
  173. package/lib/solution/ScanOrder/index.d.ts +2 -0
  174. package/lib/solution/ScanOrder/index.js +72 -2
  175. package/lib/solution/ScanOrder/menuAvailability.d.ts +24 -0
  176. package/lib/solution/ScanOrder/menuAvailability.js +203 -0
  177. package/lib/solution/UnifiedBookingSales/catalogQueryBatch.d.ts +21 -0
  178. package/lib/solution/UnifiedBookingSales/catalogQueryBatch.js +109 -0
  179. package/lib/solution/UnifiedBookingSales/index.d.ts +96 -4
  180. package/lib/solution/UnifiedBookingSales/index.js +1316 -73
  181. package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.d.ts +2 -0
  182. package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.js +2 -0
  183. package/lib/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
  184. package/lib/solution/UnifiedBookingSales/salesSettings.js +72 -0
  185. package/lib/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
  186. package/lib/solution/UnifiedBookingSales/sessionResourceCache.js +199 -0
  187. package/lib/solution/UnifiedBookingSales/types.d.ts +71 -2
  188. package/lib/solution/UnifiedBookingSales/types.js +4 -1
  189. package/lib/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
  190. package/lib/solution/UnifiedBookingSales/venueCatalogSession.js +155 -0
  191. package/lib/utils/platform.d.ts +2 -0
  192. package/lib/utils/platform.js +7 -0
  193. package/lib/utils/pos-receipt-auto-print.d.ts +4 -0
  194. package/lib/utils/pos-receipt-auto-print.js +13 -0
  195. package/package.json +1 -1
@@ -21,6 +21,7 @@ var _weighedProduct = require("./utils/weighedProduct");
21
21
  var _pickupTiming = require("./pickupTiming");
22
22
  var _dayjs = _interopRequireDefault(require("dayjs"));
23
23
  var _availability = require("../Discount/availability");
24
+ var _productVoucherGroups = require("./utils/productVoucherGroups");
24
25
  var _osPrivatePayload = require("../../utils/os-private-payload");
25
26
  var _salesNotes = require("./salesNotes");
26
27
  var _paymentUtils = require("./payment-utils");
@@ -139,6 +140,10 @@ class OrderModule extends _BaseModule.BaseModule {
139
140
  openCache = false;
140
141
  sessionStoragePersistEnabled = false;
141
142
  sessionStorageRestoreRecord = null;
143
+ orderSessionId = null;
144
+ orderSessionDestroyed = false;
145
+ orderSessionAliases = new Set();
146
+ orderReplacement = null;
142
147
  /** 只允许当前订单最新的 prepare/config 请求回写客户资产态。 */
143
148
  customerWalletPrepareConfigEpoch = 0;
144
149
  /** Payment 可能早于 prepare/config 返回;先按实例 ID 暂存卡号等待 Snapshot。 */
@@ -147,6 +152,66 @@ class OrderModule extends _BaseModule.BaseModule {
147
152
  rulesHooksOverride;
148
153
  moduleHooksOverride;
149
154
  orderHooks;
155
+ cartCommandQueue = Promise.resolve();
156
+ queueCartCommand(run) {
157
+ if (!this.orderHooks?.onBeforeCartCommit && !this.store.tempOrder?._extend?.productVoucherGroups?.length) return run();
158
+ const pending = this.cartCommandQueue.then(run, run);
159
+ this.cartCommandQueue = pending.catch(() => undefined);
160
+ return pending;
161
+ }
162
+
163
+ /** Use the exact Order normalizers/merge rules on a private draft, not a second projection. */
164
+ beginCartMutation() {
165
+ const current = this.ensureTempOrder();
166
+ const guard = this.orderHooks?.onBeforeCartCommit;
167
+ if (!guard && !current._extend?.productVoucherGroups?.length) return {
168
+ draft: current,
169
+ commit: undefined
170
+ };
171
+ const before = (0, _lodashEs.cloneDeep)(current);
172
+ const draft = (0, _lodashEs.cloneDeep)(current);
173
+ return {
174
+ draft,
175
+ commit: async options => {
176
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return current;
177
+ (0, _productVoucherGroups.validateProductVoucherGroups)(draft, this.getDiscountList(), before);
178
+ await guard?.({
179
+ currentItems: (0, _lodashEs.cloneDeep)(before.products),
180
+ proposedItems: (0, _lodashEs.cloneDeep)(draft.products)
181
+ });
182
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return current;
183
+ if (this.store.tempOrder !== current || guard !== this.orderHooks?.onBeforeCartCommit || !(0, _lodashEs.isEqual)(current, before)) {
184
+ throw Object.assign(new Error('The cart changed. Please try again.'), {
185
+ code: 'SALES_GUARD_REJECTED'
186
+ });
187
+ }
188
+ // Recheck synchronous order/availability guards after async inventory validation.
189
+ options?.beforeCommit?.();
190
+ Object.assign(current, draft);
191
+ return current;
192
+ }
193
+ };
194
+ }
195
+
196
+ /** Serializes checkout preparation with local cart commands; hydration remains outside this guard. */
197
+ async prepareCheckout(prepare) {
198
+ const run = async () => {
199
+ const order = this.ensureTempOrder();
200
+ (0, _productVoucherGroups.validateProductVoucherGroups)(order, this.getDiscountList(), undefined, true);
201
+ const items = (0, _lodashEs.cloneDeep)(order.products);
202
+ const result = await prepare(items);
203
+ if (this.store.tempOrder !== order || !(0, _lodashEs.isEqual)(order.products, items)) {
204
+ throw Object.assign(new Error('The cart changed. Please try again.'), {
205
+ code: 'SALES_GUARD_REJECTED'
206
+ });
207
+ }
208
+ (0, _productVoucherGroups.validateProductVoucherGroups)(order, this.getDiscountList(), undefined, true);
209
+ return result;
210
+ };
211
+ const pending = this.cartCommandQueue.then(run, run);
212
+ this.cartCommandQueue = pending.catch(() => undefined);
213
+ return pending;
214
+ }
150
215
  otherParams;
151
216
  // ─── 促销/赠品 ────────────────────────────────────
152
217
  /** 评估器引用;由 SalesSdkProvider 注入,未注入时 applyPromotion 静默跳过 */
@@ -364,6 +429,10 @@ class OrderModule extends _BaseModule.BaseModule {
364
429
  async initialize(core, options) {
365
430
  this.core = core;
366
431
  this.store = options.store;
432
+ this.orderReplacement = null;
433
+ this.orderSessionId = null;
434
+ this.orderSessionDestroyed = false;
435
+ this.orderSessionAliases.clear();
367
436
  const otherParams = options.otherParams || {};
368
437
  this.syncSessionStorageOptions(otherParams);
369
438
  if (this.sessionStoragePersistEnabled) {
@@ -403,10 +472,14 @@ class OrderModule extends _BaseModule.BaseModule {
403
472
  this.orderHooks = this.moduleHooksOverride || otherParams.order?.hooks || otherParams.hooks?.order;
404
473
  this.otherParams = otherParams;
405
474
  this.registerDiscountModules(options);
475
+ this.publishOrderSession(this.store.tempOrder);
406
476
  this.logInfo('OrderModule initialized successfully');
407
477
  }
408
478
  async destroy() {
409
479
  this.sessionStorageRestoreRecord = null;
480
+ this.orderReplacement = null;
481
+ this.orderSessionDestroyed = true;
482
+ this.publishOrderSession(null);
410
483
  const childModules = [this.store?.discount, this.store?.rules];
411
484
  for (const childModule of childModules) {
412
485
  if (!childModule || typeof childModule.destroy !== 'function') continue;
@@ -434,8 +507,11 @@ class OrderModule extends _BaseModule.BaseModule {
434
507
  * @example
435
508
  * orderModule.updateOtherParams({ cacheId: 'cache-2', channel: 'pos' });
436
509
  */
437
- updateOtherParams(params) {
510
+ updateOtherParams(params, options) {
438
511
  const otherParams = params || {};
512
+ if (options && Object.prototype.hasOwnProperty.call(options, 'hooks')) {
513
+ this.moduleHooksOverride = options.hooks;
514
+ }
439
515
  this.syncSessionStorageOptions(otherParams);
440
516
  this.salesSummaryModuleName = otherParams.salesSummaryModuleName;
441
517
  this.rulesHooksOverride = otherParams.rules?.hooks;
@@ -542,6 +618,26 @@ class OrderModule extends _BaseModule.BaseModule {
542
618
  hooks: this.rulesHooksOverride || this.createDefaultRulesHooks()
543
619
  });
544
620
  this.store.rules = rules;
621
+ rules.setDiscountScope((product, discount) => (0, _productVoucherGroups.allowsProductVoucher)(this.store.tempOrder, product, discount));
622
+ }
623
+ setProductVoucherGroups(groups) {
624
+ const order = this.ensureTempOrder();
625
+ const ids = new Set();
626
+ const keys = new Set();
627
+ const known = new Map(this.getDiscountList().map(discount => [String(discount.id), discount]));
628
+ for (const group of groups) {
629
+ if (!group.key || keys.has(group.key)) throw (0, _productVoucherGroups.voucherGroupError)();
630
+ keys.add(group.key);
631
+ for (const id of group.discountIds) {
632
+ const discount = known.get(String(id));
633
+ if (!discount || (discount.tag || discount.type) !== 'good_pass' || ids.has(String(id))) throw (0, _productVoucherGroups.voucherGroupError)();
634
+ ids.add(String(id));
635
+ }
636
+ }
637
+ this.ensureExtend(order).productVoucherGroups = (0, _lodashEs.cloneDeep)(groups);
638
+ }
639
+ validateProductVoucherSelection() {
640
+ (0, _productVoucherGroups.validateProductVoucherGroups)(this.ensureTempOrder(), this.getDiscountList(), undefined, true);
545
641
  }
546
642
  createDefaultRulesHooks() {
547
643
  return (0, _utils.createDefaultOrderRulesHooks)(() => this.store.tempOrder?.bookings || [], () => this.store.tempOrder?.holder_relations);
@@ -704,7 +800,7 @@ class OrderModule extends _BaseModule.BaseModule {
704
800
  apply: false
705
801
  });
706
802
  }
707
- async scanCode(code, customerId) {
803
+ async scanCode(code, customerId, options) {
708
804
  const beforeCommit = this.createCartIntentCommitGuard('scan_promotion');
709
805
  if (this.isActiveVirtualSettlementOrder(this.store.tempOrder)) {
710
806
  return {
@@ -716,16 +812,22 @@ class OrderModule extends _BaseModule.BaseModule {
716
812
  unavailableReason: _types2.UnavailableReason.ProductNotApplicable
717
813
  };
718
814
  }
815
+ const scanOrderKey = this.getDiscountConfigOrderIdentityKey(this.store.tempOrder);
719
816
  const resultDiscountWithReason = (await this.store.discount?.batchSearch(code, {
720
817
  customerId
721
818
  })) || {
722
819
  discountList: [],
723
820
  unavailableReasonKey: null
724
821
  };
822
+ if (scanOrderKey !== this.getDiscountConfigOrderIdentityKey(this.store.tempOrder)) {
823
+ throw Object.assign(new Error('The scan session ended.'), {
824
+ code: 'SALES_GUARD_REJECTED'
825
+ });
826
+ }
725
827
  const {
726
- discountList: resultDiscountList,
727
828
  unavailableReasonKey
728
829
  } = resultDiscountWithReason;
830
+ const resultDiscountList = resultDiscountWithReason.discountList.filter(discount => !options?.productVouchersOnly || (discount.tag || discount.type) === 'good_pass');
729
831
  const rulesModule = this.store.rules;
730
832
  if (!rulesModule) {
731
833
  return {
@@ -752,7 +854,7 @@ class OrderModule extends _BaseModule.BaseModule {
752
854
  isScan: true
753
855
  }));
754
856
  const currentSelected = this.getDiscountList().filter(n => n.isSelected);
755
- if (currentSelected.length && currentSelected.some(n => withScanList.some(m => m.id === n.id))) {
857
+ if (currentSelected.length && (options?.productVouchersOnly ? withScanList.every(scanned => currentSelected.some(selected => selected.id === scanned.id)) : currentSelected.some(n => withScanList.some(m => m.id === n.id)))) {
756
858
  beforeCommit();
757
859
  await this.syncScannedDiscountsToOriginalDiscountList(this.getDiscountList());
758
860
  return {
@@ -1032,6 +1134,10 @@ class OrderModule extends _BaseModule.BaseModule {
1032
1134
  }
1033
1135
  if (options?.isCurrentOrder && !options.isCurrentOrder()) return null;
1034
1136
  tempOrder.products = result.products;
1137
+ if (tempOrder.products.length === 0) {
1138
+ // 删除主商品后,促销重算可能继续移除最后的赠品。
1139
+ tempOrder.shop_discount = '0.00';
1140
+ }
1035
1141
  this.lastUnfulfilledPromotions = result.unfulfilledPromotions;
1036
1142
  this.lastGiftActions = result.giftActions;
1037
1143
  const payload = {
@@ -1198,6 +1304,111 @@ class OrderModule extends _BaseModule.BaseModule {
1198
1304
 
1199
1305
  // ─── TempOrder: 创建 & 获取 ───
1200
1306
 
1307
+ getOrderSessionAliases(order) {
1308
+ const aliases = new Set();
1309
+ if (!order) return aliases;
1310
+ for (const key of ['external_sale_number', 'order_id']) {
1311
+ const value = order[key];
1312
+ if (value !== null && value !== undefined && String(value).trim() !== '' && (key !== 'order_id' || String(value) !== '0')) {
1313
+ aliases.add(`${key}:${String(value).trim()}`);
1314
+ }
1315
+ }
1316
+ return aliases;
1317
+ }
1318
+ publishOrderSession(order, fresh = false) {
1319
+ const previousSessionId = this.orderSessionId;
1320
+ if (!order) {
1321
+ this.orderSessionId = null;
1322
+ this.orderSessionAliases.clear();
1323
+ } else {
1324
+ if (fresh || !this.orderSessionId) {
1325
+ this.orderSessionId = (0, _utils.createUuidV4)();
1326
+ this.orderSessionAliases = new Set();
1327
+ }
1328
+ this.getOrderSessionAliases(order).forEach(alias => this.orderSessionAliases.add(alias));
1329
+ }
1330
+ if (previousSessionId === this.orderSessionId || !this.core?.effects) return;
1331
+ // The session is already published. A listener failure must not turn a successful
1332
+ // reset into a failed reset or roll the active order back.
1333
+ const reportError = error => this.logWarning('Order session listener failed', {
1334
+ error: error instanceof Error ? error.message : String(error)
1335
+ });
1336
+ try {
1337
+ void Promise.resolve(this.effectsEmit('onOrderSessionChanged', {
1338
+ sessionId: this.orderSessionId,
1339
+ previousSessionId
1340
+ })).catch(reportError);
1341
+ } catch (error) {
1342
+ reportError(error);
1343
+ }
1344
+ }
1345
+ getOrderSessionId() {
1346
+ if (this.orderSessionDestroyed) return null;
1347
+ if (this.orderReplacement) return this.orderReplacement.sessionId;
1348
+ // Existing in-memory orders can be adopted during initialization. Adding a
1349
+ // remote ID later only extends the aliases; it does not create a new order.
1350
+ this.publishOrderSession(this.store?.tempOrder || null);
1351
+ return this.orderSessionId;
1352
+ }
1353
+ isOrderSessionCurrent(sessionId) {
1354
+ return !this.orderReplacement && Boolean(sessionId) && this.getOrderSessionId() === sessionId;
1355
+ }
1356
+ beginOrderReplacement(preserveOrderSessionId) {
1357
+ if (this.orderReplacement) {
1358
+ throw Object.assign(new Error('An order replacement is already pending'), {
1359
+ code: 'ORDER_SESSION_TRANSITION_PENDING'
1360
+ });
1361
+ }
1362
+ const sessionId = this.getOrderSessionId();
1363
+ if (preserveOrderSessionId && preserveOrderSessionId !== sessionId) {
1364
+ throw Object.assign(new Error('The order session has changed'), {
1365
+ code: 'ORDER_SESSION_CHANGED'
1366
+ });
1367
+ }
1368
+ const discount = this.store.discount;
1369
+ const replacement = {
1370
+ state: {
1371
+ ...this.store
1372
+ },
1373
+ sessionId,
1374
+ aliases: new Set(this.orderSessionAliases),
1375
+ originalDiscounts: (0, _lodashEs.cloneDeep)(discount?.getOriginalDiscountList?.() || []),
1376
+ discounts: (0, _lodashEs.cloneDeep)(discount?.getDiscountList?.() || []),
1377
+ walletEpoch: this.customerWalletPrepareConfigEpoch,
1378
+ pointCardCandidates: new Map(this.pointCardSnapshotCodeCandidates),
1379
+ sessionStorageRestoreRecord: this.sessionStorageRestoreRecord
1380
+ };
1381
+ this.orderReplacement = replacement;
1382
+ return replacement;
1383
+ }
1384
+ assertOrderReplacementCurrent(replacement) {
1385
+ if (this.orderReplacement !== replacement) {
1386
+ throw Object.assign(new Error('The order changed while its replacement was pending'), {
1387
+ code: 'ORDER_SESSION_CHANGED'
1388
+ });
1389
+ }
1390
+ }
1391
+ completeOrderReplacement(replacement, nextOrder, preserveOrderSessionId) {
1392
+ this.assertOrderReplacementCurrent(replacement);
1393
+ const aliases = this.getOrderSessionAliases(nextOrder);
1394
+ const sameOrder = Boolean(replacement.sessionId) && (preserveOrderSessionId === replacement.sessionId || [...aliases].some(alias => replacement.aliases.has(alias)));
1395
+ this.orderReplacement = null;
1396
+ this.publishOrderSession(nextOrder, !sameOrder);
1397
+ }
1398
+ async rollbackOrderReplacement(replacement) {
1399
+ // An explicit reset wins over the pending result, including its rollback.
1400
+ if (this.orderReplacement !== replacement) return;
1401
+ Object.assign(this.store, replacement.state);
1402
+ this.customerWalletPrepareConfigEpoch = replacement.walletEpoch;
1403
+ this.pointCardSnapshotCodeCandidates = replacement.pointCardCandidates;
1404
+ this.sessionStorageRestoreRecord = replacement.sessionStorageRestoreRecord;
1405
+ const discount = this.store.discount;
1406
+ const restore = await Promise.allSettled([discount?.setOriginalDiscountList(replacement.originalDiscounts), discount?.setDiscountList(replacement.discounts)]);
1407
+ if (restore.some(result => result.status === 'rejected')) {
1408
+ this.logWarning('Order replacement discount rollback listener failed');
1409
+ }
1410
+ if (this.orderReplacement === replacement) this.orderReplacement = null;
1411
+ }
1201
1412
  createDefaultTempOrderInstance() {
1202
1413
  return (0, _utils.createDefaultTempOrder)({
1203
1414
  now: (0, _utils.formatDateTime)(new Date())
@@ -1389,7 +1600,37 @@ class OrderModule extends _BaseModule.BaseModule {
1389
1600
  }, new _decimal.default(0));
1390
1601
  }
1391
1602
  getDepositAmount(tempOrder, summary) {
1392
- return new _decimal.default(summary.deposit_amount || tempOrder.deposit_amount || '0.00');
1603
+ const summaryAmount = summary.deposit_amount;
1604
+ const amount = summaryAmount === '' ? tempOrder.deposit_amount : summaryAmount ?? tempOrder.deposit_amount;
1605
+ return _decimal.default.min(_decimal.default.max(new _decimal.default(amount || 0), 0), this.getOrderExpectedAmount(summary));
1606
+ }
1607
+ isDepositSelectionDisabled(tempOrder) {
1608
+ return tempOrder._extend?.depositSelectionDisabled === true || tempOrder.is_deposit === 0 && new _decimal.default(tempOrder.deposit_amount || 0).gt(0);
1609
+ }
1610
+
1611
+ /** Cap only the active target; product rules, manual intent and saved snapshots stay raw. */
1612
+ applyEffectiveDepositSummary(tempOrder, summary) {
1613
+ const disabled = this.isDepositSelectionDisabled(tempOrder);
1614
+ if (disabled) {
1615
+ tempOrder._extend = {
1616
+ ...(tempOrder._extend || {}),
1617
+ depositSelectionDisabled: true
1618
+ };
1619
+ }
1620
+ const depositAmount = this.getDepositAmount(tempOrder, summary).toFixed(2);
1621
+ const hasDepositAmount = new _decimal.default(depositAmount).gt(0);
1622
+ const nextSummary = {
1623
+ ...summary,
1624
+ deposit_amount: depositAmount,
1625
+ deposit: hasDepositAmount ? {
1626
+ ...(summary.deposit || {}),
1627
+ total: depositAmount,
1628
+ hasDeposit: true
1629
+ } : undefined
1630
+ };
1631
+ tempOrder.deposit_amount = depositAmount;
1632
+ tempOrder.is_deposit = hasDepositAmount && tempOrder.is_deposit === 1 && !disabled ? 1 : 0;
1633
+ return nextSummary;
1393
1634
  }
1394
1635
  normalizeDepositAmount(amount) {
1395
1636
  return _decimal.default.max(new _decimal.default(Number(amount) || 0), 0).toDecimalPlaces(2).toFixed(2);
@@ -1403,8 +1644,19 @@ class OrderModule extends _BaseModule.BaseModule {
1403
1644
  if (!source || typeof source !== 'object') return null;
1404
1645
  const record = source;
1405
1646
  const rawDepositAmount = record.deposit_amount ?? record.summary?.deposit_amount;
1647
+ if (rawDepositAmount === undefined || rawDepositAmount === null || rawDepositAmount === '') return null;
1406
1648
  const depositAmount = this.normalizeDepositAmount(rawDepositAmount ?? 0);
1407
- if (!new _decimal.default(depositAmount).gt(0)) return null;
1649
+ if (!new _decimal.default(depositAmount).gt(0)) {
1650
+ // A saved zero is meaningful for an existing deposit product, but must not
1651
+ // freeze ordinary historical retail orders when a deposit product is added.
1652
+ const products = Array.isArray(record.products) ? record.products : [];
1653
+ const hasDepositContext = this.normalizeDepositFlag(record.is_deposit) === 1 || products.some(product => Number(product?.deposit?.total) > 0) || (0, _utils.calculateOrderProductsDeposit)(products.map(product => ({
1654
+ ...product
1655
+ })), {
1656
+ productsByUid: record._extend?.productsByUid
1657
+ }).hasDeposit;
1658
+ if (!hasDepositContext) return null;
1659
+ }
1408
1660
  return {
1409
1661
  // 兼容历史数据:旧快照缺少 is_deposit 时,沿用正定金金额的推导规则。
1410
1662
  isDeposit: this.normalizeDepositFlag(record.is_deposit) ?? 1,
@@ -1468,7 +1720,9 @@ class OrderModule extends _BaseModule.BaseModule {
1468
1720
  return tempOrder.is_deposit === 1 && depositAmount.gt(0);
1469
1721
  }
1470
1722
  getOrderExpectedAmount(summary) {
1471
- return new _decimal.default(summary.expect_amount || summary.total_amount || 0);
1723
+ const expected = summary.expect_amount;
1724
+ const amount = expected === '' ? summary.total_amount : expected ?? summary.total_amount;
1725
+ return _decimal.default.max(new _decimal.default(amount || 0), 0);
1472
1726
  }
1473
1727
  isDepositCovered(params) {
1474
1728
  const depositAmount = this.getDepositAmount(params.tempOrder, params.summary);
@@ -1517,7 +1771,7 @@ class OrderModule extends _BaseModule.BaseModule {
1517
1771
  });
1518
1772
  }
1519
1773
  resolveNextOrderPaymentType(tempOrder) {
1520
- const depositAmount = new _decimal.default(tempOrder.deposit_amount || '0.00');
1774
+ const depositAmount = this.getDepositAmount(tempOrder, this.store.summary || (0, _utils.createEmptySummary)());
1521
1775
  if (!this.isDepositOrder(tempOrder, depositAmount)) return 'normal';
1522
1776
  if (depositAmount.lte(0)) return 'normal';
1523
1777
  if (this.hasPaidNormalPayment(tempOrder.payments || [])) return 'normal';
@@ -2018,6 +2272,7 @@ class OrderModule extends _BaseModule.BaseModule {
2018
2272
  tempOrder.is_deposit = historicalDepositSnapshot.isDeposit;
2019
2273
  }
2020
2274
  }
2275
+ summary = this.applyEffectiveDepositSummary(tempOrder, summary);
2021
2276
  const isPayableAmountUnchanged = this.isSnapshotPayableAmountUnchanged(tempOrder, snapshot, summary);
2022
2277
  if (!isPayableAmountUnchanged) return null;
2023
2278
  const currentPaidPaymentSummary = this.calculatePaidPaymentSummary(tempOrder.payments || []);
@@ -2033,8 +2288,6 @@ class OrderModule extends _BaseModule.BaseModule {
2033
2288
  tempOrder.surcharges = (0, _lodashEs.cloneDeep)(snapshot.surcharges);
2034
2289
  }
2035
2290
  tempOrder.surcharge_fee = summary.surcharge_fee || tempOrder.surcharge_fee;
2036
- tempOrder.deposit_amount = this.normalizeDepositAmount(summary.deposit_amount || 0);
2037
- tempOrder.is_deposit = shouldUseManualDepositOverride ? new _decimal.default(tempOrder.deposit_amount).gt(0) ? 1 : 0 : historicalDepositSnapshot?.isDeposit ?? (new _decimal.default(tempOrder.deposit_amount).gt(0) ? 1 : 0);
2038
2291
  const previousSummary = this.store.summary;
2039
2292
  this.store.summary = summary;
2040
2293
  this.updateTempOrderPaymentStatus(tempOrder, {
@@ -2077,16 +2330,19 @@ class OrderModule extends _BaseModule.BaseModule {
2077
2330
  ensureTempOrder() {
2078
2331
  if (this.store.tempOrder) {
2079
2332
  this.ensureExternalSaleNumber(this.store.tempOrder);
2333
+ if (!this.orderReplacement) this.publishOrderSession(this.store.tempOrder);
2080
2334
  return this.store.tempOrder;
2081
2335
  }
2082
2336
  const newOrder = this.createDefaultTempOrderInstance();
2083
2337
  this.ensureExternalSaleNumber(newOrder);
2084
2338
  this.store.tempOrder = newOrder;
2339
+ this.publishOrderSession(newOrder, true);
2085
2340
  this.persistTempOrder();
2086
2341
  return newOrder;
2087
2342
  }
2088
2343
  restoreOrder() {
2089
2344
  this.logInfo('restoreOrder start', {});
2345
+ this.orderReplacement = null;
2090
2346
  this.sessionStorageRestoreRecord = null;
2091
2347
  const freshTempOrder = this.createDefaultTempOrderInstance();
2092
2348
  this.ensureExternalSaleNumber(freshTempOrder);
@@ -2097,36 +2353,45 @@ class OrderModule extends _BaseModule.BaseModule {
2097
2353
  this.store.syncState = undefined;
2098
2354
  void this.store.discount?.setOriginalDiscountList([]);
2099
2355
  void this.store.discount?.setDiscountList([]);
2356
+ this.publishOrderSession(freshTempOrder, true);
2100
2357
  this.persistTempOrder();
2101
2358
  return freshTempOrder;
2102
2359
  }
2103
2360
  getTempOrder() {
2104
- return this.store.tempOrder;
2361
+ return this.orderReplacement ? this.orderReplacement.state.tempOrder : this.store.tempOrder;
2105
2362
  }
2106
2363
  async replaceTempOrder(tempOrder, options) {
2107
2364
  if (!(0, _utils.isTempOrder)(tempOrder)) {
2108
2365
  throw new Error('无效的 tempOrder 数据');
2109
2366
  }
2110
- this.sessionStorageRestoreRecord = null;
2111
2367
  const nextTempOrder = this.normalizeTempOrderForRuntime((0, _lodashEs.cloneDeep)(tempOrder), {
2112
2368
  ensureIdentity: false
2113
2369
  });
2114
- this.store.tempOrder = nextTempOrder;
2115
- this.clearCustomerWalletRuntimeState();
2116
- if (options?.recalculateSummary !== false) {
2117
- await this.recalculateSummary({
2118
- createIfMissing: false
2119
- });
2120
- } else {
2121
- this.store.summary = (0, _utils.createEmptySummary)();
2122
- }
2123
- if (options?.persist !== false) {
2124
- this.persistTempOrder();
2125
- }
2126
- if (options?.saveDraft) {
2127
- await this.saveDraft();
2370
+ const replacement = this.beginOrderReplacement(options?.preserveOrderSessionId);
2371
+ try {
2372
+ this.sessionStorageRestoreRecord = null;
2373
+ this.store.tempOrder = nextTempOrder;
2374
+ this.clearCustomerWalletRuntimeState();
2375
+ if (options?.recalculateSummary !== false) {
2376
+ await this.recalculateSummary({
2377
+ createIfMissing: false,
2378
+ isCurrentOrder: () => this.orderReplacement === replacement
2379
+ });
2380
+ } else {
2381
+ this.store.summary = (0, _utils.createEmptySummary)();
2382
+ }
2383
+ this.assertOrderReplacementCurrent(replacement);
2384
+ if (options?.saveDraft) {
2385
+ await this.saveDraft();
2386
+ this.assertOrderReplacementCurrent(replacement);
2387
+ }
2388
+ if (options?.persist !== false) this.persistTempOrder();
2389
+ this.completeOrderReplacement(replacement, nextTempOrder, options?.preserveOrderSessionId);
2390
+ return nextTempOrder;
2391
+ } catch (error) {
2392
+ await this.rollbackOrderReplacement(replacement);
2393
+ throw error;
2128
2394
  }
2129
- return nextTempOrder;
2130
2395
  }
2131
2396
  getOrderIdentity() {
2132
2397
  const tempOrder = this.store.tempOrder;
@@ -2155,7 +2420,7 @@ class OrderModule extends _BaseModule.BaseModule {
2155
2420
  const tempOrder = this.store.tempOrder;
2156
2421
  if (!tempOrder) return null;
2157
2422
  const summary = this.store.summary || (0, _utils.createEmptySummary)();
2158
- const depositAmount = tempOrder.deposit_amount || summary.deposit_amount || '0.00';
2423
+ const depositAmount = this.getDepositAmount(tempOrder, summary);
2159
2424
  const paidPaymentSummary = this.calculatePaidPaymentSummary(tempOrder.payments || []);
2160
2425
  const amountGap = this.calculateSummaryAmountGap({
2161
2426
  tempOrder,
@@ -2163,10 +2428,10 @@ class OrderModule extends _BaseModule.BaseModule {
2163
2428
  orderPaidAmount: paidPaymentSummary.gapPaidAmount
2164
2429
  });
2165
2430
  return {
2166
- isDeposit: tempOrder.is_deposit === 1,
2167
- depositAmount,
2168
- expectAmount: summary.expect_amount || '0.00',
2169
- totalAmount: summary.total_amount || '0.00',
2431
+ isDeposit: this.isDepositOrder(tempOrder, depositAmount),
2432
+ depositAmount: depositAmount.toFixed(2),
2433
+ expectAmount: String(summary.expect_amount ?? '0.00'),
2434
+ totalAmount: String(summary.total_amount ?? '0.00'),
2170
2435
  amountGap,
2171
2436
  summary
2172
2437
  };
@@ -2269,8 +2534,12 @@ class OrderModule extends _BaseModule.BaseModule {
2269
2534
  ...existed,
2270
2535
  ...(origin !== undefined ? {
2271
2536
  origin
2537
+ } : {}),
2538
+ ...(rawProduct._productVoucherGroupKey ? {
2539
+ productVoucherGroupKey: rawProduct._productVoucherGroupKey
2272
2540
  } : {})
2273
2541
  };
2542
+ delete normalizedProduct._productVoucherGroupKey;
2274
2543
  delete normalizedProduct._origin;
2275
2544
  delete normalizedProduct.unique_identification_number;
2276
2545
  }
@@ -2480,6 +2749,13 @@ class OrderModule extends _BaseModule.BaseModule {
2480
2749
  return this.core.getModule(this.salesSummaryModuleName);
2481
2750
  }
2482
2751
  applyOrderProductsDepositSummary(tempOrder, summary) {
2752
+ const isExistingDepositDisabled = this.isDepositSelectionDisabled(tempOrder);
2753
+ if (isExistingDepositDisabled) {
2754
+ tempOrder._extend = {
2755
+ ...(tempOrder._extend || {}),
2756
+ depositSelectionDisabled: true
2757
+ };
2758
+ }
2483
2759
  const depositSummary = (0, _utils.calculateOrderProductsDeposit)(tempOrder.products || [], {
2484
2760
  productsByUid: tempOrder._extend?.productsByUid
2485
2761
  });
@@ -2501,10 +2777,9 @@ class OrderModule extends _BaseModule.BaseModule {
2501
2777
  hasDeposit: true
2502
2778
  } : undefined
2503
2779
  };
2504
- const isExistingDepositDisabled = tempOrder.is_deposit === 0 && new _decimal.default(tempOrder.deposit_amount || 0).gt(0);
2505
2780
  tempOrder.deposit_amount = depositAmount;
2506
2781
  tempOrder.is_deposit = hasDepositAmount && !isExistingDepositDisabled ? 1 : 0;
2507
- return shouldUseManualDepositOverride ? nextSummary : this.applyLastOrderDepositSnapshot(tempOrder, nextSummary);
2782
+ return this.applyEffectiveDepositSummary(tempOrder, shouldUseManualDepositOverride ? nextSummary : this.applyLastOrderDepositSnapshot(tempOrder, nextSummary));
2508
2783
  }
2509
2784
  async recalculateSummary(options) {
2510
2785
  if (options?.isCurrentOrder && !options.isCurrentOrder()) return null;
@@ -2839,11 +3114,15 @@ class OrderModule extends _BaseModule.BaseModule {
2839
3114
  updateTempOrderDepositAmount(amount) {
2840
3115
  const tempOrder = this.ensureTempOrder();
2841
3116
  const depositAmount = this.normalizeDepositAmount(amount);
3117
+ tempOrder._extend = {
3118
+ ...(tempOrder._extend || {}),
3119
+ depositSelectionDisabled: new _decimal.default(depositAmount).lte(0)
3120
+ };
2842
3121
  const previousSummary = this.store.summary || (0, _utils.createEmptySummary)();
2843
- const summaryWithDeposit = this.applyDepositAmountToSummary(tempOrder, {
3122
+ const summaryWithDeposit = this.applyEffectiveDepositSummary(tempOrder, this.applyDepositAmountToSummary(tempOrder, {
2844
3123
  ...(0, _utils.createEmptySummary)(),
2845
3124
  ...previousSummary
2846
- }, depositAmount);
3125
+ }, depositAmount));
2847
3126
  this.setManualDepositOverride(tempOrder, depositAmount);
2848
3127
  const paidPaymentSummary = this.calculatePaidPaymentSummary(tempOrder.payments || []);
2849
3128
  const summary = {
@@ -3596,6 +3875,7 @@ class OrderModule extends _BaseModule.BaseModule {
3596
3875
  const isIncomingCustomItem = productToAdd.metadata?.origin?.isCustomItem === true || productToAdd._origin?.isCustomItem === true;
3597
3876
  const shouldForceNewLine = disableMerge || !!booking || hasIncomingGoodPass || isIncomingPersistedEntitlementPass || hasIncomingBookingUid || hasIncomingHolder || isIncomingCustomItem || isWeighingProduct;
3598
3877
  const matchedIndex = shouldForceNewLine ? -1 : tempOrder.products.findIndex(item => {
3878
+ if ((0, _productVoucherGroups.productVoucherGroupKey)(tempOrder, item) !== productToAdd._productVoucherGroupKey) return false;
3599
3879
  if (this.hasGoodPassDiscount(item)) return false;
3600
3880
  if ((0, _holderRelations.getProductHolderRelations)(tempOrder, item).length > 0 || (0, _utils.hasAssignedHolderId)(item.metadata?.holder_id)) return false;
3601
3881
  const isRuntimeEntitlementPass = this.isRuntimeEntitlementAppend(item, tempOrder);
@@ -3779,16 +4059,37 @@ class OrderModule extends _BaseModule.BaseModule {
3779
4059
  * // → tempOrder.products 新增 3 行,每行 num=1,bookings 3 条
3780
4060
  */
3781
4061
  async addProductToOrder(product, booking, options) {
4062
+ return this.queueCartCommand(() => this.addProductToOrderDraft(product, booking, options));
4063
+ }
4064
+ async addProductToOrderDraft(product, booking, options) {
3782
4065
  const availabilityCommitGuard = options?.availabilityCommitGuard;
3783
4066
  availabilityCommitGuard?.();
3784
4067
  const liveTempOrder = this.ensureTempOrder();
3785
4068
  const beforeCommit = this.createCartIntentCommitGuard('add_product', liveTempOrder);
3786
- // 自动预约在草稿上准备完整批次,避免拆票期间暴露半成品,或在失败时
3787
- // 用整单快照回滚而抹掉其他入口的并发修改。人工路径保持原有写入行为。
3788
- const tempOrder = availabilityCommitGuard ? (0, _lodashEs.cloneDeep)(liveTempOrder) : liveTempOrder;
3789
- const guardedMutationFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'currency_code', 'currency_symbol', 'currency_format'];
4069
+ const mutation = this.beginCartMutation();
4070
+ // 库存/商品券校验与自动预约共用草稿,全部门禁通过后才发布完整批次。
4071
+ const tempOrder = availabilityCommitGuard && !mutation.commit ? (0, _lodashEs.cloneDeep)(liveTempOrder) : mutation.draft;
4072
+ const beforeAppend = mutation.commit ? undefined : beforeCommit;
4073
+ const guardedMutationFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'currency_code', 'currency_symbol', 'currency_format', ...(!booking && Array.isArray(product._extend?.holder_relations) ? ['holder_relations'] : [])];
3790
4074
  const readGuardedMutationFields = order => Object.fromEntries(guardedMutationFields.map(key => [key, order[key]]));
3791
4075
  const guardedMutationBaseline = availabilityCommitGuard ? (0, _lodashEs.cloneDeep)(readGuardedMutationFields(liveTempOrder)) : null;
4076
+ const beforePublish = () => {
4077
+ availabilityCommitGuard?.();
4078
+ beforeCommit();
4079
+ // 调用方的结构 revision 可能不包括备注、价格或结算元数据。
4080
+ if (availabilityCommitGuard && !(0, _lodashEs.isEqual)(readGuardedMutationFields(liveTempOrder), guardedMutationBaseline)) {
4081
+ throw Object.assign(new Error('预约加购期间订单已变化,请重新选择'), {
4082
+ code: 'AVAILABILITY_SELECTION_STALE'
4083
+ });
4084
+ }
4085
+ };
4086
+ if (options?.productVoucherGroupKey) {
4087
+ if (!tempOrder._extend?.productVoucherGroups?.some(group => group.key === options.productVoucherGroupKey)) throw (0, _productVoucherGroups.voucherGroupError)();
4088
+ product = {
4089
+ ...product,
4090
+ _productVoucherGroupKey: options.productVoucherGroupKey
4091
+ };
4092
+ }
3792
4093
  const salesNoteDrafts = (options?.salesNotes || []).map(draft => ({
3793
4094
  note_type: String(draft.note_type || '').trim(),
3794
4095
  text: {
@@ -3862,7 +4163,7 @@ class OrderModule extends _BaseModule.BaseModule {
3862
4163
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, splitLine.product, splitLine.booking, {
3863
4164
  insertAtIndex,
3864
4165
  disableMerge: options?.disableMerge,
3865
- beforeCommit
4166
+ beforeCommit: beforeAppend
3866
4167
  });
3867
4168
  availabilityCommitGuard?.();
3868
4169
  attachSalesNoteDrafts(committedProduct);
@@ -3872,7 +4173,7 @@ class OrderModule extends _BaseModule.BaseModule {
3872
4173
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, product, (0, _lodashEs.cloneDeep)(booking), {
3873
4174
  insertAtIndex,
3874
4175
  disableMerge: options?.disableMerge,
3875
- beforeCommit
4176
+ beforeCommit: beforeAppend
3876
4177
  });
3877
4178
  availabilityCommitGuard?.();
3878
4179
  attachSalesNoteDrafts(committedProduct);
@@ -3881,21 +4182,17 @@ class OrderModule extends _BaseModule.BaseModule {
3881
4182
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, product, undefined, {
3882
4183
  insertAtIndex,
3883
4184
  disableMerge: options?.disableMerge,
3884
- beforeCommit
4185
+ beforeCommit: beforeAppend
3885
4186
  });
3886
4187
  availabilityCommitGuard?.();
3887
4188
  attachSalesNoteDrafts(committedProduct);
3888
4189
  }
3889
- if (availabilityCommitGuard) {
3890
- availabilityCommitGuard();
3891
- beforeCommit();
3892
- // 调用方的结构 revision 可能不包括备注、价格或结算元数据。
3893
- // 本次会覆盖的字段也要保持原值,不能让草稿覆盖并发编辑。
3894
- if (!(0, _lodashEs.isEqual)(readGuardedMutationFields(liveTempOrder), guardedMutationBaseline)) {
3895
- throw Object.assign(new Error('预约加购期间订单已变化,请重新选择'), {
3896
- code: 'AVAILABILITY_SELECTION_STALE'
3897
- });
3898
- }
4190
+ if (mutation.commit) {
4191
+ await mutation.commit({
4192
+ beforeCommit: beforePublish
4193
+ });
4194
+ } else if (availabilityCommitGuard) {
4195
+ beforePublish();
3899
4196
  // 从最后一次门禁到真正新增之间不再 await。只发布本次新增会改写的
3900
4197
  // 字段;其余订单字段继续使用 live 对象,外部持有的订单引用也不变。
3901
4198
  Object.assign(liveTempOrder, readGuardedMutationFields(tempOrder));
@@ -3933,6 +4230,134 @@ class OrderModule extends _BaseModule.BaseModule {
3933
4230
  return liveTempOrder.products;
3934
4231
  }
3935
4232
 
4233
+ /**
4234
+ * Replaces one local Party booking and its confirmed children on a detached draft.
4235
+ * All fallible preparation precedes a guarded synchronous publication; never rolls
4236
+ * an old whole-order snapshot over concurrent edits or a newly selected order.
4237
+ */
4238
+ async replaceBookingProductWithRelatedRetail(params) {
4239
+ return this.queueCartCommand(() => this.replaceBookingProductWithRelatedRetailDraft(params));
4240
+ }
4241
+ async replaceBookingProductWithRelatedRetailDraft(params) {
4242
+ params.availabilityCommitGuard();
4243
+ const live = this.ensureTempOrder();
4244
+ const mutation = this.beginCartMutation();
4245
+ const beforeCommit = this.createCartIntentCommitGuard('update_product', live);
4246
+ const uid = String(params.productLineUid || '');
4247
+ const getUid = line => String(line.metadata?.unique_identification_number || line.unique_identification_number || '');
4248
+ const targetIndex = live.products.findIndex(line => getUid(line) === uid);
4249
+ const target = live.products[targetIndex];
4250
+ const scopeKey = String(target?.metadata?.venue_booking_scope_key || '');
4251
+ const targetBookingUid = String(target?.booking_uid || target?.metadata?.booking_uid || '');
4252
+ if (!uid || !target || !scopeKey || live.order_id || target.order_detail_id != null || Number(target.num) !== 1 || Number(params.product.num ?? 1) !== 1 || target.metadata?.venue_booking_role !== 'party_main' || params.product.metadata?.venue_booking_role !== 'party_main' || params.product.metadata?.venue_booking_scope_key !== scopeKey || !Array.isArray(params.relatedRetailProducts) || (live.payments || []).length > 0 || !targetBookingUid || String(params.booking.metadata?.unique_identification_number || '') !== targetBookingUid || (live.bookings || []).filter(booking => this.getBookingUniqueIdentificationNumber(booking) === targetBookingUid).length !== 1 || live.products.filter(line => line.metadata?.venue_booking_role === 'party_main' && line.metadata?.venue_booking_scope_key === scopeKey).length !== 1) {
4253
+ throw new Error('[Order] Party replacement requires one unsubmitted, unpaid main booking in the same scope');
4254
+ }
4255
+ const children = live.products.filter(line => line.metadata?.venue_booking_role === 'party_extra' && String(line.metadata?.venue_booking_parent_uid || '') === uid);
4256
+ if (children.some(line => !getUid(line) || line.metadata?.venue_booking_scope_key !== scopeKey || line.order_detail_id != null || this.hasLinkedBookingUid(line))) {
4257
+ throw new Error('[Order] Related retail line does not belong to this local Party scope');
4258
+ }
4259
+ const start = params.booking.start_at || `${params.booking.start_date || ''} ${params.booking.start_time || ''}`.trim();
4260
+ if (!start || !(0, _dayjs.default)(start).isValid()) throw new Error('[Order] Party service datetime is required');
4261
+ const serviceDatetime = (0, _dayjs.default)(start).format('YYYY-MM-DD HH:mm:ss');
4262
+ const ownedUids = new Set(children.map(getUid));
4263
+ const nextUids = new Set();
4264
+ const retainedChildUids = new Set();
4265
+ const nextChildren = (0, _lodashEs.cloneDeep)(params.relatedRetailProducts);
4266
+ for (const child of nextChildren) {
4267
+ const childUid = getUid(child);
4268
+ const purchaseDatetime = String(child.metadata?.venue_booking_service_datetime || '');
4269
+ const normalizedPurchaseDatetime = purchaseDatetime.length === 16 ? `${purchaseDatetime}:00` : purchaseDatetime;
4270
+ if (child.metadata?.venue_booking_role !== 'party_extra' || String(child.metadata?.venue_booking_parent_uid || '') !== uid || child.metadata?.venue_booking_scope_key !== scopeKey || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?$/.test(purchaseDatetime) || !(0, _dayjs.default)(purchaseDatetime).isValid() || (0, _dayjs.default)(purchaseDatetime).format('YYYY-MM-DD HH:mm:ss') !== normalizedPurchaseDatetime || this.hasLinkedBookingUid(child) || child.order_detail_id != null || childUid && (nextUids.has(childUid) || live.products.some(line => getUid(line) === childUid && !ownedUids.has(childUid)))) {
4271
+ throw new Error('[Order] Invalid Party extra ownership, identity, or purchase quote datetime');
4272
+ }
4273
+ if (childUid) nextUids.add(childUid);
4274
+ const previous = children.find(line => getUid(line) === childUid);
4275
+ if (previous && previous.product_id === child.product_id && Number(previous.product_variant_id || 0) === Number(child.product_variant_id || 0) && Number(previous.num) === Number(child.num ?? 1) && (0, _utils3.buildProductLineFingerprint)((0, _utils.getProductSkuOptions)(previous), previous.product_bundle) === (0, _utils3.buildProductLineFingerprint)((0, _utils.getProductSkuOptions)(child), child.product_bundle)) {
4276
+ retainedChildUids.add(childUid);
4277
+ // The same configured extra keeps completed product forms unless explicitly replaced.
4278
+ const previousForms = live._extend?.productsByUid?.[childUid]?.origin?.relation_forms;
4279
+ const rawChild = child;
4280
+ if (previousForms !== undefined && rawChild._origin?.relation_forms === undefined) {
4281
+ rawChild._origin = {
4282
+ ...(rawChild._origin || {}),
4283
+ relation_forms: (0, _lodashEs.cloneDeep)(previousForms)
4284
+ };
4285
+ }
4286
+ }
4287
+ }
4288
+ const publishedFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'holder', 'holder_relations', 'currency_code', 'currency_symbol', 'currency_format'];
4289
+ const guardedFields = [...publishedFields, 'customer_id', 'discount_list', 'shop_discount', 'payments'];
4290
+ const readFields = (order, fields) => Object.fromEntries(fields.map(key => [key, order[key]]));
4291
+ const baseline = (0, _lodashEs.cloneDeep)(readFields(live, guardedFields));
4292
+ const identity = [live.order_id, live.external_sale_number];
4293
+ const isCurrentOrder = () => this.store.tempOrder === live && live.order_id === identity[0] && live.external_sale_number === identity[1] && (params.availabilityCommitTargetGuard?.() ?? true);
4294
+ const draft = mutation.commit ? mutation.draft : (0, _lodashEs.cloneDeep)(live);
4295
+ this.ensureSalesNotesLoadedForMutation(draft);
4296
+ const removed = draft.products.filter(line => getUid(line) === uid || ownedUids.has(getUid(line)));
4297
+ draft.products = draft.products.filter(line => getUid(line) !== uid && !ownedUids.has(getUid(line)));
4298
+ for (const line of removed) this.removeLinkedBookingsForProduct(draft, line);
4299
+ (0, _holderRelations.removeProductHolderRelations)(draft, removed.filter(line => !retainedChildUids.has(getUid(line))));
4300
+ for (const line of removed) {
4301
+ if (draft._extend?.productsByUid && !retainedChildUids.has(getUid(line))) {
4302
+ delete draft._extend.productsByUid[getUid(line)];
4303
+ }
4304
+ }
4305
+ const replacement = (0, _lodashEs.cloneDeep)(params.product);
4306
+ replacement.metadata = {
4307
+ ...(replacement.metadata || {}),
4308
+ unique_identification_number: uid,
4309
+ venue_booking_service_datetime: serviceDatetime
4310
+ };
4311
+ replacement.unique_identification_number = uid;
4312
+ await this.appendProductLineToTempOrder(draft, replacement, (0, _lodashEs.cloneDeep)(params.booking), {
4313
+ insertAtIndex: targetIndex,
4314
+ disableMerge: true,
4315
+ beforeCommit
4316
+ });
4317
+ for (const [index, child] of nextChildren.entries()) {
4318
+ await this.appendProductLineToTempOrder(draft, child, undefined, {
4319
+ insertAtIndex: targetIndex + index + 1,
4320
+ disableMerge: true,
4321
+ beforeCommit
4322
+ });
4323
+ }
4324
+ this.removeSalesNotesForMissingProductLines(draft);
4325
+ this.syncTempOrderHolderFromBookings(draft);
4326
+ const beforePublish = () => {
4327
+ params.availabilityCommitGuard();
4328
+ beforeCommit();
4329
+ if (!isCurrentOrder() || !(0, _lodashEs.isEqual)(readFields(live, guardedFields), baseline)) {
4330
+ throw Object.assign(new Error('Party replacement interrupted by an order change'), {
4331
+ code: 'AVAILABILITY_SELECTION_STALE'
4332
+ });
4333
+ }
4334
+ };
4335
+ beforePublish();
4336
+ if (mutation.commit) {
4337
+ // Preserve beta's inventory and product-voucher checks before publishing.
4338
+ await mutation.commit({
4339
+ beforeCommit: beforePublish
4340
+ });
4341
+ } else {
4342
+ // No await between the final CAS and publication; preserve every unrelated live field.
4343
+ Object.assign(live, readFields(draft, publishedFields));
4344
+ }
4345
+ try {
4346
+ if (isCurrentOrder()) this.persistTempOrder();
4347
+ await this.finalizeProductOrderMutation(live, {
4348
+ isCurrentOrder
4349
+ });
4350
+ } catch (error) {
4351
+ // Already committed. Do not invite a second replacement or restore a stale snapshot.
4352
+ this.logWarning('Party replacement committed; finalization failed', {
4353
+ productLineUid: uid,
4354
+ committed: true,
4355
+ error: error instanceof Error ? error.message : String(error)
4356
+ });
4357
+ }
4358
+ return live.products;
4359
+ }
4360
+
3936
4361
  /**
3937
4362
  * 批量添加商品行,所有行追加完成后只触发一次促销、折扣、summary 重算与持久化。
3938
4363
  *
@@ -3943,9 +4368,14 @@ class OrderModule extends _BaseModule.BaseModule {
3943
4368
  * ]);
3944
4369
  */
3945
4370
  async addProductsToOrder(items, options) {
3946
- const tempOrder = this.ensureTempOrder();
4371
+ return this.queueCartCommand(() => this.addProductsToOrderDraft(items, options));
4372
+ }
4373
+ async addProductsToOrderDraft(items, options) {
4374
+ const mutation = this.beginCartMutation();
4375
+ let tempOrder = mutation.draft;
3947
4376
  if (!Array.isArray(items) || items.length === 0) return tempOrder.products;
3948
- const beforeCommit = this.createCartIntentCommitGuard('add_product', tempOrder);
4377
+ const beforeCommit = this.createCartIntentCommitGuard('add_product');
4378
+ const beforeAppend = mutation.commit ? undefined : beforeCommit;
3949
4379
  for (const item of items || []) {
3950
4380
  const {
3951
4381
  product,
@@ -3959,7 +4389,7 @@ class OrderModule extends _BaseModule.BaseModule {
3959
4389
  for (let i = 0; i < splitCount; i += 1) {
3960
4390
  const splitLine = this.createSplitBookingLine(productRecord, booking, i, splitCount);
3961
4391
  const appendResult = this.appendProductLineToTempOrder(tempOrder, splitLine.product, splitLine.booking, {
3962
- beforeCommit
4392
+ beforeCommit: beforeAppend
3963
4393
  });
3964
4394
  if (appendResult) await appendResult;
3965
4395
  }
@@ -3967,10 +4397,13 @@ class OrderModule extends _BaseModule.BaseModule {
3967
4397
  }
3968
4398
  }
3969
4399
  const appendResult = this.appendProductLineToTempOrder(tempOrder, product, booking, {
3970
- beforeCommit
4400
+ beforeCommit: beforeAppend
3971
4401
  });
3972
4402
  if (appendResult) await appendResult;
3973
4403
  }
4404
+ if (mutation.commit) tempOrder = await mutation.commit({
4405
+ beforeCommit
4406
+ });
3974
4407
  await this.finalizeProductOrderMutation(tempOrder, options);
3975
4408
  this.logInfo('addProductsToOrder success', {
3976
4409
  itemsCount: items.length
@@ -4314,12 +4747,18 @@ class OrderModule extends _BaseModule.BaseModule {
4314
4747
  return tempOrder.products[productIndex].metadata?.unique_identification_number;
4315
4748
  }
4316
4749
  async updateOrderProduct(params) {
4317
- const tempOrder = this.ensureTempOrder();
4318
- if (this.isRestrictedCartProductUpdate(tempOrder, params)) {
4319
- this.createCartIntentCommitGuard('update_product', tempOrder)();
4320
- }
4750
+ return this.queueCartCommand(() => this.updateOrderProductDraft(params));
4751
+ }
4752
+ async updateOrderProductDraft(params) {
4753
+ const mutation = this.beginCartMutation();
4754
+ let tempOrder = mutation.draft;
4755
+ const beforeCommit = this.isRestrictedCartProductUpdate(tempOrder, params) ? this.createCartIntentCommitGuard('update_product') : undefined;
4756
+ if (!mutation.commit) beforeCommit?.();
4321
4757
  const reapplyWeighedDiscountProductUids = [];
4322
4758
  const updatedProductUid = this.applyOrderProductUpdateToTempOrder(tempOrder, params, reapplyWeighedDiscountProductUids);
4759
+ if (mutation.commit) tempOrder = await mutation.commit({
4760
+ beforeCommit
4761
+ });
4323
4762
  const promotionPayload = await this.evaluatePromotion();
4324
4763
  this.applyDiscount({
4325
4764
  reapplyWeighedDiscountProductUids,
@@ -4336,14 +4775,18 @@ class OrderModule extends _BaseModule.BaseModule {
4336
4775
  });
4337
4776
  return tempOrder.products;
4338
4777
  }
4339
- async updateOrderProducts(paramsList) {
4340
- const tempOrder = this.ensureTempOrder();
4778
+ async updateOrderProducts(paramsList, options) {
4779
+ return this.queueCartCommand(() => this.updateOrderProductsDraft(paramsList, options));
4780
+ }
4781
+ async updateOrderProductsDraft(paramsList, options) {
4782
+ if (options) return this.updateOrderProductsGuarded(paramsList, options);
4783
+ const mutation = this.beginCartMutation();
4784
+ let tempOrder = mutation.draft;
4341
4785
  if (!paramsList.length) {
4342
4786
  return tempOrder.products;
4343
4787
  }
4344
- if (paramsList.some(params => this.isRestrictedCartProductUpdate(tempOrder, params))) {
4345
- this.createCartIntentCommitGuard('update_product', tempOrder)();
4346
- }
4788
+ const beforeCommit = paramsList.some(params => this.isRestrictedCartProductUpdate(tempOrder, params)) ? this.createCartIntentCommitGuard('update_product') : undefined;
4789
+ if (!mutation.commit) beforeCommit?.();
4347
4790
  const reapplyWeighedDiscountProductUids = [];
4348
4791
  const reapplyBookingDiscountProductUids = paramsList.reduce((acc, params) => {
4349
4792
  const updatedProductUid = this.applyOrderProductUpdateToTempOrder(tempOrder, params, reapplyWeighedDiscountProductUids);
@@ -4353,6 +4796,9 @@ class OrderModule extends _BaseModule.BaseModule {
4353
4796
  }
4354
4797
  return acc;
4355
4798
  }, []);
4799
+ if (mutation.commit) tempOrder = await mutation.commit({
4800
+ beforeCommit
4801
+ });
4356
4802
  await this.finalizeAfterProductsMutation(tempOrder, {
4357
4803
  reapplyWeighedDiscountProductUids,
4358
4804
  reapplyBookingDiscountProductUids: reapplyBookingDiscountProductUids.length ? reapplyBookingDiscountProductUids : undefined
@@ -4362,7 +4808,68 @@ class OrderModule extends _BaseModule.BaseModule {
4362
4808
  });
4363
4809
  return tempOrder.products;
4364
4810
  }
4811
+ async updateOrderProductsGuarded(paramsList, options) {
4812
+ const stale = () => Object.assign(new Error('Order product update interrupted by an order change'), {
4813
+ code: 'AVAILABILITY_SELECTION_STALE'
4814
+ });
4815
+ options.beforeApply?.();
4816
+ if (options.isCurrentOrder && !options.isCurrentOrder()) throw stale();
4817
+ const live = this.ensureTempOrder();
4818
+ if (!paramsList.length) return live.products;
4819
+ const mutation = this.beginCartMutation();
4820
+ const identity = [live.order_id, live.external_sale_number];
4821
+ const isCurrentOrder = () => this.store.tempOrder === live && live.order_id === identity[0] && live.external_sale_number === identity[1] && (options.isCurrentOrder?.() ?? true);
4822
+ const beforeCommit = this.createCartIntentCommitGuard('update_product', live);
4823
+ const publishedFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'holder', 'holder_relations'];
4824
+ const guardedFields = [...publishedFields, 'customer_id', 'discount_list', 'shop_discount', 'payments'];
4825
+ const readFields = (order, fields) => Object.fromEntries(fields.map(key => [key, order[key]]));
4826
+ const baseline = (0, _lodashEs.cloneDeep)(readFields(live, guardedFields));
4827
+ const draft = mutation.commit ? mutation.draft : (0, _lodashEs.cloneDeep)(live);
4828
+ const seen = new Set();
4829
+ const reapplyWeighedDiscountProductUids = [];
4830
+ const reapplyBookingDiscountProductUids = [];
4831
+ for (const params of paramsList) {
4832
+ const uid = String(params.unique_identification_number || '');
4833
+ const matches = draft.products.filter(line => String(line.metadata?.unique_identification_number || line.unique_identification_number || '') === uid);
4834
+ const target = matches[0];
4835
+ // Guarded re-quotation must identify the exact row; never fall back to another same-SKU line.
4836
+ if (!uid || seen.has(uid) || matches.length !== 1 || !target || target.product_id !== params.product_id || Number(target.product_variant_id || 0) !== Number(params.product_variant_id || 0)) throw stale();
4837
+ seen.add(uid);
4838
+ const updatedUid = this.applyOrderProductUpdateToTempOrder(draft, (0, _lodashEs.cloneDeep)(params), reapplyWeighedDiscountProductUids);
4839
+ if (params.allow_booking_discount_reapply && updatedUid) reapplyBookingDiscountProductUids.push(updatedUid);
4840
+ }
4841
+ const beforePublish = () => {
4842
+ options.beforeApply?.();
4843
+ beforeCommit();
4844
+ if (!isCurrentOrder() || !(0, _lodashEs.isEqual)(readFields(live, guardedFields), baseline)) throw stale();
4845
+ };
4846
+ beforePublish();
4847
+ if (mutation.commit) {
4848
+ await mutation.commit({
4849
+ beforeCommit: beforePublish
4850
+ });
4851
+ } else {
4852
+ Object.assign(live, readFields(draft, publishedFields));
4853
+ }
4854
+ try {
4855
+ if (isCurrentOrder()) this.persistTempOrder();
4856
+ await this.finalizeAfterProductsMutation(live, {
4857
+ reapplyWeighedDiscountProductUids,
4858
+ reapplyBookingDiscountProductUids,
4859
+ isCurrentOrder
4860
+ });
4861
+ } catch (error) {
4862
+ this.logWarning('Order product update committed; finalization failed', {
4863
+ committed: true,
4864
+ error: error instanceof Error ? error.message : String(error)
4865
+ });
4866
+ }
4867
+ return live.products;
4868
+ }
4365
4869
  async updateOrderProductQuantity(params, options) {
4870
+ return this.queueCartCommand(() => this.updateOrderProductQuantityDraft(params, options));
4871
+ }
4872
+ async updateOrderProductQuantityDraft(params, options) {
4366
4873
  const isCurrentOrder = options?.isCurrentOrder;
4367
4874
  if (isCurrentOrder && !isCurrentOrder()) return this.store.tempOrder?.products || [];
4368
4875
  const {
@@ -4374,7 +4881,8 @@ class OrderModule extends _BaseModule.BaseModule {
4374
4881
  product_sku,
4375
4882
  product_bundle
4376
4883
  } = params;
4377
- const tempOrder = this.ensureTempOrder();
4884
+ const mutation = this.beginCartMutation();
4885
+ let tempOrder = mutation.draft;
4378
4886
  this.repairDuplicateProductLineIdentities(tempOrder);
4379
4887
  const identityLookup = {
4380
4888
  product_id,
@@ -4430,11 +4938,16 @@ class OrderModule extends _BaseModule.BaseModule {
4430
4938
  throw new _virtualSettlement.VirtualCurrencyBalanceError(balance.toFixed(2), requiredAmount.toFixed(2));
4431
4939
  }
4432
4940
  }
4433
- if (normalizedProduct.num > targetProduct.num) {
4434
- this.createCartIntentCommitGuard('increase_quantity', tempOrder)();
4435
- }
4941
+ const beforeCommit = normalizedProduct.num > targetProduct.num ? this.createCartIntentCommitGuard('increase_quantity') : undefined;
4942
+ if (!mutation.commit) beforeCommit?.();
4436
4943
  if (isCurrentOrder && !isCurrentOrder()) return tempOrder.products;
4437
4944
  tempOrder.products[productIndex] = normalizedProduct;
4945
+ if (mutation.commit) {
4946
+ tempOrder = await mutation.commit({
4947
+ beforeCommit,
4948
+ isCurrentOrder
4949
+ });
4950
+ }
4438
4951
  if (isCurrentOrder) {
4439
4952
  await this.finalizeProductOrderMutation(tempOrder, {
4440
4953
  skipEditDiscountConfigRefresh: true,
@@ -4497,16 +5010,25 @@ class OrderModule extends _BaseModule.BaseModule {
4497
5010
  * await this.finalizeAfterProductsMutation(tempOrder);
4498
5011
  */
4499
5012
  async finalizeAfterProductsMutation(tempOrder, options) {
5013
+ const isCurrentOrder = options?.isCurrentOrder;
5014
+ if (isCurrentOrder && !isCurrentOrder()) return;
4500
5015
  this.syncTempOrderHolderFromBookings(tempOrder);
4501
- const promotionPayload = await this.evaluatePromotion();
5016
+ const promotionPayload = await this.evaluatePromotion(isCurrentOrder ? {
5017
+ isCurrentOrder
5018
+ } : undefined);
5019
+ if (isCurrentOrder && !isCurrentOrder()) return;
4502
5020
  this.applyDiscount({
4503
5021
  reapplyBookingDiscountProductUids: options?.reapplyBookingDiscountProductUids,
4504
5022
  reapplyWeighedDiscountProductUids: options?.reapplyWeighedDiscountProductUids
4505
5023
  });
4506
5024
  this.sanitizeTempOrderProducts(tempOrder);
4507
- await this.recalculateSummary({
4508
- createIfMissing: true
5025
+ const summary = await this.recalculateSummary({
5026
+ createIfMissing: true,
5027
+ ...(isCurrentOrder ? {
5028
+ isCurrentOrder
5029
+ } : {})
4509
5030
  });
5031
+ if (isCurrentOrder && (!isCurrentOrder() || !summary)) return;
4510
5032
  this.persistTempOrder();
4511
5033
  this.emitPromotionApplied(promotionPayload);
4512
5034
  }
@@ -4518,9 +5040,17 @@ class OrderModule extends _BaseModule.BaseModule {
4518
5040
  * await order.removeProductsFromOrder([identityA, identityB]);
4519
5041
  */
4520
5042
  async removeProductsFromOrder(identities, options) {
5043
+ return this.queueCartCommand(() => this.removeProductsFromOrderDraft(identities, options));
5044
+ }
5045
+ async removeProductsFromOrderDraft(identities, options) {
4521
5046
  const isCurrentOrder = options?.isCurrentOrder;
4522
5047
  if (isCurrentOrder && !isCurrentOrder()) return this.store.tempOrder?.products || [];
4523
- const tempOrder = this.ensureTempOrder();
5048
+ // Keep the pre-removal snapshot guard separate from the ownership guard:
5049
+ // deleting these rows must not make the async finalization reject its own mutation.
5050
+ if (identities.length) options?.beforeApply?.();
5051
+ if (isCurrentOrder && !isCurrentOrder()) return this.store.tempOrder?.products || [];
5052
+ const mutation = this.beginCartMutation();
5053
+ let tempOrder = mutation.draft;
4524
5054
  if (!identities.length) {
4525
5055
  return tempOrder.products;
4526
5056
  }
@@ -4588,6 +5118,14 @@ class OrderModule extends _BaseModule.BaseModule {
4588
5118
  }
4589
5119
  (0, _holderRelations.removeProductHolderRelations)(tempOrder, productsBeforeRemove.filter(product => !tempOrder.products.includes(product)));
4590
5120
  this.removeSalesNotesForMissingProductLines(tempOrder);
5121
+ if (tempOrder.products.length === 0) {
5122
+ // 整单折扣随购物车清空,避免重新加购时沿用上一批商品的优惠。
5123
+ tempOrder.shop_discount = '0.00';
5124
+ }
5125
+ if (mutation.commit) tempOrder = await mutation.commit({
5126
+ isCurrentOrder,
5127
+ beforeCommit: options?.beforeApply
5128
+ });
4591
5129
  if (isCurrentOrder) {
4592
5130
  await this.finalizeProductOrderMutation(tempOrder, {
4593
5131
  skipEditDiscountConfigRefresh: true,
@@ -4606,15 +5144,20 @@ class OrderModule extends _BaseModule.BaseModule {
4606
5144
  }
4607
5145
 
4608
5146
  /**
4609
- * 仅清空购物车行(products / bookings),不重置整单。
5147
+ * 清空购物车行(products / bookings)及整单折扣,不重置整单。
4610
5148
  * 普通整单 note 保持不变;以商品行为主体的 Sales Notes 同步删除。
4611
5149
  */
4612
5150
  async clearOrderCartLines() {
4613
- const tempOrder = this.ensureTempOrder();
5151
+ return this.queueCartCommand(() => this.clearOrderCartLinesDraft());
5152
+ }
5153
+ async clearOrderCartLinesDraft() {
5154
+ const mutation = this.beginCartMutation();
5155
+ let tempOrder = mutation.draft;
4614
5156
  this.ensureSalesNotesLoadedForMutation(tempOrder);
4615
5157
  (0, _holderRelations.removeProductHolderRelations)(tempOrder, tempOrder.products);
4616
5158
  tempOrder.products = [];
4617
5159
  tempOrder.bookings = [];
5160
+ tempOrder.shop_discount = '0.00';
4618
5161
  (0, _virtualSettlement.releaseTempOrderSettlementState)(tempOrder);
4619
5162
  this.removeSalesNotesForMissingProductLines(tempOrder);
4620
5163
  this.syncTempOrderHolderFromBookings(tempOrder);
@@ -4624,6 +5167,7 @@ class OrderModule extends _BaseModule.BaseModule {
4624
5167
  productsByUid: {}
4625
5168
  };
4626
5169
  }
5170
+ if (mutation.commit) tempOrder = await mutation.commit();
4627
5171
  const promotionPayload = await this.evaluatePromotion();
4628
5172
  this.applyDiscount();
4629
5173
  this.sanitizeTempOrderProducts(tempOrder);
@@ -4762,6 +5306,7 @@ class OrderModule extends _BaseModule.BaseModule {
4762
5306
  async runSubmitTempOrder(params) {
4763
5307
  const tempOrder = this.ensureTempOrder();
4764
5308
  if ((0, _localEftposState.requiresLocalPaymentRefresh)(tempOrder)) throw new Error(_localEftposState.PAYMENT_REFRESH_MESSAGE);
5309
+ (0, _productVoucherGroups.validateProductVoucherGroups)(tempOrder, this.getDiscountList(), undefined, true);
4765
5310
  this.prepareVirtualSettlementTempOrder(tempOrder);
4766
5311
  const isOnlineStorePlatform = this.isOnlineStorePlatform();
4767
5312
  const shouldConfirmPendingVoucherPayments = params?.confirmPendingVoucherPayments !== false;
@@ -5299,6 +5844,19 @@ class OrderModule extends _BaseModule.BaseModule {
5299
5844
  * 例如数组字段、商品行唯一值、价格 metadata、summary 派生状态和 _extend。
5300
5845
  */
5301
5846
  async hydrateTempOrderFromRecord(record, options) {
5847
+ const replacement = this.beginOrderReplacement(options?.preserveOrderSessionId);
5848
+ try {
5849
+ const nextTempOrder = await this.prepareHydratedTempOrder(record, options, replacement);
5850
+ this.assertOrderReplacementCurrent(replacement);
5851
+ this.persistTempOrder();
5852
+ this.completeOrderReplacement(replacement, nextTempOrder, options?.preserveOrderSessionId);
5853
+ return nextTempOrder;
5854
+ } catch (error) {
5855
+ await this.rollbackOrderReplacement(replacement);
5856
+ throw error;
5857
+ }
5858
+ }
5859
+ async prepareHydratedTempOrder(record, options, replacement) {
5302
5860
  const sourceRaw = record && typeof record === 'object' && record.data && record.order_id == null ? record.data : record || {};
5303
5861
  const duplicateProductIdentityRepair = (0, _orderCollectionIdentity.repairDuplicateProductLineIdentities)(Array.isArray(sourceRaw.products) ? sourceRaw.products : [], sourceRaw._extend?.productsByUid);
5304
5862
  const duplicateIdentityReadySource = duplicateProductIdentityRepair.repairs.length ? {
@@ -5354,13 +5912,15 @@ class OrderModule extends _BaseModule.BaseModule {
5354
5912
  this.store.summary = (0, _utils.createEmptySummary)();
5355
5913
  this.store.lastOrderInfo = undefined;
5356
5914
  await this.store.discount?.setOriginalDiscountList((0, _lodashEs.cloneDeep)(restoredSessionDiscounts));
5915
+ this.assertOrderReplacementCurrent(replacement);
5357
5916
  await this.store.discount?.setDiscountList((0, _lodashEs.cloneDeep)(restoredSessionDiscounts));
5917
+ this.assertOrderReplacementCurrent(replacement);
5358
5918
  if (options?.recalcOnHydrate) {
5359
5919
  await this.recalculateSummary({
5360
- createIfMissing: false
5920
+ createIfMissing: false,
5921
+ isCurrentOrder: () => this.orderReplacement === replacement
5361
5922
  });
5362
5923
  }
5363
- this.persistTempOrder();
5364
5924
  return nextTempOrder;
5365
5925
  }
5366
5926
 
@@ -5373,6 +5933,9 @@ class OrderModule extends _BaseModule.BaseModule {
5373
5933
  };
5374
5934
  const rawSummary = raw.summary && typeof raw.summary === 'object' ? raw.summary : {};
5375
5935
  const historicalDepositSnapshot = this.getHistoricalDepositSnapshot(sourceLastOrderInfo);
5936
+ if (historicalDepositSnapshot && this.normalizeDepositFlag(raw.is_deposit) === null) {
5937
+ nextTempOrder.is_deposit = historicalDepositSnapshot.isDeposit;
5938
+ }
5376
5939
  const summarySurcharges = Array.isArray(rawSummary.surcharges) ? rawSummary.surcharges.map(s => ({
5377
5940
  ...(s || {})
5378
5941
  })) : (0, _lodashEs.cloneDeep)(nextTempOrder.surcharges || []);
@@ -5417,14 +5980,30 @@ class OrderModule extends _BaseModule.BaseModule {
5417
5980
  if (!shouldSkipEmptyDiscountSync) {
5418
5981
  OrderModule.populateSavedAmounts(nextTempOrder.products, nextDiscounts);
5419
5982
  await this.store.discount?.setOriginalDiscountList(nextDiscounts);
5983
+ this.assertOrderReplacementCurrent(replacement);
5420
5984
  await this.store.discount?.setDiscountList(nextDiscounts);
5985
+ this.assertOrderReplacementCurrent(replacement);
5421
5986
  }
5422
5987
  if (options?.recalcOnHydrate) {
5423
5988
  await this.recalculateSummary({
5424
- createIfMissing: false
5989
+ createIfMissing: false,
5990
+ isCurrentOrder: () => this.orderReplacement === replacement
5991
+ });
5992
+ } else if (!isMergedSalesDetailHydrate && [rawSummary.expect_amount, rawSummary.total_amount].some(amount => amount !== undefined && amount !== null && amount !== '')) {
5993
+ // Keep the remote baseline intact; only normalize the active priced order.
5994
+ const previousSummary = this.store.summary;
5995
+ const summary = this.applyEffectiveDepositSummary(nextTempOrder, previousSummary);
5996
+ summary.amount_gap = this.calculateSummaryAmountGap({
5997
+ tempOrder: nextTempOrder,
5998
+ summary,
5999
+ orderPaidAmount: this.calculatePaidPaymentSummary(nextTempOrder.payments || []).gapPaidAmount
6000
+ });
6001
+ this.store.summary = summary;
6002
+ this.updateTempOrderPaymentStatus(nextTempOrder, {
6003
+ previousSummary,
6004
+ summary
5425
6005
  });
5426
6006
  }
5427
- this.persistTempOrder();
5428
6007
  return nextTempOrder;
5429
6008
  }
5430
6009