@pisell/pisellos 0.10.71 → 0.10.73

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 (31) hide show
  1. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  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 -4
  6. package/dist/modules/Order/index.js +1401 -764
  7. package/dist/modules/Order/types.d.ts +24 -1
  8. package/dist/modules/Order/types.js +4 -0
  9. package/dist/server/index.js +5 -2
  10. package/dist/solution/BaseSales/index.d.ts +2 -2
  11. package/dist/solution/BaseSales/index.js +8 -8
  12. package/dist/solution/BookingByStep/index.d.ts +1 -1
  13. package/dist/solution/UnifiedBookingSales/index.d.ts +15 -0
  14. package/dist/solution/UnifiedBookingSales/index.js +1082 -596
  15. package/dist/solution/UnifiedBookingSales/types.d.ts +17 -1
  16. package/lib/model/strategy/adapter/promotion/index.js +46 -1
  17. package/lib/modules/BookingContext/index.d.ts +2 -2
  18. package/lib/modules/BookingContext/index.js +42 -10
  19. package/lib/modules/BookingContext/types.d.ts +2 -0
  20. package/lib/modules/Order/index.d.ts +13 -4
  21. package/lib/modules/Order/index.js +284 -24
  22. package/lib/modules/Order/types.d.ts +24 -1
  23. package/lib/modules/Order/types.js +2 -0
  24. package/lib/server/index.js +5 -1
  25. package/lib/solution/BaseSales/index.d.ts +2 -2
  26. package/lib/solution/BaseSales/index.js +2 -2
  27. package/lib/solution/BookingByStep/index.d.ts +1 -1
  28. package/lib/solution/UnifiedBookingSales/index.d.ts +15 -0
  29. package/lib/solution/UnifiedBookingSales/index.js +343 -44
  30. package/lib/solution/UnifiedBookingSales/types.d.ts +17 -1
  31. package/package.json +1 -1
@@ -48,6 +48,7 @@ Object.keys(_salesSettings).forEach(function (key) {
48
48
  });
49
49
  });
50
50
  var _getDateIsInSchedule = require("../../modules/Schedule/getDateIsInSchedule");
51
+ var _clientDataVariants = require("../../modules/ProductList/clientDataVariants");
51
52
  var _ResourcePlanner = require("../../modules/ResourcePlanner");
52
53
  var _types = require("./types");
53
54
  Object.keys(_types).forEach(function (key) {
@@ -1058,6 +1059,11 @@ function buildBookingFromAvailabilitySelection(params) {
1058
1059
  unified_booking_sales: true,
1059
1060
  availability_candidate_key: candidate.key,
1060
1061
  availability_source: candidate.source,
1062
+ availability_business_date: candidate.businessDate || candidate.date,
1063
+ availability_timezone: candidate.timezone,
1064
+ ...(candidate.primaryScheduleRef ? {
1065
+ availability_primary_schedule_ref: (0, _lodashEs.cloneDeep)(candidate.primaryScheduleRef)
1066
+ } : {}),
1061
1067
  availability_slice_start_at: candidate.startAt,
1062
1068
  availability_slice_end_at: candidate.endAt,
1063
1069
  availability_schedule_refs: candidate.scheduleRefs,
@@ -1915,7 +1921,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1915
1921
  return [booking];
1916
1922
  });
1917
1923
  }
1924
+ shouldApplyMultipleBookingScheduling() {
1925
+ const platform = (0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform);
1926
+ return platform === 'pos' || platform === 'webpos';
1927
+ }
1918
1928
  resolveLoadedDefaultBookingStart(holderIds, fallback) {
1929
+ // Customer channels keep their entry default instead of following cart bookings.
1930
+ // Keep this callback installed so BookingContext cannot fall back to Board.
1931
+ if (!this.shouldApplyMultipleBookingScheduling()) return (0, _salesSettings.normalizeBookingDateTime)(fallback);
1919
1932
  const settings = this.getLoadedSalesSettings();
1920
1933
  return (0, _salesSettings.resolveDefaultBookingStart)({
1921
1934
  bookings: this.getProductBookingsForScheduling(),
@@ -1927,6 +1940,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1927
1940
 
1928
1941
  /** Used by the SKU flow after Holder changes, without changing an explicit user-selected time. */
1929
1942
  async resolveDefaultBookingStart(params) {
1943
+ if (!this.shouldApplyMultipleBookingScheduling()) return (0, _salesSettings.normalizeBookingDateTime)(params.fallback);
1930
1944
  await this.getSalesSettings();
1931
1945
  return this.resolveLoadedDefaultBookingStart(params.holderIds, params.fallback);
1932
1946
  }
@@ -1945,6 +1959,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1945
1959
 
1946
1960
  /** Re-evaluate an automatic default after Holder enrichment, or restore a known explicit TimeBar start. */
1947
1961
  async applyDefaultBookingStart(cacheItem, options = {}) {
1962
+ if (!this.shouldApplyMultipleBookingScheduling()) return cacheItem;
1948
1963
  if (!cacheItem?.new || !(0, _utils.isBookingProduct)(cacheItem) || (0, _utils.isSessionProduct)(cacheItem) || cacheItem?._extend?.other?.session) return cacheItem;
1949
1964
  const extend = cacheItem._extend || {};
1950
1965
  const currentStart = (0, _salesSettings.getBookingBoundary)(extend, 'start');
@@ -2147,6 +2162,128 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2147
2162
  * product because session products carry their fixed intervals there.
2148
2163
  */
2149
2164
  async loadProducts(params = {}, options) {
2165
+ const catalogScope = this.otherParams.catalogScopeKey;
2166
+ const result = await this.loadCatalogProducts(params, options);
2167
+ if (catalogScope !== this.otherParams.catalogScopeKey) {
2168
+ throw Object.assign(new Error('Product scope changed'), {
2169
+ name: 'AbortError'
2170
+ });
2171
+ }
2172
+ this.unifiedProductCatalog = Array.isArray(result) ? [...result] : [];
2173
+ await this.core.effects.emit(`${this.name}:onProductsLoaded`, result);
2174
+ return result;
2175
+ }
2176
+
2177
+ /**
2178
+ * Queries one explicitly configured menu scope without publishing the sales catalog.
2179
+ * The returned graph is detached from ProductList's shared ID cache. Callers own its
2180
+ * membership and must requery/reprice with the service datetime after a context change.
2181
+ * Missing/invalid menu configuration fails closed instead of querying every product.
2182
+ */
2183
+ async queryCatalogSnapshot(params) {
2184
+ if (!Array.isArray(params.menu_list_ids) || params.menu_list_ids.length === 0 || params.menu_list_ids.some(id => !Number.isInteger(id) || id <= 0)) {
2185
+ return [];
2186
+ }
2187
+ const {
2188
+ product_ids,
2189
+ ...scopeParams
2190
+ } = (0, _lodashEs.cloneDeep)(params);
2191
+ // The OS Server ID-query branch intentionally bypasses menus. Apply IDs only after
2192
+ // querying the configured menu so an isolated scope cannot leak other products.
2193
+ const result = await this.loadCatalogProducts({
2194
+ ...scopeParams,
2195
+ menu_list_ids: [...new Set(params.menu_list_ids)]
2196
+ });
2197
+ const list = Array.isArray(result) ? result : [];
2198
+ return (0, _lodashEs.cloneDeep)(product_ids?.length ? list.filter(product => product_ids.some(id => Number(id) === Number(product.id))) : list);
2199
+ }
2200
+
2201
+ /** Full SKU/bundle detail, after verifying membership in the explicit day/menu scope. */
2202
+ async queryCatalogProductDetail(params) {
2203
+ const {
2204
+ product_id,
2205
+ product_ids: _ignoredIds,
2206
+ ...catalogParams
2207
+ } = (0, _lodashEs.cloneDeep)(params);
2208
+ if (!Number.isInteger(product_id) || product_id <= 0) return undefined;
2209
+ const schedule_date = catalogParams.schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD');
2210
+ const schedule_datetime = catalogParams.schedule_datetime || `${schedule_date} ${(0, _dayjs.default)().format('HH:mm:ss')}`;
2211
+ const scopedParams = {
2212
+ ...catalogParams,
2213
+ schedule_date,
2214
+ schedule_datetime
2215
+ };
2216
+ const member = (await this.queryCatalogSnapshot(scopedParams)).find(item => Number(item.id) === product_id);
2217
+ if (!member) return undefined;
2218
+ const baseUrl = String(this.request.baseUrl || ((0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) ? '/h5' : '/shop')).replace(/\/+$/, '');
2219
+ const localPath = `/product/query/${product_id}`;
2220
+ const handledByOsServer = this.core.server?.hasRoute?.('get', `${baseUrl}${localPath}`) === true;
2221
+ const channelMap = {
2222
+ online_store: 'online-store',
2223
+ scan_to_order: 'online-store',
2224
+ 'scan-to-order': 'online-store',
2225
+ scan_to_order_2: 'online-store',
2226
+ scan_to_order_3: 'scantoorder3'
2227
+ };
2228
+ const channel = channelMap[this.otherParams?.channel] || this.otherParams?.channel;
2229
+ const businessCode = this.otherParams?.businessCode ?? this.otherParams?.business_code;
2230
+ const strategy_context = {
2231
+ ...(channel ? {
2232
+ channel
2233
+ } : {}),
2234
+ ...(businessCode ? {
2235
+ business_code: businessCode
2236
+ } : {}),
2237
+ ...(scopedParams.strategy_context || {})
2238
+ };
2239
+ let customerId = scopedParams.customer_id;
2240
+ if (customerId == null) customerId = this.core.getPlugin?.('user')?.get?.()?.id;
2241
+ const queryPayload = {
2242
+ ...scopedParams,
2243
+ customer_id: customerId,
2244
+ strategy_context,
2245
+ application_code: channel,
2246
+ is_eject: 1,
2247
+ open_bundle: 1,
2248
+ with_schedule: 1,
2249
+ with: [..._clientDataVariants.PRODUCT_QUERY_DATA_VARIANT_RELATIONS],
2250
+ ...((0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) ? {} : {
2251
+ open_quotation: 1
2252
+ })
2253
+ };
2254
+ const response = await this.request.get(baseUrl === '/shop' ? localPath : `/product/show/${product_id}`, queryPayload, {
2255
+ osServer: true,
2256
+ useCache: false,
2257
+ customToast: () => {}
2258
+ });
2259
+ if (response?.status === false || Number(response?.code) >= 400) throw new Error('[UnifiedBookingSales] Product detail query failed');
2260
+ const raw = response?.data?.item ?? response?.data;
2261
+ if (!raw || Number(raw.id ?? raw.product_id) !== product_id) return undefined;
2262
+ if (raw.status && raw.status !== 'published') return undefined;
2263
+ if (!handledByOsServer) this.store.products?.rememberRawProductQueryResult?.([(0, _lodashEs.cloneDeep)(raw)]);
2264
+ const resolved = (0, _clientDataVariants.resolveClientDataVariants)({
2265
+ core: this.core,
2266
+ otherParams: this.otherParams,
2267
+ products: [(0, _lodashEs.cloneDeep)(raw)],
2268
+ queryPayload,
2269
+ handledByOsServer
2270
+ })[0];
2271
+ // Detail owns relation arrays. Never synthesize empty groups from list counts.
2272
+ if (!resolved) return undefined;
2273
+ const detail = {
2274
+ ...member,
2275
+ ...resolved,
2276
+ metadata: {
2277
+ ...(member.metadata || {}),
2278
+ ...(resolved.metadata || {})
2279
+ }
2280
+ };
2281
+ for (const key of ['bundle_group', 'bundle_groups', 'option_group', 'variant_group', 'variant']) {
2282
+ if (!Object.prototype.hasOwnProperty.call(resolved, key)) delete detail[key];
2283
+ }
2284
+ return (0, _lodashEs.cloneDeep)(detail);
2285
+ }
2286
+ async loadCatalogProducts(params = {}, options) {
2150
2287
  if (!this.store.products) throw new Error('[UnifiedBookingSales] products 模块未初始化');
2151
2288
  const catalogScope = this.otherParams.catalogScopeKey;
2152
2289
  const schedule_date = params.schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD');
@@ -2164,8 +2301,6 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2164
2301
  name: 'AbortError'
2165
2302
  });
2166
2303
  }
2167
- this.unifiedProductCatalog = Array.isArray(result) ? [...result] : [];
2168
- await this.core.effects.emit(`${this.name}:onProductsLoaded`, result);
2169
2304
  return result;
2170
2305
  }
2171
2306
  async queryProducts(params = {}) {
@@ -2358,10 +2493,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2358
2493
  sourceProduct
2359
2494
  });
2360
2495
  if (orderProduct && typeof orderProduct === 'object') {
2496
+ const venueMetadata = Object.fromEntries(['venue_booking_role', 'venue_booking_parent_uid', 'venue_booking_service_datetime', 'venue_booking_scope_key'].filter(key => sourceProduct.metadata?.[key] !== undefined).map(key => [key, sourceProduct.metadata[key]]));
2361
2497
  // BaseSales may rebuild metadata from its price source. Stamp ownership and the selected
2362
2498
  // quotation shelf after that transform so neither booking adds nor edits lose quote identity.
2363
2499
  orderProduct.metadata = {
2364
2500
  ...(orderProduct.metadata || {}),
2501
+ ...venueMetadata,
2365
2502
  [ownershipKey]: true,
2366
2503
  ...(quotationShelfId !== undefined ? {
2367
2504
  quotation_shelf_id: quotationShelfId
@@ -2443,7 +2580,38 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2443
2580
  if (!orderProduct) {
2444
2581
  throw new Error('[UnifiedBookingSales] 无法生成零售商品订单行');
2445
2582
  }
2446
- return this.addProductToOrder(orderProduct);
2583
+ if (orderProduct.metadata?.venue_booking_role === 'party_extra') {
2584
+ const order = this.getTempOrder();
2585
+ const meta = orderProduct.metadata;
2586
+ const parentUid = String(meta.venue_booking_parent_uid || '');
2587
+ const scopeKey = String(meta.venue_booking_scope_key || '');
2588
+ const service = String(meta.venue_booking_service_datetime || '');
2589
+ const identity = [order?.order_id, order?.external_sale_number];
2590
+ const isCurrentOrder = () => this.getTempOrder() === order && order?.order_id === identity[0] && order?.external_sale_number === identity[1];
2591
+ const guard = () => {
2592
+ params.availabilityCommitGuard?.();
2593
+ const parent = (order?.products || []).find(line => getProductLineUid(line) === parentUid);
2594
+ const parentService = String(parent?.metadata?.venue_booking_service_datetime || '');
2595
+ if (!isCurrentOrder() || !order || order.order_id || !parentUid || !scopeKey || parent?.metadata?.venue_booking_role !== 'party_main' || parent?.metadata?.venue_booking_scope_key !== scopeKey || !service || !parentService || !(0, _dayjs.default)(service).isValid() || !(0, _dayjs.default)(parentService).isValid() || (0, _dayjs.default)(service).format('YYYY-MM-DD HH:mm:ss') !== (0, _dayjs.default)(parentService).format('YYYY-MM-DD HH:mm:ss')) throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'Party 主商品或服务时间已变化,请重新确认附加商品');
2596
+ };
2597
+ guard();
2598
+ delete orderProduct.unique_identification_number;
2599
+ delete orderProduct.metadata.unique_identification_number;
2600
+ return this.addProductToOrder(orderProduct, undefined, {
2601
+ disableMerge: true,
2602
+ availabilityCommitGuard: guard,
2603
+ availabilityCommitTargetGuard: isCurrentOrder,
2604
+ salesNotes: params.salesNotes
2605
+ });
2606
+ }
2607
+ return this.addProductToOrder(orderProduct, undefined, {
2608
+ ...(params.availabilityCommitGuard ? {
2609
+ availabilityCommitGuard: params.availabilityCommitGuard
2610
+ } : {}),
2611
+ ...(params.salesNotes ? {
2612
+ salesNotes: params.salesNotes
2613
+ } : {})
2614
+ });
2447
2615
  }
2448
2616
  normalizeAvailabilityDateRange(params, timezone) {
2449
2617
  const today = (0, _localClock.formatLocalDate)((0, _localClock.localDateToScalar)(new Date()));
@@ -2498,8 +2666,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2498
2666
  params
2499
2667
  });
2500
2668
  }
2501
- if (!hasProductAnchor && !params.catalogScope) {
2502
- throw new _ResourcePlanner.AvailabilityError('MISSING_CATALOG_SCOPE', '缺少 productIds 时必须提供 catalogScope', {
2669
+ if (!hasProductAnchor && !params.catalogScope && !Array.isArray(params.rawProducts)) {
2670
+ throw new _ResourcePlanner.AvailabilityError('MISSING_CATALOG_SCOPE', '缺少 productIds 时必须提供 catalogScope 或 rawProducts', {
2503
2671
  params
2504
2672
  });
2505
2673
  }
@@ -2602,12 +2770,15 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2602
2770
  dateRange
2603
2771
  } = params;
2604
2772
  const explicitProductIds = prepare.productIds || [];
2773
+ const publishCatalog = prepare.publishCatalog !== false;
2774
+ const loadProducts = query => publishCatalog ? this.loadProducts(query) : prepare.catalogScope?.type === 'productList' ? this.queryCatalogSnapshot(query) : this.loadCatalogProducts(query);
2605
2775
  let rawProducts = [];
2606
2776
  if (Array.isArray(prepare.rawProducts)) {
2607
2777
  rawProducts = prepare.rawProducts;
2608
- this.unifiedProductCatalog = [...rawProducts];
2778
+ if (publishCatalog) this.unifiedProductCatalog = [...rawProducts];
2609
2779
  } else if (explicitProductIds.length > 0) {
2610
- rawProducts = await this.loadProducts({
2780
+ rawProducts = await loadProducts({
2781
+ ...(!publishCatalog && prepare.catalogScope?.type === 'productList' ? prepare.catalogScope.params : {}),
2611
2782
  product_ids: explicitProductIds,
2612
2783
  schedule_date: dateRange.startDate
2613
2784
  });
@@ -2623,15 +2794,15 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2623
2794
  const productIds = uniqueAvailabilityIds([...scheduleProductIds, ...(this.store.schedule.getOtherProductsIds?.() || [])]);
2624
2795
  if (productIds.length > 0) {
2625
2796
  assertAvailabilityCatalogProductIds(productIds, 'prepare.catalogScope.scheduleProductIds');
2626
- rawProducts = await this.loadProducts({
2797
+ rawProducts = await loadProducts({
2627
2798
  product_ids: productIds,
2628
2799
  schedule_date: dateRange.startDate
2629
2800
  });
2630
2801
  } else {
2631
- this.unifiedProductCatalog = [];
2802
+ if (publishCatalog) this.unifiedProductCatalog = [];
2632
2803
  }
2633
2804
  } else if (prepare.catalogScope?.type === 'productList') {
2634
- rawProducts = await this.loadProducts({
2805
+ rawProducts = await loadProducts({
2635
2806
  ...prepare.catalogScope.params,
2636
2807
  schedule_date: prepare.catalogScope.params.schedule_date || dateRange.startDate
2637
2808
  });
@@ -2742,7 +2913,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2742
2913
  resourceOccupancies: []
2743
2914
  };
2744
2915
  }
2745
- if (Array.isArray(params.rawResources)) {
2916
+ if (Array.isArray(params.rawResources) && params.fetchPolicy !== 'refresh') {
2746
2917
  return buildAvailabilityResourcesFromV2({
2747
2918
  rawResources: params.rawResources,
2748
2919
  scheduleList: params.scheduleList,
@@ -2769,10 +2940,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2769
2940
  resourceOccupancies: []
2770
2941
  };
2771
2942
  }
2772
- const rawResources = await this.fetchAndPublishAvailabilityResourcesV2({
2943
+ const remoteQuery = {
2773
2944
  timezone: params.timezone,
2774
2945
  dateRange: params.dateRange,
2775
- resourceIds,
2946
+ resourceIds
2947
+ };
2948
+ const rawResources = params.fetchPolicy === 'refresh' ? await this.refreshAvailabilityRemoteResourceQuery(remoteQuery) : await this.fetchAndPublishAvailabilityResourcesV2({
2949
+ ...remoteQuery,
2776
2950
  useCacheOnHit: true
2777
2951
  });
2778
2952
  return buildAvailabilityResourcesFromV2({
@@ -2997,7 +3171,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2997
3171
  products,
2998
3172
  rawResources: normalizedPrepareParams.rawResources,
2999
3173
  scheduleList,
3000
- fetchPolicy: options.resourceFetchPolicy || 'default',
3174
+ // An explicit internal policy (notably commit's cache_only) remains authoritative.
3175
+ fetchPolicy: options.resourceFetchPolicy || (normalizedPrepareParams.refreshOccupancies ? 'refresh' : 'default'),
3001
3176
  fallbackResources: options.fallbackResources
3002
3177
  });
3003
3178
  const tempOrder = this.getTempOrder();
@@ -3282,18 +3457,22 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3282
3457
  projectionEntry
3283
3458
  } = await this.ensureAvailabilityContextProjection(contextId, 'get_product_time_ranges');
3284
3459
  const contextVersion = context.activeVersion;
3460
+ const strictAvailability = context.prepareParams.strictAvailability === true;
3285
3461
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3286
- const allowOutsideOperatingHoursForRequestedStartTimes = isPosAvailabilityRequest && Object.values(request.durationStartTimesByProductId || {}).some(startTimes => Array.isArray(startTimes) && startTimes.length > 0);
3462
+ const allowOutsideOperatingHoursForRequestedStartTimes = isPosAvailabilityRequest && !strictAvailability && Object.values(request.durationStartTimesByProductId || {}).some(startTimes => Array.isArray(startTimes) && startTimes.length > 0);
3287
3463
  return (0, _ResourcePlanner.getProductTimeRanges)(projectionEntry.projection, {
3288
3464
  ...request,
3289
3465
  ...(allowOutsideOperatingHoursForRequestedStartTimes ? {
3290
3466
  allowOutsideOperatingHoursForRequestedStartTimes: true
3467
+ } : {}),
3468
+ ...(strictAvailability ? {
3469
+ allowOutsideOperatingHoursForRequestedStartTimes: false
3291
3470
  } : {})
3292
3471
  }, {
3293
3472
  evaluatedAt: this.getAvailabilityRuntimeDateTime(),
3294
- useExactDurationCandidateMinute: isPosAvailabilityRequest,
3295
- allowSessionCustomRanges: isPosAvailabilityRequest,
3296
- allowExcludedScheduleDateOverride: isPosAvailabilityRequest
3473
+ useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
3474
+ allowSessionCustomRanges: isPosAvailabilityRequest && !strictAvailability,
3475
+ allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
3297
3476
  }).map(group => ({
3298
3477
  ...group,
3299
3478
  ranges: group.ranges.map(candidate => this.decorateAvailabilityCandidate(context.contextId, contextVersion, candidate))
@@ -3308,10 +3487,11 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3308
3487
  refreshed
3309
3488
  } = await this.ensureAvailabilityContextProjection(contextId, 'query_booking_availability');
3310
3489
  this.assertContextualQueryFreshness(context, request);
3490
+ const strictAvailability = context.prepareParams.strictAvailability === true;
3311
3491
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3312
3492
  const result = (0, _ResourcePlanner.queryAvailabilityProjection)(projectionEntry.projection, request, {
3313
- useExactDurationCandidateMinute: isPosAvailabilityRequest,
3314
- allowExcludedScheduleDateOverride: isPosAvailabilityRequest
3493
+ useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
3494
+ allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
3315
3495
  });
3316
3496
  const contextVersion = context.activeVersion;
3317
3497
  const contextualResult = result.target === 'time' ? {
@@ -3345,6 +3525,20 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3345
3525
  refreshed
3346
3526
  };
3347
3527
  }
3528
+
3529
+ /** Reads detached resource metadata from the current context; never refreshes or performs I/O. */
3530
+ getAvailabilityResources(contextId, expectedVersion) {
3531
+ const context = this.getAvailabilityContextEntry(contextId);
3532
+ const entry = this.getActiveAvailabilityProjectionEntry(context);
3533
+ if (!entry || entry.contextVersion !== context.activeVersion || entry.orderRevision !== this.getCurrentOrderRevision() || expectedVersion !== undefined && context.activeVersion !== expectedVersion) {
3534
+ throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '资源上下文已变化,请重新查询当前候选', {
3535
+ contextId,
3536
+ expectedVersion,
3537
+ currentContextVersion: context.activeVersion
3538
+ });
3539
+ }
3540
+ return (0, _lodashEs.cloneDeep)([...entry.projection.resources]);
3541
+ }
3348
3542
  releaseAvailabilityContext(contextId) {
3349
3543
  const context = this.availabilityContextRegistry.get(contextId);
3350
3544
  if (!context) return;
@@ -3398,6 +3592,27 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3398
3592
  candidate: params.candidate
3399
3593
  });
3400
3594
  }
3595
+ const isEditingSelection = params.mode === 'edit' || params.mode === 'replace';
3596
+ const isPartyReplacement = params.mode === 'replace' || params.relatedRetailProducts !== undefined;
3597
+ if (isPartyReplacement && (!isEditingSelection || !Array.isArray(params.relatedRetailProducts))) {
3598
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Party replacement requires edit/replace mode and the confirmed complete extras array');
3599
+ }
3600
+ const strictAvailability = this.availabilityContextRegistry.get(normalizedContextId)?.prepareParams.strictAvailability === true;
3601
+ const hasCommitGuard = strictAvailability || isPartyReplacement || Boolean(params.availabilityCommitGuard);
3602
+ params.availabilityCommitGuard?.();
3603
+ // Stabilize the locally generated sale identity before taking the guard snapshot.
3604
+ if (hasCommitGuard) this.store.order?.ensureTempOrder?.();
3605
+ const guardedOrder = hasCommitGuard ? this.getTempOrder() : null;
3606
+ const getGuardedCommitIdentity = () => JSON.stringify(stableValue({
3607
+ scope: this.getAvailabilityScopeDescriptor(),
3608
+ shopId: this.otherParams?.shop_id ?? this.otherParams?.shopId,
3609
+ contextShopId: this.core?.context?.shop_id,
3610
+ orderId: this.getTempOrder()?.order_id,
3611
+ externalSaleNumber: this.getTempOrder()?.external_sale_number
3612
+ }));
3613
+ const guardedCommitIdentity = hasCommitGuard ? getGuardedCommitIdentity() : '';
3614
+ const availabilityCommitTargetGuard = () => this.getTempOrder() === guardedOrder && getGuardedCommitIdentity() === guardedCommitIdentity;
3615
+ let guardedCommitPublished = false;
3401
3616
  await this.tryAcquireAvailabilityCommitLock(normalizedContextId);
3402
3617
  try {
3403
3618
  const bookingCount = Number(params.bookingCount ?? 1);
@@ -3406,7 +3621,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3406
3621
  bookingCount: params.bookingCount
3407
3622
  });
3408
3623
  }
3409
- if (params.mode === 'edit' && bookingCount !== 1) {
3624
+ if (isEditingSelection && bookingCount !== 1) {
3410
3625
  throw new _ResourcePlanner.AvailabilityError('INVALID_RESERVATION_QUANTITY', '编辑预约商品时 bookingCount 必须为 1', {
3411
3626
  bookingCount
3412
3627
  });
@@ -3437,7 +3652,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3437
3652
  });
3438
3653
  }
3439
3654
  const boundEditingUids = context.prepareParams.editingProductLineUids || [];
3440
- if (params.mode === 'edit') {
3655
+ if (isEditingSelection) {
3441
3656
  if (!params.productLineUid || !boundEditingUids.includes(String(params.productLineUid))) {
3442
3657
  throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'edit context 与当前商品行不匹配,请重新 prepare 编辑上下文', {
3443
3658
  contextId: normalizedContextId,
@@ -3481,16 +3696,16 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3481
3696
  candidateProductId: params.candidate.productId
3482
3697
  });
3483
3698
  }
3484
- if (params.mode === 'edit' && !params.productLineUid) {
3699
+ if (isEditingSelection && !params.productLineUid) {
3485
3700
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', 'edit 模式必须提供 productLineUid');
3486
3701
  }
3487
- const editingLine = params.mode === 'edit' ? this.findProductLineByUid(String(params.productLineUid)) : undefined;
3488
- if (params.mode === 'edit' && !editingLine) {
3702
+ const editingLine = isEditingSelection ? this.findProductLineByUid(String(params.productLineUid)) : undefined;
3703
+ if (isEditingSelection && !editingLine) {
3489
3704
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', '找不到要编辑的预约商品行', {
3490
3705
  productLineUid: params.productLineUid
3491
3706
  });
3492
3707
  }
3493
- if (editingLine && !sameAvailabilityId(editingLine.product_id ?? editingLine.id, params.candidate.productId)) {
3708
+ if (editingLine && params.mode !== 'replace' && !sameAvailabilityId(editingLine.product_id ?? editingLine.id, params.candidate.productId)) {
3494
3709
  throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '编辑商品行与 candidate 商品不一致', {
3495
3710
  productLineUid: params.productLineUid,
3496
3711
  productLineProductId: editingLine.product_id ?? editingLine.id,
@@ -3521,7 +3736,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3521
3736
  };
3522
3737
  const commitSnapshot = await this.buildAvailabilityProjectionSnapshot({
3523
3738
  ...this.cloneAvailabilityPrepareParams(prepareParams),
3524
- editingProductLineUids: params.mode === 'edit' && params.productLineUid ? [params.productLineUid] : []
3739
+ editingProductLineUids: isEditingSelection && params.productLineUid ? [params.productLineUid] : []
3525
3740
  }, {
3526
3741
  resourceFetchPolicy: 'cache_only',
3527
3742
  fallbackResources,
@@ -3548,7 +3763,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3548
3763
  this.assertAvailabilityCommitWriteCAS(commitWriteGuard);
3549
3764
  const candidateDurationMinutes = getCandidateDurationMinutes(params.candidate);
3550
3765
  const candidateStartTime = getCandidateStartTime(params.candidate);
3551
- const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3766
+ const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !strictAvailability;
3552
3767
  const refreshedRanges = (0, _ResourcePlanner.getProductTimeRanges)(refreshedProjection, {
3553
3768
  productIds: [params.candidate.productId],
3554
3769
  dateRange: {
@@ -3569,6 +3784,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3569
3784
  } : {})
3570
3785
  } : {})
3571
3786
  }, {
3787
+ ...(strictAvailability ? {
3788
+ evaluatedAt: this.getAvailabilityRuntimeDateTime()
3789
+ } : {}),
3572
3790
  useExactDurationCandidateMinute: allowPosAvailabilityOverride,
3573
3791
  allowSessionCustomRanges: allowPosAvailabilityOverride,
3574
3792
  allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
@@ -3653,9 +3871,30 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3653
3871
  expectedOrderRevision: revalidationEntry.orderRevision
3654
3872
  };
3655
3873
  const refreshedCandidate = this.decorateAvailabilityCandidate(normalizedContextId, revalidatedContext.activeVersion, refreshedCandidateBase);
3874
+ // Order may await line/runtime setup. Its guarded transaction invokes this
3875
+ // again immediately before publishing, while the live cart is unchanged.
3876
+ const availabilityCommitGuard = hasCommitGuard ? () => {
3877
+ params.availabilityCommitGuard?.();
3878
+ this.assertAvailabilityCommitWriteCAS(commitWriteGuard);
3879
+ if (!availabilityCommitTargetGuard()) {
3880
+ throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '预约加购期间订单或业务已变化');
3881
+ }
3882
+ if (!strictAvailability) return;
3883
+ const currentValidation = (0, _ResourcePlanner.validateAvailabilitySelection)(refreshedProjection, {
3884
+ candidate: refreshedCandidateBase,
3885
+ requirementSelections: params.requirementSelections,
3886
+ partySize,
3887
+ bookingCount
3888
+ });
3889
+ if (!currentValidation.ok) {
3890
+ throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '所选时间在加购前已不可用,请重新选择', {
3891
+ validation: currentValidation
3892
+ });
3893
+ }
3894
+ } : undefined;
3656
3895
  const existingBooking = editingLine ? this.findLinkedBooking(editingLine) : undefined;
3657
3896
  const existingBookingUid = existingBooking ? getBookingUid(existingBooking) : '';
3658
- if (params.mode === 'edit' && !existingBookingUid) {
3897
+ if (isEditingSelection && !existingBookingUid) {
3659
3898
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', '编辑商品行缺少关联 booking', {
3660
3899
  productLineUid: params.productLineUid
3661
3900
  });
@@ -3667,9 +3906,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3667
3906
  product,
3668
3907
  resources: refreshedProjection.resources,
3669
3908
  bookingUid: existingBookingUid || undefined,
3670
- holder: params.orderProduct?._extend?.holder ?? existingBooking?.holder ?? existingBooking?.metadata?.holder,
3671
- holderIds: params.orderProduct?._extend?.holder_id ?? params.orderProduct?._extend?.holder?.form_record ?? existingBooking?.metadata?.holder_id ?? existingBooking?.holder?.form_record
3909
+ holder: params.orderProduct?._extend?.holder ?? (params.mode === 'replace' ? undefined : existingBooking?.holder ?? existingBooking?.metadata?.holder),
3910
+ holderIds: params.orderProduct?._extend?.holder_id ?? params.orderProduct?._extend?.holder?.form_record ?? (params.mode === 'replace' ? undefined : existingBooking?.metadata?.holder_id ?? existingBooking?.holder?.form_record)
3672
3911
  });
3912
+ if (params.mode === 'replace') {
3913
+ // A different product must not inherit the previous product/resource's completed forms.
3914
+ booking.holder = booking.holder || null;
3915
+ booking.relation_forms = [];
3916
+ }
3673
3917
  const transformed = this.buildUnifiedOrderProduct({
3674
3918
  ...params.orderProduct,
3675
3919
  num: bookingCount,
@@ -3686,13 +3930,43 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3686
3930
  unified_booking_sales: true,
3687
3931
  availability_candidate_key: refreshedCandidate.key,
3688
3932
  availability_context_id: normalizedContextId,
3689
- availability_context_version: refreshedCandidate.availabilityContextVersion
3933
+ availability_context_version: refreshedCandidate.availabilityContextVersion,
3934
+ ...(['tickets', 'party_main'].includes(transformed.metadata?.venue_booking_role) ? {
3935
+ venue_booking_service_datetime: `${booking.start_date} ${booking.start_time}`
3936
+ } : {})
3690
3937
  };
3691
3938
  let productLineUid = '';
3692
3939
  let bookingUid = '';
3693
3940
  let productLineUids = [];
3694
3941
  let bookingUids = [];
3695
- if (params.mode === 'edit' && editingLine && params.productLineUid) {
3942
+ if (isPartyReplacement && editingLine && params.productLineUid) {
3943
+ const relatedRetailProducts = params.relatedRetailProducts.map(source => {
3944
+ const line = this.buildUnifiedOrderProduct(source, 'unified_booking_sales_retail');
3945
+ if (!line) throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '无法生成附加商品订单行');
3946
+ // This is the only replacement-specific UID restore. Order checks ownership/collisions.
3947
+ const sourceUid = getProductLineUid(source);
3948
+ if (sourceUid) {
3949
+ line.metadata = {
3950
+ ...(line.metadata || {}),
3951
+ unique_identification_number: sourceUid
3952
+ };
3953
+ }
3954
+ return line;
3955
+ });
3956
+ await this.store.order.replaceBookingProductWithRelatedRetail({
3957
+ productLineUid: params.productLineUid,
3958
+ product: transformed,
3959
+ booking,
3960
+ relatedRetailProducts: relatedRetailProducts,
3961
+ availabilityCommitGuard: availabilityCommitGuard,
3962
+ availabilityCommitTargetGuard
3963
+ });
3964
+ guardedCommitPublished = true;
3965
+ productLineUid = params.productLineUid;
3966
+ bookingUid = existingBookingUid;
3967
+ productLineUids = [productLineUid];
3968
+ bookingUids = [bookingUid];
3969
+ } else if (params.mode === 'edit' && editingLine && params.productLineUid) {
3696
3970
  transformed.product_sku = transformed.product_sku ?? editingLine.product_sku;
3697
3971
  transformed.product_bundle = transformed.product_bundle ?? editingLine.product_bundle;
3698
3972
  transformed.booking_uid = existingBookingUid;
@@ -3702,7 +3976,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3702
3976
  unique_identification_number: params.productLineUid,
3703
3977
  booking_uid: existingBookingUid
3704
3978
  };
3705
- await this.updateOrderProduct({
3979
+ const update = {
3706
3980
  product_id: transformed.product_id ?? editingLine.product_id,
3707
3981
  product_variant_id: transformed.product_variant_id ?? editingLine.product_variant_id ?? 0,
3708
3982
  unique_identification_number: params.productLineUid,
@@ -3714,7 +3988,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3714
3988
  ...(params.allowBookingDiscountReapply !== undefined ? {
3715
3989
  allow_booking_discount_reapply: params.allowBookingDiscountReapply
3716
3990
  } : {})
3717
- });
3991
+ };
3992
+ if (availabilityCommitGuard) {
3993
+ await this.updateOrderProducts([update], {
3994
+ beforeApply: availabilityCommitGuard,
3995
+ isCurrentOrder: availabilityCommitTargetGuard
3996
+ });
3997
+ guardedCommitPublished = true;
3998
+ } else await this.updateOrderProduct(update);
3718
3999
  productLineUid = params.productLineUid;
3719
4000
  bookingUid = existingBookingUid;
3720
4001
  productLineUids = [productLineUid];
@@ -3722,12 +4003,20 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3722
4003
  } else {
3723
4004
  const beforeProductLineUids = new Set((this.getTempOrder()?.products || []).map(line => getProductLineUid(line)).filter(Boolean));
3724
4005
  const beforeBookingUids = new Set((this.getTempOrder()?.bookings || []).map(item => getBookingUid(item)).filter(Boolean));
3725
- const products = await this.addProductToOrder(transformed, booking, params.salesNotes?.length ? {
3726
- salesNotes: params.salesNotes
4006
+ availabilityCommitGuard?.();
4007
+ const products = await this.addProductToOrder(transformed, booking, params.salesNotes?.length || availabilityCommitGuard ? {
4008
+ ...(params.salesNotes?.length ? {
4009
+ salesNotes: params.salesNotes
4010
+ } : {}),
4011
+ ...(availabilityCommitGuard ? {
4012
+ availabilityCommitGuard,
4013
+ availabilityCommitTargetGuard
4014
+ } : {})
3727
4015
  } : undefined);
4016
+ guardedCommitPublished = hasCommitGuard;
3728
4017
  const addedLines = products.filter(line => sameAvailabilityId(line.product_id ?? line.id, refreshedCandidate.productId) && line.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeProductLineUids.has(getProductLineUid(line)));
3729
4018
  productLineUids = addedLines.map(line => getProductLineUid(line)).filter(Boolean);
3730
- const addedBookings = (this.getTempOrder()?.bookings || []).filter(item => item.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeBookingUids.has(getBookingUid(item)));
4019
+ const addedBookings = ((hasCommitGuard ? guardedOrder : this.getTempOrder())?.bookings || []).filter(item => item.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeBookingUids.has(getBookingUid(item)));
3731
4020
  bookingUids = addedBookings.map(item => getBookingUid(item)).filter(Boolean);
3732
4021
  if (bookingUids.length === 0) {
3733
4022
  bookingUids = addedLines.map(line => String(line.booking_uid ?? line.metadata?.booking_uid ?? '')).filter(Boolean);
@@ -3735,12 +4024,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3735
4024
  productLineUid = productLineUids[productLineUids.length - 1] || '';
3736
4025
  bookingUid = bookingUids[bookingUids.length - 1] || '';
3737
4026
  }
3738
- this.invalidateAvailabilityContextsAfterCommit();
3739
- const nextContext = this.getAvailabilityContextEntry(normalizedContextId);
4027
+ const targetStillCurrent = !hasCommitGuard || availabilityCommitTargetGuard();
4028
+ if (targetStillCurrent) this.invalidateAvailabilityContextsAfterCommit();else this.removeAvailabilityContext(normalizedContextId);
4029
+ const nextContext = hasCommitGuard ? this.availabilityContextRegistry.get(normalizedContextId) : this.getAvailabilityContextEntry(normalizedContextId);
3740
4030
  const result = {
3741
4031
  contextId: normalizedContextId,
3742
- contextVersion: nextContext.activeVersion,
3743
- tempOrder: this.getTempOrder(),
4032
+ contextVersion: nextContext?.activeVersion ?? refreshedCandidate.availabilityContextVersion,
4033
+ tempOrder: hasCommitGuard ? guardedOrder : this.getTempOrder(),
3744
4034
  validation,
3745
4035
  candidate: refreshedCandidate,
3746
4036
  productLineUid,
@@ -3748,10 +4038,19 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3748
4038
  productLineUids,
3749
4039
  bookingUids
3750
4040
  };
3751
- await this.core.effects.emit(`${this.name}:${_types.UnifiedBookingSalesHooks.onAvailabilitySelectionCommitted}`, result);
4041
+ if (targetStillCurrent) {
4042
+ // A notification failure after publication must not invite a duplicate add.
4043
+ const emit = () => this.core.effects.emit(`${this.name}:${_types.UnifiedBookingSalesHooks.onAvailabilitySelectionCommitted}`, result);
4044
+ if (guardedCommitPublished) {
4045
+ try {
4046
+ await emit();
4047
+ } catch {/* The cart mutation has already succeeded. */}
4048
+ } else await emit();
4049
+ }
3752
4050
  return result;
3753
4051
  } finally {
3754
- await this.releaseAvailabilityCommitLock(normalizedContextId);
4052
+ const release = this.releaseAvailabilityCommitLock(normalizedContextId);
4053
+ if (guardedCommitPublished) await release.catch(() => undefined);else await release;
3755
4054
  }
3756
4055
  }
3757
4056
  }