@pisell/pisellos 2.3.187 → 2.3.190

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 (47) hide show
  1. package/dist/modules/BookingContext/utils/productExtend.d.ts +9 -1
  2. package/dist/modules/BookingContext/utils/productExtend.js +47 -13
  3. package/dist/modules/Order/index.d.ts +15 -5
  4. package/dist/modules/Order/index.js +1161 -921
  5. package/dist/modules/Order/types.d.ts +16 -4
  6. package/dist/modules/Order/utils.d.ts +1 -3
  7. package/dist/modules/Order/utils.js +2 -5
  8. package/dist/modules/Product/index.d.ts +1 -1
  9. package/dist/modules/ResourcePlanner/planner.js +29 -2
  10. package/dist/modules/ResourcePlanner/types.d.ts +6 -0
  11. package/dist/modules/Rules/index.js +19 -30
  12. package/dist/solution/BaseSales/index.d.ts +4 -0
  13. package/dist/solution/BaseSales/index.js +204 -176
  14. package/dist/solution/BaseSales/types.d.ts +1 -0
  15. package/dist/solution/BaseSales/types.js +1 -0
  16. package/dist/solution/BookingByStep/index.d.ts +2 -2
  17. package/dist/solution/BookingByStep/index.js +8 -5
  18. package/dist/solution/BookingByStep/utils/resources.d.ts +10 -0
  19. package/dist/solution/BookingByStep/utils/resources.js +117 -76
  20. package/dist/solution/BookingTicket/index.js +52 -31
  21. package/dist/solution/UnifiedBookingSales/index.d.ts +3 -0
  22. package/dist/solution/UnifiedBookingSales/index.js +279 -204
  23. package/dist/solution/UnifiedBookingSales/types.d.ts +6 -1
  24. package/lib/modules/BookingContext/utils/productExtend.d.ts +9 -1
  25. package/lib/modules/BookingContext/utils/productExtend.js +38 -5
  26. package/lib/modules/Order/index.d.ts +15 -5
  27. package/lib/modules/Order/index.js +167 -21
  28. package/lib/modules/Order/types.d.ts +16 -4
  29. package/lib/modules/Order/utils.d.ts +1 -3
  30. package/lib/modules/Order/utils.js +2 -5
  31. package/lib/modules/Product/index.d.ts +1 -1
  32. package/lib/modules/ResourcePlanner/planner.js +25 -1
  33. package/lib/modules/ResourcePlanner/types.d.ts +6 -0
  34. package/lib/modules/Rules/index.js +9 -19
  35. package/lib/solution/BaseSales/index.d.ts +4 -0
  36. package/lib/solution/BaseSales/index.js +14 -0
  37. package/lib/solution/BaseSales/types.d.ts +1 -0
  38. package/lib/solution/BaseSales/types.js +1 -0
  39. package/lib/solution/BookingByStep/index.d.ts +2 -2
  40. package/lib/solution/BookingByStep/index.js +8 -2
  41. package/lib/solution/BookingByStep/utils/resources.d.ts +10 -0
  42. package/lib/solution/BookingByStep/utils/resources.js +25 -15
  43. package/lib/solution/BookingTicket/index.js +8 -2
  44. package/lib/solution/UnifiedBookingSales/index.d.ts +3 -0
  45. package/lib/solution/UnifiedBookingSales/index.js +80 -15
  46. package/lib/solution/UnifiedBookingSales/types.d.ts +6 -1
  47. package/package.json +1 -1
@@ -265,6 +265,10 @@ export interface GetProductTimeRangesRequest {
265
265
  durationStartTimesByProductId?: Record<string, string[]>;
266
266
  /** Restore only the exact remembered start; recompute the end from current product/windows. */
267
267
  rememberedStartAtByProductId?: Record<string, string>;
268
+ /** Order-scoped v2 memory preserves the complete actual booking interval. */
269
+ rememberedTimeByProductId?: Record<string, AvailabilityAbsoluteRange>;
270
+ /** Required by the POS facade before accepting v2 remembered intervals. */
271
+ orderSessionId?: string;
268
272
  /** Edit only: preserve the full actual start plus an explicit durationMinutesByProductId. */
269
273
  editingStartAtByProductId?: Record<string, string>;
270
274
  /**
@@ -279,6 +283,8 @@ export interface GetProductTimeRangesRuntimeOptions {
279
283
  useDurationTimeGrid?: boolean;
280
284
  /** Automatic remembered selection must not use POS opening-minute cutoff exceptions. */
281
285
  enforceSaleCutoff?: boolean;
286
+ /** Internal POS capability, validated against the current order session by the facade. */
287
+ rememberedTimeByProductId?: Record<string, AvailabilityAbsoluteRange>;
282
288
  /**
283
289
  * Internal POS capability: fixed-duration candidates start from the stable
284
290
  * context anchor's current minute instead of rounding up to ten minutes, and
@@ -940,22 +940,6 @@ class RulesModule extends _BaseModule.BaseModule {
940
940
 
941
941
  // 记录已应用优惠券的商品信息
942
942
  const appliedDiscountProducts = new Map();
943
- const hasPayableOptions = product => {
944
- return (product.options || []).reduce((total, option) => {
945
- const unitPrice = Number(option._original_price ?? option._original_add_price ?? option.price ?? option.add_price ?? 0);
946
- const quantity = Number(option.num ?? option.quantity ?? 1);
947
- if (!Number.isFinite(unitPrice) || !Number.isFinite(quantity) || quantity <= 0) {
948
- return total;
949
- }
950
- return total.plus(new _decimal.default(unitPrice).mul(quantity));
951
- }, new _decimal.default(0)).greaterThan(0);
952
- };
953
-
954
- // 只排除赠品主项的零可抵扣金额;收费 option 和独立 bundle 保持原有规则。
955
- const isGiftWithoutDeductibleAmount = (flatItem, discount) => {
956
- if (flatItem.type !== 'main' || !flatItem.originProduct?.metadata?._giftInfo || Number(flatItem.price || 0) > 0) return false;
957
- return !discount.config?.deductOptionPrice || !hasPayableOptions(flatItem.product);
958
- };
959
943
 
960
944
  // 可用性和实际应用共用金额判断;零基础价商品可按策略抵扣收费 option。
961
945
  const isDiscountCardPriceAvailable = (flatItem, discount) => {
@@ -966,7 +950,14 @@ class RulesModule extends _BaseModule.BaseModule {
966
950
  if (flatItem.type !== 'main' || Number(flatItem.price) !== 0 || !['discount_card', 'product_discount_card'].includes(discount.tag || discount.type || '') || !discount.config?.deductOptionPrice || (0, _utils.isOrderLevelFixedAmountDiscount)(discount)) {
967
951
  return false;
968
952
  }
969
- return hasPayableOptions(product);
953
+ return (product.options || []).reduce((total, option) => {
954
+ const unitPrice = Number(option._original_price ?? option._original_add_price ?? option.price ?? option.add_price ?? 0);
955
+ const quantity = Number(option.num ?? option.quantity ?? 1);
956
+ if (!Number.isFinite(unitPrice) || !Number.isFinite(quantity) || quantity <= 0) {
957
+ return total;
958
+ }
959
+ return total.plus(new _decimal.default(unitPrice).mul(quantity));
960
+ }, new _decimal.default(0)).greaterThan(0);
970
961
  };
971
962
 
972
963
  // 首先遍历所有商品和所有优惠券,确定每个优惠券的适用范围,包括isSelected为false的优惠券
@@ -1021,7 +1012,7 @@ class RulesModule extends _BaseModule.BaseModule {
1021
1012
  }
1022
1013
 
1023
1014
  // 判断优惠券是否适用于该商品
1024
- if (isAvailableProduct && !isItemRewardProductDiscount && !isGiftWithoutDeductibleAmount(flatItem, discount) && isLimitedProduct && timeLimit && isBundleAvailable && discount.config?.isAvailable && ((0, _entitlementPass.isFullCoveragePass)(discount) || isDiscountCardPriceAvailable(flatItem, discount)) && (!(0, _entitlementPass.isEntitlementPass)(discount) || (0, _entitlementPass.getRemainingEntitlementUses)(discount, 0, 1) > 0)) {
1015
+ if (isAvailableProduct && !isItemRewardProductDiscount && isLimitedProduct && timeLimit && isBundleAvailable && discount.config?.isAvailable && ((0, _entitlementPass.isFullCoveragePass)(discount) || isDiscountCardPriceAvailable(flatItem, discount)) && (!(0, _entitlementPass.isEntitlementPass)(discount) || (0, _entitlementPass.getRemainingEntitlementUses)(discount, 0, 1) > 0)) {
1025
1016
  // 记录此优惠券适用的商品
1026
1017
  discountApplicability.get(discount.id)?.push(product.id);
1027
1018
  if (flatItem.type === 'main' && (0, _promotionSelection.isPromotionDiscountCard)(discount)) {
@@ -1170,7 +1161,6 @@ class RulesModule extends _BaseModule.BaseModule {
1170
1161
 
1171
1162
  // 找到适用于此商品的所有优惠券,仅考虑isSelected不为false的优惠券
1172
1163
  const applicableDiscounts = sortedDiscountList.filter(discount => {
1173
- if (isGiftWithoutDeductibleAmount(flatItem, discount)) return false;
1174
1164
  if (this.discountScope && !this.discountScope(originProduct, discount)) return false;
1175
1165
  if (this.isItemRewardProductDiscount(product)) return false;
1176
1166
  if (isCardBlockedByPromotion(flatItem, discount)) return false;
@@ -82,6 +82,7 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
82
82
  private salesDetailHydrateQueue;
83
83
  private serverOrderChangeUnsubscribe;
84
84
  private paymentMethodsChangedUnsubscribe;
85
+ private orderSessionChangedUnsubscribe;
85
86
  private serverOrderChangeHydrateInFlight;
86
87
  private queuedServerOrderChanges;
87
88
  private serverOrderChangeSyncEnabled;
@@ -116,6 +117,7 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
116
117
  private syncCurrentSalesDetailFromServerOrderChange;
117
118
  private registerServerOrderChangeSync;
118
119
  private registerPaymentMethodsChangeSync;
120
+ private registerOrderSessionChangeSync;
119
121
  private hydrateLatestLoadedSalesDetail;
120
122
  private hydrateOrderPaymentNames;
121
123
  get payment(): PaymentModule | undefined;
@@ -265,6 +267,8 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
265
267
  /** 获取附加费用(运费/服务费/税费等)。 */
266
268
  getSurcharges(): ISalesSurcharge[];
267
269
  getTempOrder(): OrderTempOrder | null;
270
+ getOrderSessionId(): string | null;
271
+ isOrderSessionCurrent(sessionId: string): boolean;
268
272
  replaceTempOrder(tempOrder: OrderTempOrder, options?: ReplaceTempOrderOptions): Promise<OrderTempOrder>;
269
273
  getOrderIdentity(): import("../../modules/Order/types").OrderIdentitySnapshot | null;
270
274
  getOrderSnapshot(): import("../../modules/Order/types").OrderSnapshot | null;
@@ -576,6 +576,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
576
576
  salesDetailHydrateQueue = Promise.resolve();
577
577
  serverOrderChangeUnsubscribe = null;
578
578
  paymentMethodsChangedUnsubscribe = null;
579
+ orderSessionChangedUnsubscribe = null;
579
580
  serverOrderChangeHydrateInFlight = null;
580
581
  queuedServerOrderChanges = [];
581
582
  serverOrderChangeSyncEnabled = false;
@@ -736,6 +737,10 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
736
737
  await this.getPaymentMethodsAsync();
737
738
  });
738
739
  }
740
+ registerOrderSessionChangeSync() {
741
+ this.orderSessionChangedUnsubscribe?.();
742
+ this.orderSessionChangedUnsubscribe = this.store.order?.effectsOn?.('onOrderSessionChanged', payload => this.effectsEmit(_types.BaseSalesHookNames.onOrderSessionChanged, payload)) || null;
743
+ }
739
744
  async hydrateLatestLoadedSalesDetail(record, loadSequence, options) {
740
745
  let hydratedSales = null;
741
746
  let skippedBeforeHydrate = false;
@@ -1732,6 +1737,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1732
1737
  await this.getPaymentMethodsAsync();
1733
1738
  this.registerPaymentMethodsChangeSync();
1734
1739
  this.registerServerOrderChangeSync();
1740
+ this.registerOrderSessionChangeSync();
1735
1741
  this.core.effects.emit(`${this.name}:onInited`, {});
1736
1742
  }
1737
1743
  async destroy() {
@@ -1741,6 +1747,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1741
1747
  this.serverOrderChangeUnsubscribe = null;
1742
1748
  this.paymentMethodsChangedUnsubscribe?.();
1743
1749
  this.paymentMethodsChangedUnsubscribe = null;
1750
+ this.orderSessionChangedUnsubscribe?.();
1751
+ this.orderSessionChangedUnsubscribe = null;
1744
1752
  for (const key of Object.keys(this.store)) {
1745
1753
  if (this.reusedSharedSubModuleNames.has(key)) continue;
1746
1754
  const sub = this.store[key];
@@ -1873,6 +1881,12 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1873
1881
  const result = this.store.order?.getTempOrder() || null;
1874
1882
  return result;
1875
1883
  }
1884
+ getOrderSessionId() {
1885
+ return this.store.order?.getOrderSessionId?.() || null;
1886
+ }
1887
+ isOrderSessionCurrent(sessionId) {
1888
+ return this.store.order?.isOrderSessionCurrent?.(sessionId) || false;
1889
+ }
1876
1890
  async replaceTempOrder(tempOrder, options) {
1877
1891
  if (!this.store.order) throw new Error('order 模块未初始化');
1878
1892
  const nextTempOrder = await this.store.order.replaceTempOrder(tempOrder, options);
@@ -13,6 +13,7 @@ import type { SubmitPayloadEnhancer } from '../../modules/Order/utils';
13
13
  export declare const BaseSalesHookNames: {
14
14
  readonly onInited: "onInited";
15
15
  readonly onDestroy: "onDestroy";
16
+ readonly onOrderSessionChanged: "onOrderSessionChanged";
16
17
  readonly onRetryInit: "onRetryInit";
17
18
  readonly onRefresh: "onRefresh";
18
19
  readonly onCartValidationChanged: "onCartValidationChanged";
@@ -12,6 +12,7 @@ exports.createBaseSalesHook = createBaseSalesHook;
12
12
  const BaseSalesHookNames = exports.BaseSalesHookNames = {
13
13
  onInited: 'onInited',
14
14
  onDestroy: 'onDestroy',
15
+ onOrderSessionChanged: 'onOrderSessionChanged',
15
16
  onRetryInit: 'onRetryInit',
16
17
  onRefresh: 'onRefresh',
17
18
  onCartValidationChanged: 'onCartValidationChanged',
@@ -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 | 1 | 2 | 3 | 5 | 4 | 6;
331
+ weekNum: 0 | 2 | 1 | 3 | 4 | 5 | 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<"normal" | "duration" | "session">;
378
+ getProductTypeById(id: number): Promise<"duration" | "normal" | "session">;
379
379
  /**
380
380
  * 提供给 UI 的方法,减轻 UI 层的计算压力,UI 层只需要传递 cartItemId 和 resourceCode 即返回对应的 renderList
381
381
  *
@@ -2222,11 +2222,17 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
2222
2222
  start_at: (0, _dayjs.default)(item.start),
2223
2223
  end_at: (0, _dayjs.default)(item.end)
2224
2224
  })) {
2225
- mSet.set(m.id, m.pax ?? 1);
2225
+ mSet.set(m.id, {
2226
+ ...m,
2227
+ pax: m.pax ?? 1
2228
+ });
2226
2229
  }
2227
2230
  });
2228
2231
  });
2229
- acc += Array.from(mSet.values()).reduce((acc, curr) => acc + curr, 0);
2232
+ acc += (0, _resources.getPeakConcurrentPax)(Array.from(mSet.values()), {
2233
+ start_at: (0, _dayjs.default)(item.start),
2234
+ end_at: (0, _dayjs.default)(item.end)
2235
+ });
2230
2236
  return acc;
2231
2237
  }, 0);
2232
2238
  // 如果已使用容量超过了当前类型资源的容量,则不可用
@@ -7,6 +7,11 @@ import { CartItem, ProductData } from '../../../modules';
7
7
  *
8
8
  */
9
9
  type DateType = Dayjs;
10
+ interface EventItem {
11
+ pax: number;
12
+ start_at: DateType;
13
+ end_at: DateType;
14
+ }
10
15
  export interface TimeSliceItem {
11
16
  start_time: string;
12
17
  end_time: string;
@@ -20,6 +25,11 @@ export interface ResourceItem {
20
25
  interface BookingItem {
21
26
  [key: string]: any;
22
27
  }
28
+ /** 计算目标区间内的最大同时占用人数;事件去重由调用方负责。 */
29
+ export declare const getPeakConcurrentPax: (eventList: EventItem[], timeSlice: {
30
+ start_at: DateType;
31
+ end_at: DateType;
32
+ }) => number;
23
33
  /**
24
34
  * @title: 判断两个时间段是否有重叠
25
35
  * @description:
@@ -7,7 +7,7 @@ exports.checkSessionProductLeadTime = checkSessionProductLeadTime;
7
7
  exports.checkTwoResourcesIntersection = checkTwoResourcesIntersection;
8
8
  exports.filterResourcesByFormItem = filterResourcesByFormItem;
9
9
  exports.filterScheduleByDateRange = filterScheduleByDateRange;
10
- exports.getResourcesByProduct = exports.getResourcesByIds = exports.getOthersSelectedResources = exports.getOthersCartSelectedResources = exports.getIsUsableByTimeItem = exports.formatResources = void 0;
10
+ exports.getResourcesByProduct = exports.getResourcesByIds = exports.getPeakConcurrentPax = exports.getOthersSelectedResources = exports.getOthersCartSelectedResources = exports.getIsUsableByTimeItem = exports.formatResources = void 0;
11
11
  exports.getResourcesIdsByProduct = getResourcesIdsByProduct;
12
12
  exports.mergeSubResourcesTimeSlices = exports.isConflict = exports.getTimesIntersection = exports.getTimeSlicesByResources = exports.getTimeSlicesByResource = void 0;
13
13
  exports.sortCombinedResources = sortCombinedResources;
@@ -20,18 +20,27 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
20
20
  *
21
21
  */
22
22
 
23
- /**
24
- * @title: 获取重叠剩余量
25
- * @description:
26
- * @param {any} eventList
27
- * @param {number} current
28
- * @return {*}
29
- * @Author: zhiwei.Wang
30
- */
31
- const getUseableEventCount = (eventList, current) => {
32
- return (eventList || []).reduce((pre, event) => {
33
- return pre - event.pax;
34
- }, current || 0);
23
+ /** 计算目标区间内的最大同时占用人数;事件去重由调用方负责。 */
24
+ const getPeakConcurrentPax = (eventList, timeSlice) => {
25
+ const start = (0, _dayjs.default)(timeSlice.start_at).valueOf();
26
+ const end = (0, _dayjs.default)(timeSlice.end_at).valueOf();
27
+ const changes = new Map();
28
+ for (const event of eventList || []) {
29
+ const eventStart = Math.max(start, (0, _dayjs.default)(event.start_at).valueOf());
30
+ const eventEnd = Math.min(end, (0, _dayjs.default)(event.end_at).valueOf());
31
+ if (!(eventStart < eventEnd)) continue;
32
+ const pax = Number(event.pax);
33
+ changes.set(eventStart, (changes.get(eventStart) ?? 0) + pax);
34
+ changes.set(eventEnd, (changes.get(eventEnd) ?? 0) - pax);
35
+ }
36
+ let current = 0;
37
+ let peak = 0;
38
+ // 同一时刻合并增减量,保持 [start, end) 语义,首尾相接不叠加。
39
+ for (const [, change] of [...changes].sort(([a], [b]) => a - b)) {
40
+ current += change;
41
+ peak = Math.max(peak, current);
42
+ }
43
+ return peak;
35
44
  };
36
45
 
37
46
  /**
@@ -42,6 +51,7 @@ const getUseableEventCount = (eventList, current) => {
42
51
  * @return {*}
43
52
  * @Author: zhiwei.Wang
44
53
  */
54
+ exports.getPeakConcurrentPax = getPeakConcurrentPax;
45
55
  const isConflict = (event, current) => {
46
56
  const eventStart = (0, _dayjs.default)(event.start_at);
47
57
  const eventEnd = (0, _dayjs.default)(event.end_at);
@@ -132,8 +142,8 @@ const checkCapacity = ({
132
142
  });
133
143
  });
134
144
 
135
- // 减去重叠的总量
136
- let conflictCount = getUseableEventCount(conflict, resource.capacity);
145
+ // 多人预约按同时占用峰值扣减,不能把先后到访的所有人数相加。
146
+ const conflictCount = resource.resourceType === 'single' ? conflict.reduce((remaining, event) => remaining - event.pax, resource.capacity || 0) : (resource.capacity || 0) - getPeakConcurrentPax(conflict, timeSlice);
137
147
 
138
148
  // 同一时间段内只能进行一个预约,无论容量是否已满。
139
149
  if (resource.resourceType === 'single') {
@@ -1621,7 +1621,9 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
1621
1621
  resourcesOriginMap: state.resourcesOriginMap,
1622
1622
  date,
1623
1623
  presetStartTime: extra?.presetStartTime ?? (0, _BookingContext.derivePresetStartTimeFromDate)(date),
1624
- ...(extra || {})
1624
+ ...(extra || {}),
1625
+ orderSessionId: this.getOrderSessionId() ?? undefined,
1626
+ isOrderSessionCurrent: sessionId => this.isOrderSessionCurrent(sessionId)
1625
1627
  };
1626
1628
  }
1627
1629
 
@@ -1713,7 +1715,9 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
1713
1715
  presetStartTime: extra?.presetStartTime ?? (0, _BookingContext.derivePresetStartTimeFromDate)(date),
1714
1716
  customerId: orderCustomerId,
1715
1717
  ...(extra || {}),
1716
- channel: this.getSubmitOrderSalesChannel()
1718
+ channel: this.getSubmitOrderSalesChannel(),
1719
+ orderSessionId: this.getOrderSessionId() ?? undefined,
1720
+ isOrderSessionCurrent: sessionId => this.isOrderSessionCurrent(sessionId)
1717
1721
  };
1718
1722
  }
1719
1723
 
@@ -2147,6 +2151,8 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
2147
2151
  await this.replaceTempOrder({
2148
2152
  ...tempOrder,
2149
2153
  vouchers: nextVouchers
2154
+ }, {
2155
+ preserveOrderSessionId: this.getOrderSessionId() || undefined
2150
2156
  });
2151
2157
  }
2152
2158
  this.core.effects.emit(`${this.name}:onVouchersChange`, {});
@@ -131,6 +131,9 @@ export declare class UnifiedBookingSalesImpl extends BookingTicket {
131
131
  private cloneAvailabilityPrepareParams;
132
132
  private getAvailabilityDurationCandidateAnchorAt;
133
133
  private createAvailabilityContextRef;
134
+ /** Accept the v2 interval only within the POS order that recorded it. */
135
+ private resolveOrderRememberedTimes;
136
+ private assertRememberedOrderSession;
134
137
  private emitAvailabilityDiagnostic;
135
138
  private touchAvailabilityContext;
136
139
  private touchAvailabilityProjection;
@@ -1651,12 +1651,48 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1651
1651
  contextId: context.contextId,
1652
1652
  ...(projection && this.usesDurationTimeGrid(projection) ? {
1653
1653
  durationTimeSelection: {
1654
- version: 1,
1655
- currentBusinessDate: this.getCurrentAvailabilityBusinessDate(projection)
1654
+ version: 2,
1655
+ currentBusinessDate: this.getCurrentAvailabilityBusinessDate(projection),
1656
+ orderSessionId: this.getOrderSessionId()
1656
1657
  }
1657
1658
  } : {})
1658
1659
  };
1659
1660
  }
1661
+
1662
+ /** Accept the v2 interval only within the POS order that recorded it. */
1663
+ resolveOrderRememberedTimes(context, projection, ranges, orderSessionId) {
1664
+ if (ranges === undefined) return undefined;
1665
+ if (String(this.otherParams?.platform ?? '').trim().toLowerCase() !== 'pos' || context.prepareParams.editingProductLineUids?.length || !this.usesDurationTimeGrid(projection)) return undefined;
1666
+ this.assertRememberedOrderSession(orderSessionId);
1667
+ if (!isRecord(ranges) || !Object.keys(ranges).length) {
1668
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间区间不能为空');
1669
+ }
1670
+ const offset = (0, _localClock.extractFixedOffsetMinutes)(projection.meta.now) ?? this.getAvailabilityRuntimeOffsetMinutes();
1671
+ return Object.fromEntries(Object.entries(ranges).map(([productId, range]) => {
1672
+ try {
1673
+ const normalize = value => {
1674
+ if (typeof value !== 'string') throw new Error('Missing interval boundary');
1675
+ const scalar = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(value));
1676
+ const inputOffset = (0, _localClock.extractFixedOffsetMinutes)(value) ?? offset;
1677
+ return (0, _localClock.formatLocalDateTime)(scalar + (offset - inputOffset) * 60000, offset);
1678
+ };
1679
+ const startAt = normalize(range.startAt);
1680
+ const endAt = normalize(range.endAt);
1681
+ if (endAt <= startAt) throw new Error('Invalid interval');
1682
+ return [productId, {
1683
+ startAt,
1684
+ endAt
1685
+ }];
1686
+ } catch {
1687
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间必须包含有效且递增的开始和结束时间');
1688
+ }
1689
+ }));
1690
+ }
1691
+ assertRememberedOrderSession(orderSessionId) {
1692
+ if (!orderSessionId || !this.isOrderSessionCurrent(orderSessionId)) {
1693
+ throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '记忆时间所属订单已变化,请重新选择');
1694
+ }
1695
+ }
1660
1696
  async emitAvailabilityDiagnostic(payload) {
1661
1697
  await this.core?.effects?.emit?.(`${this.name}:${_types.UnifiedBookingSalesHooks.onAvailabilityProjectionDiagnostic}`, {
1662
1698
  ...payload,
@@ -2104,13 +2140,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2104
2140
  buildBookingCalcContext(extra) {
2105
2141
  return {
2106
2142
  ...super.buildBookingCalcContext(extra),
2107
- resolveDefaultBookingStart: (cacheItem, fallback) => this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
2143
+ resolveDefaultBookingStart: (cacheItem, fallback) => extra?.useCurrentTimeAfterRememberedExpiry ? (0, _salesSettings.normalizeBookingDateTime)(fallback) : this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
2108
2144
  };
2109
2145
  }
2110
2146
  buildAddProductCtx(extra) {
2111
2147
  return {
2112
2148
  ...super.buildAddProductCtx(extra),
2113
- resolveDefaultBookingStart: (cacheItem, fallback) => this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
2149
+ resolveDefaultBookingStart: (cacheItem, fallback) => extra?.useCurrentTimeAfterRememberedExpiry ? (0, _salesSettings.normalizeBookingDateTime)(fallback) : this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
2114
2150
  };
2115
2151
  }
2116
2152
 
@@ -3601,14 +3637,16 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3601
3637
  endDate: businessDate
3602
3638
  };
3603
3639
  }
3604
- const rememberedStartAtByProductId = isPosAvailabilityRequest && !isEditingContext ? request.rememberedStartAtByProductId : undefined;
3605
- const allowOutsideOperatingHoursForRequestedStartTimes = isPosAvailabilityRequest && !rememberedStartAtByProductId && (editingStarts.length > 0 || Object.values(request.durationStartTimesByProductId || {}).some(startTimes => Array.isArray(startTimes) && startTimes.length > 0));
3640
+ const rememberedTimeByProductId = this.resolveOrderRememberedTimes(context, projectionEntry.projection, request.rememberedTimeByProductId, request.orderSessionId);
3641
+ const rememberedStartAtByProductId = !rememberedTimeByProductId && isPosAvailabilityRequest && !isEditingContext ? request.rememberedStartAtByProductId : undefined;
3642
+ const allowOutsideOperatingHoursForRequestedStartTimes = isPosAvailabilityRequest && !rememberedStartAtByProductId && !rememberedTimeByProductId && (editingStarts.length > 0 || Object.values(request.durationStartTimesByProductId || {}).some(startTimes => Array.isArray(startTimes) && startTimes.length > 0));
3606
3643
  return (0, _ResourcePlanner.getProductTimeRanges)(projectionEntry.projection, {
3607
3644
  ...request,
3608
3645
  dateRange,
3609
3646
  editingStartAtByProductId,
3610
3647
  rememberedStartAtByProductId,
3611
- ...(rememberedStartAtByProductId ? {
3648
+ rememberedTimeByProductId,
3649
+ ...(rememberedStartAtByProductId || rememberedTimeByProductId ? {
3612
3650
  allowOutsideOperatingHoursForRequestedStartTimes: false
3613
3651
  } : {}),
3614
3652
  ...(allowOutsideOperatingHoursForRequestedStartTimes ? {
@@ -3617,7 +3655,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3617
3655
  }, {
3618
3656
  evaluatedAt: this.getAvailabilityRuntimeDateTime(),
3619
3657
  useDurationTimeGrid: this.usesDurationTimeGrid(projectionEntry.projection),
3620
- enforceSaleCutoff: Boolean(rememberedStartAtByProductId),
3658
+ enforceSaleCutoff: Boolean(rememberedStartAtByProductId || rememberedTimeByProductId),
3659
+ rememberedTimeByProductId,
3621
3660
  useExactDurationCandidateMinute: isPosAvailabilityRequest,
3622
3661
  allowSessionCustomRanges: isPosAvailabilityRequest,
3623
3662
  allowExcludedScheduleDateOverride: isPosAvailabilityRequest
@@ -3636,6 +3675,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3636
3675
  } = await this.ensureAvailabilityContextProjection(contextId, 'query_booking_availability');
3637
3676
  this.assertContextualQueryFreshness(context, request);
3638
3677
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3678
+ const rememberedTimeByProductId = request.selectionIntent === 'remembered' ? this.resolveOrderRememberedTimes(context, projectionEntry.projection, request.rememberedTimeByProductId, request.orderSessionId) : undefined;
3639
3679
  const queryRequest = request.target === 'date' || request.target === 'product' ? {
3640
3680
  ...request,
3641
3681
  dateRange: request.dateRange || this.getAvailabilityBusinessDateRange(projectionEntry.projection)
@@ -3643,6 +3683,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3643
3683
  const result = (0, _ResourcePlanner.queryAvailabilityProjection)(projectionEntry.projection, queryRequest, {
3644
3684
  useDurationTimeGrid: this.usesDurationTimeGrid(projectionEntry.projection),
3645
3685
  enforceSaleCutoff: isPosAvailabilityRequest && !context.prepareParams.editingProductLineUids?.length && request.selectionIntent === 'remembered',
3686
+ rememberedTimeByProductId,
3646
3687
  useExactDurationCandidateMinute: isPosAvailabilityRequest,
3647
3688
  allowExcludedScheduleDateOverride: isPosAvailabilityRequest
3648
3689
  });
@@ -3750,6 +3791,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3750
3791
  });
3751
3792
  }
3752
3793
  const isRememberedSelection = params.selectionIntent === 'remembered';
3794
+ const isOrderRememberedSelection = isRememberedSelection && params.orderSessionId !== undefined;
3753
3795
  if (isRememberedSelection && (String(this.otherParams?.platform ?? '').trim().toLowerCase() !== 'pos' || params.mode !== 'add')) {
3754
3796
  throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间自动提交仅支持 POS 新增 duration 商品');
3755
3797
  }
@@ -3757,16 +3799,21 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3757
3799
  params.availabilityCommitGuard?.();
3758
3800
  // Stabilize the locally generated sale identity before taking the guard snapshot.
3759
3801
  if (hasCommitGuard) this.store.order?.ensureTempOrder?.();
3760
- const rememberedOrder = hasCommitGuard ? this.getTempOrder() : null;
3802
+ if (isOrderRememberedSelection) this.assertRememberedOrderSession(params.orderSessionId);
3803
+ let rememberedOrder = hasCommitGuard ? this.getTempOrder() : null;
3761
3804
  const getRememberedCommitIdentity = () => JSON.stringify(stableValue({
3762
3805
  scope: this.getAvailabilityScopeDescriptor(),
3763
3806
  shopId: this.otherParams?.shop_id ?? this.otherParams?.shopId,
3764
3807
  contextShopId: this.core?.context?.shop_id,
3765
- orderId: this.getTempOrder()?.order_id,
3766
- externalSaleNumber: this.getTempOrder()?.external_sale_number
3808
+ ...(isOrderRememberedSelection ? {
3809
+ orderSessionId: this.getOrderSessionId()
3810
+ } : {
3811
+ orderId: this.getTempOrder()?.order_id,
3812
+ externalSaleNumber: this.getTempOrder()?.external_sale_number
3813
+ })
3767
3814
  }));
3768
3815
  const rememberedCommitIdentity = hasCommitGuard ? getRememberedCommitIdentity() : '';
3769
- const availabilityCommitTargetGuard = () => this.getTempOrder() === rememberedOrder && getRememberedCommitIdentity() === rememberedCommitIdentity;
3816
+ const availabilityCommitTargetGuard = () => (isOrderRememberedSelection ? this.isOrderSessionCurrent(params.orderSessionId) : this.getTempOrder() === rememberedOrder) && getRememberedCommitIdentity() === rememberedCommitIdentity;
3770
3817
  let guardedCommitPublished = false;
3771
3818
  await this.tryAcquireAvailabilityCommitLock(normalizedContextId);
3772
3819
  try {
@@ -3924,13 +3971,21 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3924
3971
  const candidateStartTime = getCandidateStartTime(params.candidate);
3925
3972
  const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !isRememberedSelection;
3926
3973
  const candidateBusinessDate = params.candidate.businessDate || (selectedProduct?.kind === 'duration' && this.usesDurationTimeGrid(refreshedProjection) ? (0, _ResourcePlanner.getDurationBusinessDate)(refreshedProjection, params.candidate.startAt) : params.candidate.startAt.slice(0, 10));
3974
+ const rememberedTimeByProductId = isOrderRememberedSelection ? this.resolveOrderRememberedTimes(context, refreshedProjection, {
3975
+ [String(params.candidate.productId)]: {
3976
+ startAt: params.candidate.bookingStartAt,
3977
+ endAt: params.candidate.bookingEndAt
3978
+ }
3979
+ }, params.orderSessionId) : undefined;
3927
3980
  const refreshedRanges = (0, _ResourcePlanner.getProductTimeRanges)(refreshedProjection, {
3928
3981
  productIds: [params.candidate.productId],
3929
3982
  dateRange: {
3930
3983
  startDate: candidateBusinessDate,
3931
3984
  endDate: candidateBusinessDate
3932
3985
  },
3933
- ...(isRememberedSelection ? {
3986
+ ...(rememberedTimeByProductId ? {
3987
+ rememberedTimeByProductId
3988
+ } : isRememberedSelection ? {
3934
3989
  rememberedStartAtByProductId: {
3935
3990
  [String(params.candidate.productId)]: params.candidate.bookingStartAt
3936
3991
  },
@@ -3961,6 +4016,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3961
4016
  evaluatedAt: this.getAvailabilityRuntimeDateTime(),
3962
4017
  useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
3963
4018
  enforceSaleCutoff: isRememberedSelection,
4019
+ rememberedTimeByProductId,
3964
4020
  useExactDurationCandidateMinute: allowPosAvailabilityOverride,
3965
4021
  allowSessionCustomRanges: allowPosAvailabilityOverride,
3966
4022
  allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
@@ -3987,6 +4043,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3987
4043
  }, {
3988
4044
  useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
3989
4045
  enforceSaleCutoff: isRememberedSelection,
4046
+ rememberedTimeByProductId,
3990
4047
  useExactDurationCandidateMinute: allowPosAvailabilityOverride,
3991
4048
  allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
3992
4049
  });
@@ -4055,6 +4112,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4055
4112
  if (!availabilityCommitTargetGuard()) {
4056
4113
  throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '记忆时间加购期间订单或业务已变化');
4057
4114
  }
4115
+ // Same-order immutable snapshots and generated sale IDs preserve the session.
4116
+ // Capture the actual object Order is about to publish, not an earlier snapshot.
4117
+ if (isOrderRememberedSelection) rememberedOrder = this.getTempOrder();
4058
4118
  if (!isRememberedSelection) return;
4059
4119
  const currentValidation = (0, _ResourcePlanner.validateAvailabilitySelection)(refreshedProjection, {
4060
4120
  candidate: refreshedCandidateBase,
@@ -4063,7 +4123,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4063
4123
  bookingCount
4064
4124
  }, {
4065
4125
  useDurationTimeGrid: true,
4066
- enforceSaleCutoff: true
4126
+ enforceSaleCutoff: true,
4127
+ rememberedTimeByProductId
4067
4128
  });
4068
4129
  if (!currentValidation.ok) {
4069
4130
  throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '记忆时间在加购前已不可用,请重新选择', {
@@ -4168,8 +4229,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4168
4229
  availabilityCommitTargetGuard
4169
4230
  } : {})
4170
4231
  } : undefined);
4171
- products = await this.removeBookingProductsOutsideStartDate(booking.start_date);
4172
4232
  guardedCommitPublished = hasCommitGuard;
4233
+ // A completed add can publish before a different order becomes current.
4234
+ // Keep its returned lines and never clean up products on that next order.
4235
+ if (!hasCommitGuard || availabilityCommitTargetGuard()) {
4236
+ products = await this.removeBookingProductsOutsideStartDate(booking.start_date);
4237
+ }
4173
4238
  const addedLines = products.filter(line => sameAvailabilityId(line.product_id ?? line.id, refreshedCandidate.productId) && line.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeProductLineUids.has(getProductLineUid(line)));
4174
4239
  productLineUids = addedLines.map(line => getProductLineUid(line)).filter(Boolean);
4175
4240
  const addedBookings = ((hasCommitGuard ? rememberedOrder : this.getTempOrder())?.bookings || []).filter(item => item.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeBookingUids.has(getBookingUid(item)));
@@ -74,8 +74,9 @@ export interface AvailabilityContextRef {
74
74
  contextId: string;
75
75
  /** POS/Kiosk duration protocol capability and business-day default. */
76
76
  durationTimeSelection?: {
77
- version: 1;
77
+ version: 2;
78
78
  currentBusinessDate: string;
79
+ orderSessionId: string | null;
79
80
  };
80
81
  }
81
82
  export interface ContextualProductTimeRange extends ProductTimeRange {
@@ -100,6 +101,8 @@ export type ContextualAvailabilityQuery = (Omit<Extract<AvailabilityQuery, {
100
101
  })) & {
101
102
  /** Automatic remembered selection must not inherit POS manual exceptions. */
102
103
  selectionIntent?: 'remembered' | 'manual';
104
+ rememberedTimeByProductId?: GetProductTimeRangesRequest['rememberedTimeByProductId'];
105
+ orderSessionId?: string;
103
106
  };
104
107
  export type ContextualTimeAvailabilityItem = Omit<TimeAvailabilityItem, keyof ProductTimeRange> & ContextualProductTimeRange;
105
108
  export interface ContextualTimeAvailabilityGroup extends Omit<TimeAvailabilityGroup, 'times'> {
@@ -165,6 +168,8 @@ export interface ContextualCommitAvailabilitySelectionParams {
165
168
  mode: 'add' | 'edit';
166
169
  /** Only POS duration add supports automatic remembered-time commits. */
167
170
  selectionIntent?: 'remembered' | 'manual';
171
+ /** v2 remembered commits must still belong to the order that saved the interval. */
172
+ orderSessionId?: string;
168
173
  /** Local UI intent guard, checked again immediately before the Order mutation. */
169
174
  availabilityCommitGuard?: () => void;
170
175
  productLineUid?: string;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "2.3.187",
4
+ "version": "2.3.190",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",