@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
@@ -49,6 +49,7 @@ Object.keys(_salesSettings).forEach(function (key) {
49
49
  });
50
50
  });
51
51
  var _getDateIsInSchedule = require("../../modules/Schedule/getDateIsInSchedule");
52
+ var _clientDataVariants = require("../../modules/ProductList/clientDataVariants");
52
53
  var _ResourcePlanner = require("../../modules/ResourcePlanner");
53
54
  var _types = require("./types");
54
55
  Object.keys(_types).forEach(function (key) {
@@ -63,7 +64,10 @@ Object.keys(_types).forEach(function (key) {
63
64
  });
64
65
  });
65
66
  var _remoteOccupancyCache = require("./remoteOccupancyCache");
67
+ var _sessionResourceCache = require("./sessionResourceCache");
66
68
  var _businessAvailability = require("./businessAvailability");
69
+ var _catalogQueryBatch = require("./catalogQueryBatch");
70
+ var _venueCatalogSession = require("./venueCatalogSession");
67
71
  var _BookingTicket = require("../BookingTicket");
68
72
  var _localClock = require("../../modules/ResourcePlanner/localClock");
69
73
  var _platform = require("../../utils/platform");
@@ -231,6 +235,7 @@ const MAX_AVAILABILITY_RANGE_DAYS = 90;
231
235
  const MAX_AVAILABILITY_CONTEXT_REGISTRY = 128;
232
236
  const MAX_AVAILABILITY_PROJECTION_POOL = 16;
233
237
  const MAX_REMOTE_OCCUPANCY_RESOURCE_DATE_CELLS = 4096;
238
+ const PREVIEW_OCCUPANCY_CACHE_MAX_AGE_MS = 30 * 1000;
234
239
  function isValidClockTime(value) {
235
240
  const match = /^(\d{2}):(\d{2})$/.exec(value);
236
241
  if (!match) return false;
@@ -1073,6 +1078,11 @@ function buildBookingFromAvailabilitySelection(params) {
1073
1078
  unified_booking_sales: true,
1074
1079
  availability_candidate_key: candidate.key,
1075
1080
  availability_source: candidate.source,
1081
+ availability_business_date: candidate.businessDate || candidate.date,
1082
+ availability_timezone: candidate.timezone,
1083
+ ...(candidate.primaryScheduleRef ? {
1084
+ availability_primary_schedule_ref: (0, _lodashEs.cloneDeep)(candidate.primaryScheduleRef)
1085
+ } : {}),
1076
1086
  availability_slice_start_at: candidate.startAt,
1077
1087
  availability_slice_end_at: candidate.endAt,
1078
1088
  availability_schedule_refs: candidate.scheduleRefs,
@@ -1233,8 +1243,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1233
1243
  runtimeOpenDataModule = null;
1234
1244
  runtimeOpenDataCore;
1235
1245
  runtimeOpenDataGeneration = 0;
1246
+ runtimeInitializationGeneration = 0;
1236
1247
  runtimeOpenDataDestroyed = false;
1237
1248
  unifiedProductCatalog = [];
1249
+ venueCatalogSessions = new Set();
1250
+ venueCatalogSessionKey;
1251
+ venueCatalogMenus;
1252
+ venueVariantDetails = new Map();
1238
1253
  availabilityRuntimeOffsetMinutes = null;
1239
1254
  availabilityScheduleCatalog = null;
1240
1255
  availabilityProjectionSequence = 0;
@@ -1245,6 +1260,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1245
1260
  availabilityPrepareInFlight = new Map();
1246
1261
  availabilityProjectionRefreshInFlight = new Map();
1247
1262
  availabilityRemoteOccupancyCache = new _remoteOccupancyCache.AvailabilityRemoteOccupancyCache(MAX_REMOTE_OCCUPANCY_RESOURCE_DATE_CELLS);
1263
+ availabilitySessionResourceCache = new _sessionResourceCache.AvailabilitySessionResourceCache();
1248
1264
  availabilityRemoteResourceQueryInFlight = new Map();
1249
1265
  availabilityRemoteResourceQuerySequence = 0;
1250
1266
  availabilityRemoteResourceEpoch = 0;
@@ -1253,15 +1269,24 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1253
1269
  allergyItemRuleConfigs = [];
1254
1270
  allergyItemRuleConfigsPromise = null;
1255
1271
  async initialize(core, options = {}) {
1272
+ const initializationGeneration = ++this.runtimeInitializationGeneration;
1256
1273
  this.resetRuntimeOpenData();
1257
1274
  this.runtimeOpenDataDestroyed = false;
1258
- const openDataGeneration = this.runtimeOpenDataGeneration;
1259
1275
  this.availabilityScheduleCatalog = null;
1260
1276
  this.availabilityRuntimeOffsetMinutes = (0, _localClock.captureRuntimeOffsetMinutes)();
1261
1277
  this.clearAvailabilityRemoteResourceState();
1262
1278
  this.resetAllergyItemRuleState();
1263
- await super.initialize(core, options);
1264
- if (this.runtimeOpenDataDestroyed || openDataGeneration !== this.runtimeOpenDataGeneration) {
1279
+ // BaseSales synchronously installs this runtime before its first await. Cache
1280
+ // refreshes during that await are valid; they are not a new initialization.
1281
+ const initialization = super.initialize(core, options);
1282
+ const scope = this.getRuntimeOpenDataScope();
1283
+ const openDataModule = this.store.openData;
1284
+ await initialization;
1285
+ if (this.runtimeOpenDataDestroyed || initializationGeneration !== this.runtimeInitializationGeneration) {
1286
+ // A destroyed/reinitialized instance must not publish a ready snapshot.
1287
+ return;
1288
+ }
1289
+ if (core !== this.core || openDataModule !== this.store.openData || scope !== this.getRuntimeOpenDataScope()) {
1265
1290
  throw new Error('Store settings changed. Please try again.');
1266
1291
  }
1267
1292
  this.captureAvailabilityScheduleCatalog();
@@ -1537,6 +1562,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1537
1562
  clearAvailabilityRemoteResourceState() {
1538
1563
  this.availabilityRemoteResourceEpoch += 1;
1539
1564
  this.availabilityRemoteOccupancyCache.clear();
1565
+ this.availabilitySessionResourceCache.clear();
1540
1566
  this.availabilityRemoteResourceQueryInFlight.clear();
1541
1567
  this.availabilityRemoteResourceQuerySequence = 0;
1542
1568
  }
@@ -1588,6 +1614,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1588
1614
  }
1589
1615
  }
1590
1616
  async destroy() {
1617
+ this.runtimeInitializationGeneration += 1;
1591
1618
  this.runtimeOpenDataDestroyed = true;
1592
1619
  this.clearOpenDataCache();
1593
1620
  this.availabilityScheduleCatalog = null;
@@ -2431,6 +2458,529 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2431
2458
  * product because session products carry their fixed intervals there.
2432
2459
  */
2433
2460
  async loadProducts(params = {}, options) {
2461
+ const result = await this.loadCatalogProducts(params, options);
2462
+ this.unifiedProductCatalog = Array.isArray(result) ? [...result] : [];
2463
+ await this.core.effects.emit(`${this.name}:onProductsLoaded`, result);
2464
+ return result;
2465
+ }
2466
+
2467
+ /**
2468
+ * Queries one explicitly configured menu scope without publishing the sales catalog.
2469
+ * The returned graph is detached from ProductList's shared ID cache. Callers own its
2470
+ * membership and must requery/reprice with the service datetime after a context change.
2471
+ * Missing/invalid menu configuration fails closed instead of querying every product.
2472
+ */
2473
+ async queryCatalogSnapshot(params) {
2474
+ if (!Array.isArray(params.menu_list_ids) || params.menu_list_ids.length === 0 || params.menu_list_ids.some(id => !Number.isInteger(id) || id <= 0)) {
2475
+ return [];
2476
+ }
2477
+ const {
2478
+ product_ids,
2479
+ ...scopeParams
2480
+ } = (0, _lodashEs.cloneDeep)(params);
2481
+ // The OS Server ID-query branch intentionally bypasses menus. Apply IDs only after
2482
+ // querying the configured menu so an isolated scope cannot leak other products.
2483
+ const result = await this.loadCatalogProducts({
2484
+ ...scopeParams,
2485
+ menu_list_ids: [...new Set(params.menu_list_ids)]
2486
+ });
2487
+ const list = Array.isArray(result) ? result : [];
2488
+ return (0, _lodashEs.cloneDeep)(product_ids?.length ? list.filter(product => product_ids.some(id => Number(id) === Number(product.id))) : list);
2489
+ }
2490
+
2491
+ /** Full SKU/bundle detail, after verifying membership in the explicit day/menu scope. */
2492
+ async queryCatalogProductDetail(params) {
2493
+ return this.loadCatalogProductDetail(params, query => this.queryCatalogSnapshot(query));
2494
+ }
2495
+ isVenueCatalogLocalPricingActive() {
2496
+ return this.venueCatalogSessions.size > 0;
2497
+ }
2498
+ getVenueCatalogLocalPriceSource(productId, selectedProduct) {
2499
+ const scope = this.getRuntimeOpenDataScope();
2500
+ const role = selectedProduct?.metadata?.venue_booking_role;
2501
+ const poolRole = role === 'party_extra' || role === 'tickets_extra' ? 'extras' : role === 'party_main' || role === 'tickets' ? 'main' : undefined;
2502
+ const matches = Array.from(this.venueCatalogSessions).filter(entry => entry.scope === scope && entry.generation === this.runtimeInitializationGeneration && (!poolRole || entry.role === poolRole) && entry.pool?.products.some(row => Number(row.id) === productId));
2503
+ if (!matches.length) return undefined;
2504
+ const pool = matches[0].pool;
2505
+ const product = this.getVenueCatalogHydratedProduct(pool.products.find(row => Number(row.id) === productId));
2506
+ // Legacy promotion/gift inputs may have no venue role. Equivalent complete
2507
+ // sources are unambiguous; different pool snapshots must never use Set order.
2508
+ if (matches.slice(1).some(entry => !(0, _lodashEs.isEqual)(product, this.getVenueCatalogHydratedProduct(entry.pool.products.find(row => Number(row.id) === productId))) || !(0, _lodashEs.isEqual)(pool.pricingMenus, entry.pool.pricingMenus))) return undefined;
2509
+ return {
2510
+ product: (0, _lodashEs.cloneDeep)(product),
2511
+ menuList: (0, _lodashEs.cloneDeep)(pool.pricingMenus)
2512
+ };
2513
+ }
2514
+ async getProductByIds(ids, options) {
2515
+ const active = this.isVenueCatalogLocalPricingActive();
2516
+ const products = await super.getProductByIds(ids, active ? {
2517
+ loadMissing: false
2518
+ } : options);
2519
+ return active ? products.map(product => this.getVenueCatalogHydratedProduct(product)) : products;
2520
+ }
2521
+ getVenueCatalogHydratedProduct(product) {
2522
+ const variants = this.venueVariantDetails.get(Number(product.id ?? product.product_id))?.data;
2523
+ return variants ? {
2524
+ ...(0, _lodashEs.cloneDeep)(product),
2525
+ variant: (0, _lodashEs.cloneDeep)(variants)
2526
+ } : (0, _lodashEs.cloneDeep)(product);
2527
+ }
2528
+
2529
+ /** Explicit user opening for legacy promotion/gift SKU hosts. Pure readers never call this. */
2530
+ async prepareVenueCatalogProductDetail(params) {
2531
+ if (!this.isVenueCatalogLocalPricingActive()) throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_REQUIRED', 'Open a venue catalog before configuring this product.');
2532
+ const owner = this.venueCatalogSessionKey;
2533
+ const scope = this.getRuntimeOpenDataScope();
2534
+ const generation = this.runtimeInitializationGeneration;
2535
+ const source = this.getVenueCatalogLocalPriceSource(params.product_id);
2536
+ if (!source) return undefined;
2537
+ await this.hydrateVenueVariantDetail(source.product, params);
2538
+ if (this.runtimeOpenDataDestroyed || !this.isVenueCatalogLocalPricingActive() || owner !== this.venueCatalogSessionKey || scope !== this.getRuntimeOpenDataScope() || generation !== this.runtimeInitializationGeneration) {
2539
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_STALE', 'The venue catalog changed while loading product options.');
2540
+ }
2541
+ return this.getVenueCatalogHydratedProduct(source.product);
2542
+ }
2543
+ async hydrateVenueVariantDetail(raw, params) {
2544
+ // is_variant is the backend's explicit gate. Ordinary retail never requests detail.
2545
+ if (Number(raw.is_variant) !== 1) return;
2546
+ const count = Number(raw.variant_count) || 0;
2547
+ if (Array.isArray(raw.variant) && raw.variant.length > 0 && raw.variant.length >= count) return;
2548
+ const productId = Number(raw.id ?? raw.product_id);
2549
+ let entry = this.venueVariantDetails.get(productId);
2550
+ if (entry?.failed && params.retry === true) {
2551
+ this.venueVariantDetails.delete(productId);
2552
+ entry = undefined;
2553
+ }
2554
+ if (!entry) {
2555
+ const owner = this.venueCatalogSessionKey;
2556
+ const scope = this.getRuntimeOpenDataScope();
2557
+ const generation = this.runtimeInitializationGeneration;
2558
+ const core = this.core;
2559
+ const request = this.request;
2560
+ const next = {
2561
+ promise: Promise.resolve([])
2562
+ };
2563
+ const assertCurrent = () => {
2564
+ if (this.runtimeOpenDataDestroyed || !this.isVenueCatalogLocalPricingActive() || owner !== this.venueCatalogSessionKey || scope !== this.getRuntimeOpenDataScope() || generation !== this.runtimeInitializationGeneration || core !== this.core || request !== this.request || this.venueVariantDetails.get(productId) !== next) {
2565
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_STALE', 'The venue catalog changed while loading product options.');
2566
+ }
2567
+ };
2568
+ this.venueVariantDetails.set(productId, next);
2569
+ next.promise = Promise.resolve().then(async () => {
2570
+ assertCurrent();
2571
+ const response = await request.get(`/product/show/${productId}`, {
2572
+ open_bundle: 1,
2573
+ with_schedule: 1,
2574
+ is_eject: 1,
2575
+ with: [..._clientDataVariants.PRODUCT_QUERY_DATA_VARIANT_RELATIONS]
2576
+ }, {
2577
+ useCache: false,
2578
+ customToast: () => {}
2579
+ });
2580
+ assertCurrent();
2581
+ if (response?.status === false || response?.code != null && Number(response.code) !== 200) {
2582
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_VARIANT_DETAIL_FAILED', response?.message || 'Product options could not be loaded.');
2583
+ }
2584
+ const detail = response?.data?.item ?? response?.data;
2585
+ if (Number(detail?.id ?? detail?.product_id) !== productId || !Array.isArray(detail?.variant) || !detail.variant.length || detail.variant.length < count) {
2586
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_VARIANT_DETAIL_INCOMPLETE', 'Complete product variants are unavailable. Please retry.');
2587
+ }
2588
+ const variants = detail.variant.map(value => {
2589
+ const variant = (0, _lodashEs.cloneDeep)(value);
2590
+ const original = variant._dataVariant?.original;
2591
+ const evaluated = variant._dataVariant || Array.isArray(variant.metadata?.data_variant_ids);
2592
+ const basePrice = original?.price ?? original?.base_price ?? variant.base_price ?? (evaluated ? undefined : variant.price);
2593
+ if (!Number.isSafeInteger(Number(variant.id)) || Number(variant.id) <= 0 || basePrice === undefined || basePrice === null || basePrice === '' || !Number.isFinite(Number(basePrice))) {
2594
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_VARIANT_DETAIL_INCOMPLETE', 'The base price for a product variant is unavailable.');
2595
+ }
2596
+ // Copy only combination SKU data. The pool's price/data_variants and
2597
+ // pricing metadata remain its original baseline for every later context.
2598
+ variant.price = basePrice;
2599
+ variant.base_price = basePrice;
2600
+ if (variant.selling_price !== undefined) variant.selling_price = basePrice;
2601
+ delete variant._dataVariant;
2602
+ if (variant.metadata) delete variant.metadata.data_variant_ids;
2603
+ return variant;
2604
+ });
2605
+ next.data = variants;
2606
+ for (const pool of this.venueCatalogSessions) {
2607
+ if (pool.scope !== scope || !pool.pool) continue;
2608
+ const product = pool.pool.products.find(row => Number(row.id) === productId);
2609
+ if (!product) continue;
2610
+ const hydrated = this.getVenueCatalogHydratedProduct(product);
2611
+ this.store.products?.rememberRawProductQueryResult?.([(0, _lodashEs.cloneDeep)(hydrated)]);
2612
+ this.store.products?.addProduct?.([(0, _lodashEs.cloneDeep)(hydrated)]);
2613
+ }
2614
+ return variants;
2615
+ }).catch(error => {
2616
+ next.failed = true;
2617
+ throw error;
2618
+ });
2619
+ entry = next;
2620
+ }
2621
+ await entry.promise;
2622
+ }
2623
+
2624
+ /** One complete raw product query per explicitly configured pool for this page lifetime. */
2625
+ createVenueCatalogSession(params) {
2626
+ if (!(0, _platform.isCustomerUserPlatform)(this.otherParams?.platform)) {
2627
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_PLATFORM_UNSUPPORTED', 'Venue catalog sessions require a customer platform.');
2628
+ }
2629
+ const ids = params.menu_list_ids;
2630
+ if (!Array.isArray(ids) || !ids.length || ids.some(id => !Number.isSafeInteger(id) || id <= 0)) {
2631
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_MENU_REQUIRED', 'Choose an explicit menu for this venue product pool.');
2632
+ }
2633
+ const menuIds = [...new Set(ids)].sort((a, b) => a - b);
2634
+ const scope = this.getRuntimeOpenDataScope();
2635
+ const generation = this.runtimeInitializationGeneration;
2636
+ const core = this.core;
2637
+ const request = this.request;
2638
+ const entry = {
2639
+ scope,
2640
+ generation,
2641
+ role: params.poolRole
2642
+ };
2643
+ const sessionKey = JSON.stringify([scope, generation, params.sessionKey ?? null]);
2644
+ if (!this.venueCatalogSessions.size || sessionKey !== this.venueCatalogSessionKey) {
2645
+ // React may create new page pools before disposing the old page's pools.
2646
+ // The explicit session identity prevents reusing old-order occupancy then.
2647
+ this.venueCatalogSessions.clear();
2648
+ this.venueCatalogSessionKey = sessionKey;
2649
+ this.venueCatalogMenus = undefined;
2650
+ this.venueVariantDetails.clear();
2651
+ this.availabilitySessionResourceCache.clear();
2652
+ }
2653
+ this.venueCatalogSessions.add(entry);
2654
+ const assertCurrent = () => {
2655
+ if (!this.venueCatalogSessions.has(entry)) {
2656
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_DISPOSED', 'The venue catalog session is closed.');
2657
+ }
2658
+ if (this.runtimeOpenDataDestroyed || this.core !== core || this.request !== request || generation !== this.runtimeInitializationGeneration || scope !== this.getRuntimeOpenDataScope()) {
2659
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_STALE', 'The venue store context changed. Reopen the booking page.');
2660
+ }
2661
+ };
2662
+ const now = () => {
2663
+ const timezone = String(this.otherParams?.businessTimezone || this.getPickupTimingContextData('timezone') || '').trim();
2664
+ if (!timezone) throw (0, _venueCatalogSession.venueCatalogError)('VENUE_TIMEZONE_REQUIRED', 'The venue timezone is not ready.');
2665
+ const parts = new Intl.DateTimeFormat('en-GB', {
2666
+ timeZone: timezone,
2667
+ year: 'numeric',
2668
+ month: '2-digit',
2669
+ day: '2-digit',
2670
+ hour: '2-digit',
2671
+ minute: '2-digit',
2672
+ second: '2-digit',
2673
+ hourCycle: 'h23'
2674
+ }).formatToParts(new Date());
2675
+ const part = type => parts.find(item => item.type === type)?.value;
2676
+ return `${part('year')}-${part('month')}-${part('day')} ${part('hour')}:${part('minute')}:${part('second')}`;
2677
+ };
2678
+ const snapshot = (pool, input) => {
2679
+ assertCurrent();
2680
+ if (input.menu_list_ids && JSON.stringify([...new Set(input.menu_list_ids)].sort((a, b) => a - b)) !== JSON.stringify(menuIds)) {
2681
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_MENU_SCOPE_CHANGED', 'This catalog session belongs to another menu.');
2682
+ }
2683
+ const current = now();
2684
+ const datetime = input.schedule_datetime || (input.schedule_date ? `${input.schedule_date} ${current.slice(11)}` : current);
2685
+ if (!(0, _localClock.parseLocalDateTime)(datetime.replace('T', ' ')) || input.schedule_date && datetime.slice(0, 10) !== input.schedule_date) {
2686
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_DATETIME_INVALID', 'Choose a valid venue catalog date and time.');
2687
+ }
2688
+ const menus = (0, _venueCatalogSession.activeVenueMenus)(pool.menus, this.getAvailabilityScheduleCatalog(), datetime, Boolean(input.schedule_date && !input.schedule_datetime));
2689
+ let products = pool.products.filter(product => menus.some(menu => (0, _venueCatalogSession.productMatchesVenueMenu)(product, menu))).map(product => this.getVenueCatalogHydratedProduct(product));
2690
+ if (input.product_ids?.length) products = products.filter(product => input.product_ids.some(id => Number(id) === Number(product.id)));
2691
+ const user = this.core.getPlugin?.('user');
2692
+ const queryPayload = {
2693
+ schedule_date: datetime.slice(0, 10),
2694
+ schedule_datetime: datetime,
2695
+ customer_id: input.customer_id ?? this.getTempOrder()?.customer_id ?? user?.get?.()?.id,
2696
+ strategy_context: {
2697
+ ...this.getPriceQueryStrategyContext(),
2698
+ ...(input.strategy_context || {})
2699
+ }
2700
+ };
2701
+ const result = (0, _clientDataVariants.tryResolveClientDataVariants)({
2702
+ core: this.core,
2703
+ otherParams: this.otherParams,
2704
+ products: (0, _lodashEs.cloneDeep)(products),
2705
+ queryPayload,
2706
+ handledByOsServer: false,
2707
+ scheduleList: this.getAvailabilityScheduleCatalog(),
2708
+ menuList: pool.pricingMenus
2709
+ });
2710
+ if (result.status !== 'resolved' && result.status !== 'empty') {
2711
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_LOCAL_PRICE_UNAVAILABLE', 'Complete product pricing rules are not ready. Please retry.');
2712
+ }
2713
+ return result.products.slice().sort((a, b) => Number(b.sort || 0) - Number(a.sort || 0));
2714
+ };
2715
+ return (0, _venueCatalogSession.createVenueCatalogSessionAdapter)({
2716
+ assertCurrent,
2717
+ load: async () => {
2718
+ if (!this.venueCatalogMenus || this.venueCatalogMenus.scope !== scope) {
2719
+ const promise = request.get('/form/data/v1', {
2720
+ skip: 1,
2721
+ num: 999,
2722
+ code: 'menu_list'
2723
+ }, {
2724
+ useCache: false,
2725
+ customToast: () => {}
2726
+ }).then(response => (0, _venueCatalogSession.readVenueCatalogList)(response, 'Venue menus'));
2727
+ this.venueCatalogMenus = {
2728
+ scope,
2729
+ promise
2730
+ };
2731
+ void promise.catch(() => {
2732
+ if (this.venueCatalogMenus?.promise === promise) this.venueCatalogMenus = undefined;
2733
+ });
2734
+ }
2735
+ const pricingMenus = await this.venueCatalogMenus.promise;
2736
+ const menus = (0, _venueCatalogSession.validateVenueMenus)(pricingMenus, menuIds);
2737
+ assertCurrent();
2738
+ // A menu query with a date may exclude future members. Read the raw ID union
2739
+ // without menu/time/customer pricing filters, then filter collection/all menus locally.
2740
+ const onlyIds = menus.every(menu => menu.partyroom_package.type === 'products');
2741
+ const onlyCollections = menus.every(menu => menu.partyroom_package.type === 'product_collection');
2742
+ const productIds = onlyIds ? [...new Set(menus.flatMap(menu => menu.partyroom_package.products.map(product => Number(product.product_id))))] : undefined;
2743
+ const collections = onlyCollections ? [...new Set(menus.flatMap(menu => menu.partyroom_package.products.map(product => String(product.product_collection_id))))] : undefined;
2744
+ const products = onlyIds && !productIds?.length ? [] : await this.store.products.loadVenueCatalogPool({
2745
+ product_ids: productIds,
2746
+ collection: collections,
2747
+ category_ids: params.category_ids,
2748
+ extension_type: params.extension_type,
2749
+ cacheId: this.cacheId
2750
+ });
2751
+ assertCurrent();
2752
+ const pool = {
2753
+ menus,
2754
+ pricingMenus: (0, _lodashEs.cloneDeep)(pricingMenus),
2755
+ products: products.filter(product => menus.some(menu => (0, _venueCatalogSession.productMatchesVenueMenu)(product, menu)))
2756
+ };
2757
+ entry.pool = (0, _lodashEs.cloneDeep)(pool);
2758
+ // Legacy marketing lookups can reuse complete records without changing
2759
+ // either pool's membership or publishing a replacement sales catalog.
2760
+ this.store.products.rememberRawProductQueryResult((0, _lodashEs.cloneDeep)(pool.products));
2761
+ this.store.products.addProduct((0, _lodashEs.cloneDeep)(pool.products));
2762
+ return pool;
2763
+ },
2764
+ snapshot,
2765
+ prepareDetail: async (pool, query) => {
2766
+ const raw = pool.products.find(product => Number(product.id) === Number(query.product_id));
2767
+ if (raw) await this.hydrateVenueVariantDetail(raw, query);
2768
+ assertCurrent();
2769
+ },
2770
+ quote: async (pool, query) => {
2771
+ const product = query.product;
2772
+ const productId = Number(product?.product_id ?? product?.id);
2773
+ const booking = query.booking;
2774
+ const datetime = booking?.start_date ? `${booking.start_date} ${booking.start_time || '00:00:00'}` : query.datetime || now();
2775
+ if (!snapshot(pool, {
2776
+ product_ids: [productId],
2777
+ schedule_datetime: datetime,
2778
+ customer_id: query.customer_id == null ? undefined : Number(query.customer_id)
2779
+ }).length) {
2780
+ throw (0, _venueCatalogSession.venueCatalogError)('VENUE_PRODUCT_UNAVAILABLE', 'This product is unavailable in the selected menu at this time.');
2781
+ }
2782
+ const raw = pool.products.find(row => Number(row.id) === productId);
2783
+ if (!raw) throw (0, _venueCatalogSession.venueCatalogError)('VENUE_PRODUCT_UNAVAILABLE', 'This product is not in the venue catalog.');
2784
+ const result = await this.calculateVenueCatalogProductBookingPrice({
2785
+ ...query,
2786
+ datetime
2787
+ }, {
2788
+ product: this.getVenueCatalogHydratedProduct(raw),
2789
+ menuList: pool.pricingMenus
2790
+ });
2791
+ assertCurrent();
2792
+ return result;
2793
+ },
2794
+ onRetry: () => {
2795
+ for (const [id, detail] of this.venueVariantDetails) if (detail.failed) this.venueVariantDetails.delete(id);
2796
+ },
2797
+ onDispose: () => {
2798
+ this.venueCatalogSessions.delete(entry);
2799
+ if (!this.venueCatalogSessions.size) {
2800
+ this.venueCatalogSessionKey = undefined;
2801
+ this.venueCatalogMenus = undefined;
2802
+ this.venueVariantDetails.clear();
2803
+ this.availabilitySessionResourceCache.clear();
2804
+ }
2805
+ }
2806
+ });
2807
+ }
2808
+
2809
+ /**
2810
+ * Opt-in calendar/card preview batching. Results expire after sixty seconds or a
2811
+ * runtime change; the next read starts a fresh clock/cache. Selection and submit
2812
+ * must keep using the ordinary fresh query methods. Call dispose on owner cleanup.
2813
+ */
2814
+ createCatalogQueryBatch() {
2815
+ return (0, _catalogQueryBatch.createCatalogQueryBatchAdapter)({
2816
+ runtime: () => {
2817
+ if (this.runtimeOpenDataDestroyed) throw new Error('The booking service is closed.');
2818
+ const user = this.core.getPlugin?.('user');
2819
+ const productParams = this.store.products?.otherParams || this.otherParams || {};
2820
+ const fatherModule = String(productParams.fatherModule || '').trim();
2821
+ const schedule = (fatherModule ? this.core.getModule?.(`${fatherModule}_schedule`) : null) || this.core.getModule?.('schedule');
2822
+ const evaluator = this.core.context?.dataVariantEvaluator;
2823
+ // OpenData hydration is not a catalog input. Its temporary null/reload cycle
2824
+ // must not expire a batch while a parallel preview reads sales settings.
2825
+ const {
2826
+ openData: _openData,
2827
+ ...otherParams
2828
+ } = this.otherParams || {};
2829
+ const {
2830
+ openData: _productOpenData,
2831
+ ...productOtherParams
2832
+ } = productParams;
2833
+ return {
2834
+ references: [this.core, this.request, this.store.products, this.core.server, user, this.appPlugin, this.core.getPlugin?.('request'), this.core.getPlugin?.('app'), schedule, evaluator],
2835
+ values: {
2836
+ initialization: this.runtimeInitializationGeneration,
2837
+ scope: this.getRuntimeOpenDataScope(),
2838
+ requestBaseUrl: this.request.baseUrl,
2839
+ customerId: user?.get?.()?.id,
2840
+ otherParams,
2841
+ productOtherParams
2842
+ },
2843
+ refreshValues: {
2844
+ scheduleList: schedule?.getScheduleList?.(),
2845
+ contextScheduleList: this.core.context?.scheduleList,
2846
+ contextMenuList: this.core.context?.menuList,
2847
+ strategyConfigs: evaluator?.getStrategyConfigs?.()
2848
+ }
2849
+ };
2850
+ },
2851
+ normalize: (params, now) => {
2852
+ const date = params.schedule_date || (0, _dayjs.default)(now).format('YYYY-MM-DD');
2853
+ const user = this.core.getPlugin?.('user');
2854
+ const explicitCustomer = params.customer_id;
2855
+ if (explicitCustomer != null && (!Number.isSafeInteger(Number(explicitCustomer)) || Number(explicitCustomer) <= 0)) {
2856
+ throw new Error('Catalog query customer_id must be a positive integer.');
2857
+ }
2858
+ const fallbackCustomer = user?.get?.()?.id;
2859
+ const customer = explicitCustomer ?? (Number.isSafeInteger(Number(fallbackCustomer)) && Number(fallbackCustomer) > 0 ? Number(fallbackCustomer) : undefined);
2860
+ const productParams = this.store.products?.otherParams || this.otherParams || {};
2861
+ const channelMap = {
2862
+ online_store: 'online-store',
2863
+ scan_to_order: 'online-store',
2864
+ 'scan-to-order': 'online-store',
2865
+ scan_to_order_2: 'online-store',
2866
+ scan_to_order_3: 'scantoorder3'
2867
+ };
2868
+ const channel = channelMap[productParams.channel] || productParams.channel;
2869
+ const businessCode = productParams.businessCode ?? productParams.business_code;
2870
+ const sorted = items => [...new Set(items)].sort((a, b) => String(a).localeCompare(String(b)));
2871
+ return {
2872
+ ...params,
2873
+ menu_list_ids: Array.isArray(params.menu_list_ids) ? sorted(params.menu_list_ids) : params.menu_list_ids,
2874
+ category_ids: sorted(params.category_ids || []),
2875
+ collection: Array.isArray(params.collection) ? sorted(params.collection) : params.collection,
2876
+ extension_type: params.extension_type ? sorted(params.extension_type) : undefined,
2877
+ with_count: sorted(params.with_count ?? ['bundleGroup', 'optionGroup']),
2878
+ with_schedule: params.with_schedule ?? 1,
2879
+ status: params.status ?? 'published',
2880
+ schedule_date: date,
2881
+ schedule_datetime: params.schedule_datetime || `${date} ${(0, _dayjs.default)(now).format('HH:mm:ss')}`,
2882
+ customer_id: customer == null ? undefined : Number(customer),
2883
+ strategy_context: {
2884
+ ...(channel ? {
2885
+ channel
2886
+ } : {}),
2887
+ ...(businessCode ? {
2888
+ business_code: businessCode
2889
+ } : {}),
2890
+ ...(params.strategy_context || {})
2891
+ }
2892
+ };
2893
+ },
2894
+ key: params => JSON.stringify(stableValue(params)),
2895
+ snapshot: params => this.queryCatalogSnapshot(params),
2896
+ detail: (params, snapshot) => this.loadCatalogProductDetail(params, snapshot)
2897
+ });
2898
+ }
2899
+ async loadCatalogProductDetail(params, loadSnapshot) {
2900
+ const {
2901
+ product_id,
2902
+ product_ids: _ignoredIds,
2903
+ ...catalogParams
2904
+ } = (0, _lodashEs.cloneDeep)(params);
2905
+ if (!Number.isInteger(product_id) || product_id <= 0) return undefined;
2906
+ const schedule_date = catalogParams.schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD');
2907
+ const schedule_datetime = catalogParams.schedule_datetime || `${schedule_date} ${(0, _dayjs.default)().format('HH:mm:ss')}`;
2908
+ const scopedParams = {
2909
+ ...catalogParams,
2910
+ schedule_date,
2911
+ schedule_datetime
2912
+ };
2913
+ const member = (await loadSnapshot(scopedParams)).find(item => Number(item.id) === product_id);
2914
+ if (!member) return undefined;
2915
+ const baseUrl = String(this.request.baseUrl || ((0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) ? '/h5' : '/shop')).replace(/\/+$/, '');
2916
+ const localPath = `/product/query/${product_id}`;
2917
+ const handledByOsServer = this.core.server?.hasRoute?.('get', `${baseUrl}${localPath}`) === true;
2918
+ const channelMap = {
2919
+ online_store: 'online-store',
2920
+ scan_to_order: 'online-store',
2921
+ 'scan-to-order': 'online-store',
2922
+ scan_to_order_2: 'online-store',
2923
+ scan_to_order_3: 'scantoorder3'
2924
+ };
2925
+ const channel = channelMap[this.otherParams?.channel] || this.otherParams?.channel;
2926
+ const businessCode = this.otherParams?.businessCode ?? this.otherParams?.business_code;
2927
+ const strategy_context = {
2928
+ ...(channel ? {
2929
+ channel
2930
+ } : {}),
2931
+ ...(businessCode ? {
2932
+ business_code: businessCode
2933
+ } : {}),
2934
+ ...(scopedParams.strategy_context || {})
2935
+ };
2936
+ let customerId = scopedParams.customer_id;
2937
+ if (customerId == null) customerId = this.core.getPlugin?.('user')?.get?.()?.id;
2938
+ const queryPayload = {
2939
+ ...scopedParams,
2940
+ customer_id: customerId,
2941
+ strategy_context,
2942
+ application_code: channel,
2943
+ is_eject: 1,
2944
+ open_bundle: 1,
2945
+ with_schedule: 1,
2946
+ with: [..._clientDataVariants.PRODUCT_QUERY_DATA_VARIANT_RELATIONS],
2947
+ ...((0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) ? {} : {
2948
+ open_quotation: 1
2949
+ })
2950
+ };
2951
+ const response = await this.request.get(baseUrl === '/shop' ? localPath : `/product/show/${product_id}`, queryPayload, {
2952
+ osServer: true,
2953
+ useCache: false,
2954
+ customToast: () => {}
2955
+ });
2956
+ if (response?.status === false || Number(response?.code) >= 400) throw new Error('[UnifiedBookingSales] Product detail query failed');
2957
+ const raw = response?.data?.item ?? response?.data;
2958
+ if (!raw || Number(raw.id ?? raw.product_id) !== product_id) return undefined;
2959
+ if (raw.status && raw.status !== 'published') return undefined;
2960
+ if (!handledByOsServer) this.store.products?.rememberRawProductQueryResult?.([(0, _lodashEs.cloneDeep)(raw)]);
2961
+ const resolved = (0, _clientDataVariants.resolveClientDataVariants)({
2962
+ core: this.core,
2963
+ otherParams: this.otherParams,
2964
+ products: [(0, _lodashEs.cloneDeep)(raw)],
2965
+ queryPayload,
2966
+ handledByOsServer
2967
+ })[0];
2968
+ // Detail owns relation arrays. Never synthesize empty groups from list counts.
2969
+ if (!resolved) return undefined;
2970
+ const detail = {
2971
+ ...member,
2972
+ ...resolved,
2973
+ metadata: {
2974
+ ...(member.metadata || {}),
2975
+ ...(resolved.metadata || {})
2976
+ }
2977
+ };
2978
+ for (const key of ['bundle_group', 'bundle_groups', 'option_group', 'variant_group', 'variant']) {
2979
+ if (!Object.prototype.hasOwnProperty.call(resolved, key)) delete detail[key];
2980
+ }
2981
+ return (0, _lodashEs.cloneDeep)(detail);
2982
+ }
2983
+ async loadCatalogProducts(params = {}, options) {
2434
2984
  if (!this.store.products) throw new Error('[UnifiedBookingSales] products 模块未初始化');
2435
2985
  const catalogScope = this.otherParams.catalogScopeKey;
2436
2986
  const schedule_date = params.schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD');
@@ -2448,8 +2998,6 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2448
2998
  name: 'AbortError'
2449
2999
  });
2450
3000
  }
2451
- this.unifiedProductCatalog = Array.isArray(result) ? [...result] : [];
2452
- await this.core.effects.emit(`${this.name}:onProductsLoaded`, result);
2453
3001
  return result;
2454
3002
  }
2455
3003
  async queryProducts(params = {}) {
@@ -2656,10 +3204,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2656
3204
  } : {})
2657
3205
  });
2658
3206
  if (orderProduct && typeof orderProduct === 'object') {
3207
+ 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]]));
2659
3208
  // BaseSales may rebuild metadata from its price source. Stamp ownership and the selected
2660
3209
  // quotation shelf after that transform so neither booking adds nor edits lose quote identity.
2661
3210
  orderProduct.metadata = {
2662
3211
  ...(orderProduct.metadata || {}),
3212
+ ...venueMetadata,
2663
3213
  [ownershipKey]: true,
2664
3214
  ...(hasDurationQuote || quoteMethod === 'fixed_price' ? {
2665
3215
  pricing_method: {
@@ -2717,6 +3267,11 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2717
3267
  return this.stageProducts(params, 'unified_booking_sales_retail');
2718
3268
  }
2719
3269
 
3270
+ /** Explicit capability: order-scoped Tickets extras use guarded writes without implicit SKU merging. */
3271
+ supportsVenueTicketExtras() {
3272
+ return true;
3273
+ }
3274
+
2720
3275
  /**
2721
3276
  * Adds one retail line without replacing the cart's existing retail selection.
2722
3277
  * This is intentionally separate from stageRetailProducts(), whose contract is
@@ -2749,7 +3304,81 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2749
3304
  if (!orderProduct) {
2750
3305
  throw new Error('[UnifiedBookingSales] 无法生成零售商品订单行');
2751
3306
  }
2752
- return this.addProductToOrder(orderProduct);
3307
+ if (orderProduct.metadata?.venue_booking_role === 'tickets_extra') {
3308
+ const order = this.getTempOrder();
3309
+ const meta = orderProduct.metadata;
3310
+ const scopeKey = String(meta.venue_booking_scope_key || '');
3311
+ const purchaseDatetime = String(meta.venue_booking_service_datetime || '');
3312
+ const identity = [order?.order_id, order?.external_sale_number, order?.customer_id];
3313
+ const isCurrentOrder = () => this.getTempOrder() === order && order?.order_id === identity[0] && order?.external_sale_number === identity[1] && order?.customer_id === identity[2];
3314
+ const guard = () => {
3315
+ params.availabilityCommitGuard?.();
3316
+ if (!isCurrentOrder() || !order || order.order_id || !scopeKey || meta.venue_booking_parent_uid || orderProduct.booking_uid || meta.booking_uid || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?$/.test(purchaseDatetime) || !(0, _dayjs.default)(purchaseDatetime).isValid() || !(order.products || []).some(line => line.metadata?.venue_booking_role === 'tickets' && line.metadata?.venue_booking_scope_key === scopeKey)) {
3317
+ throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '门票订单或购买时间已变化,请重新确认附加商品');
3318
+ }
3319
+ };
3320
+ guard();
3321
+ // Retail extras are order-owned, with their own UID and no Holder/booking.
3322
+ delete orderProduct.unique_identification_number;
3323
+ delete meta.unique_identification_number;
3324
+ delete meta.venue_booking_parent_uid;
3325
+ orderProduct.holder_config = {
3326
+ status: 'disable',
3327
+ required: 0
3328
+ };
3329
+ meta.holder_config = {
3330
+ status: 'disable',
3331
+ required: 0
3332
+ };
3333
+ return this.addProductToOrder(orderProduct, undefined, {
3334
+ disableMerge: true,
3335
+ availabilityCommitGuard: guard,
3336
+ availabilityCommitTargetGuard: isCurrentOrder,
3337
+ salesNotes: params.salesNotes
3338
+ });
3339
+ }
3340
+ if (orderProduct.metadata?.venue_booking_role === 'party_extra') {
3341
+ const order = this.getTempOrder();
3342
+ const meta = orderProduct.metadata;
3343
+ const parentUid = String(meta.venue_booking_parent_uid || '');
3344
+ const scopeKey = String(meta.venue_booking_scope_key || '');
3345
+ // The persisted legacy key holds this retail extra's venue-local purchase quote time.
3346
+ // Its parent UID owns the extra; the parent's appointment time does not price it.
3347
+ const purchaseDatetime = String(meta.venue_booking_service_datetime || '');
3348
+ const normalizedPurchaseDatetime = purchaseDatetime.length === 16 ? `${purchaseDatetime}:00` : purchaseDatetime;
3349
+ const identity = [order?.order_id, order?.external_sale_number];
3350
+ const isCurrentOrder = () => this.getTempOrder() === order && order?.order_id === identity[0] && order?.external_sale_number === identity[1];
3351
+ const guard = () => {
3352
+ params.availabilityCommitGuard?.();
3353
+ const parent = (order?.products || []).find(line => getProductLineUid(line) === parentUid);
3354
+ if (!isCurrentOrder() || !order || order.order_id || !parentUid || !scopeKey || parent?.metadata?.venue_booking_role !== 'party_main' || parent?.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) throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'Party 主商品或附加商品报价上下文已变化,请重新确认附加商品');
3355
+ };
3356
+ guard();
3357
+ delete orderProduct.unique_identification_number;
3358
+ delete orderProduct.metadata.unique_identification_number;
3359
+ orderProduct.holder_config = {
3360
+ status: 'disable',
3361
+ required: 0
3362
+ };
3363
+ orderProduct.metadata.holder_config = {
3364
+ status: 'disable',
3365
+ required: 0
3366
+ };
3367
+ return this.addProductToOrder(orderProduct, undefined, {
3368
+ disableMerge: true,
3369
+ availabilityCommitGuard: guard,
3370
+ availabilityCommitTargetGuard: isCurrentOrder,
3371
+ salesNotes: params.salesNotes
3372
+ });
3373
+ }
3374
+ return this.addProductToOrder(orderProduct, undefined, {
3375
+ ...(params.availabilityCommitGuard ? {
3376
+ availabilityCommitGuard: params.availabilityCommitGuard
3377
+ } : {}),
3378
+ ...(params.salesNotes ? {
3379
+ salesNotes: params.salesNotes
3380
+ } : {})
3381
+ });
2753
3382
  }
2754
3383
  normalizeAvailabilityDateRange(params, timezone) {
2755
3384
  const today = (0, _localClock.formatLocalDate)((0, _localClock.localDateToScalar)(new Date()));
@@ -2795,6 +3424,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2795
3424
  };
2796
3425
  }
2797
3426
  assertAvailabilityPrepareParams(params) {
3427
+ if (params.occupancyCachePolicy !== undefined && params.occupancyCachePolicy !== 'cache_first' && params.occupancyCachePolicy !== 'session') {
3428
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Unknown occupancyCachePolicy');
3429
+ }
2798
3430
  assertAvailabilityCatalogProductIds(params.productIds, 'prepare.productIds');
2799
3431
  const hasProductAnchor = Array.isArray(params.productIds) && params.productIds.length > 0;
2800
3432
  const hasResourceAnchor = Array.isArray(params.resourceIds) && params.resourceIds.length > 0;
@@ -2804,8 +3436,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2804
3436
  params
2805
3437
  });
2806
3438
  }
2807
- if (!hasProductAnchor && !params.catalogScope) {
2808
- throw new _ResourcePlanner.AvailabilityError('MISSING_CATALOG_SCOPE', '缺少 productIds 时必须提供 catalogScope', {
3439
+ if (!hasProductAnchor && !params.catalogScope && !Array.isArray(params.rawProducts)) {
3440
+ throw new _ResourcePlanner.AvailabilityError('MISSING_CATALOG_SCOPE', '缺少 productIds 时必须提供 catalogScope 或 rawProducts', {
2809
3441
  params
2810
3442
  });
2811
3443
  }
@@ -2922,12 +3554,15 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2922
3554
  dateRange
2923
3555
  } = params;
2924
3556
  const explicitProductIds = prepare.productIds || [];
3557
+ const publishCatalog = prepare.publishCatalog !== false;
3558
+ const loadProducts = query => publishCatalog ? this.loadProducts(query) : prepare.catalogScope?.type === 'productList' ? this.queryCatalogSnapshot(query) : this.loadCatalogProducts(query);
2925
3559
  let rawProducts = [];
2926
3560
  if (Array.isArray(prepare.rawProducts)) {
2927
3561
  rawProducts = prepare.rawProducts;
2928
- this.unifiedProductCatalog = [...rawProducts];
3562
+ if (publishCatalog) this.unifiedProductCatalog = [...rawProducts];
2929
3563
  } else if (explicitProductIds.length > 0) {
2930
- rawProducts = await this.loadProducts({
3564
+ rawProducts = await loadProducts({
3565
+ ...(!publishCatalog && prepare.catalogScope?.type === 'productList' ? prepare.catalogScope.params : {}),
2931
3566
  product_ids: explicitProductIds,
2932
3567
  schedule_date: dateRange.startDate
2933
3568
  });
@@ -2943,15 +3578,15 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2943
3578
  const productIds = uniqueAvailabilityIds([...scheduleProductIds, ...(this.store.schedule.getOtherProductsIds?.() || [])]);
2944
3579
  if (productIds.length > 0) {
2945
3580
  assertAvailabilityCatalogProductIds(productIds, 'prepare.catalogScope.scheduleProductIds');
2946
- rawProducts = await this.loadProducts({
3581
+ rawProducts = await loadProducts({
2947
3582
  product_ids: productIds,
2948
3583
  schedule_date: dateRange.startDate
2949
3584
  });
2950
3585
  } else {
2951
- this.unifiedProductCatalog = [];
3586
+ if (publishCatalog) this.unifiedProductCatalog = [];
2952
3587
  }
2953
3588
  } else if (prepare.catalogScope?.type === 'productList') {
2954
- rawProducts = await this.loadProducts({
3589
+ rawProducts = await loadProducts({
2955
3590
  ...prepare.catalogScope.params,
2956
3591
  schedule_date: prepare.catalogScope.params.schedule_date || dateRange.startDate
2957
3592
  });
@@ -2979,10 +3614,72 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2979
3614
  useCache: false
2980
3615
  });
2981
3616
  const data = response?.data;
3617
+ if (params.strictResponse && response?.status === false) {
3618
+ const message = response?.message;
3619
+ throw Object.assign(new Error(typeof message === 'string' && message.trim() ? message : 'Unable to load booking resource details.'), {
3620
+ code: response?.code
3621
+ });
3622
+ }
2982
3623
  if (Array.isArray(data)) return data;
2983
3624
  if (Array.isArray(data?.list)) return data.list;
3625
+ if (params.strictResponse) {
3626
+ throw new Error('Booking resource details returned an invalid response.');
3627
+ }
2984
3628
  return [];
2985
3629
  }
3630
+
3631
+ /** Fresh read-only metadata for confirmation forms/policies; does not create a projection or mutate BookingContext. */
3632
+ async queryBookingResourceDetails(params) {
3633
+ const date = params?.date;
3634
+ try {
3635
+ if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error('date');
3636
+ (0, _localClock.parseLocalDate)(date);
3637
+ } catch {
3638
+ throw this.createAvailabilityFacadeError('INVALID_DATE_RANGE', 'A valid booking date is required to load resource details.');
3639
+ }
3640
+ if (!Array.isArray(params?.resourceIds) || !params.resourceIds.length || params.resourceIds.some(id => !['number', 'string'].includes(typeof id) || !/^\d+$/.test(String(id)) || !Number.isSafeInteger(Number(id)) || Number(id) <= 0)) {
3641
+ throw this.createAvailabilityFacadeError('INVALID_TARGET_FILTER', 'Selected resource IDs are required to load resource details.');
3642
+ }
3643
+ const resourceIds = [...new Set(params.resourceIds.map(id => String(Number(id))))];
3644
+ const core = this.core;
3645
+ const request = this.request;
3646
+ const generation = this.runtimeInitializationGeneration;
3647
+ const scope = this.getRuntimeOpenDataScope();
3648
+ const assertCurrent = () => {
3649
+ if (this.runtimeOpenDataDestroyed || !request || core !== this.core || request !== this.request || generation !== this.runtimeInitializationGeneration || scope !== this.getRuntimeOpenDataScope()) {
3650
+ throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'Booking settings changed. Please reload the resource details.');
3651
+ }
3652
+ };
3653
+ assertCurrent();
3654
+ const resourceQuery = {
3655
+ dateRange: {
3656
+ startDate: date,
3657
+ endDate: date
3658
+ },
3659
+ resourceIds
3660
+ };
3661
+ // Match normalizeAvailabilityPrepareDescriptor so confirmation reuses exactly
3662
+ // the same resource/date coverage as the selection projection.
3663
+ const timezone = String(this.otherParams?.businessTimezone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai').trim();
3664
+ const resources = this.isVenueCatalogLocalPricingActive() ? await this.availabilitySessionResourceCache.load({
3665
+ scopeKey: `${scope}:${this.buildAvailabilityRemoteResourceScopeKey(timezone)}`,
3666
+ timezoneName: timezone,
3667
+ ...resourceQuery,
3668
+ fetch: query => this.fetchAvailabilityResourcesV2({
3669
+ ...query,
3670
+ strictResponse: true
3671
+ })
3672
+ }) : await this.fetchAvailabilityResourcesV2({
3673
+ ...resourceQuery,
3674
+ strictResponse: true
3675
+ });
3676
+ assertCurrent();
3677
+ const byId = new Map(resources.filter(isRecord).map(resource => [String(resource.id), resource]));
3678
+ if (resourceIds.some(id => !byId.has(id))) {
3679
+ throw this.createAvailabilityFacadeError('INVALID_TARGET_FILTER', 'A selected booking resource is no longer available.');
3680
+ }
3681
+ return (0, _lodashEs.cloneDeep)(resourceIds.map(id => byId.get(id)));
3682
+ }
2986
3683
  async fetchAndPublishAvailabilityResourcesV2(params) {
2987
3684
  const normalizedResourceIds = this.normalizeAvailabilityIdList(params.resourceIds) || [];
2988
3685
  if (normalizedResourceIds.length === 0) return [];
@@ -2990,7 +3687,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2990
3687
  const cacheParams = {
2991
3688
  scopeKey,
2992
3689
  resourceIds: normalizedResourceIds,
2993
- dateRange: params.dateRange
3690
+ dateRange: params.dateRange,
3691
+ maxAgeMs: params.maxAgeMs
2994
3692
  };
2995
3693
  const cachedRawResources = this.availabilityRemoteOccupancyCache.read(cacheParams);
2996
3694
  if (cachedRawResources) {
@@ -3005,6 +3703,22 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3005
3703
  }
3006
3704
  return cachedRawResources;
3007
3705
  }
3706
+ if (params.maxAgeMs !== undefined) {
3707
+ // A visible-month request can cover a concurrent day/resource-subset preview.
3708
+ // Only share fully covering requests; partial overlaps keep the normal fetch path.
3709
+ const epoch = this.availabilityRemoteResourceEpoch;
3710
+ const covering = Array.from(this.availabilityRemoteResourceQueryInFlight.values()).find(entry => entry.epoch === epoch && entry.scopeKey === scopeKey && entry.dateRange.startDate <= params.dateRange.startDate && entry.dateRange.endDate >= params.dateRange.endDate && normalizedResourceIds.every(id => entry.resourceIds.some(other => String(other) === String(id))));
3711
+ if (covering) {
3712
+ await covering.promise;
3713
+ if (epoch !== this.availabilityRemoteResourceEpoch) {
3714
+ throw this.createAvailabilityFacadeError('AVAILABILITY_CONTEXT_NOT_FOUND', 'Resource settings changed while loading. Please prepare again.');
3715
+ }
3716
+ // Read a detached, correctly sliced graph after publication. A newer overlapping
3717
+ // response may have invalidated cells, in which case fetch this exact range below.
3718
+ const coveredResources = this.availabilityRemoteOccupancyCache.read(cacheParams);
3719
+ if (coveredResources) return coveredResources;
3720
+ }
3721
+ }
3008
3722
  return await this.refreshAvailabilityRemoteResourceQuery({
3009
3723
  timezone: params.timezone,
3010
3724
  dateRange: params.dateRange,
@@ -3026,19 +3740,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3026
3740
  }
3027
3741
  this.availabilityRemoteResourceQuerySequence += 1;
3028
3742
  const writeVersion = this.availabilityRemoteResourceQuerySequence;
3743
+ const scopeKey = this.buildAvailabilityRemoteResourceScopeKey(params.timezone);
3029
3744
  const promise = this.fetchAvailabilityResourcesV2({
3030
3745
  dateRange: params.dateRange,
3031
3746
  resourceIds: normalizedResourceIds
3032
- });
3033
- this.availabilityRemoteResourceQueryInFlight.set(queryKey, {
3034
- epoch,
3035
- promise
3036
- });
3037
- try {
3038
- const rawResources = await promise;
3747
+ }).then(rawResources => {
3039
3748
  if (epoch === this.availabilityRemoteResourceEpoch) {
3040
3749
  this.availabilityRemoteOccupancyCache.publish({
3041
- scopeKey: this.buildAvailabilityRemoteResourceScopeKey(params.timezone),
3750
+ scopeKey,
3042
3751
  timezoneName: params.timezone,
3043
3752
  resourceIds: normalizedResourceIds,
3044
3753
  dateRange: params.dateRange,
@@ -3047,6 +3756,18 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3047
3756
  });
3048
3757
  }
3049
3758
  return rawResources;
3759
+ });
3760
+ this.availabilityRemoteResourceQueryInFlight.set(queryKey, {
3761
+ epoch,
3762
+ scopeKey,
3763
+ dateRange: {
3764
+ ...params.dateRange
3765
+ },
3766
+ resourceIds: [...normalizedResourceIds],
3767
+ promise
3768
+ });
3769
+ try {
3770
+ return await promise;
3050
3771
  } finally {
3051
3772
  const current = this.availabilityRemoteResourceQueryInFlight.get(queryKey);
3052
3773
  if (current?.promise === promise) {
@@ -3062,7 +3783,25 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3062
3783
  resourceOccupancies: []
3063
3784
  };
3064
3785
  }
3065
- if (Array.isArray(params.rawResources)) {
3786
+ if (params.fetchPolicy === 'session') {
3787
+ const rawResources = await this.availabilitySessionResourceCache.load({
3788
+ scopeKey: `${this.getRuntimeOpenDataScope()}:${this.buildAvailabilityRemoteResourceScopeKey(params.timezone)}`,
3789
+ timezoneName: params.timezone,
3790
+ resourceIds,
3791
+ dateRange: params.dateRange,
3792
+ fetch: query => this.fetchAvailabilityResourcesV2({
3793
+ ...query,
3794
+ strictResponse: true
3795
+ })
3796
+ });
3797
+ return buildAvailabilityResourcesFromV2({
3798
+ rawResources,
3799
+ scheduleList: params.scheduleList,
3800
+ dateRange: params.dateRange,
3801
+ fixedOffsetMinutes: this.getAvailabilityRuntimeOffsetMinutes()
3802
+ });
3803
+ }
3804
+ if (Array.isArray(params.rawResources) && params.fetchPolicy !== 'refresh') {
3066
3805
  return buildAvailabilityResourcesFromV2({
3067
3806
  rawResources: params.rawResources,
3068
3807
  scheduleList: params.scheduleList,
@@ -3089,11 +3828,17 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3089
3828
  resourceOccupancies: []
3090
3829
  };
3091
3830
  }
3092
- const rawResources = await this.fetchAndPublishAvailabilityResourcesV2({
3831
+ const remoteQuery = {
3093
3832
  timezone: params.timezone,
3094
3833
  dateRange: params.dateRange,
3095
- resourceIds,
3096
- useCacheOnHit: true
3834
+ resourceIds
3835
+ };
3836
+ const rawResources = params.fetchPolicy === 'refresh' ? await this.refreshAvailabilityRemoteResourceQuery(remoteQuery) : await this.fetchAndPublishAvailabilityResourcesV2({
3837
+ ...remoteQuery,
3838
+ useCacheOnHit: params.fetchPolicy !== 'cache_first',
3839
+ ...(params.fetchPolicy === 'cache_first' ? {
3840
+ maxAgeMs: PREVIEW_OCCUPANCY_CACHE_MAX_AGE_MS
3841
+ } : {})
3097
3842
  });
3098
3843
  return buildAvailabilityResourcesFromV2({
3099
3844
  rawResources,
@@ -3327,7 +4072,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3327
4072
  products,
3328
4073
  rawResources: normalizedPrepareParams.rawResources,
3329
4074
  scheduleList,
3330
- fetchPolicy: options.resourceFetchPolicy || 'default',
4075
+ // Explicit Venue sessions retain physical occupancy coverage across preview,
4076
+ // selection and commit. Cart-derived occupancy is still rebuilt below.
4077
+ fetchPolicy: normalizedPrepareParams.occupancyCachePolicy === 'session' ? 'session' : options.resourceFetchPolicy || (normalizedPrepareParams.refreshOccupancies ? 'refresh' : normalizedPrepareParams.occupancyCachePolicy === 'cache_first' ? 'cache_first' : 'default'),
3331
4078
  fallbackResources: options.fallbackResources
3332
4079
  });
3333
4080
  const tempOrder = this.getTempOrder();
@@ -3612,6 +4359,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3612
4359
  projectionEntry
3613
4360
  } = await this.ensureAvailabilityContextProjection(contextId, 'get_product_time_ranges');
3614
4361
  const contextVersion = context.activeVersion;
4362
+ const strictAvailability = context.prepareParams.strictAvailability === true;
3615
4363
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3616
4364
  const isEditingContext = Boolean(context.prepareParams.editingProductLineUids?.length);
3617
4365
  const editingOffset = (0, _localClock.extractFixedOffsetMinutes)(projectionEntry.projection.meta.now) ?? this.getAvailabilityRuntimeOffsetMinutes();
@@ -3639,7 +4387,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3639
4387
  }
3640
4388
  const rememberedTimeByProductId = this.resolveOrderRememberedTimes(context, projectionEntry.projection, request.rememberedTimeByProductId, request.orderSessionId);
3641
4389
  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));
4390
+ const allowOutsideOperatingHoursForRequestedStartTimes = isPosAvailabilityRequest && !strictAvailability && !rememberedStartAtByProductId && !rememberedTimeByProductId && (editingStarts.length > 0 || Object.values(request.durationStartTimesByProductId || {}).some(startTimes => Array.isArray(startTimes) && startTimes.length > 0));
3643
4391
  return (0, _ResourcePlanner.getProductTimeRanges)(projectionEntry.projection, {
3644
4392
  ...request,
3645
4393
  dateRange,
@@ -3651,15 +4399,18 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3651
4399
  } : {}),
3652
4400
  ...(allowOutsideOperatingHoursForRequestedStartTimes ? {
3653
4401
  allowOutsideOperatingHoursForRequestedStartTimes: true
4402
+ } : {}),
4403
+ ...(strictAvailability ? {
4404
+ allowOutsideOperatingHoursForRequestedStartTimes: false
3654
4405
  } : {})
3655
4406
  }, {
3656
4407
  evaluatedAt: this.getAvailabilityRuntimeDateTime(),
3657
4408
  useDurationTimeGrid: this.usesDurationTimeGrid(projectionEntry.projection),
3658
- enforceSaleCutoff: Boolean(rememberedStartAtByProductId || rememberedTimeByProductId),
4409
+ enforceSaleCutoff: strictAvailability || Boolean(rememberedStartAtByProductId || rememberedTimeByProductId),
3659
4410
  rememberedTimeByProductId,
3660
- useExactDurationCandidateMinute: isPosAvailabilityRequest,
3661
- allowSessionCustomRanges: isPosAvailabilityRequest,
3662
- allowExcludedScheduleDateOverride: isPosAvailabilityRequest
4411
+ useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
4412
+ allowSessionCustomRanges: isPosAvailabilityRequest && !strictAvailability,
4413
+ allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
3663
4414
  }).map(group => ({
3664
4415
  ...group,
3665
4416
  ranges: group.ranges.map(candidate => this.decorateAvailabilityCandidate(context.contextId, contextVersion, candidate))
@@ -3674,6 +4425,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3674
4425
  refreshed
3675
4426
  } = await this.ensureAvailabilityContextProjection(contextId, 'query_booking_availability');
3676
4427
  this.assertContextualQueryFreshness(context, request);
4428
+ const strictAvailability = context.prepareParams.strictAvailability === true;
3677
4429
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3678
4430
  const rememberedTimeByProductId = request.selectionIntent === 'remembered' ? this.resolveOrderRememberedTimes(context, projectionEntry.projection, request.rememberedTimeByProductId, request.orderSessionId) : undefined;
3679
4431
  const queryRequest = request.target === 'date' || request.target === 'product' ? {
@@ -3682,10 +4434,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3682
4434
  } : request;
3683
4435
  const result = (0, _ResourcePlanner.queryAvailabilityProjection)(projectionEntry.projection, queryRequest, {
3684
4436
  useDurationTimeGrid: this.usesDurationTimeGrid(projectionEntry.projection),
3685
- enforceSaleCutoff: isPosAvailabilityRequest && !context.prepareParams.editingProductLineUids?.length && request.selectionIntent === 'remembered',
4437
+ enforceSaleCutoff: strictAvailability || isPosAvailabilityRequest && !context.prepareParams.editingProductLineUids?.length && request.selectionIntent === 'remembered',
3686
4438
  rememberedTimeByProductId,
3687
- useExactDurationCandidateMinute: isPosAvailabilityRequest,
3688
- allowExcludedScheduleDateOverride: isPosAvailabilityRequest
4439
+ useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
4440
+ allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
3689
4441
  });
3690
4442
  const contextVersion = context.activeVersion;
3691
4443
  const contextualResult = result.target === 'time' ? {
@@ -3719,6 +4471,20 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3719
4471
  refreshed
3720
4472
  };
3721
4473
  }
4474
+
4475
+ /** Reads detached resource metadata from the current context; never refreshes or performs I/O. */
4476
+ getAvailabilityResources(contextId, expectedVersion) {
4477
+ const context = this.getAvailabilityContextEntry(contextId);
4478
+ const entry = this.getActiveAvailabilityProjectionEntry(context);
4479
+ if (!entry || entry.contextVersion !== context.activeVersion || entry.orderRevision !== this.getCurrentOrderRevision() || expectedVersion !== undefined && context.activeVersion !== expectedVersion) {
4480
+ throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '资源上下文已变化,请重新查询当前候选', {
4481
+ contextId,
4482
+ expectedVersion,
4483
+ currentContextVersion: context.activeVersion
4484
+ });
4485
+ }
4486
+ return (0, _lodashEs.cloneDeep)([...entry.projection.resources]);
4487
+ }
3722
4488
  releaseAvailabilityContext(contextId) {
3723
4489
  const context = this.availabilityContextRegistry.get(contextId);
3724
4490
  if (!context) return;
@@ -3790,12 +4556,18 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3790
4556
  candidate: params.candidate
3791
4557
  });
3792
4558
  }
4559
+ const isEditingSelection = params.mode === 'edit' || params.mode === 'replace';
4560
+ const isPartyReplacement = params.mode === 'replace' || params.relatedRetailProducts !== undefined;
4561
+ if (isPartyReplacement && (!isEditingSelection || !Array.isArray(params.relatedRetailProducts))) {
4562
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Party replacement requires edit/replace mode and the confirmed complete extras array');
4563
+ }
3793
4564
  const isRememberedSelection = params.selectionIntent === 'remembered';
3794
4565
  const isOrderRememberedSelection = isRememberedSelection && params.orderSessionId !== undefined;
3795
4566
  if (isRememberedSelection && (String(this.otherParams?.platform ?? '').trim().toLowerCase() !== 'pos' || params.mode !== 'add')) {
3796
4567
  throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间自动提交仅支持 POS 新增 duration 商品');
3797
4568
  }
3798
- const hasCommitGuard = isRememberedSelection || Boolean(params.availabilityCommitGuard);
4569
+ const strictAvailability = this.availabilityContextRegistry.get(normalizedContextId)?.prepareParams.strictAvailability === true;
4570
+ const hasCommitGuard = strictAvailability || isRememberedSelection || isPartyReplacement || Boolean(params.availabilityCommitGuard);
3799
4571
  params.availabilityCommitGuard?.();
3800
4572
  // Stabilize the locally generated sale identity before taking the guard snapshot.
3801
4573
  if (hasCommitGuard) this.store.order?.ensureTempOrder?.();
@@ -3823,7 +4595,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3823
4595
  bookingCount: params.bookingCount
3824
4596
  });
3825
4597
  }
3826
- if (params.mode === 'edit' && bookingCount !== 1) {
4598
+ if (isEditingSelection && bookingCount !== 1) {
3827
4599
  throw new _ResourcePlanner.AvailabilityError('INVALID_RESERVATION_QUANTITY', '编辑预约商品时 bookingCount 必须为 1', {
3828
4600
  bookingCount
3829
4601
  });
@@ -3854,7 +4626,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3854
4626
  });
3855
4627
  }
3856
4628
  const boundEditingUids = context.prepareParams.editingProductLineUids || [];
3857
- if (params.mode === 'edit') {
4629
+ if (isEditingSelection) {
3858
4630
  if (!params.productLineUid || !boundEditingUids.includes(String(params.productLineUid))) {
3859
4631
  throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'edit context 与当前商品行不匹配,请重新 prepare 编辑上下文', {
3860
4632
  contextId: normalizedContextId,
@@ -3898,16 +4670,16 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3898
4670
  candidateProductId: params.candidate.productId
3899
4671
  });
3900
4672
  }
3901
- if (params.mode === 'edit' && !params.productLineUid) {
4673
+ if (isEditingSelection && !params.productLineUid) {
3902
4674
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', 'edit 模式必须提供 productLineUid');
3903
4675
  }
3904
- const editingLine = params.mode === 'edit' ? this.findProductLineByUid(String(params.productLineUid)) : undefined;
3905
- if (params.mode === 'edit' && !editingLine) {
4676
+ const editingLine = isEditingSelection ? this.findProductLineByUid(String(params.productLineUid)) : undefined;
4677
+ if (isEditingSelection && !editingLine) {
3906
4678
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', '找不到要编辑的预约商品行', {
3907
4679
  productLineUid: params.productLineUid
3908
4680
  });
3909
4681
  }
3910
- if (editingLine && !sameAvailabilityId(editingLine.product_id ?? editingLine.id, params.candidate.productId)) {
4682
+ if (editingLine && params.mode !== 'replace' && !sameAvailabilityId(editingLine.product_id ?? editingLine.id, params.candidate.productId)) {
3911
4683
  throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '编辑商品行与 candidate 商品不一致', {
3912
4684
  productLineUid: params.productLineUid,
3913
4685
  productLineProductId: editingLine.product_id ?? editingLine.id,
@@ -3942,7 +4714,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3942
4714
  };
3943
4715
  const commitSnapshot = await this.buildAvailabilityProjectionSnapshot({
3944
4716
  ...this.cloneAvailabilityPrepareParams(prepareParams),
3945
- editingProductLineUids: params.mode === 'edit' && params.productLineUid ? [params.productLineUid] : []
4717
+ editingProductLineUids: isEditingSelection && params.productLineUid ? [params.productLineUid] : []
3946
4718
  }, {
3947
4719
  resourceFetchPolicy: 'cache_only',
3948
4720
  fallbackResources,
@@ -3969,7 +4741,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3969
4741
  this.assertAvailabilityCommitWriteCAS(commitWriteGuard);
3970
4742
  const candidateDurationMinutes = getCandidateDurationMinutes(params.candidate);
3971
4743
  const candidateStartTime = getCandidateStartTime(params.candidate);
3972
- const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !isRememberedSelection;
4744
+ const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !isRememberedSelection && !strictAvailability;
3973
4745
  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
4746
  const rememberedTimeByProductId = isOrderRememberedSelection ? this.resolveOrderRememberedTimes(context, refreshedProjection, {
3975
4747
  [String(params.candidate.productId)]: {
@@ -3998,7 +4770,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3998
4770
  durationMinutesByProductId: {
3999
4771
  [String(params.candidate.productId)]: candidateDurationMinutes
4000
4772
  },
4001
- ...(params.mode === 'edit' && selectedProduct?.kind === 'duration' ? {
4773
+ ...(isEditingSelection && selectedProduct?.kind === 'duration' ? {
4002
4774
  editingStartAtByProductId: {
4003
4775
  [String(params.candidate.productId)]: params.candidate.bookingStartAt
4004
4776
  }
@@ -4015,7 +4787,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4015
4787
  }, {
4016
4788
  evaluatedAt: this.getAvailabilityRuntimeDateTime(),
4017
4789
  useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
4018
- enforceSaleCutoff: isRememberedSelection,
4790
+ enforceSaleCutoff: strictAvailability || isRememberedSelection,
4019
4791
  rememberedTimeByProductId,
4020
4792
  useExactDurationCandidateMinute: allowPosAvailabilityOverride,
4021
4793
  allowSessionCustomRanges: allowPosAvailabilityOverride,
@@ -4042,7 +4814,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4042
4814
  bookingCount
4043
4815
  }, {
4044
4816
  useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
4045
- enforceSaleCutoff: isRememberedSelection,
4817
+ enforceSaleCutoff: strictAvailability || isRememberedSelection,
4046
4818
  rememberedTimeByProductId,
4047
4819
  useExactDurationCandidateMinute: allowPosAvailabilityOverride,
4048
4820
  allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
@@ -4115,26 +4887,26 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4115
4887
  // Same-order immutable snapshots and generated sale IDs preserve the session.
4116
4888
  // Capture the actual object Order is about to publish, not an earlier snapshot.
4117
4889
  if (isOrderRememberedSelection) rememberedOrder = this.getTempOrder();
4118
- if (!isRememberedSelection) return;
4890
+ if (!isRememberedSelection && !strictAvailability) return;
4119
4891
  const currentValidation = (0, _ResourcePlanner.validateAvailabilitySelection)(refreshedProjection, {
4120
4892
  candidate: refreshedCandidateBase,
4121
4893
  requirementSelections: params.requirementSelections,
4122
4894
  partySize,
4123
4895
  bookingCount
4124
4896
  }, {
4125
- useDurationTimeGrid: true,
4897
+ useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
4126
4898
  enforceSaleCutoff: true,
4127
4899
  rememberedTimeByProductId
4128
4900
  });
4129
4901
  if (!currentValidation.ok) {
4130
- throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '记忆时间在加购前已不可用,请重新选择', {
4902
+ throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '所选时间在加购前已不可用,请重新选择', {
4131
4903
  validation: currentValidation
4132
4904
  });
4133
4905
  }
4134
4906
  } : undefined;
4135
4907
  const existingBooking = editingLine ? this.findLinkedBooking(editingLine) : undefined;
4136
4908
  const existingBookingUid = existingBooking ? getBookingUid(existingBooking) : '';
4137
- if (params.mode === 'edit' && !existingBookingUid) {
4909
+ if (isEditingSelection && !existingBookingUid) {
4138
4910
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', '编辑商品行缺少关联 booking', {
4139
4911
  productLineUid: params.productLineUid
4140
4912
  });
@@ -4146,9 +4918,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4146
4918
  product,
4147
4919
  resources: refreshedProjection.resources,
4148
4920
  bookingUid: existingBookingUid || undefined,
4149
- holder: params.orderProduct?._extend?.holder ?? existingBooking?.holder ?? existingBooking?.metadata?.holder,
4150
- holderIds: params.orderProduct?._extend?.holder_id ?? params.orderProduct?._extend?.holder?.form_record ?? existingBooking?.metadata?.holder_id ?? existingBooking?.holder?.form_record
4921
+ holder: params.orderProduct?._extend?.holder ?? (params.mode === 'replace' ? undefined : existingBooking?.holder ?? existingBooking?.metadata?.holder),
4922
+ holderIds: params.orderProduct?._extend?.holder_id ?? params.orderProduct?._extend?.holder?.form_record ?? (params.mode === 'replace' ? undefined : existingBooking?.metadata?.holder_id ?? existingBooking?.holder?.form_record)
4151
4923
  });
4924
+ if (params.mode === 'replace') {
4925
+ // A different product must not inherit the previous product/resource's completed forms.
4926
+ booking.holder = booking.holder || null;
4927
+ booking.relation_forms = [];
4928
+ }
4152
4929
  if (isRememberedSelection && params.orderProduct?._extend?.resource) {
4153
4930
  // AutoClose 与编辑共用旧资源协议。仅复用其结构,实际资源及每份容量
4154
4931
  // 必须与本次严格校验结果一致;时间、Holder 和校验元数据仍使用上面的结果。
@@ -4182,13 +4959,53 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4182
4959
  unified_booking_sales: true,
4183
4960
  availability_candidate_key: refreshedCandidate.key,
4184
4961
  availability_context_id: normalizedContextId,
4185
- availability_context_version: refreshedCandidate.availabilityContextVersion
4962
+ availability_context_version: refreshedCandidate.availabilityContextVersion,
4963
+ ...(['tickets', 'party_main'].includes(transformed.metadata?.venue_booking_role) ? {
4964
+ venue_booking_service_datetime: `${booking.start_date} ${booking.start_time}`
4965
+ } : {})
4186
4966
  };
4187
4967
  let productLineUid = '';
4188
4968
  let bookingUid = '';
4189
4969
  let productLineUids = [];
4190
4970
  let bookingUids = [];
4191
- if (params.mode === 'edit' && editingLine && params.productLineUid) {
4971
+ if (isPartyReplacement && editingLine && params.productLineUid) {
4972
+ const relatedRetailProducts = params.relatedRetailProducts.map(source => {
4973
+ const line = this.buildUnifiedOrderProduct(source, 'unified_booking_sales_retail');
4974
+ if (!line) throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '无法生成附加商品订单行');
4975
+ if (line.metadata?.venue_booking_role === 'party_extra') {
4976
+ line.holder_config = {
4977
+ status: 'disable',
4978
+ required: 0
4979
+ };
4980
+ line.metadata.holder_config = {
4981
+ status: 'disable',
4982
+ required: 0
4983
+ };
4984
+ }
4985
+ // This is the only replacement-specific UID restore. Order checks ownership/collisions.
4986
+ const sourceUid = getProductLineUid(source);
4987
+ if (sourceUid) {
4988
+ line.metadata = {
4989
+ ...(line.metadata || {}),
4990
+ unique_identification_number: sourceUid
4991
+ };
4992
+ }
4993
+ return line;
4994
+ });
4995
+ await this.store.order.replaceBookingProductWithRelatedRetail({
4996
+ productLineUid: params.productLineUid,
4997
+ product: transformed,
4998
+ booking,
4999
+ relatedRetailProducts: relatedRetailProducts,
5000
+ availabilityCommitGuard: availabilityCommitGuard,
5001
+ availabilityCommitTargetGuard
5002
+ });
5003
+ guardedCommitPublished = true;
5004
+ productLineUid = params.productLineUid;
5005
+ bookingUid = existingBookingUid;
5006
+ productLineUids = [productLineUid];
5007
+ bookingUids = [bookingUid];
5008
+ } else if (params.mode === 'edit' && editingLine && params.productLineUid) {
4192
5009
  transformed.product_sku = transformed.product_sku ?? editingLine.product_sku;
4193
5010
  transformed.product_bundle = transformed.product_bundle ?? editingLine.product_bundle;
4194
5011
  transformed.booking_uid = existingBookingUid;