@pisell/pisellos 2.3.191 → 2.3.192

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 (59) hide show
  1. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  2. package/dist/modules/BookingContext/index.d.ts +2 -2
  3. package/dist/modules/BookingContext/index.js +55 -25
  4. package/dist/modules/BookingContext/types.d.ts +2 -0
  5. package/dist/modules/Order/index.d.ts +13 -5
  6. package/dist/modules/Order/index.js +1053 -554
  7. package/dist/modules/Order/types.d.ts +20 -1
  8. package/dist/modules/Order/types.js +4 -0
  9. package/dist/modules/Product/index.d.ts +1 -1
  10. package/dist/modules/ProductList/clientDataVariants.js +6 -2
  11. package/dist/modules/ProductList/index.d.ts +2 -0
  12. package/dist/modules/ProductList/index.js +125 -39
  13. package/dist/modules/ResourcePlanner/planner.js +5 -0
  14. package/dist/server/index.js +5 -2
  15. package/dist/solution/BaseSales/index.d.ts +14 -3
  16. package/dist/solution/BaseSales/index.js +285 -195
  17. package/dist/solution/BookingByStep/index.d.ts +2 -2
  18. package/dist/solution/UnifiedBookingSales/catalogQueryBatch.d.ts +21 -0
  19. package/dist/solution/UnifiedBookingSales/catalogQueryBatch.js +202 -0
  20. package/dist/solution/UnifiedBookingSales/index.d.ts +49 -1
  21. package/dist/solution/UnifiedBookingSales/index.js +2276 -902
  22. package/dist/solution/UnifiedBookingSales/remoteOccupancyCache.d.ts +2 -0
  23. package/dist/solution/UnifiedBookingSales/remoteOccupancyCache.js +4 -0
  24. package/dist/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
  25. package/dist/solution/UnifiedBookingSales/sessionResourceCache.js +271 -0
  26. package/dist/solution/UnifiedBookingSales/types.d.ts +64 -1
  27. package/dist/solution/UnifiedBookingSales/types.js +7 -1
  28. package/dist/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
  29. package/dist/solution/UnifiedBookingSales/venueCatalogSession.js +277 -0
  30. package/lib/model/strategy/adapter/promotion/index.js +46 -1
  31. package/lib/modules/BookingContext/index.d.ts +2 -2
  32. package/lib/modules/BookingContext/index.js +42 -10
  33. package/lib/modules/BookingContext/types.d.ts +2 -0
  34. package/lib/modules/Order/index.d.ts +13 -5
  35. package/lib/modules/Order/index.js +208 -7
  36. package/lib/modules/Order/types.d.ts +20 -1
  37. package/lib/modules/Order/types.js +2 -0
  38. package/lib/modules/Product/index.d.ts +1 -1
  39. package/lib/modules/ProductList/clientDataVariants.js +6 -2
  40. package/lib/modules/ProductList/index.d.ts +2 -0
  41. package/lib/modules/ProductList/index.js +56 -0
  42. package/lib/modules/ResourcePlanner/planner.js +4 -0
  43. package/lib/server/index.js +5 -1
  44. package/lib/solution/BaseSales/index.d.ts +14 -3
  45. package/lib/solution/BaseSales/index.js +67 -2
  46. package/lib/solution/BookingByStep/index.d.ts +2 -2
  47. package/lib/solution/UnifiedBookingSales/catalogQueryBatch.d.ts +21 -0
  48. package/lib/solution/UnifiedBookingSales/catalogQueryBatch.js +109 -0
  49. package/lib/solution/UnifiedBookingSales/index.d.ts +49 -1
  50. package/lib/solution/UnifiedBookingSales/index.js +872 -55
  51. package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.d.ts +2 -0
  52. package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.js +2 -0
  53. package/lib/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
  54. package/lib/solution/UnifiedBookingSales/sessionResourceCache.js +199 -0
  55. package/lib/solution/UnifiedBookingSales/types.d.ts +64 -1
  56. package/lib/solution/UnifiedBookingSales/types.js +4 -1
  57. package/lib/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
  58. package/lib/solution/UnifiedBookingSales/venueCatalogSession.js +151 -0
  59. package/package.json +1 -1
@@ -4178,6 +4178,134 @@ class OrderModule extends _BaseModule.BaseModule {
4178
4178
  return liveTempOrder.products;
4179
4179
  }
4180
4180
 
4181
+ /**
4182
+ * Replaces one local Party booking and its confirmed children on a detached draft.
4183
+ * All fallible preparation precedes a guarded synchronous publication; never rolls
4184
+ * an old whole-order snapshot over concurrent edits or a newly selected order.
4185
+ */
4186
+ async replaceBookingProductWithRelatedRetail(params) {
4187
+ return this.queueCartCommand(() => this.replaceBookingProductWithRelatedRetailDraft(params));
4188
+ }
4189
+ async replaceBookingProductWithRelatedRetailDraft(params) {
4190
+ params.availabilityCommitGuard();
4191
+ const live = this.ensureTempOrder();
4192
+ const mutation = this.beginCartMutation();
4193
+ const beforeCommit = this.createCartIntentCommitGuard('update_product', live);
4194
+ const uid = String(params.productLineUid || '');
4195
+ const getUid = line => String(line.metadata?.unique_identification_number || line.unique_identification_number || '');
4196
+ const targetIndex = live.products.findIndex(line => getUid(line) === uid);
4197
+ const target = live.products[targetIndex];
4198
+ const scopeKey = String(target?.metadata?.venue_booking_scope_key || '');
4199
+ const targetBookingUid = String(target?.booking_uid || target?.metadata?.booking_uid || '');
4200
+ 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) {
4201
+ throw new Error('[Order] Party replacement requires one unsubmitted, unpaid main booking in the same scope');
4202
+ }
4203
+ const children = live.products.filter(line => line.metadata?.venue_booking_role === 'party_extra' && String(line.metadata?.venue_booking_parent_uid || '') === uid);
4204
+ if (children.some(line => !getUid(line) || line.metadata?.venue_booking_scope_key !== scopeKey || line.order_detail_id != null || this.hasLinkedBookingUid(line))) {
4205
+ throw new Error('[Order] Related retail line does not belong to this local Party scope');
4206
+ }
4207
+ const start = params.booking.start_at || `${params.booking.start_date || ''} ${params.booking.start_time || ''}`.trim();
4208
+ if (!start || !(0, _dayjs.default)(start).isValid()) throw new Error('[Order] Party service datetime is required');
4209
+ const serviceDatetime = (0, _dayjs.default)(start).format('YYYY-MM-DD HH:mm:ss');
4210
+ const ownedUids = new Set(children.map(getUid));
4211
+ const nextUids = new Set();
4212
+ const retainedChildUids = new Set();
4213
+ const nextChildren = (0, _lodashEs.cloneDeep)(params.relatedRetailProducts);
4214
+ for (const child of nextChildren) {
4215
+ const childUid = getUid(child);
4216
+ const purchaseDatetime = String(child.metadata?.venue_booking_service_datetime || '');
4217
+ const normalizedPurchaseDatetime = purchaseDatetime.length === 16 ? `${purchaseDatetime}:00` : purchaseDatetime;
4218
+ 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)))) {
4219
+ throw new Error('[Order] Invalid Party extra ownership, identity, or purchase quote datetime');
4220
+ }
4221
+ if (childUid) nextUids.add(childUid);
4222
+ const previous = children.find(line => getUid(line) === childUid);
4223
+ 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)) {
4224
+ retainedChildUids.add(childUid);
4225
+ // The same configured extra keeps completed product forms unless explicitly replaced.
4226
+ const previousForms = live._extend?.productsByUid?.[childUid]?.origin?.relation_forms;
4227
+ const rawChild = child;
4228
+ if (previousForms !== undefined && rawChild._origin?.relation_forms === undefined) {
4229
+ rawChild._origin = {
4230
+ ...(rawChild._origin || {}),
4231
+ relation_forms: (0, _lodashEs.cloneDeep)(previousForms)
4232
+ };
4233
+ }
4234
+ }
4235
+ }
4236
+ const publishedFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'holder', 'holder_relations', 'currency_code', 'currency_symbol', 'currency_format'];
4237
+ const guardedFields = [...publishedFields, 'customer_id', 'discount_list', 'shop_discount', 'payments'];
4238
+ const readFields = (order, fields) => Object.fromEntries(fields.map(key => [key, order[key]]));
4239
+ const baseline = (0, _lodashEs.cloneDeep)(readFields(live, guardedFields));
4240
+ const identity = [live.order_id, live.external_sale_number];
4241
+ const isCurrentOrder = () => this.store.tempOrder === live && live.order_id === identity[0] && live.external_sale_number === identity[1] && (params.availabilityCommitTargetGuard?.() ?? true);
4242
+ const draft = mutation.commit ? mutation.draft : (0, _lodashEs.cloneDeep)(live);
4243
+ this.ensureSalesNotesLoadedForMutation(draft);
4244
+ const removed = draft.products.filter(line => getUid(line) === uid || ownedUids.has(getUid(line)));
4245
+ draft.products = draft.products.filter(line => getUid(line) !== uid && !ownedUids.has(getUid(line)));
4246
+ for (const line of removed) this.removeLinkedBookingsForProduct(draft, line);
4247
+ (0, _holderRelations.removeProductHolderRelations)(draft, removed.filter(line => !retainedChildUids.has(getUid(line))));
4248
+ for (const line of removed) {
4249
+ if (draft._extend?.productsByUid && !retainedChildUids.has(getUid(line))) {
4250
+ delete draft._extend.productsByUid[getUid(line)];
4251
+ }
4252
+ }
4253
+ const replacement = (0, _lodashEs.cloneDeep)(params.product);
4254
+ replacement.metadata = {
4255
+ ...(replacement.metadata || {}),
4256
+ unique_identification_number: uid,
4257
+ venue_booking_service_datetime: serviceDatetime
4258
+ };
4259
+ replacement.unique_identification_number = uid;
4260
+ await this.appendProductLineToTempOrder(draft, replacement, (0, _lodashEs.cloneDeep)(params.booking), {
4261
+ insertAtIndex: targetIndex,
4262
+ disableMerge: true,
4263
+ beforeCommit
4264
+ });
4265
+ for (const [index, child] of nextChildren.entries()) {
4266
+ await this.appendProductLineToTempOrder(draft, child, undefined, {
4267
+ insertAtIndex: targetIndex + index + 1,
4268
+ disableMerge: true,
4269
+ beforeCommit
4270
+ });
4271
+ }
4272
+ this.removeSalesNotesForMissingProductLines(draft);
4273
+ this.syncTempOrderHolderFromBookings(draft);
4274
+ const beforePublish = () => {
4275
+ params.availabilityCommitGuard();
4276
+ beforeCommit();
4277
+ if (!isCurrentOrder() || !(0, _lodashEs.isEqual)(readFields(live, guardedFields), baseline)) {
4278
+ throw Object.assign(new Error('Party replacement interrupted by an order change'), {
4279
+ code: 'AVAILABILITY_SELECTION_STALE'
4280
+ });
4281
+ }
4282
+ };
4283
+ beforePublish();
4284
+ if (mutation.commit) {
4285
+ // Preserve beta's inventory and product-voucher checks before publishing.
4286
+ await mutation.commit({
4287
+ beforeCommit: beforePublish
4288
+ });
4289
+ } else {
4290
+ // No await between the final CAS and publication; preserve every unrelated live field.
4291
+ Object.assign(live, readFields(draft, publishedFields));
4292
+ }
4293
+ try {
4294
+ if (isCurrentOrder()) this.persistTempOrder();
4295
+ await this.finalizeProductOrderMutation(live, {
4296
+ isCurrentOrder
4297
+ });
4298
+ } catch (error) {
4299
+ // Already committed. Do not invite a second replacement or restore a stale snapshot.
4300
+ this.logWarning('Party replacement committed; finalization failed', {
4301
+ productLineUid: uid,
4302
+ committed: true,
4303
+ error: error instanceof Error ? error.message : String(error)
4304
+ });
4305
+ }
4306
+ return live.products;
4307
+ }
4308
+
4181
4309
  /**
4182
4310
  * 批量添加商品行,所有行追加完成后只触发一次促销、折扣、summary 重算与持久化。
4183
4311
  *
@@ -4595,10 +4723,11 @@ class OrderModule extends _BaseModule.BaseModule {
4595
4723
  });
4596
4724
  return tempOrder.products;
4597
4725
  }
4598
- async updateOrderProducts(paramsList) {
4599
- return this.queueCartCommand(() => this.updateOrderProductsDraft(paramsList));
4726
+ async updateOrderProducts(paramsList, options) {
4727
+ return this.queueCartCommand(() => this.updateOrderProductsDraft(paramsList, options));
4600
4728
  }
4601
- async updateOrderProductsDraft(paramsList) {
4729
+ async updateOrderProductsDraft(paramsList, options) {
4730
+ if (options) return this.updateOrderProductsGuarded(paramsList, options);
4602
4731
  const mutation = this.beginCartMutation();
4603
4732
  let tempOrder = mutation.draft;
4604
4733
  if (!paramsList.length) {
@@ -4627,6 +4756,64 @@ class OrderModule extends _BaseModule.BaseModule {
4627
4756
  });
4628
4757
  return tempOrder.products;
4629
4758
  }
4759
+ async updateOrderProductsGuarded(paramsList, options) {
4760
+ const stale = () => Object.assign(new Error('Order product update interrupted by an order change'), {
4761
+ code: 'AVAILABILITY_SELECTION_STALE'
4762
+ });
4763
+ options.beforeApply?.();
4764
+ if (options.isCurrentOrder && !options.isCurrentOrder()) throw stale();
4765
+ const live = this.ensureTempOrder();
4766
+ if (!paramsList.length) return live.products;
4767
+ const mutation = this.beginCartMutation();
4768
+ const identity = [live.order_id, live.external_sale_number];
4769
+ const isCurrentOrder = () => this.store.tempOrder === live && live.order_id === identity[0] && live.external_sale_number === identity[1] && (options.isCurrentOrder?.() ?? true);
4770
+ const beforeCommit = this.createCartIntentCommitGuard('update_product', live);
4771
+ const publishedFields = ['products', 'bookings', 'notes', '_extend', 'metadata', 'holder', 'holder_relations'];
4772
+ const guardedFields = [...publishedFields, 'customer_id', 'discount_list', 'shop_discount', 'payments'];
4773
+ const readFields = (order, fields) => Object.fromEntries(fields.map(key => [key, order[key]]));
4774
+ const baseline = (0, _lodashEs.cloneDeep)(readFields(live, guardedFields));
4775
+ const draft = mutation.commit ? mutation.draft : (0, _lodashEs.cloneDeep)(live);
4776
+ const seen = new Set();
4777
+ const reapplyWeighedDiscountProductUids = [];
4778
+ const reapplyBookingDiscountProductUids = [];
4779
+ for (const params of paramsList) {
4780
+ const uid = String(params.unique_identification_number || '');
4781
+ const matches = draft.products.filter(line => String(line.metadata?.unique_identification_number || line.unique_identification_number || '') === uid);
4782
+ const target = matches[0];
4783
+ // Guarded re-quotation must identify the exact row; never fall back to another same-SKU line.
4784
+ 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();
4785
+ seen.add(uid);
4786
+ const updatedUid = this.applyOrderProductUpdateToTempOrder(draft, (0, _lodashEs.cloneDeep)(params), reapplyWeighedDiscountProductUids);
4787
+ if (params.allow_booking_discount_reapply && updatedUid) reapplyBookingDiscountProductUids.push(updatedUid);
4788
+ }
4789
+ const beforePublish = () => {
4790
+ options.beforeApply?.();
4791
+ beforeCommit();
4792
+ if (!isCurrentOrder() || !(0, _lodashEs.isEqual)(readFields(live, guardedFields), baseline)) throw stale();
4793
+ };
4794
+ beforePublish();
4795
+ if (mutation.commit) {
4796
+ await mutation.commit({
4797
+ beforeCommit: beforePublish
4798
+ });
4799
+ } else {
4800
+ Object.assign(live, readFields(draft, publishedFields));
4801
+ }
4802
+ try {
4803
+ if (isCurrentOrder()) this.persistTempOrder();
4804
+ await this.finalizeAfterProductsMutation(live, {
4805
+ reapplyWeighedDiscountProductUids,
4806
+ reapplyBookingDiscountProductUids,
4807
+ isCurrentOrder
4808
+ });
4809
+ } catch (error) {
4810
+ this.logWarning('Order product update committed; finalization failed', {
4811
+ committed: true,
4812
+ error: error instanceof Error ? error.message : String(error)
4813
+ });
4814
+ }
4815
+ return live.products;
4816
+ }
4630
4817
  async updateOrderProductQuantity(params, options) {
4631
4818
  return this.queueCartCommand(() => this.updateOrderProductQuantityDraft(params, options));
4632
4819
  }
@@ -4771,16 +4958,25 @@ class OrderModule extends _BaseModule.BaseModule {
4771
4958
  * await this.finalizeAfterProductsMutation(tempOrder);
4772
4959
  */
4773
4960
  async finalizeAfterProductsMutation(tempOrder, options) {
4961
+ const isCurrentOrder = options?.isCurrentOrder;
4962
+ if (isCurrentOrder && !isCurrentOrder()) return;
4774
4963
  this.syncTempOrderHolderFromBookings(tempOrder);
4775
- const promotionPayload = await this.evaluatePromotion();
4964
+ const promotionPayload = await this.evaluatePromotion(isCurrentOrder ? {
4965
+ isCurrentOrder
4966
+ } : undefined);
4967
+ if (isCurrentOrder && !isCurrentOrder()) return;
4776
4968
  this.applyDiscount({
4777
4969
  reapplyBookingDiscountProductUids: options?.reapplyBookingDiscountProductUids,
4778
4970
  reapplyWeighedDiscountProductUids: options?.reapplyWeighedDiscountProductUids
4779
4971
  });
4780
4972
  this.sanitizeTempOrderProducts(tempOrder);
4781
- await this.recalculateSummary({
4782
- createIfMissing: true
4973
+ const summary = await this.recalculateSummary({
4974
+ createIfMissing: true,
4975
+ ...(isCurrentOrder ? {
4976
+ isCurrentOrder
4977
+ } : {})
4783
4978
  });
4979
+ if (isCurrentOrder && (!isCurrentOrder() || !summary)) return;
4784
4980
  this.persistTempOrder();
4785
4981
  this.emitPromotionApplied(promotionPayload);
4786
4982
  }
@@ -4797,6 +4993,10 @@ class OrderModule extends _BaseModule.BaseModule {
4797
4993
  async removeProductsFromOrderDraft(identities, options) {
4798
4994
  const isCurrentOrder = options?.isCurrentOrder;
4799
4995
  if (isCurrentOrder && !isCurrentOrder()) return this.store.tempOrder?.products || [];
4996
+ // Keep the pre-removal snapshot guard separate from the ownership guard:
4997
+ // deleting these rows must not make the async finalization reject its own mutation.
4998
+ if (identities.length) options?.beforeApply?.();
4999
+ if (isCurrentOrder && !isCurrentOrder()) return this.store.tempOrder?.products || [];
4800
5000
  const mutation = this.beginCartMutation();
4801
5001
  let tempOrder = mutation.draft;
4802
5002
  if (!identities.length) {
@@ -4871,7 +5071,8 @@ class OrderModule extends _BaseModule.BaseModule {
4871
5071
  tempOrder.shop_discount = '0.00';
4872
5072
  }
4873
5073
  if (mutation.commit) tempOrder = await mutation.commit({
4874
- isCurrentOrder
5074
+ isCurrentOrder,
5075
+ beforeCommit: options?.beforeApply
4875
5076
  });
4876
5077
  if (isCurrentOrder) {
4877
5078
  await this.finalizeProductOrderMutation(tempOrder, {
@@ -487,11 +487,22 @@ export interface AddProductToOrderOptions {
487
487
  /** 发布后的订单/业务归属检查;只用于阻止旧异步收尾写入新单,不再校验截止或 revision。 */
488
488
  availabilityCommitTargetGuard?: () => boolean;
489
489
  }
490
+ /** Atomic replacement of one unsubmitted Party booking and its explicitly confirmed retail children. */
491
+ export interface ReplaceBookingProductWithRelatedRetailParams {
492
+ productLineUid: string;
493
+ product: Partial<OrderProduct> & OrderProductIdentity;
494
+ booking: AddProductBookingInput;
495
+ relatedRetailProducts: Array<Partial<OrderProduct> & OrderProductIdentity>;
496
+ availabilityCommitGuard: () => void;
497
+ availabilityCommitTargetGuard?: () => boolean;
498
+ }
490
499
  /**
491
500
  * 删除商品后的可选位置保持策略。
492
501
  * 预约合并行减量时仍删除最新真实行,再把剩余代表行移动到被删除代表行原位置。
493
502
  */
494
503
  export interface RemoveProductsFromOrderOptions {
504
+ /** Validate the selected row/cascade snapshot before mutation; may throw. Not called during finalization. */
505
+ beforeApply?: () => void;
495
506
  /** 自动购物车写入的订单归属检查;失效时不再变更或发布异步收尾结果。 */
496
507
  isCurrentOrder?: () => boolean;
497
508
  preserveDisplayPosition?: {
@@ -536,6 +547,13 @@ export interface UpdateOrderProductParams {
536
547
  */
537
548
  allow_booking_discount_reapply?: boolean;
538
549
  }
550
+ /** Opt-in atomic draft update for asynchronous re-quotation callers. */
551
+ export interface UpdateOrderProductsOptions {
552
+ /** Validate the quoted source snapshot immediately before publication; may throw. */
553
+ beforeApply?: () => void;
554
+ /** Order/business ownership only. Called after publication too; exclude old prices/quantities. */
555
+ isCurrentOrder?: () => boolean;
556
+ }
539
557
  /** 仅更新购物车行数量;行定位语义与 updateOrderProduct / removeProductFromOrder 保持一致 */
540
558
  export interface UpdateOrderProductQuantityParams extends OrderProductIdentity {
541
559
  num: number;
@@ -932,6 +950,7 @@ export interface OrderModuleAPI {
932
950
  updateTempOrderBuzzer: (buzzer: string) => string;
933
951
  updateTempOrderContactsInfo: (contactsInfo: Record<string, any> | null) => Record<string, any> | null;
934
952
  addProductToOrder: (product: Partial<OrderProduct> & OrderProductIdentity, booking?: AddProductBookingInput, options?: AddProductToOrderOptions) => Promise<OrderProduct[]>;
953
+ replaceBookingProductWithRelatedRetail: (params: ReplaceBookingProductWithRelatedRetailParams) => Promise<OrderProduct[]>;
935
954
  getSalesNotes: () => SalesNote[];
936
955
  createSalesNotesMutationSnapshot: () => SalesNotesMutationSnapshot;
937
956
  restoreSalesNotesMutationSnapshot: (snapshot: SalesNotesMutationSnapshot) => void;
@@ -940,7 +959,7 @@ export interface OrderModuleAPI {
940
959
  clearSalesNotes: () => Promise<void>;
941
960
  updateOrderProduct: (params: UpdateOrderProductParams) => Promise<OrderProduct[]>;
942
961
  /** 批量更新购物车行,末尾仅触发一次促销重算与 summary 刷新 */
943
- updateOrderProducts: (paramsList: UpdateOrderProductParams[]) => Promise<OrderProduct[]>;
962
+ updateOrderProducts: (paramsList: UpdateOrderProductParams[], options?: UpdateOrderProductsOptions) => Promise<OrderProduct[]>;
944
963
  updateOrderProductQuantity: (params: UpdateOrderProductQuantityParams, options?: {
945
964
  isCurrentOrder?: () => boolean;
946
965
  }) => 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
  * 订单信息
@@ -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(): "duration" | "normal" | "session";
52
+ getProductType(): "normal" | "duration" | "session";
53
53
  }
@@ -37,7 +37,9 @@ function collectReferencedRuleIds(products) {
37
37
  if (!Array.isArray(variants)) return;
38
38
  variants.forEach(variant => {
39
39
  const id = String(variant?.data_variant_rule_id ?? '').trim();
40
- if (id) ids.add(id);
40
+ // Rule 0 is the default-variant sentinel, not a strategy to load.
41
+ // Keep the evaluator responsible for its pricing/settlement semantics.
42
+ if (id && Number(id) !== 0) ids.add(id);
41
43
  });
42
44
  };
43
45
  products.forEach(product => {
@@ -56,10 +58,12 @@ function isEvaluatorReady(evaluator, products) {
56
58
  // A referenced Data Variant cannot be evaluated authoritatively until those
57
59
  // configs have arrived. Evaluators without this capability remain compatible.
58
60
  if (typeof evaluator.getStrategyConfigs === 'function') {
61
+ const referencedRuleIds = collectReferencedRuleIds(products);
62
+ if (referencedRuleIds.size === 0) return true;
59
63
  const configs = evaluator.getStrategyConfigs();
60
64
  if (!Array.isArray(configs) || configs.length === 0) return false;
61
65
  const availableRuleIds = new Set(configs.map(config => String(config?.metadata?.id ?? '').trim()).filter(Boolean));
62
- return Array.from(collectReferencedRuleIds(products)).every(id => availableRuleIds.has(id));
66
+ return Array.from(referencedRuleIds).every(id => availableRuleIds.has(id));
63
67
  }
64
68
  return true;
65
69
  }
@@ -37,6 +37,8 @@ export declare class ProductList extends BaseModule implements Module {
37
37
  schedule_date?: string;
38
38
  channel?: string;
39
39
  }): Promise<any>;
40
+ /** Venue-only raw, complete pool load. No date/customer evaluation and no shared catalog publication. */
41
+ loadVenueCatalogPool(params?: Pick<ProductListLoadProductsParams, 'product_ids' | 'collection' | 'category_ids' | 'extension_type' | 'cacheId'>): Promise<ProductData[]>;
40
42
  /**
41
43
  * Remember raw remote product records before client-side Data Variant
42
44
  * evaluation. Quote-only reads can then always start from a clean baseline.
@@ -265,6 +265,62 @@ class ProductList extends _BaseModule.BaseModule {
265
265
  return productsData.data;
266
266
  }
267
267
 
268
+ /** Venue-only raw, complete pool load. No date/customer evaluation and no shared catalog publication. */
269
+ async loadVenueCatalogPool(params = {}) {
270
+ const channelMap = {
271
+ online_store: 'online-store',
272
+ scan_to_order: 'online-store',
273
+ 'scan-to-order': 'online-store',
274
+ scan_to_order_2: 'online-store',
275
+ scan_to_order_3: 'scantoorder3'
276
+ };
277
+ const channel = this.otherParams?.channel;
278
+ const response = await this.request.post('/product/query', {
279
+ // The customer endpoint otherwise filters out future/variant members.
280
+ open_quotation: 0,
281
+ open_bundle: 1,
282
+ with: [..._clientDataVariants.PRODUCT_QUERY_DATA_VARIANT_RELATIONS],
283
+ with_count: ['bundleGroup', 'optionGroup'],
284
+ with_schedule: 1,
285
+ status: 'published',
286
+ num: 500,
287
+ skip: 1,
288
+ is_eject: 1,
289
+ // Channel is stable for this runtime owner and remains a server publication
290
+ // filter. Date/customer/menu membership and pricing are evaluated locally.
291
+ application_code: typeof channel === 'string' ? channelMap[channel] || channel : channel,
292
+ ...(params.product_ids?.length ? {
293
+ ids: params.product_ids
294
+ } : {}),
295
+ ...(params.collection ? {
296
+ collection: params.collection
297
+ } : {}),
298
+ ...(params.category_ids?.length ? {
299
+ category_ids: params.category_ids
300
+ } : {}),
301
+ ...(params.extension_type?.length ? {
302
+ extension_type: params.extension_type
303
+ } : {}),
304
+ front_end_cache_id: params.cacheId
305
+ }, {
306
+ useCache: false,
307
+ customToast: () => {}
308
+ });
309
+ const data = response?.data;
310
+ if (response?.status === false || response?.code != null && Number(response.code) !== 200 || !Array.isArray(data?.list)) {
311
+ throw Object.assign(new Error(response?.message || 'The complete venue product pool could not be loaded.'), {
312
+ code: 'VENUE_CATALOG_LOAD_FAILED'
313
+ });
314
+ }
315
+ const total = data.total ?? data.total_count ?? data.total_num;
316
+ if (total != null && Number.isFinite(Number(total)) && Number(total) > data.list.length || total == null && data.list.length >= 500) {
317
+ throw Object.assign(new Error('The venue product pool is incomplete. A single complete catalog response is required.'), {
318
+ code: 'VENUE_CATALOG_INCOMPLETE'
319
+ });
320
+ }
321
+ return (0, _lodashEs.cloneDeep)(data.list);
322
+ }
323
+
268
324
  /**
269
325
  * Remember raw remote product records before client-side Data Variant
270
326
  * evaluation. Quote-only reads can then always start from a clean baseline.
@@ -569,6 +569,10 @@ function buildCellKey(params) {
569
569
  return [String(params.productId), params.groupId, String(params.resourceId), params.start, params.end].join(':');
570
570
  }
571
571
  function dedupeOccupancyRefKey(occupancy) {
572
+ const sessionKey = occupancy.raw?.__availabilitySessionOccupancyKey;
573
+ if (typeof sessionKey === 'string' && sessionKey) {
574
+ return `session:${JSON.stringify([String(occupancy.resourceId), sessionKey])}`;
575
+ }
572
576
  if (occupancy.scheduleEventId !== undefined && occupancy.scheduleEventId !== null) {
573
577
  return `scheduleEvent:${String(occupancy.resourceId)}:${String(occupancy.scheduleEventId)}`;
574
578
  }
@@ -1879,7 +1879,11 @@ class Server {
1879
1879
  return this.computeProductQueryResult({
1880
1880
  schedule_date,
1881
1881
  schedule_datetime: scheduleDatetime,
1882
- product_id: productId
1882
+ product_id: productId,
1883
+ ...(data && typeof data === 'object' ? {
1884
+ customer_id: data.customer_id,
1885
+ strategy_context: data.strategy_context
1886
+ } : {})
1883
1887
  });
1884
1888
  };
1885
1889
 
@@ -7,7 +7,7 @@ import { OrderModule } from '../../modules/Order';
7
7
  import { type PickupTimingBookingInput } from '../../modules/Order/pickupTiming';
8
8
  import type { PickupTimingAvailability, PickupTimingSelection, PickupTimingValidationResult } from '../../modules/FulfillmentTiming';
9
9
  import { type ContactInfoConfig } from '../../modules/OpenData/contactInfo';
10
- 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';
10
+ 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';
11
11
  import type { SubmitPayloadEnhancer } from '../../modules/Order/utils';
12
12
  import type { Discount, VirtualCurrencyAsset } from '../../modules/Discount/types';
13
13
  import { RequestPlugin, WindowPlugin } from '../../plugins';
@@ -135,7 +135,7 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
135
135
  * /product/query 的智能定价评估只读取 strategy_context;
136
136
  * application_code 仅作为接口兼容字段,不能替代 channel / business_code。
137
137
  */
138
- private getPriceQueryStrategyContext;
138
+ protected getPriceQueryStrategyContext(channel?: string): Record<string, any>;
139
139
  /**
140
140
  * 子类可在商品重报价前准备客户维度的策略上下文,例如等待 Wallet/优惠资产加载。
141
141
  */
@@ -162,6 +162,12 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
162
162
  private prepareRawProductForPriceQuery;
163
163
  private resolveLocalProductForPriceQuery;
164
164
  private loadProductsForPriceQuery;
165
+ /** Opt-in subclasses may supply page-owned raw pools; ordinary sales keep remote fallback. */
166
+ protected isVenueCatalogLocalPricingActive(): boolean;
167
+ protected getVenueCatalogLocalPriceSource(_productId: number, _selectedProduct?: Record<string, any>): {
168
+ product: Record<string, any>;
169
+ menuList: Record<string, any>[];
170
+ } | undefined;
165
171
  private resolveProductsForPriceQuery;
166
172
  private getAuthoritativeBundleItems;
167
173
  private findAuthoritativeBundleItem;
@@ -535,6 +541,11 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
535
541
  submitBeforeSend?: boolean;
536
542
  }): Promise<T>;
537
543
  transformBaseProductToOrderProduct(params: TransformBaseProductToOrderProductParams): import("./utils/transformBaseProductToOrderProduct").BaseProductOrderProductInput | null;
544
+ /** Explicit pool source avoids races between two simultaneous Venue pricing contexts. */
545
+ protected calculateVenueCatalogProductBookingPrice(params: BaseSalesCalculateProductBookingPriceParams, source: {
546
+ product: Record<string, any>;
547
+ menuList: Record<string, any>[];
548
+ }): Promise<BaseSalesProductBookingPriceResult>;
538
549
  calculateProductBookingPrice(params: BaseSalesCalculateProductBookingPriceParams): Promise<BaseSalesProductBookingPriceResult>;
539
550
  getQuotationCustomerScopeInfo(): BaseSalesQuotationCustomerScopeInfo;
540
551
  private hasSmartPricingStrategies;
@@ -548,7 +559,7 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
548
559
  validateProductVoucherSelection(): void;
549
560
  addProductToOrder(product: Partial<BaseSalesOrderProduct> & BaseSalesOrderProductIdentity, booking?: AddProductBookingInput, options?: AddProductToOrderOptions): Promise<import("../../modules/Order/types").OrderProduct[]>;
550
561
  updateOrderProduct(params: UpdateOrderProductParams): Promise<import("../../modules/Order/types").OrderProduct[]>;
551
- updateOrderProducts(paramsList: UpdateOrderProductParams[]): Promise<import("../../modules/Order/types").OrderProduct[]>;
562
+ updateOrderProducts(paramsList: UpdateOrderProductParams[], options?: UpdateOrderProductsOptions): Promise<import("../../modules/Order/types").OrderProduct[]>;
552
563
  updateOrderProductQuantity(params: BaseSalesUpdateOrderProductQuantityParams): Promise<import("../../modules/Order/types").OrderProduct[]>;
553
564
  updateOrderBooking(params: UpdateOrderBookingParams): any[];
554
565
  /**
@@ -1058,6 +1058,9 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1058
1058
  products: [preparedProduct],
1059
1059
  queryPayload: params.queryPayload,
1060
1060
  handledByOsServer: false,
1061
+ ...(params.menuList ? {
1062
+ menuList: params.menuList
1063
+ } : {}),
1061
1064
  ...(scheduleList ? {
1062
1065
  scheduleList
1063
1066
  } : {})
@@ -1113,6 +1116,14 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1113
1116
  return productsById;
1114
1117
  }
1115
1118
  }
1119
+
1120
+ /** Opt-in subclasses may supply page-owned raw pools; ordinary sales keep remote fallback. */
1121
+ isVenueCatalogLocalPricingActive() {
1122
+ return false;
1123
+ }
1124
+ getVenueCatalogLocalPriceSource(_productId, _selectedProduct) {
1125
+ return undefined;
1126
+ }
1116
1127
  async resolveProductsForPriceQuery(params) {
1117
1128
  const selectedProducts = params.priceQueries.map(item => item.product || {});
1118
1129
  const productIds = selectedProducts.map(product => this.getPriceQueryProductId(product));
@@ -1120,6 +1131,30 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1120
1131
  if (!ids.length) {
1121
1132
  return selectedProducts.map(() => null);
1122
1133
  }
1134
+
1135
+ // An explicitly active Venue pool owns all its product reads. Missing raw data
1136
+ // or rules must fail visibly; never silently spend a second list/detail request.
1137
+ if (this.isVenueCatalogLocalPricingActive()) {
1138
+ const queryPayload = this.buildPriceQueryPayload({
1139
+ ids,
1140
+ schedule: params.schedule,
1141
+ customerId: params.customerId,
1142
+ channel: params.channel
1143
+ });
1144
+ return selectedProducts.map((selectedProduct, index) => {
1145
+ const source = productIds[index] == null ? undefined : this.getVenueCatalogLocalPriceSource(productIds[index], selectedProduct);
1146
+ const resolved = source && this.resolveLocalProductForPriceQuery({
1147
+ selectedProduct,
1148
+ rawProduct: source.product,
1149
+ menuList: source.menuList,
1150
+ queryPayload
1151
+ });
1152
+ if (!resolved) throw Object.assign(new Error('The complete venue product or pricing rules are not ready. Reload the catalog before continuing.'), {
1153
+ code: 'VENUE_LOCAL_PRICE_UNAVAILABLE'
1154
+ });
1155
+ return resolved;
1156
+ });
1157
+ }
1123
1158
  const handledByOsServer = this.request ? (0, _clientDataVariants.isProductQueryHandledByOsServer)(this.core, this.request) : false;
1124
1159
  const canUseLocalFastPath = this.isCustomerUserPriceQuery() && !handledByOsServer;
1125
1160
  if (!canUseLocalFastPath) {
@@ -4224,6 +4259,36 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
4224
4259
  transformBaseProductToOrderProduct(params) {
4225
4260
  return (0, _transformBaseProductToOrderProduct.transformBaseProductToOrderProduct)(params);
4226
4261
  }
4262
+
4263
+ /** Explicit pool source avoids races between two simultaneous Venue pricing contexts. */
4264
+ async calculateVenueCatalogProductBookingPrice(params, source) {
4265
+ const customerId = params.customer_id ?? this.getCurrentOrderCustomerId();
4266
+ await this.prepareProductPriceQueryContext(customerId);
4267
+ const channel = this.getPriceQueryChannel(params.channel);
4268
+ const queryPayload = this.buildPriceQueryPayload({
4269
+ ids: [Number(source.product.id)],
4270
+ schedule: this.getPriceQuerySchedule(params),
4271
+ customerId,
4272
+ channel
4273
+ });
4274
+ const authoritativeProduct = this.resolveLocalProductForPriceQuery({
4275
+ selectedProduct: params.product,
4276
+ rawProduct: source.product,
4277
+ menuList: source.menuList,
4278
+ queryPayload
4279
+ });
4280
+ if (!authoritativeProduct) throw Object.assign(new Error('Complete product pricing rules are not ready. Please retry.'), {
4281
+ code: 'VENUE_LOCAL_PRICE_UNAVAILABLE'
4282
+ });
4283
+ return (0, _quotationPrice.calculateBaseSalesProductBookingPrice)({
4284
+ ...params,
4285
+ channel,
4286
+ customer_id: customerId,
4287
+ product: this.mergeProductForPriceQuery(params.product, authoritativeProduct),
4288
+ fallback_price: undefined,
4289
+ quotation: undefined
4290
+ });
4291
+ }
4227
4292
  async calculateProductBookingPrice(params) {
4228
4293
  const [result] = await this.calculateProductBookingPrices([params]);
4229
4294
  return result;
@@ -4471,10 +4536,10 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
4471
4536
  throw error;
4472
4537
  }
4473
4538
  }
4474
- async updateOrderProducts(paramsList) {
4539
+ async updateOrderProducts(paramsList, options) {
4475
4540
  try {
4476
4541
  if (!this.store.order) throw new Error('order 模块未初始化');
4477
- const products = await this.store.order.updateOrderProducts(paramsList);
4542
+ const products = await this.store.order.updateOrderProducts(paramsList, options);
4478
4543
  return products;
4479
4544
  } catch (error) {
4480
4545
  throw error;
@@ -328,7 +328,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
328
328
  date: string;
329
329
  status: string;
330
330
  week: string;
331
- weekNum: 0 | 2 | 1 | 3 | 4 | 5 | 6;
331
+ weekNum: 0 | 1 | 2 | 3 | 5 | 4 | 6;
332
332
  }[]>;
333
333
  submitTimeSlot(timeSlots: TimeSliceItem): void;
334
334
  private getScheduleDataByIds;
@@ -375,7 +375,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
375
375
  };
376
376
  setOtherData(key: string, value: any): void;
377
377
  getOtherData(key: string): any;
378
- getProductTypeById(id: number): Promise<"duration" | "normal" | "session">;
378
+ getProductTypeById(id: number): Promise<"normal" | "duration" | "session">;
379
379
  /**
380
380
  * 提供给 UI 的方法,减轻 UI 层的计算压力,UI 层只需要传递 cartItemId 和 resourceCode 即返回对应的 renderList
381
381
  *