@pisell/pisellos 2.3.170 → 2.3.172

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 (82) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.js +1 -0
  3. package/dist/inventory/index.d.ts +92 -0
  4. package/dist/inventory/index.js +509 -0
  5. package/dist/model/strategy/adapter/promotion/evaluator.js +5 -4
  6. package/dist/modules/Discount/index.js +1 -0
  7. package/dist/modules/Discount/types.d.ts +4 -0
  8. package/dist/modules/Order/index.d.ts +25 -3
  9. package/dist/modules/Order/index.js +1791 -1318
  10. package/dist/modules/Order/types.d.ts +7 -0
  11. package/dist/modules/Order/utils/discountProductLineIdentity.js +2 -2
  12. package/dist/modules/Order/utils/productVoucherGroups.d.ts +15 -0
  13. package/dist/modules/Order/utils/productVoucherGroups.js +115 -0
  14. package/dist/modules/Payment/walletpass.js +32 -6
  15. package/dist/modules/Product/index.d.ts +1 -1
  16. package/dist/modules/ProductList/index.js +33 -12
  17. package/dist/modules/Rules/index.d.ts +5 -10
  18. package/dist/modules/Rules/index.js +197 -107
  19. package/dist/modules/Rules/promotionSelection.d.ts +14 -0
  20. package/dist/modules/Rules/promotionSelection.js +390 -0
  21. package/dist/modules/Rules/types.d.ts +9 -0
  22. package/dist/server/modules/order/index.d.ts +6 -0
  23. package/dist/server/modules/order/index.js +782 -447
  24. package/dist/solution/BaseSales/index.d.ts +16 -1
  25. package/dist/solution/BaseSales/index.js +1545 -1339
  26. package/dist/solution/BaseSales/utils/cartPromotion.js +5 -2
  27. package/dist/solution/BookingByStep/index.d.ts +2 -2
  28. package/dist/solution/BookingTicket/index.js +200 -108
  29. package/dist/solution/BookingTicket/types.d.ts +14 -2
  30. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +1 -1
  31. package/dist/solution/BookingTicket/utils/addProductDecision.js +4 -3
  32. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +94 -58
  33. package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +10 -0
  34. package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +117 -0
  35. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +1 -0
  36. package/dist/solution/BookingTicket/utils/scan/handleScan.js +2 -1
  37. package/dist/solution/UnifiedBookingSales/index.d.ts +1 -1
  38. package/dist/solution/UnifiedBookingSales/index.js +69 -49
  39. package/dist/utils/platform.d.ts +2 -0
  40. package/dist/utils/platform.js +6 -0
  41. package/lib/index.d.ts +1 -0
  42. package/lib/index.js +12 -0
  43. package/lib/inventory/index.d.ts +92 -0
  44. package/lib/inventory/index.js +287 -0
  45. package/lib/model/strategy/adapter/promotion/evaluator.js +5 -4
  46. package/lib/model/strategy/adapter/promotion/index.js +1 -46
  47. package/lib/modules/Discount/index.js +1 -0
  48. package/lib/modules/Discount/types.d.ts +4 -0
  49. package/lib/modules/Order/index.d.ts +25 -3
  50. package/lib/modules/Order/index.js +203 -38
  51. package/lib/modules/Order/types.d.ts +7 -0
  52. package/lib/modules/Order/utils/discountProductLineIdentity.js +1 -1
  53. package/lib/modules/Order/utils/productVoucherGroups.d.ts +15 -0
  54. package/lib/modules/Order/utils/productVoucherGroups.js +64 -0
  55. package/lib/modules/Payment/walletpass.js +23 -1
  56. package/lib/modules/Product/index.d.ts +1 -1
  57. package/lib/modules/ProductList/index.js +15 -0
  58. package/lib/modules/Rules/index.d.ts +5 -10
  59. package/lib/modules/Rules/index.js +68 -22
  60. package/lib/modules/Rules/promotionSelection.d.ts +14 -0
  61. package/lib/modules/Rules/promotionSelection.js +230 -0
  62. package/lib/modules/Rules/types.d.ts +9 -0
  63. package/lib/server/modules/order/index.d.ts +6 -0
  64. package/lib/server/modules/order/index.js +226 -29
  65. package/lib/solution/BaseSales/index.d.ts +16 -1
  66. package/lib/solution/BaseSales/index.js +108 -14
  67. package/lib/solution/BaseSales/utils/cartPromotion.js +5 -2
  68. package/lib/solution/BookingByStep/index.d.ts +2 -2
  69. package/lib/solution/BookingTicket/index.js +38 -2
  70. package/lib/solution/BookingTicket/types.d.ts +14 -2
  71. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +1 -1
  72. package/lib/solution/BookingTicket/utils/addProductDecision.js +4 -3
  73. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +14 -2
  74. package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +10 -0
  75. package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +71 -0
  76. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +1 -0
  77. package/lib/solution/BookingTicket/utils/scan/handleScan.js +2 -1
  78. package/lib/solution/UnifiedBookingSales/index.d.ts +1 -1
  79. package/lib/solution/UnifiedBookingSales/index.js +14 -3
  80. package/lib/utils/platform.d.ts +2 -0
  81. package/lib/utils/platform.js +7 -0
  82. 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");
@@ -147,6 +148,66 @@ class OrderModule extends _BaseModule.BaseModule {
147
148
  rulesHooksOverride;
148
149
  moduleHooksOverride;
149
150
  orderHooks;
151
+ cartCommandQueue = Promise.resolve();
152
+ queueCartCommand(run) {
153
+ if (!this.orderHooks?.onBeforeCartCommit && !this.store.tempOrder?._extend?.productVoucherGroups?.length) return run();
154
+ const pending = this.cartCommandQueue.then(run, run);
155
+ this.cartCommandQueue = pending.catch(() => undefined);
156
+ return pending;
157
+ }
158
+
159
+ /** Use the exact Order normalizers/merge rules on a private draft, not a second projection. */
160
+ beginCartMutation() {
161
+ const current = this.ensureTempOrder();
162
+ const guard = this.orderHooks?.onBeforeCartCommit;
163
+ if (!guard && !current._extend?.productVoucherGroups?.length) return {
164
+ draft: current,
165
+ commit: undefined
166
+ };
167
+ const before = (0, _lodashEs.cloneDeep)(current);
168
+ const draft = (0, _lodashEs.cloneDeep)(current);
169
+ return {
170
+ draft,
171
+ commit: async options => {
172
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return current;
173
+ (0, _productVoucherGroups.validateProductVoucherGroups)(draft, this.getDiscountList(), before);
174
+ await guard?.({
175
+ currentItems: (0, _lodashEs.cloneDeep)(before.products),
176
+ proposedItems: (0, _lodashEs.cloneDeep)(draft.products)
177
+ });
178
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return current;
179
+ if (this.store.tempOrder !== current || guard !== this.orderHooks?.onBeforeCartCommit || !(0, _lodashEs.isEqual)(current, before)) {
180
+ throw Object.assign(new Error('The cart changed. Please try again.'), {
181
+ code: 'SALES_GUARD_REJECTED'
182
+ });
183
+ }
184
+ // Recheck synchronous order/availability guards after async inventory validation.
185
+ options?.beforeCommit?.();
186
+ Object.assign(current, draft);
187
+ return current;
188
+ }
189
+ };
190
+ }
191
+
192
+ /** Serializes checkout preparation with local cart commands; hydration remains outside this guard. */
193
+ async prepareCheckout(prepare) {
194
+ const run = async () => {
195
+ const order = this.ensureTempOrder();
196
+ (0, _productVoucherGroups.validateProductVoucherGroups)(order, this.getDiscountList(), undefined, true);
197
+ const items = (0, _lodashEs.cloneDeep)(order.products);
198
+ const result = await prepare(items);
199
+ if (this.store.tempOrder !== order || !(0, _lodashEs.isEqual)(order.products, items)) {
200
+ throw Object.assign(new Error('The cart changed. Please try again.'), {
201
+ code: 'SALES_GUARD_REJECTED'
202
+ });
203
+ }
204
+ (0, _productVoucherGroups.validateProductVoucherGroups)(order, this.getDiscountList(), undefined, true);
205
+ return result;
206
+ };
207
+ const pending = this.cartCommandQueue.then(run, run);
208
+ this.cartCommandQueue = pending.catch(() => undefined);
209
+ return pending;
210
+ }
150
211
  otherParams;
151
212
  // ─── 促销/赠品 ────────────────────────────────────
152
213
  /** 评估器引用;由 SalesSdkProvider 注入,未注入时 applyPromotion 静默跳过 */
@@ -434,8 +495,11 @@ class OrderModule extends _BaseModule.BaseModule {
434
495
  * @example
435
496
  * orderModule.updateOtherParams({ cacheId: 'cache-2', channel: 'pos' });
436
497
  */
437
- updateOtherParams(params) {
498
+ updateOtherParams(params, options) {
438
499
  const otherParams = params || {};
500
+ if (options && Object.prototype.hasOwnProperty.call(options, 'hooks')) {
501
+ this.moduleHooksOverride = options.hooks;
502
+ }
439
503
  this.syncSessionStorageOptions(otherParams);
440
504
  this.salesSummaryModuleName = otherParams.salesSummaryModuleName;
441
505
  this.rulesHooksOverride = otherParams.rules?.hooks;
@@ -542,6 +606,26 @@ class OrderModule extends _BaseModule.BaseModule {
542
606
  hooks: this.rulesHooksOverride || this.createDefaultRulesHooks()
543
607
  });
544
608
  this.store.rules = rules;
609
+ rules.setDiscountScope((product, discount) => (0, _productVoucherGroups.allowsProductVoucher)(this.store.tempOrder, product, discount));
610
+ }
611
+ setProductVoucherGroups(groups) {
612
+ const order = this.ensureTempOrder();
613
+ const ids = new Set();
614
+ const keys = new Set();
615
+ const known = new Map(this.getDiscountList().map(discount => [String(discount.id), discount]));
616
+ for (const group of groups) {
617
+ if (!group.key || keys.has(group.key)) throw (0, _productVoucherGroups.voucherGroupError)();
618
+ keys.add(group.key);
619
+ for (const id of group.discountIds) {
620
+ const discount = known.get(String(id));
621
+ if (!discount || (discount.tag || discount.type) !== 'good_pass' || ids.has(String(id))) throw (0, _productVoucherGroups.voucherGroupError)();
622
+ ids.add(String(id));
623
+ }
624
+ }
625
+ this.ensureExtend(order).productVoucherGroups = (0, _lodashEs.cloneDeep)(groups);
626
+ }
627
+ validateProductVoucherSelection() {
628
+ (0, _productVoucherGroups.validateProductVoucherGroups)(this.ensureTempOrder(), this.getDiscountList(), undefined, true);
545
629
  }
546
630
  createDefaultRulesHooks() {
547
631
  return (0, _utils.createDefaultOrderRulesHooks)(() => this.store.tempOrder?.bookings || [], () => this.store.tempOrder?.holder_relations);
@@ -593,6 +677,7 @@ class OrderModule extends _BaseModule.BaseModule {
593
677
  }
594
678
  if (discountList) {
595
679
  const currentDiscountList = this.store.discount?.getDiscountList() || [];
680
+ const currentPromotionSelections = new Map(currentDiscountList.filter(discount => !discount.isEditMode && discount.promotionSelection).map(discount => [String(discount.id), discount]));
596
681
  const currentCommittedDiscounts = currentDiscountList.filter(discount => discount?.isEditMode || discount?.committedAppliedProductDetails?.length);
597
682
  const currentScanDiscounts = currentDiscountList.filter(discount => discount?.isScan);
598
683
  const currentScanDiscountById = new Map(currentScanDiscounts.flatMap(discount => {
@@ -630,6 +715,16 @@ class OrderModule extends _BaseModule.BaseModule {
630
715
  isManualSelect: currentScanDiscount.isManualSelect ?? nextDiscount.isManualSelect
631
716
  };
632
717
  }
718
+ const currentSelection = currentPromotionSelections.get(String(discount.id));
719
+ if (currentSelection) {
720
+ nextDiscount = {
721
+ ...nextDiscount,
722
+ promotionSelection: currentSelection.promotionSelection,
723
+ promotionSelectionStrategyIds: currentSelection.promotionSelectionStrategyIds,
724
+ isManualSelect: currentSelection.isManualSelect,
725
+ isSelected: currentSelection.isSelected
726
+ };
727
+ }
633
728
  return [nextDiscount];
634
729
  });
635
730
  const retainedCommittedDiscounts = currentCommittedDiscounts.filter(discount => {
@@ -693,7 +788,7 @@ class OrderModule extends _BaseModule.BaseModule {
693
788
  apply: false
694
789
  });
695
790
  }
696
- async scanCode(code, customerId) {
791
+ async scanCode(code, customerId, options) {
697
792
  const beforeCommit = this.createCartIntentCommitGuard('scan_promotion');
698
793
  if (this.isActiveVirtualSettlementOrder(this.store.tempOrder)) {
699
794
  return {
@@ -705,16 +800,22 @@ class OrderModule extends _BaseModule.BaseModule {
705
800
  unavailableReason: _types2.UnavailableReason.ProductNotApplicable
706
801
  };
707
802
  }
803
+ const scanOrderKey = this.getDiscountConfigOrderIdentityKey(this.store.tempOrder);
708
804
  const resultDiscountWithReason = (await this.store.discount?.batchSearch(code, {
709
805
  customerId
710
806
  })) || {
711
807
  discountList: [],
712
808
  unavailableReasonKey: null
713
809
  };
810
+ if (scanOrderKey !== this.getDiscountConfigOrderIdentityKey(this.store.tempOrder)) {
811
+ throw Object.assign(new Error('The scan session ended.'), {
812
+ code: 'SALES_GUARD_REJECTED'
813
+ });
814
+ }
714
815
  const {
715
- discountList: resultDiscountList,
716
816
  unavailableReasonKey
717
817
  } = resultDiscountWithReason;
818
+ const resultDiscountList = resultDiscountWithReason.discountList.filter(discount => !options?.productVouchersOnly || (discount.tag || discount.type) === 'good_pass');
718
819
  const rulesModule = this.store.rules;
719
820
  if (!rulesModule) {
720
821
  return {
@@ -741,7 +842,7 @@ class OrderModule extends _BaseModule.BaseModule {
741
842
  isScan: true
742
843
  }));
743
844
  const currentSelected = this.getDiscountList().filter(n => n.isSelected);
744
- if (currentSelected.length && currentSelected.some(n => withScanList.some(m => m.id === n.id))) {
845
+ 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)))) {
745
846
  beforeCommit();
746
847
  await this.syncScannedDiscountsToOriginalDiscountList(this.getDiscountList());
747
848
  return {
@@ -2258,8 +2359,12 @@ class OrderModule extends _BaseModule.BaseModule {
2258
2359
  ...existed,
2259
2360
  ...(origin !== undefined ? {
2260
2361
  origin
2362
+ } : {}),
2363
+ ...(rawProduct._productVoucherGroupKey ? {
2364
+ productVoucherGroupKey: rawProduct._productVoucherGroupKey
2261
2365
  } : {})
2262
2366
  };
2367
+ delete normalizedProduct._productVoucherGroupKey;
2263
2368
  delete normalizedProduct._origin;
2264
2369
  delete normalizedProduct.unique_identification_number;
2265
2370
  }
@@ -3585,6 +3690,7 @@ class OrderModule extends _BaseModule.BaseModule {
3585
3690
  const isIncomingCustomItem = productToAdd.metadata?.origin?.isCustomItem === true || productToAdd._origin?.isCustomItem === true;
3586
3691
  const shouldForceNewLine = disableMerge || !!booking || hasIncomingGoodPass || isIncomingPersistedEntitlementPass || hasIncomingBookingUid || hasIncomingHolder || isIncomingCustomItem || isWeighingProduct;
3587
3692
  const matchedIndex = shouldForceNewLine ? -1 : tempOrder.products.findIndex(item => {
3693
+ if ((0, _productVoucherGroups.productVoucherGroupKey)(tempOrder, item) !== productToAdd._productVoucherGroupKey) return false;
3588
3694
  if (this.hasGoodPassDiscount(item)) return false;
3589
3695
  if ((0, _holderRelations.getProductHolderRelations)(tempOrder, item).length > 0 || (0, _utils.hasAssignedHolderId)(item.metadata?.holder_id)) return false;
3590
3696
  const isRuntimeEntitlementPass = this.isRuntimeEntitlementAppend(item, tempOrder);
@@ -3768,16 +3874,37 @@ class OrderModule extends _BaseModule.BaseModule {
3768
3874
  * // → tempOrder.products 新增 3 行,每行 num=1,bookings 3 条
3769
3875
  */
3770
3876
  async addProductToOrder(product, booking, options) {
3877
+ return this.queueCartCommand(() => this.addProductToOrderDraft(product, booking, options));
3878
+ }
3879
+ async addProductToOrderDraft(product, booking, options) {
3771
3880
  const availabilityCommitGuard = options?.availabilityCommitGuard;
3772
3881
  availabilityCommitGuard?.();
3773
3882
  const liveTempOrder = this.ensureTempOrder();
3774
3883
  const beforeCommit = this.createCartIntentCommitGuard('add_product', liveTempOrder);
3775
- // 自动预约在草稿上准备完整批次,避免拆票期间暴露半成品,或在失败时
3776
- // 用整单快照回滚而抹掉其他入口的并发修改。人工路径保持原有写入行为。
3777
- const tempOrder = availabilityCommitGuard ? (0, _lodashEs.cloneDeep)(liveTempOrder) : liveTempOrder;
3884
+ const mutation = this.beginCartMutation();
3885
+ // 库存/商品券校验与自动预约共用草稿,全部门禁通过后才发布完整批次。
3886
+ const tempOrder = availabilityCommitGuard && !mutation.commit ? (0, _lodashEs.cloneDeep)(liveTempOrder) : mutation.draft;
3887
+ const beforeAppend = mutation.commit ? undefined : beforeCommit;
3778
3888
  const guardedMutationFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'currency_code', 'currency_symbol', 'currency_format'];
3779
3889
  const readGuardedMutationFields = order => Object.fromEntries(guardedMutationFields.map(key => [key, order[key]]));
3780
3890
  const guardedMutationBaseline = availabilityCommitGuard ? (0, _lodashEs.cloneDeep)(readGuardedMutationFields(liveTempOrder)) : null;
3891
+ const beforePublish = () => {
3892
+ availabilityCommitGuard?.();
3893
+ beforeCommit();
3894
+ // 调用方的结构 revision 可能不包括备注、价格或结算元数据。
3895
+ if (availabilityCommitGuard && !(0, _lodashEs.isEqual)(readGuardedMutationFields(liveTempOrder), guardedMutationBaseline)) {
3896
+ throw Object.assign(new Error('预约加购期间订单已变化,请重新选择'), {
3897
+ code: 'AVAILABILITY_SELECTION_STALE'
3898
+ });
3899
+ }
3900
+ };
3901
+ if (options?.productVoucherGroupKey) {
3902
+ if (!tempOrder._extend?.productVoucherGroups?.some(group => group.key === options.productVoucherGroupKey)) throw (0, _productVoucherGroups.voucherGroupError)();
3903
+ product = {
3904
+ ...product,
3905
+ _productVoucherGroupKey: options.productVoucherGroupKey
3906
+ };
3907
+ }
3781
3908
  const salesNoteDrafts = (options?.salesNotes || []).map(draft => ({
3782
3909
  note_type: String(draft.note_type || '').trim(),
3783
3910
  text: {
@@ -3851,7 +3978,7 @@ class OrderModule extends _BaseModule.BaseModule {
3851
3978
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, splitLine.product, splitLine.booking, {
3852
3979
  insertAtIndex,
3853
3980
  disableMerge: options?.disableMerge,
3854
- beforeCommit
3981
+ beforeCommit: beforeAppend
3855
3982
  });
3856
3983
  availabilityCommitGuard?.();
3857
3984
  attachSalesNoteDrafts(committedProduct);
@@ -3861,7 +3988,7 @@ class OrderModule extends _BaseModule.BaseModule {
3861
3988
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, product, (0, _lodashEs.cloneDeep)(booking), {
3862
3989
  insertAtIndex,
3863
3990
  disableMerge: options?.disableMerge,
3864
- beforeCommit
3991
+ beforeCommit: beforeAppend
3865
3992
  });
3866
3993
  availabilityCommitGuard?.();
3867
3994
  attachSalesNoteDrafts(committedProduct);
@@ -3870,21 +3997,17 @@ class OrderModule extends _BaseModule.BaseModule {
3870
3997
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, product, undefined, {
3871
3998
  insertAtIndex,
3872
3999
  disableMerge: options?.disableMerge,
3873
- beforeCommit
4000
+ beforeCommit: beforeAppend
3874
4001
  });
3875
4002
  availabilityCommitGuard?.();
3876
4003
  attachSalesNoteDrafts(committedProduct);
3877
4004
  }
3878
- if (availabilityCommitGuard) {
3879
- availabilityCommitGuard();
3880
- beforeCommit();
3881
- // 调用方的结构 revision 可能不包括备注、价格或结算元数据。
3882
- // 本次会覆盖的字段也要保持原值,不能让草稿覆盖并发编辑。
3883
- if (!(0, _lodashEs.isEqual)(readGuardedMutationFields(liveTempOrder), guardedMutationBaseline)) {
3884
- throw Object.assign(new Error('预约加购期间订单已变化,请重新选择'), {
3885
- code: 'AVAILABILITY_SELECTION_STALE'
3886
- });
3887
- }
4005
+ if (mutation.commit) {
4006
+ await mutation.commit({
4007
+ beforeCommit: beforePublish
4008
+ });
4009
+ } else if (availabilityCommitGuard) {
4010
+ beforePublish();
3888
4011
  // 从最后一次门禁到真正新增之间不再 await。只发布本次新增会改写的
3889
4012
  // 字段;其余订单字段继续使用 live 对象,外部持有的订单引用也不变。
3890
4013
  Object.assign(liveTempOrder, readGuardedMutationFields(tempOrder));
@@ -3932,9 +4055,14 @@ class OrderModule extends _BaseModule.BaseModule {
3932
4055
  * ]);
3933
4056
  */
3934
4057
  async addProductsToOrder(items, options) {
3935
- const tempOrder = this.ensureTempOrder();
4058
+ return this.queueCartCommand(() => this.addProductsToOrderDraft(items, options));
4059
+ }
4060
+ async addProductsToOrderDraft(items, options) {
4061
+ const mutation = this.beginCartMutation();
4062
+ let tempOrder = mutation.draft;
3936
4063
  if (!Array.isArray(items) || items.length === 0) return tempOrder.products;
3937
- const beforeCommit = this.createCartIntentCommitGuard('add_product', tempOrder);
4064
+ const beforeCommit = this.createCartIntentCommitGuard('add_product');
4065
+ const beforeAppend = mutation.commit ? undefined : beforeCommit;
3938
4066
  for (const item of items || []) {
3939
4067
  const {
3940
4068
  product,
@@ -3948,7 +4076,7 @@ class OrderModule extends _BaseModule.BaseModule {
3948
4076
  for (let i = 0; i < splitCount; i += 1) {
3949
4077
  const splitLine = this.createSplitBookingLine(productRecord, booking, i, splitCount);
3950
4078
  const appendResult = this.appendProductLineToTempOrder(tempOrder, splitLine.product, splitLine.booking, {
3951
- beforeCommit
4079
+ beforeCommit: beforeAppend
3952
4080
  });
3953
4081
  if (appendResult) await appendResult;
3954
4082
  }
@@ -3956,10 +4084,13 @@ class OrderModule extends _BaseModule.BaseModule {
3956
4084
  }
3957
4085
  }
3958
4086
  const appendResult = this.appendProductLineToTempOrder(tempOrder, product, booking, {
3959
- beforeCommit
4087
+ beforeCommit: beforeAppend
3960
4088
  });
3961
4089
  if (appendResult) await appendResult;
3962
4090
  }
4091
+ if (mutation.commit) tempOrder = await mutation.commit({
4092
+ beforeCommit
4093
+ });
3963
4094
  await this.finalizeProductOrderMutation(tempOrder, options);
3964
4095
  this.logInfo('addProductsToOrder success', {
3965
4096
  itemsCount: items.length
@@ -4303,12 +4434,18 @@ class OrderModule extends _BaseModule.BaseModule {
4303
4434
  return tempOrder.products[productIndex].metadata?.unique_identification_number;
4304
4435
  }
4305
4436
  async updateOrderProduct(params) {
4306
- const tempOrder = this.ensureTempOrder();
4307
- if (this.isRestrictedCartProductUpdate(tempOrder, params)) {
4308
- this.createCartIntentCommitGuard('update_product', tempOrder)();
4309
- }
4437
+ return this.queueCartCommand(() => this.updateOrderProductDraft(params));
4438
+ }
4439
+ async updateOrderProductDraft(params) {
4440
+ const mutation = this.beginCartMutation();
4441
+ let tempOrder = mutation.draft;
4442
+ const beforeCommit = this.isRestrictedCartProductUpdate(tempOrder, params) ? this.createCartIntentCommitGuard('update_product') : undefined;
4443
+ if (!mutation.commit) beforeCommit?.();
4310
4444
  const reapplyWeighedDiscountProductUids = [];
4311
4445
  const updatedProductUid = this.applyOrderProductUpdateToTempOrder(tempOrder, params, reapplyWeighedDiscountProductUids);
4446
+ if (mutation.commit) tempOrder = await mutation.commit({
4447
+ beforeCommit
4448
+ });
4312
4449
  const promotionPayload = await this.evaluatePromotion();
4313
4450
  this.applyDiscount({
4314
4451
  reapplyWeighedDiscountProductUids,
@@ -4326,13 +4463,16 @@ class OrderModule extends _BaseModule.BaseModule {
4326
4463
  return tempOrder.products;
4327
4464
  }
4328
4465
  async updateOrderProducts(paramsList) {
4329
- const tempOrder = this.ensureTempOrder();
4466
+ return this.queueCartCommand(() => this.updateOrderProductsDraft(paramsList));
4467
+ }
4468
+ async updateOrderProductsDraft(paramsList) {
4469
+ const mutation = this.beginCartMutation();
4470
+ let tempOrder = mutation.draft;
4330
4471
  if (!paramsList.length) {
4331
4472
  return tempOrder.products;
4332
4473
  }
4333
- if (paramsList.some(params => this.isRestrictedCartProductUpdate(tempOrder, params))) {
4334
- this.createCartIntentCommitGuard('update_product', tempOrder)();
4335
- }
4474
+ const beforeCommit = paramsList.some(params => this.isRestrictedCartProductUpdate(tempOrder, params)) ? this.createCartIntentCommitGuard('update_product') : undefined;
4475
+ if (!mutation.commit) beforeCommit?.();
4336
4476
  const reapplyWeighedDiscountProductUids = [];
4337
4477
  const reapplyBookingDiscountProductUids = paramsList.reduce((acc, params) => {
4338
4478
  const updatedProductUid = this.applyOrderProductUpdateToTempOrder(tempOrder, params, reapplyWeighedDiscountProductUids);
@@ -4342,6 +4482,9 @@ class OrderModule extends _BaseModule.BaseModule {
4342
4482
  }
4343
4483
  return acc;
4344
4484
  }, []);
4485
+ if (mutation.commit) tempOrder = await mutation.commit({
4486
+ beforeCommit
4487
+ });
4345
4488
  await this.finalizeAfterProductsMutation(tempOrder, {
4346
4489
  reapplyWeighedDiscountProductUids,
4347
4490
  reapplyBookingDiscountProductUids: reapplyBookingDiscountProductUids.length ? reapplyBookingDiscountProductUids : undefined
@@ -4352,6 +4495,9 @@ class OrderModule extends _BaseModule.BaseModule {
4352
4495
  return tempOrder.products;
4353
4496
  }
4354
4497
  async updateOrderProductQuantity(params, options) {
4498
+ return this.queueCartCommand(() => this.updateOrderProductQuantityDraft(params, options));
4499
+ }
4500
+ async updateOrderProductQuantityDraft(params, options) {
4355
4501
  const isCurrentOrder = options?.isCurrentOrder;
4356
4502
  if (isCurrentOrder && !isCurrentOrder()) return this.store.tempOrder?.products || [];
4357
4503
  const {
@@ -4363,7 +4509,8 @@ class OrderModule extends _BaseModule.BaseModule {
4363
4509
  product_sku,
4364
4510
  product_bundle
4365
4511
  } = params;
4366
- const tempOrder = this.ensureTempOrder();
4512
+ const mutation = this.beginCartMutation();
4513
+ let tempOrder = mutation.draft;
4367
4514
  this.repairDuplicateProductLineIdentities(tempOrder);
4368
4515
  const identityLookup = {
4369
4516
  product_id,
@@ -4419,11 +4566,16 @@ class OrderModule extends _BaseModule.BaseModule {
4419
4566
  throw new _virtualSettlement.VirtualCurrencyBalanceError(balance.toFixed(2), requiredAmount.toFixed(2));
4420
4567
  }
4421
4568
  }
4422
- if (normalizedProduct.num > targetProduct.num) {
4423
- this.createCartIntentCommitGuard('increase_quantity', tempOrder)();
4424
- }
4569
+ const beforeCommit = normalizedProduct.num > targetProduct.num ? this.createCartIntentCommitGuard('increase_quantity') : undefined;
4570
+ if (!mutation.commit) beforeCommit?.();
4425
4571
  if (isCurrentOrder && !isCurrentOrder()) return tempOrder.products;
4426
4572
  tempOrder.products[productIndex] = normalizedProduct;
4573
+ if (mutation.commit) {
4574
+ tempOrder = await mutation.commit({
4575
+ beforeCommit,
4576
+ isCurrentOrder
4577
+ });
4578
+ }
4427
4579
  if (isCurrentOrder) {
4428
4580
  await this.finalizeProductOrderMutation(tempOrder, {
4429
4581
  skipEditDiscountConfigRefresh: true,
@@ -4507,9 +4659,13 @@ class OrderModule extends _BaseModule.BaseModule {
4507
4659
  * await order.removeProductsFromOrder([identityA, identityB]);
4508
4660
  */
4509
4661
  async removeProductsFromOrder(identities, options) {
4662
+ return this.queueCartCommand(() => this.removeProductsFromOrderDraft(identities, options));
4663
+ }
4664
+ async removeProductsFromOrderDraft(identities, options) {
4510
4665
  const isCurrentOrder = options?.isCurrentOrder;
4511
4666
  if (isCurrentOrder && !isCurrentOrder()) return this.store.tempOrder?.products || [];
4512
- const tempOrder = this.ensureTempOrder();
4667
+ const mutation = this.beginCartMutation();
4668
+ let tempOrder = mutation.draft;
4513
4669
  if (!identities.length) {
4514
4670
  return tempOrder.products;
4515
4671
  }
@@ -4577,6 +4733,9 @@ class OrderModule extends _BaseModule.BaseModule {
4577
4733
  }
4578
4734
  (0, _holderRelations.removeProductHolderRelations)(tempOrder, productsBeforeRemove.filter(product => !tempOrder.products.includes(product)));
4579
4735
  this.removeSalesNotesForMissingProductLines(tempOrder);
4736
+ if (mutation.commit) tempOrder = await mutation.commit({
4737
+ isCurrentOrder
4738
+ });
4580
4739
  if (isCurrentOrder) {
4581
4740
  await this.finalizeProductOrderMutation(tempOrder, {
4582
4741
  skipEditDiscountConfigRefresh: true,
@@ -4599,7 +4758,11 @@ class OrderModule extends _BaseModule.BaseModule {
4599
4758
  * 普通整单 note 保持不变;以商品行为主体的 Sales Notes 同步删除。
4600
4759
  */
4601
4760
  async clearOrderCartLines() {
4602
- const tempOrder = this.ensureTempOrder();
4761
+ return this.queueCartCommand(() => this.clearOrderCartLinesDraft());
4762
+ }
4763
+ async clearOrderCartLinesDraft() {
4764
+ const mutation = this.beginCartMutation();
4765
+ let tempOrder = mutation.draft;
4603
4766
  this.ensureSalesNotesLoadedForMutation(tempOrder);
4604
4767
  (0, _holderRelations.removeProductHolderRelations)(tempOrder, tempOrder.products);
4605
4768
  tempOrder.products = [];
@@ -4613,6 +4776,7 @@ class OrderModule extends _BaseModule.BaseModule {
4613
4776
  productsByUid: {}
4614
4777
  };
4615
4778
  }
4779
+ if (mutation.commit) tempOrder = await mutation.commit();
4616
4780
  const promotionPayload = await this.evaluatePromotion();
4617
4781
  this.applyDiscount();
4618
4782
  this.sanitizeTempOrderProducts(tempOrder);
@@ -4751,6 +4915,7 @@ class OrderModule extends _BaseModule.BaseModule {
4751
4915
  async runSubmitTempOrder(params) {
4752
4916
  const tempOrder = this.ensureTempOrder();
4753
4917
  if ((0, _localEftposState.requiresLocalPaymentRefresh)(tempOrder)) throw new Error(_localEftposState.PAYMENT_REFRESH_MESSAGE);
4918
+ (0, _productVoucherGroups.validateProductVoucherGroups)(tempOrder, this.getDiscountList(), undefined, true);
4754
4919
  this.prepareVirtualSettlementTempOrder(tempOrder);
4755
4920
  const isOnlineStorePlatform = this.isOnlineStorePlatform();
4756
4921
  const shouldConfirmPendingVoucherPayments = params?.confirmPendingVoucherPayments !== false;
@@ -457,6 +457,8 @@ export type AddProductBookingInput = Record<string, any>;
457
457
  * 避免步进器修改数量改变该组展示位置。
458
458
  */
459
459
  export interface AddProductToOrderOptions {
460
+ /** Associates a selection with an existing runtime voucher group. */
461
+ productVoucherGroupKey?: string;
460
462
  insertAfterProductUid?: string;
461
463
  /** 新增商品行插入 products 首位,优先于 insertAfterProductUid。 */
462
464
  insertAtStart?: boolean;
@@ -557,6 +559,11 @@ export interface OrderHooksConfig {
557
559
  beforeCartIntentCommit?: (context: OrderCartIntentCommitContext) => void;
558
560
  /** Captures tenant/business runtime identity for asynchronous cart intents. */
559
561
  getCartIntentScope?: () => unknown;
562
+ /** Awaited before a local cart draft is published. Reject to leave the live order unchanged. */
563
+ onBeforeCartCommit?: (context: {
564
+ currentItems: readonly OrderProduct[];
565
+ proposedItems: readonly OrderProduct[];
566
+ }) => void | Promise<void>;
560
567
  onBeforeMergeProductToOrder?: (context: OrderProductMergeDecisionContext) => OrderProductMergeDecisionResult | Promise<OrderProductMergeDecisionResult>;
561
568
  }
562
569
  /**
@@ -241,7 +241,7 @@ function consolidateDiscountFreeProductLines(tempOrder) {
241
241
  bundle_selling_price: String(bundle?.bundle_selling_price ?? '')
242
242
  }))
243
243
  });
244
- const mergeKey = [discountSplitOriginUid, product.product_id, product.product_variant_id ?? 0, fingerprint, priceSignature].join('#');
244
+ const mergeKey = [discountSplitOriginUid, productUid ? tempOrder._extend?.productsByUid?.[productUid]?.productVoucherGroupKey ?? '' : '', product.product_id, product.product_variant_id ?? 0, fingerprint, priceSignature].join('#');
245
245
  const matchedIndex = productIndexByKey.get(mergeKey);
246
246
 
247
247
  // 当前拆分来源 + 商品结构组合第一次出现时,保留该行作为回并目标。
@@ -0,0 +1,15 @@
1
+ import type { Discount } from '../../Discount/types';
2
+ import type { OrderTempOrder } from '../types';
3
+ /** Runtime-only allocation constraints. Never copied into order/product metadata. */
4
+ export interface ProductVoucherGroup {
5
+ key: string;
6
+ discountIds: Array<number | string>;
7
+ }
8
+ export declare function productVoucherGroupKey(order: OrderTempOrder, product: any): string | undefined;
9
+ export declare function isUsableProductVoucher(discount: Discount): boolean;
10
+ export declare function voucherGroupError(): Error & {
11
+ code: string;
12
+ };
13
+ export declare function allowsProductVoucher(order: OrderTempOrder | null | undefined, product: any, discount: Discount): boolean;
14
+ /** Reductions stay possible when a voucher expires; checkout always requires full coverage. */
15
+ export declare function validateProductVoucherGroups(order: OrderTempOrder, discounts: Discount[], previous?: OrderTempOrder, requireCoverage?: boolean): void;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.allowsProductVoucher = allowsProductVoucher;
7
+ exports.isUsableProductVoucher = isUsableProductVoucher;
8
+ exports.productVoucherGroupKey = productVoucherGroupKey;
9
+ exports.validateProductVoucherGroups = validateProductVoucherGroups;
10
+ exports.voucherGroupError = voucherGroupError;
11
+ var _availability = require("../../Discount/availability");
12
+ var _dayjs = _interopRequireDefault(require("dayjs"));
13
+ var _utils = require("../../../solution/ShopDiscount/utils");
14
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
+ /** Runtime-only allocation constraints. Never copied into order/product metadata. */
16
+
17
+ function productVoucherGroupKey(order, product) {
18
+ const uid = product?.metadata?.unique_identification_number ?? product?.unique_identification_number;
19
+ return order._extend?.productsByUid?.[String(uid)]?.productVoucherGroupKey;
20
+ }
21
+ function isUsableProductVoucher(discount) {
22
+ return (discount.tag || discount.type) === 'good_pass' && !discount.isEditMode && !discount.isDisabled && !(0, _availability.getDiscountUsageBlockReason)(discount) && !(0, _utils.getDiscountTimeUnavailableReason)(discount, (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss'));
23
+ }
24
+ function voucherGroupError() {
25
+ return Object.assign(new Error('The selected items no longer match the available vouchers. Please adjust your selection.'), {
26
+ code: 'PRODUCT_VOUCHER_GROUP_INVALID'
27
+ });
28
+ }
29
+ function allowsProductVoucher(order, product, discount) {
30
+ const groups = order?._extend?.productVoucherGroups;
31
+ if (!order || !groups?.length) return true;
32
+ const key = productVoucherGroupKey(order, product);
33
+ if (!key) return !groups.some(group => group.discountIds.some(id => String(id) === String(discount.id)));
34
+ return (discount.tag || discount.type) === 'good_pass' && Boolean(groups.find(group => group.key === key)?.discountIds.some(id => String(id) === String(discount.id)));
35
+ }
36
+
37
+ /** Reductions stay possible when a voucher expires; checkout always requires full coverage. */
38
+ function validateProductVoucherGroups(order, discounts, previous, requireCoverage = false) {
39
+ const groups = order._extend?.productVoucherGroups;
40
+ if (!groups?.length) return;
41
+ const usedIds = new Set();
42
+ const byId = new Map(discounts.filter(isUsableProductVoucher).map(discount => [String(discount.id), discount]));
43
+ const quantity = item => Number(item.num ?? item.product_quantity ?? 0);
44
+ for (const group of groups) {
45
+ const items = order.products.filter(item => productVoucherGroupKey(order, item) === group.key);
46
+ const selected = items.reduce((sum, item) => sum + quantity(item), 0);
47
+ const before = previous?.products.filter(item => productVoucherGroupKey(previous, item) === group.key).reduce((sum, item) => sum + quantity(item), 0) ?? 0;
48
+ if (!requireCoverage && previous && selected <= before) continue;
49
+ const ids = new Set(group.discountIds.map(String).filter(id => byId.has(id)));
50
+ if (!Number.isInteger(selected) || selected < 0 || selected > ids.size) throw voucherGroupError();
51
+ if (!requireCoverage) continue;
52
+ for (const item of items) {
53
+ const applied = (item.discount_list || []).filter(entry => (entry.type || entry.tag) === 'good_pass');
54
+ // Rules splits a good_pass allocation into one physical line per instance.
55
+ const id = String(applied[0]?.discount?.resource_id ?? '');
56
+ const voucher = byId.get(id);
57
+ if (quantity(item) !== 1 || applied.length !== 1 || !ids.has(id) || !voucher?.isAvailable || voucher.config?.isAvailable === false || usedIds.has(id)) throw voucherGroupError();
58
+ usedIds.add(id);
59
+ }
60
+ }
61
+ if (order.products.some(item => !groups.some(group => group.key === productVoucherGroupKey(order, item)))) {
62
+ throw voucherGroupError();
63
+ }
64
+ }
@@ -1146,7 +1146,10 @@ class WalletPassPaymentImpl {
1146
1146
  if (paymentAssets.length > 0) {
1147
1147
  this.searchResults = mergeWalletAssets(this.searchResults, paymentAssets);
1148
1148
  }
1149
- const asset = paymentAssets.find(item => String(item?.code || '') === normalizedCode) || paymentAssets[0];
1149
+ const matchedAsset = paymentAssets.find(item => String(item?.code || '') === normalizedCode);
1150
+ // 精确命中券码时仅处理该券;未命中时处理接口返回的全部结果。
1151
+ const assetsToApply = matchedAsset ? [matchedAsset] : paymentAssets;
1152
+ const asset = assetsToApply[0];
1150
1153
  if (!asset) {
1151
1154
  return {
1152
1155
  type: 'normalCode',
@@ -1155,6 +1158,25 @@ class WalletPassPaymentImpl {
1155
1158
  state: this.getWalletAssetsState()
1156
1159
  };
1157
1160
  }
1161
+
1162
+ // 根据 code 找不到结果时,则使用接口返回的所有券数据(扫手环)
1163
+ if (!matchedAsset && assetsToApply.length > 1) {
1164
+ const items = mergeWalletAssets(this.walletAssetsState.items, assetsToApply);
1165
+ const assetIds = assetsToApply.map(item => getWalletAssetId(item)).filter(id => id !== undefined && id !== null);
1166
+ const selectionSources = {
1167
+ ...this.walletAssetsState.selectionSources
1168
+ };
1169
+ assetIds.forEach(id => {
1170
+ selectionSources[String(id)] = 'scan';
1171
+ });
1172
+ const selected = this.walletAssetsBehavior.autoSelectAfterSearch ? this.recalculateWalletAssets(items, Array.from(new Set([...this.walletAssetsState.selectedIds, ...assetIds])), selectionSources) : this.recalculateWalletAssets(items, this.walletAssetsState.selectedIds, this.walletAssetsState.selectionSources);
1173
+ return {
1174
+ type: result.type,
1175
+ asset,
1176
+ selected: assetIds.some(id => selected.selectedIds.includes(id)),
1177
+ state: selected
1178
+ };
1179
+ }
1158
1180
  const items = mergeWalletAssets(this.walletAssetsState.items, [asset]);
1159
1181
  const recalculatedState = this.recalculateWalletAssets(items, this.walletAssetsState.selectedIds, this.walletAssetsState.selectionSources);
1160
1182
  const assetId = getWalletAssetId(asset);
@@ -49,5 +49,5 @@ export declare class Product extends BaseModule implements Module {
49
49
  getCategories(): ProductCategory[];
50
50
  setOtherParams(key: string, value: any): void;
51
51
  getOtherParams(): any;
52
- getProductType(): "normal" | "duration" | "session";
52
+ getProductType(): "duration" | "normal" | "session";
53
53
  }