@pisell/pisellos 0.10.70 → 0.10.72

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 (42) hide show
  1. package/dist/modules/BookingContext/utils/productExtend.d.ts +5 -0
  2. package/dist/modules/BookingContext/utils/productExtend.js +61 -23
  3. package/dist/modules/OpenData/index.d.ts +1 -0
  4. package/dist/modules/OpenData/index.js +1 -0
  5. package/dist/modules/OpenData/salesSettings.d.ts +32 -0
  6. package/dist/modules/OpenData/salesSettings.js +80 -0
  7. package/dist/modules/OpenData/types.d.ts +13 -0
  8. package/dist/modules/Order/index.d.ts +13 -4
  9. package/dist/modules/Order/index.js +1401 -764
  10. package/dist/modules/Order/types.d.ts +24 -1
  11. package/dist/modules/Order/types.js +4 -0
  12. package/dist/server/index.js +5 -2
  13. package/dist/solution/BaseSales/index.d.ts +2 -2
  14. package/dist/solution/BaseSales/index.js +8 -8
  15. package/dist/solution/BookingTicket/index.d.ts +2 -2
  16. package/dist/solution/UnifiedBookingSales/index.d.ts +36 -1
  17. package/dist/solution/UnifiedBookingSales/index.js +1434 -709
  18. package/dist/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
  19. package/dist/solution/UnifiedBookingSales/salesSettings.js +81 -0
  20. package/dist/solution/UnifiedBookingSales/types.d.ts +17 -1
  21. package/lib/model/strategy/adapter/promotion/index.js +1 -46
  22. package/lib/modules/BookingContext/utils/productExtend.d.ts +5 -0
  23. package/lib/modules/BookingContext/utils/productExtend.js +36 -3
  24. package/lib/modules/OpenData/index.d.ts +1 -0
  25. package/lib/modules/OpenData/index.js +12 -0
  26. package/lib/modules/OpenData/salesSettings.d.ts +32 -0
  27. package/lib/modules/OpenData/salesSettings.js +70 -0
  28. package/lib/modules/OpenData/types.d.ts +13 -0
  29. package/lib/modules/Order/index.d.ts +13 -4
  30. package/lib/modules/Order/index.js +284 -24
  31. package/lib/modules/Order/types.d.ts +24 -1
  32. package/lib/modules/Order/types.js +2 -0
  33. package/lib/server/index.js +5 -1
  34. package/lib/solution/BaseSales/index.d.ts +2 -2
  35. package/lib/solution/BaseSales/index.js +2 -2
  36. package/lib/solution/BookingTicket/index.d.ts +2 -2
  37. package/lib/solution/UnifiedBookingSales/index.d.ts +36 -1
  38. package/lib/solution/UnifiedBookingSales/index.js +463 -45
  39. package/lib/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
  40. package/lib/solution/UnifiedBookingSales/salesSettings.js +72 -0
  41. package/lib/solution/UnifiedBookingSales/types.d.ts +17 -1
  42. package/package.json +1 -1
@@ -148,18 +148,18 @@ class OrderModule extends _BaseModule.BaseModule {
148
148
  moduleHooksOverride;
149
149
  orderHooks;
150
150
  cartCommandQueue = Promise.resolve();
151
- queueCartCommand(run) {
152
- if (!this.orderHooks?.onBeforeCartCommit && !this.store.tempOrder?._extend?.productVoucherGroups?.length) return run();
151
+ queueCartCommand(run, forceQueue = false) {
152
+ if (!forceQueue && !this.orderHooks?.onBeforeCartCommit && !this.store.tempOrder?._extend?.productVoucherGroups?.length) return run();
153
153
  const pending = this.cartCommandQueue.then(run, run);
154
154
  this.cartCommandQueue = pending.catch(() => undefined);
155
155
  return pending;
156
156
  }
157
157
 
158
158
  /** Use the exact Order normalizers/merge rules on a private draft, not a second projection. */
159
- beginCartMutation() {
159
+ beginCartMutation(options) {
160
160
  const current = this.ensureTempOrder();
161
161
  const guard = this.orderHooks?.onBeforeCartCommit;
162
- if (!guard && !current._extend?.productVoucherGroups?.length) return {
162
+ if (!options?.forceDraft && !guard && !current._extend?.productVoucherGroups?.length) return {
163
163
  current,
164
164
  draft: current,
165
165
  commit: undefined
@@ -182,6 +182,13 @@ class OrderModule extends _BaseModule.BaseModule {
182
182
  }
183
183
  // Recheck the accepted intent's scope after asynchronous inventory validation.
184
184
  beforeCommit?.();
185
+ // Opt-in booking guards may inspect or reject the source snapshot here.
186
+ // Never publish over a mutation made by that last synchronous callback.
187
+ if (options?.forceDraft && (this.store.tempOrder !== current || !(0, _lodashEs.isEqual)(current, before))) {
188
+ throw Object.assign(new Error('The cart changed. Please try again.'), {
189
+ code: 'SALES_GUARD_REJECTED'
190
+ });
191
+ }
185
192
  Object.assign(current, draft);
186
193
  return current;
187
194
  }
@@ -1004,7 +1011,8 @@ class OrderModule extends _BaseModule.BaseModule {
1004
1011
  * - 不主动调用 applyDiscount / recalculateSummary,调用方负责跟进;
1005
1012
  * - 返回的 payload 只能在 applyDiscount(商品写路径还需 summary/persist)完成后发布。
1006
1013
  */
1007
- async evaluatePromotion() {
1014
+ async evaluatePromotion(options) {
1015
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return null;
1008
1016
  if (this.isApplyingPromotion || this.isEmittingPromotionApplied) {
1009
1017
  return null;
1010
1018
  }
@@ -1065,6 +1073,14 @@ class OrderModule extends _BaseModule.BaseModule {
1065
1073
  continue;
1066
1074
  }
1067
1075
  }
1076
+ const giftBaseline = options?.isCurrentOrder ? (0, _lodashEs.cloneDeep)({
1077
+ products: tempOrder.products,
1078
+ bookings: tempOrder.bookings
1079
+ }) : null;
1080
+ const isGiftResultCurrent = () => !options?.isCurrentOrder || options.isCurrentOrder() && (0, _lodashEs.isEqual)(giftBaseline, {
1081
+ products: tempOrder.products,
1082
+ bookings: tempOrder.bookings
1083
+ });
1068
1084
  try {
1069
1085
  const giftResult = await this.giftSelectResolver({
1070
1086
  strategyId: addAction.strategyId,
@@ -1073,6 +1089,7 @@ class OrderModule extends _BaseModule.BaseModule {
1073
1089
  giftOptions: addAction.giftOptions,
1074
1090
  sourceProductIds: addAction.sourceProductIds
1075
1091
  });
1092
+ if (!isGiftResultCurrent()) return null;
1076
1093
  const giftProducts = Array.isArray(giftResult) ? giftResult : giftResult?.products;
1077
1094
  const giftBookings = Array.isArray(giftResult) ? [] : giftResult?.bookings || [];
1078
1095
  if (Array.isArray(giftProducts) && giftProducts.length > 0) {
@@ -1093,12 +1110,14 @@ class OrderModule extends _BaseModule.BaseModule {
1093
1110
  }
1094
1111
  }
1095
1112
  } catch (error) {
1113
+ if (!isGiftResultCurrent()) return null;
1096
1114
  // 用户取消 / 选择失败 → 视为放弃本次新增
1097
1115
  console.warn('[OrderModule] giftSelectResolver rejected, skip add gift', addAction.strategyId, error);
1098
1116
  }
1099
1117
  }
1100
1118
  }
1101
1119
  }
1120
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return null;
1102
1121
  tempOrder.products = result.products;
1103
1122
  this.lastUnfulfilledPromotions = result.unfulfilledPromotions;
1104
1123
  this.lastGiftActions = result.giftActions;
@@ -2579,6 +2598,7 @@ class OrderModule extends _BaseModule.BaseModule {
2579
2598
  return shouldUseManualDepositOverride ? nextSummary : this.applyLastOrderDepositSnapshot(tempOrder, nextSummary);
2580
2599
  }
2581
2600
  async recalculateSummary(options) {
2601
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return null;
2582
2602
  const tempOrder = options?.createIfMissing ? this.ensureTempOrder() : this.store.tempOrder;
2583
2603
  if (!tempOrder) return null;
2584
2604
  this.sanitizeTempOrderProducts(tempOrder);
@@ -2588,7 +2608,7 @@ class OrderModule extends _BaseModule.BaseModule {
2588
2608
  const snapshotSummary = shouldReuseOriginalSnapshot ? this.restoreOriginalSnapshotIfProductsUnchanged(tempOrder, originalSnapshot) : null;
2589
2609
  if (snapshotSummary) return snapshotSummary;
2590
2610
  const shouldFullRecalculateFromSnapshot = Boolean(originalSnapshot);
2591
- const summaryProducts = shouldFullRecalculateFromSnapshot ? (0, _lodashEs.cloneDeep)(tempOrder.products || []) : tempOrder.products;
2611
+ const summaryProducts = shouldFullRecalculateFromSnapshot || options?.isCurrentOrder ? (0, _lodashEs.cloneDeep)(tempOrder.products || []) : tempOrder.products;
2592
2612
  if (shouldFullRecalculateFromSnapshot) {
2593
2613
  this.clearPersistedAmountFieldsForFullRecalc(summaryProducts || []);
2594
2614
  }
@@ -2626,6 +2646,10 @@ class OrderModule extends _BaseModule.BaseModule {
2626
2646
  });
2627
2647
  return this.store.summary;
2628
2648
  }
2649
+ const summaryBaseline = options?.isCurrentOrder ? (0, _lodashEs.cloneDeep)({
2650
+ tempOrder,
2651
+ summary: this.store.summary
2652
+ }) : null;
2629
2653
  const salesSummaryResult = await salesSummary.getSummary({
2630
2654
  products: summaryProducts,
2631
2655
  isPriceIncludeTax: tempOrder.is_price_include_tax,
@@ -2635,7 +2659,11 @@ class OrderModule extends _BaseModule.BaseModule {
2635
2659
  channel: this.otherParams.channel
2636
2660
  } : {})
2637
2661
  });
2638
- if (shouldFullRecalculateFromSnapshot) {
2662
+ if (options?.isCurrentOrder && (!options.isCurrentOrder() || !(0, _lodashEs.isEqual)(summaryBaseline, {
2663
+ tempOrder,
2664
+ summary: this.store.summary
2665
+ }))) return null;
2666
+ if (shouldFullRecalculateFromSnapshot || options?.isCurrentOrder) {
2639
2667
  tempOrder.products = summaryProducts;
2640
2668
  }
2641
2669
  this.syncSummaryProductMetadata(tempOrder.products || []);
@@ -3565,20 +3593,27 @@ class OrderModule extends _BaseModule.BaseModule {
3565
3593
  * await this.finalizeProductOrderMutation(tempOrder);
3566
3594
  */
3567
3595
  async finalizeProductOrderMutation(tempOrder, options) {
3596
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return;
3568
3597
  this.syncTempOrderHolderFromBookings(tempOrder);
3569
3598
  this.prepareVirtualSettlementTempOrder(tempOrder);
3570
3599
  const isVirtualSettlement = this.isActiveVirtualSettlementOrder(tempOrder);
3571
3600
  if (!options?.skipEditDiscountConfigRefresh && !isVirtualSettlement) {
3572
3601
  await this.ensureEditDiscountConfigForProductChange(tempOrder);
3573
3602
  }
3574
- const promotionPayload = !options?.skipDiscountRecalculation && !isVirtualSettlement ? await this.evaluatePromotion() : null;
3603
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return;
3604
+ const promotionPayload = !options?.skipDiscountRecalculation && !isVirtualSettlement ? await this.evaluatePromotion({
3605
+ isCurrentOrder: options?.isCurrentOrder
3606
+ }) : null;
3607
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) return;
3575
3608
  if (!options?.skipDiscountRecalculation && !isVirtualSettlement) {
3576
3609
  this.applyDiscount();
3577
3610
  }
3578
3611
  this.sanitizeTempOrderProducts(tempOrder);
3579
- await this.recalculateSummary({
3580
- createIfMissing: true
3612
+ const summary = await this.recalculateSummary({
3613
+ createIfMissing: true,
3614
+ isCurrentOrder: options?.isCurrentOrder
3581
3615
  });
3616
+ if (options?.isCurrentOrder && (!options.isCurrentOrder() || !summary)) return;
3582
3617
  this.persistTempOrder();
3583
3618
  this.emitPromotionApplied(promotionPayload);
3584
3619
  }
@@ -3820,12 +3855,25 @@ class OrderModule extends _BaseModule.BaseModule {
3820
3855
  * // → tempOrder.products 新增 3 行,每行 num=1,bookings 3 条
3821
3856
  */
3822
3857
  async addProductToOrder(product, booking, options) {
3823
- return this.queueCartCommand(() => this.addProductToOrderDraft(product, booking, options));
3858
+ return this.queueCartCommand(() => this.addProductToOrderDraft(product, booking, options), Boolean(options?.availabilityCommitGuard || options?.availabilityCommitTargetGuard));
3824
3859
  }
3825
3860
  async addProductToOrderDraft(product, booking, options) {
3826
- const mutation = this.beginCartMutation();
3861
+ const guarded = Boolean(options?.availabilityCommitGuard || options?.availabilityCommitTargetGuard);
3862
+ options?.availabilityCommitGuard?.();
3863
+ const mutation = this.beginCartMutation({
3864
+ forceDraft: guarded
3865
+ });
3827
3866
  let tempOrder = mutation.draft;
3828
- const beforeCommit = this.createCartIntentCommitGuard('add_product', mutation.current);
3867
+ const intentCommitGuard = this.createCartIntentCommitGuard('add_product', mutation.current);
3868
+ const identity = [mutation.current.order_id, mutation.current.external_sale_number];
3869
+ const isCurrentOrder = () => this.store.tempOrder === mutation.current && mutation.current.order_id === identity[0] && mutation.current.external_sale_number === identity[1] && (options?.availabilityCommitTargetGuard?.() ?? true);
3870
+ const beforeCommit = () => {
3871
+ options?.availabilityCommitGuard?.();
3872
+ if (guarded && !isCurrentOrder()) throw Object.assign(new Error('Booking add belongs to a previous order'), {
3873
+ code: 'AVAILABILITY_SELECTION_STALE'
3874
+ });
3875
+ intentCommitGuard();
3876
+ };
3829
3877
  if (options?.productVoucherGroupKey) {
3830
3878
  if (!tempOrder._extend?.productVoucherGroups?.some(group => group.key === options.productVoucherGroupKey)) throw (0, _productVoucherGroups.voucherGroupError)();
3831
3879
  product = {
@@ -3932,7 +3980,22 @@ class OrderModule extends _BaseModule.BaseModule {
3932
3980
  throw error;
3933
3981
  }
3934
3982
  if (mutation.commit) tempOrder = await mutation.commit(beforeCommit);
3935
- await this.finalizeProductOrderMutation(tempOrder);
3983
+ if (guarded) {
3984
+ try {
3985
+ if (isCurrentOrder()) this.persistTempOrder();
3986
+ await this.finalizeProductOrderMutation(tempOrder, {
3987
+ isCurrentOrder
3988
+ });
3989
+ } catch (error) {
3990
+ this.logWarning('addProductToOrder committed; finalization failed', {
3991
+ product_id: product.product_id,
3992
+ committed: true,
3993
+ error: error instanceof Error ? error.message : String(error)
3994
+ });
3995
+ }
3996
+ } else {
3997
+ await this.finalizeProductOrderMutation(tempOrder);
3998
+ }
3936
3999
  this.logInfo('addProductToOrder success', {
3937
4000
  product_id: product.product_id,
3938
4001
  with_booking: !!booking
@@ -3940,6 +4003,127 @@ class OrderModule extends _BaseModule.BaseModule {
3940
4003
  return tempOrder.products;
3941
4004
  }
3942
4005
 
4006
+ /**
4007
+ * Replaces one local Party booking and its confirmed children on a detached draft.
4008
+ * All fallible preparation precedes a guarded synchronous publication; never rolls
4009
+ * an old whole-order snapshot over concurrent edits or a newly selected order.
4010
+ */
4011
+ async replaceBookingProductWithRelatedRetail(params) {
4012
+ return this.queueCartCommand(() => this.replaceBookingProductWithRelatedRetailDraft(params), true);
4013
+ }
4014
+ async replaceBookingProductWithRelatedRetailDraft(params) {
4015
+ params.availabilityCommitGuard();
4016
+ const mutation = this.beginCartMutation({
4017
+ forceDraft: true
4018
+ });
4019
+ const live = mutation.current;
4020
+ const beforeCommit = this.createCartIntentCommitGuard('update_product', live);
4021
+ const uid = String(params.productLineUid || '');
4022
+ const getUid = line => String(line.metadata?.unique_identification_number || line.unique_identification_number || '');
4023
+ const targetIndex = live.products.findIndex(line => getUid(line) === uid);
4024
+ const target = live.products[targetIndex];
4025
+ const scopeKey = String(target?.metadata?.venue_booking_scope_key || '');
4026
+ const targetBookingUid = String(target?.booking_uid || target?.metadata?.booking_uid || '');
4027
+ if (!uid || !target || !scopeKey || live.order_id || live.products.filter(line => getUid(line) === uid).length !== 1 || 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) {
4028
+ throw new Error('[Order] Party replacement requires one unsubmitted, unpaid main booking in the same scope');
4029
+ }
4030
+ const children = live.products.filter(line => line.metadata?.venue_booking_role === 'party_extra' && String(line.metadata?.venue_booking_parent_uid || '') === uid);
4031
+ if (children.some(line => !getUid(line) || live.products.filter(candidate => getUid(candidate) === getUid(line)).length !== 1 || line.metadata?.venue_booking_scope_key !== scopeKey || line.order_detail_id != null || this.hasLinkedBookingUid(line))) {
4032
+ throw new Error('[Order] Related retail line does not belong to this local Party scope');
4033
+ }
4034
+ const start = params.booking.start_at || `${params.booking.start_date || ''} ${params.booking.start_time || ''}`.trim();
4035
+ if (!start || !(0, _dayjs.default)(start).isValid()) throw new Error('[Order] Party service datetime is required');
4036
+ const serviceDatetime = (0, _dayjs.default)(start).format('YYYY-MM-DD HH:mm:ss');
4037
+ const ownedUids = new Set(children.map(getUid));
4038
+ const nextUids = new Set();
4039
+ const retainedChildUids = new Set();
4040
+ const nextChildren = (0, _lodashEs.cloneDeep)(params.relatedRetailProducts);
4041
+ for (const child of nextChildren) {
4042
+ const childUid = getUid(child);
4043
+ const service = String(child.metadata?.venue_booking_service_datetime || '');
4044
+ if (child.metadata?.venue_booking_role !== 'party_extra' || String(child.metadata?.venue_booking_parent_uid || '') !== uid || child.metadata?.venue_booking_scope_key !== scopeKey || !service || !(0, _dayjs.default)(service).isValid() || (0, _dayjs.default)(service).format('YYYY-MM-DD HH:mm:ss') !== serviceDatetime || this.hasLinkedBookingUid(child) || child.order_detail_id != null || childUid && (nextUids.has(childUid) || live.products.some(line => getUid(line) === childUid && !ownedUids.has(childUid)))) {
4045
+ throw new Error('[Order] Invalid Party extra ownership, identity, or service datetime');
4046
+ }
4047
+ if (childUid) nextUids.add(childUid);
4048
+ const previous = children.find(line => getUid(line) === childUid);
4049
+ 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)) {
4050
+ retainedChildUids.add(childUid);
4051
+ // The same configured extra keeps completed product forms unless explicitly replaced.
4052
+ const previousForms = live._extend?.productsByUid?.[childUid]?.origin?.relation_forms;
4053
+ const rawChild = child;
4054
+ if (previousForms !== undefined && rawChild._origin?.relation_forms === undefined) {
4055
+ rawChild._origin = {
4056
+ ...(rawChild._origin || {}),
4057
+ relation_forms: (0, _lodashEs.cloneDeep)(previousForms)
4058
+ };
4059
+ }
4060
+ }
4061
+ }
4062
+ const publishedFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'holder', 'holder_relations', 'currency_code', 'currency_symbol', 'currency_format'];
4063
+ const guardedFields = [...publishedFields, 'customer_id', 'discount_list', 'shop_discount', 'payments'];
4064
+ const readFields = (order, fields) => Object.fromEntries(fields.map(key => [key, order[key]]));
4065
+ const baseline = (0, _lodashEs.cloneDeep)(readFields(live, guardedFields));
4066
+ const identity = [live.order_id, live.external_sale_number];
4067
+ const isCurrentOrder = () => this.store.tempOrder === live && live.order_id === identity[0] && live.external_sale_number === identity[1] && (params.availabilityCommitTargetGuard?.() ?? true);
4068
+ const draft = mutation.draft;
4069
+ this.ensureSalesNotesLoadedForMutation(draft);
4070
+ const removed = draft.products.filter(line => getUid(line) === uid || ownedUids.has(getUid(line)));
4071
+ draft.products = draft.products.filter(line => getUid(line) !== uid && !ownedUids.has(getUid(line)));
4072
+ for (const line of removed) this.removeLinkedBookingsForProduct(draft, line);
4073
+ (0, _holderRelations.removeProductHolderRelations)(draft, removed.filter(line => !retainedChildUids.has(getUid(line))));
4074
+ for (const line of removed) {
4075
+ if (draft._extend?.productsByUid && !retainedChildUids.has(getUid(line))) {
4076
+ delete draft._extend.productsByUid[getUid(line)];
4077
+ }
4078
+ }
4079
+ const replacement = (0, _lodashEs.cloneDeep)(params.product);
4080
+ replacement.metadata = {
4081
+ ...(replacement.metadata || {}),
4082
+ unique_identification_number: uid,
4083
+ venue_booking_service_datetime: serviceDatetime
4084
+ };
4085
+ replacement.unique_identification_number = uid;
4086
+ await this.appendProductLineToTempOrder(draft, replacement, (0, _lodashEs.cloneDeep)(params.booking), {
4087
+ insertAtIndex: targetIndex,
4088
+ disableMerge: true,
4089
+ beforeCommit
4090
+ });
4091
+ for (const [index, child] of nextChildren.entries()) {
4092
+ await this.appendProductLineToTempOrder(draft, child, undefined, {
4093
+ insertAtIndex: targetIndex + index + 1,
4094
+ disableMerge: true,
4095
+ beforeCommit
4096
+ });
4097
+ }
4098
+ this.removeSalesNotesForMissingProductLines(draft);
4099
+ this.syncTempOrderHolderFromBookings(draft);
4100
+ // Develop owns inventory/voucher validation and the whole-draft CAS. Recheck
4101
+ // the availability intent after that await, immediately before its publication.
4102
+ await mutation.commit?.(() => {
4103
+ params.availabilityCommitGuard();
4104
+ beforeCommit();
4105
+ if (!isCurrentOrder() || !(0, _lodashEs.isEqual)(readFields(live, guardedFields), baseline)) {
4106
+ throw Object.assign(new Error('Party replacement interrupted by an order change'), {
4107
+ code: 'AVAILABILITY_SELECTION_STALE'
4108
+ });
4109
+ }
4110
+ });
4111
+ try {
4112
+ if (isCurrentOrder()) this.persistTempOrder();
4113
+ await this.finalizeProductOrderMutation(live, {
4114
+ isCurrentOrder
4115
+ });
4116
+ } catch (error) {
4117
+ // Already committed. Do not invite a second replacement or restore a stale snapshot.
4118
+ this.logWarning('Party replacement committed; finalization failed', {
4119
+ productLineUid: uid,
4120
+ committed: true,
4121
+ error: error instanceof Error ? error.message : String(error)
4122
+ });
4123
+ }
4124
+ return live.products;
4125
+ }
4126
+
3943
4127
  /**
3944
4128
  * 批量添加商品行,所有行追加完成后只触发一次促销、折扣、summary 重算与持久化。
3945
4129
  *
@@ -4352,10 +4536,11 @@ class OrderModule extends _BaseModule.BaseModule {
4352
4536
  });
4353
4537
  return tempOrder.products;
4354
4538
  }
4355
- async updateOrderProducts(paramsList) {
4356
- return this.queueCartCommand(() => this.updateOrderProductsDraft(paramsList));
4539
+ async updateOrderProducts(paramsList, options) {
4540
+ return this.queueCartCommand(() => this.updateOrderProductsDraft(paramsList, options), Boolean(options));
4357
4541
  }
4358
- async updateOrderProductsDraft(paramsList) {
4542
+ async updateOrderProductsDraft(paramsList, options) {
4543
+ if (options) return this.updateOrderProductsGuarded(paramsList, options);
4359
4544
  const mutation = this.beginCartMutation();
4360
4545
  let tempOrder = mutation.draft;
4361
4546
  if (!paramsList.length) {
@@ -4382,6 +4567,58 @@ class OrderModule extends _BaseModule.BaseModule {
4382
4567
  });
4383
4568
  return tempOrder.products;
4384
4569
  }
4570
+ async updateOrderProductsGuarded(paramsList, options) {
4571
+ const stale = () => Object.assign(new Error('Order product update interrupted by an order change'), {
4572
+ code: 'AVAILABILITY_SELECTION_STALE'
4573
+ });
4574
+ options.beforeApply?.();
4575
+ if (options.isCurrentOrder && !options.isCurrentOrder()) throw stale();
4576
+ const mutation = this.beginCartMutation({
4577
+ forceDraft: true
4578
+ });
4579
+ const live = mutation.current;
4580
+ if (!paramsList.length) return live.products;
4581
+ const identity = [live.order_id, live.external_sale_number];
4582
+ const isCurrentOrder = () => this.store.tempOrder === live && live.order_id === identity[0] && live.external_sale_number === identity[1] && (options.isCurrentOrder?.() ?? true);
4583
+ const beforeCommit = this.createCartIntentCommitGuard('update_product', live);
4584
+ const publishedFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'holder', 'holder_relations'];
4585
+ const guardedFields = [...publishedFields, 'customer_id', 'discount_list', 'shop_discount', 'payments'];
4586
+ const readFields = (order, fields) => Object.fromEntries(fields.map(key => [key, order[key]]));
4587
+ const baseline = (0, _lodashEs.cloneDeep)(readFields(live, guardedFields));
4588
+ const draft = mutation.draft;
4589
+ const seen = new Set();
4590
+ const reapplyWeighedDiscountProductUids = [];
4591
+ const reapplyBookingDiscountProductUids = [];
4592
+ for (const params of paramsList) {
4593
+ const uid = String(params.unique_identification_number || '');
4594
+ const matches = draft.products.filter(line => String(line.metadata?.unique_identification_number || line.unique_identification_number || '') === uid);
4595
+ const target = matches[0];
4596
+ // Guarded re-quotation must identify the exact row; never fall back to another same-SKU line.
4597
+ 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();
4598
+ seen.add(uid);
4599
+ const updatedUid = this.applyOrderProductUpdateToTempOrder(draft, (0, _lodashEs.cloneDeep)(params), reapplyWeighedDiscountProductUids);
4600
+ if (params.allow_booking_discount_reapply && updatedUid) reapplyBookingDiscountProductUids.push(updatedUid);
4601
+ }
4602
+ await mutation.commit?.(() => {
4603
+ options.beforeApply?.();
4604
+ beforeCommit();
4605
+ if (!isCurrentOrder() || !(0, _lodashEs.isEqual)(readFields(live, guardedFields), baseline)) throw stale();
4606
+ });
4607
+ try {
4608
+ if (isCurrentOrder()) this.persistTempOrder();
4609
+ await this.finalizeAfterProductsMutation(live, {
4610
+ reapplyWeighedDiscountProductUids,
4611
+ reapplyBookingDiscountProductUids,
4612
+ isCurrentOrder
4613
+ });
4614
+ } catch (error) {
4615
+ this.logWarning('Order product update committed; finalization failed', {
4616
+ committed: true,
4617
+ error: error instanceof Error ? error.message : String(error)
4618
+ });
4619
+ }
4620
+ return live.products;
4621
+ }
4385
4622
  async updateOrderProductQuantity(params) {
4386
4623
  return this.queueCartCommand(() => this.updateOrderProductQuantityDraft(params));
4387
4624
  }
@@ -4511,16 +4748,25 @@ class OrderModule extends _BaseModule.BaseModule {
4511
4748
  * await this.finalizeAfterProductsMutation(tempOrder);
4512
4749
  */
4513
4750
  async finalizeAfterProductsMutation(tempOrder, options) {
4751
+ const isCurrentOrder = options?.isCurrentOrder;
4752
+ if (isCurrentOrder && !isCurrentOrder()) return;
4514
4753
  this.syncTempOrderHolderFromBookings(tempOrder);
4515
- const promotionPayload = await this.evaluatePromotion();
4754
+ const promotionPayload = await this.evaluatePromotion(isCurrentOrder ? {
4755
+ isCurrentOrder
4756
+ } : undefined);
4757
+ if (isCurrentOrder && !isCurrentOrder()) return;
4516
4758
  this.applyDiscount({
4517
4759
  reapplyBookingDiscountProductUids: options?.reapplyBookingDiscountProductUids,
4518
4760
  reapplyWeighedDiscountProductUids: options?.reapplyWeighedDiscountProductUids
4519
4761
  });
4520
4762
  this.sanitizeTempOrderProducts(tempOrder);
4521
- await this.recalculateSummary({
4522
- createIfMissing: true
4763
+ const summary = await this.recalculateSummary({
4764
+ createIfMissing: true,
4765
+ ...(isCurrentOrder ? {
4766
+ isCurrentOrder
4767
+ } : {})
4523
4768
  });
4769
+ if (isCurrentOrder && (!isCurrentOrder() || !summary)) return;
4524
4770
  this.persistTempOrder();
4525
4771
  this.emitPromotionApplied(promotionPayload);
4526
4772
  }
@@ -4532,11 +4778,23 @@ class OrderModule extends _BaseModule.BaseModule {
4532
4778
  * await order.removeProductsFromOrder([identityA, identityB]);
4533
4779
  */
4534
4780
  async removeProductsFromOrder(identities, options) {
4535
- return this.queueCartCommand(() => this.removeProductsFromOrderDraft(identities, options));
4781
+ return this.queueCartCommand(() => this.removeProductsFromOrderDraft(identities, options), Boolean(options?.isCurrentOrder));
4536
4782
  }
4537
4783
  async removeProductsFromOrderDraft(identities, options) {
4538
- const mutation = this.beginCartMutation();
4784
+ if (options?.isCurrentOrder && !options.isCurrentOrder()) {
4785
+ return this.store.tempOrder?.products || [];
4786
+ }
4787
+ const mutation = this.beginCartMutation({
4788
+ forceDraft: Boolean(options?.isCurrentOrder)
4789
+ });
4539
4790
  let tempOrder = mutation.draft;
4791
+ const identity = [mutation.current.order_id, mutation.current.external_sale_number];
4792
+ const isCurrentOrder = () => this.store.tempOrder === mutation.current && mutation.current.order_id === identity[0] && mutation.current.external_sale_number === identity[1] && (options?.isCurrentOrder?.() ?? true);
4793
+ const beforeCommit = options?.isCurrentOrder ? () => {
4794
+ if (!isCurrentOrder()) throw Object.assign(new Error('Order product removal interrupted by an order change'), {
4795
+ code: 'AVAILABILITY_SELECTION_STALE'
4796
+ });
4797
+ } : undefined;
4540
4798
  if (!identities.length) {
4541
4799
  return tempOrder.products;
4542
4800
  }
@@ -4604,8 +4862,10 @@ class OrderModule extends _BaseModule.BaseModule {
4604
4862
  }
4605
4863
  (0, _holderRelations.removeProductHolderRelations)(tempOrder, productsBeforeRemove.filter(product => !tempOrder.products.includes(product)));
4606
4864
  this.removeSalesNotesForMissingProductLines(tempOrder);
4607
- if (mutation.commit) tempOrder = await mutation.commit();
4608
- await this.finalizeAfterProductsMutation(tempOrder);
4865
+ if (mutation.commit) tempOrder = await mutation.commit(beforeCommit);
4866
+ await this.finalizeAfterProductsMutation(tempOrder, options?.isCurrentOrder ? {
4867
+ isCurrentOrder
4868
+ } : undefined);
4609
4869
  this.logInfo('removeProductsFromOrder success', {
4610
4870
  identities
4611
4871
  });
@@ -463,12 +463,27 @@ export interface AddProductToOrderOptions {
463
463
  disableMerge?: boolean;
464
464
  /** 商品行 UID 落定后,由 OrderModule 原子绑定到该行的 Sales Notes 草稿。 */
465
465
  salesNotes?: SalesNoteDraftInput[];
466
+ /** Validate the captured booking intent before preparation and draft publication. */
467
+ availabilityCommitGuard?: () => void;
468
+ /** Ownership only; remains valid after this mutation changes products and prices. */
469
+ availabilityCommitTargetGuard?: () => boolean;
470
+ }
471
+ /** Atomic replacement of one unsubmitted Party booking and its explicitly confirmed retail children. */
472
+ export interface ReplaceBookingProductWithRelatedRetailParams {
473
+ productLineUid: string;
474
+ product: Partial<OrderProduct> & OrderProductIdentity;
475
+ booking: AddProductBookingInput;
476
+ relatedRetailProducts: Array<Partial<OrderProduct> & OrderProductIdentity>;
477
+ availabilityCommitGuard: () => void;
478
+ availabilityCommitTargetGuard?: () => boolean;
466
479
  }
467
480
  /**
468
481
  * 删除商品后的可选位置保持策略。
469
482
  * 预约合并行减量时仍删除最新真实行,再把剩余代表行移动到被删除代表行原位置。
470
483
  */
471
484
  export interface RemoveProductsFromOrderOptions {
485
+ /** Prevent an asynchronous deletion/finalization from crossing order or business scopes. */
486
+ isCurrentOrder?: () => boolean;
472
487
  preserveDisplayPosition?: {
473
488
  remainingProductUid: string;
474
489
  anchorProductUid: string;
@@ -511,6 +526,13 @@ export interface UpdateOrderProductParams {
511
526
  */
512
527
  allow_booking_discount_reapply?: boolean;
513
528
  }
529
+ /** Opt-in atomic draft update for asynchronous re-quotation callers. */
530
+ export interface UpdateOrderProductsOptions {
531
+ /** Validate the quoted source snapshot immediately before publication; may throw. */
532
+ beforeApply?: () => void;
533
+ /** Order/business ownership only. Called after publication too; exclude old prices/quantities. */
534
+ isCurrentOrder?: () => boolean;
535
+ }
514
536
  /** 仅更新购物车行数量;行定位语义与 updateOrderProduct / removeProductFromOrder 保持一致 */
515
537
  export interface UpdateOrderProductQuantityParams extends OrderProductIdentity {
516
538
  num: number;
@@ -903,6 +925,7 @@ export interface OrderModuleAPI {
903
925
  updateTempOrderBuzzer: (buzzer: string) => string;
904
926
  updateTempOrderContactsInfo: (contactsInfo: Record<string, any> | null) => Record<string, any> | null;
905
927
  addProductToOrder: (product: Partial<OrderProduct> & OrderProductIdentity, booking?: AddProductBookingInput, options?: AddProductToOrderOptions) => Promise<OrderProduct[]>;
928
+ replaceBookingProductWithRelatedRetail: (params: ReplaceBookingProductWithRelatedRetailParams) => Promise<OrderProduct[]>;
906
929
  getSalesNotes: () => SalesNote[];
907
930
  createSalesNotesMutationSnapshot: () => SalesNotesMutationSnapshot;
908
931
  restoreSalesNotesMutationSnapshot: (snapshot: SalesNotesMutationSnapshot) => void;
@@ -911,7 +934,7 @@ export interface OrderModuleAPI {
911
934
  clearSalesNotes: () => Promise<void>;
912
935
  updateOrderProduct: (params: UpdateOrderProductParams) => Promise<OrderProduct[]>;
913
936
  /** 批量更新购物车行,末尾仅触发一次促销重算与 summary 刷新 */
914
- updateOrderProducts: (paramsList: UpdateOrderProductParams[]) => Promise<OrderProduct[]>;
937
+ updateOrderProducts: (paramsList: UpdateOrderProductParams[], options?: UpdateOrderProductsOptions) => Promise<OrderProduct[]>;
915
938
  updateOrderProductQuantity: (params: UpdateOrderProductQuantityParams) => Promise<OrderProduct[]>;
916
939
  updateOrderBooking: (params: UpdateOrderBookingParams) => any[];
917
940
  removeProductFromOrder: (identity: OrderProductIdentity, options?: RemoveProductsFromOrderOptions) => Promise<OrderProduct[]>;
@@ -69,11 +69,13 @@ let OrderHooks = exports.OrderHooks = /*#__PURE__*/function (OrderHooks) {
69
69
  * 默认追加到 products 尾部;预约数量同步可插入到既有预约组的最新行之后,
70
70
  * 避免步进器修改数量改变该组展示位置。
71
71
  */
72
+ /** Atomic replacement of one unsubmitted Party booking and its explicitly confirmed retail children. */
72
73
  /**
73
74
  * 删除商品后的可选位置保持策略。
74
75
  * 预约合并行减量时仍删除最新真实行,再把剩余代表行移动到被删除代表行原位置。
75
76
  */
76
77
  /** 更新购物车行:仅传 SKU 时命中同 SKU 第一行;多行同 SKU 须传 unique_identification_number / 选项指纹等 */
78
+ /** Opt-in atomic draft update for asynchronous re-quotation callers. */
77
79
  /** 仅更新购物车行数量;行定位语义与 updateOrderProduct / removeProductFromOrder 保持一致 */
78
80
  /**
79
81
  * 订单信息
@@ -1809,7 +1809,11 @@ class Server {
1809
1809
  return this.computeProductQueryResult({
1810
1810
  schedule_date,
1811
1811
  schedule_datetime: scheduleDatetime,
1812
- product_id: productId
1812
+ product_id: productId,
1813
+ ...(data && typeof data === 'object' ? {
1814
+ customer_id: data.customer_id,
1815
+ strategy_context: data.strategy_context
1816
+ } : {})
1813
1817
  });
1814
1818
  };
1815
1819
 
@@ -6,7 +6,7 @@ import { OrderModule } from '../../modules/Order';
6
6
  import { type PickupTimingBookingInput } from '../../modules/Order/pickupTiming';
7
7
  import type { PickupTimingAvailability, PickupTimingSelection, PickupTimingValidationResult } from '../../modules/FulfillmentTiming';
8
8
  import { type ContactInfoConfig } from '../../modules/OpenData/contactInfo';
9
- import type { AddProductBookingInput, AddProductToOrderOptions, LoadSalesDetailParams, OrderPaymentData, OrderPaymentUpdateOptions, OrderPaymentUpdateResult, OrderPaymentSource, SendCustomerPayLinkParams, SyncPaymentsToOrderParams, SyncPaymentsToOrderResult, UpdateTempOrderCustomerInput, UpdateOrderBookingParams, UpdateOrderProductParams, OrderTempOrder, OrderSummary, OrderPromotionEvaluator, OrderGiftSelectResolver, OrderUnfulfilledPromotion, OrderLastGiftActions, RemoveProductsFromOrderOptions, ReplaceTempOrderOptions, SalesNote, SalesNotesMutationSnapshot, SetSalesNoteInput, PickupReferenceMode, ShopServiceData, ShopServiceType } from '../../modules/Order/types';
9
+ import type { AddProductBookingInput, AddProductToOrderOptions, LoadSalesDetailParams, OrderPaymentData, OrderPaymentUpdateOptions, OrderPaymentUpdateResult, OrderPaymentSource, SendCustomerPayLinkParams, SyncPaymentsToOrderParams, SyncPaymentsToOrderResult, UpdateTempOrderCustomerInput, UpdateOrderBookingParams, UpdateOrderProductParams, UpdateOrderProductsOptions, OrderTempOrder, OrderSummary, OrderPromotionEvaluator, OrderGiftSelectResolver, OrderUnfulfilledPromotion, OrderLastGiftActions, RemoveProductsFromOrderOptions, ReplaceTempOrderOptions, SalesNote, SalesNotesMutationSnapshot, SetSalesNoteInput, PickupReferenceMode, ShopServiceData, ShopServiceType } from '../../modules/Order/types';
10
10
  import type { SubmitPayloadEnhancer } from '../../modules/Order/utils';
11
11
  import type { Discount, VirtualCurrencyAsset } from '../../modules/Discount/types';
12
12
  import { RequestPlugin, WindowPlugin } from '../../plugins';
@@ -535,7 +535,7 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
535
535
  validateProductVoucherSelection(): void;
536
536
  addProductToOrder(product: Partial<BaseSalesOrderProduct> & BaseSalesOrderProductIdentity, booking?: AddProductBookingInput, options?: AddProductToOrderOptions): Promise<import("../../modules/Order/types").OrderProduct[]>;
537
537
  updateOrderProduct(params: UpdateOrderProductParams): Promise<import("../../modules/Order/types").OrderProduct[]>;
538
- updateOrderProducts(paramsList: UpdateOrderProductParams[]): Promise<import("../../modules/Order/types").OrderProduct[]>;
538
+ updateOrderProducts(paramsList: UpdateOrderProductParams[], options?: UpdateOrderProductsOptions): Promise<import("../../modules/Order/types").OrderProduct[]>;
539
539
  updateOrderProductQuantity(params: BaseSalesUpdateOrderProductQuantityParams): Promise<import("../../modules/Order/types").OrderProduct[]>;
540
540
  updateOrderBooking(params: UpdateOrderBookingParams): any[];
541
541
  /**
@@ -4181,10 +4181,10 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
4181
4181
  throw error;
4182
4182
  }
4183
4183
  }
4184
- async updateOrderProducts(paramsList) {
4184
+ async updateOrderProducts(paramsList, options) {
4185
4185
  try {
4186
4186
  if (!this.store.order) throw new Error('order 模块未初始化');
4187
- const products = await this.store.order.updateOrderProducts(paramsList);
4187
+ const products = await this.store.order.updateOrderProducts(paramsList, options);
4188
4188
  return products;
4189
4189
  } catch (error) {
4190
4190
  throw error;
@@ -441,7 +441,7 @@ export declare class BookingTicketImpl extends BaseSalesImpl implements Module {
441
441
  /**
442
442
  * 构造 BookingContext 计算上下文(供 getProductExtend / getResourceByIds 等读 API 复用)。
443
443
  */
444
- private buildBookingCalcContext;
444
+ protected buildBookingCalcContext(extra?: Partial<BookingCalcContext>): BookingCalcContext;
445
445
  /**
446
446
  * 取商品当前可选资源列表(透传 OS BookingContext utils#getResourceByIds)。
447
447
  * `extraResources` 用于把拖入未绑定的资源也展示出来。
@@ -474,7 +474,7 @@ export declare class BookingTicketImpl extends BaseSalesImpl implements Module {
474
474
  /**
475
475
  * 拼装 addProductDecision 通用上下文(从 store 自取)。
476
476
  */
477
- private buildAddProductCtx;
477
+ protected buildAddProductCtx(extra?: Partial<AddProductDecideContext>): AddProductDecideContext;
478
478
  /**
479
479
  * 加车两阶段主决策(规格弹窗 / 资源编辑 / 直接加车)。
480
480
  * 与 ticketBooking `handleSelectProduct` + `handleBooking4Service` 等价。