@pisell/pisellos 0.10.70 → 0.10.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/modules/BookingContext/utils/productExtend.d.ts +5 -0
  2. package/dist/modules/BookingContext/utils/productExtend.js +61 -23
  3. package/dist/modules/OpenData/index.d.ts +1 -0
  4. package/dist/modules/OpenData/index.js +1 -0
  5. package/dist/modules/OpenData/salesSettings.d.ts +32 -0
  6. package/dist/modules/OpenData/salesSettings.js +80 -0
  7. package/dist/modules/OpenData/types.d.ts +13 -0
  8. package/dist/modules/Order/index.d.ts +13 -4
  9. package/dist/modules/Order/index.js +1401 -764
  10. package/dist/modules/Order/types.d.ts +24 -1
  11. package/dist/modules/Order/types.js +4 -0
  12. package/dist/server/index.js +5 -2
  13. package/dist/solution/BaseSales/index.d.ts +2 -2
  14. package/dist/solution/BaseSales/index.js +8 -8
  15. package/dist/solution/BookingTicket/index.d.ts +2 -2
  16. package/dist/solution/UnifiedBookingSales/index.d.ts +36 -1
  17. package/dist/solution/UnifiedBookingSales/index.js +1434 -709
  18. package/dist/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
  19. package/dist/solution/UnifiedBookingSales/salesSettings.js +81 -0
  20. package/dist/solution/UnifiedBookingSales/types.d.ts +17 -1
  21. package/lib/model/strategy/adapter/promotion/index.js +1 -46
  22. package/lib/modules/BookingContext/utils/productExtend.d.ts +5 -0
  23. package/lib/modules/BookingContext/utils/productExtend.js +36 -3
  24. package/lib/modules/OpenData/index.d.ts +1 -0
  25. package/lib/modules/OpenData/index.js +12 -0
  26. package/lib/modules/OpenData/salesSettings.d.ts +32 -0
  27. package/lib/modules/OpenData/salesSettings.js +70 -0
  28. package/lib/modules/OpenData/types.d.ts +13 -0
  29. package/lib/modules/Order/index.d.ts +13 -4
  30. package/lib/modules/Order/index.js +284 -24
  31. package/lib/modules/Order/types.d.ts +24 -1
  32. package/lib/modules/Order/types.js +2 -0
  33. package/lib/server/index.js +5 -1
  34. package/lib/solution/BaseSales/index.d.ts +2 -2
  35. package/lib/solution/BaseSales/index.js +2 -2
  36. package/lib/solution/BookingTicket/index.d.ts +2 -2
  37. package/lib/solution/UnifiedBookingSales/index.d.ts +36 -1
  38. package/lib/solution/UnifiedBookingSales/index.js +463 -45
  39. package/lib/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
  40. package/lib/solution/UnifiedBookingSales/salesSettings.js +72 -0
  41. package/lib/solution/UnifiedBookingSales/types.d.ts +17 -1
  42. package/package.json +1 -1
@@ -32,9 +32,23 @@ exports.normalizeProductForAvailability = normalizeProductForAvailability;
32
32
  var _dayjs = _interopRequireDefault(require("dayjs"));
33
33
  var _lodashEs = require("lodash-es");
34
34
  var _modules = require("../../modules");
35
+ var _pickupTiming = require("../../modules/Order/pickupTiming");
35
36
  var _utils = require("../../modules/BookingContext/utils");
36
37
  var _OpenData = require("../../modules/OpenData");
38
+ var _salesSettings = require("./salesSettings");
39
+ Object.keys(_salesSettings).forEach(function (key) {
40
+ if (key === "default" || key === "__esModule") return;
41
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
42
+ if (key in exports && exports[key] === _salesSettings[key]) return;
43
+ Object.defineProperty(exports, key, {
44
+ enumerable: true,
45
+ get: function () {
46
+ return _salesSettings[key];
47
+ }
48
+ });
49
+ });
37
50
  var _getDateIsInSchedule = require("../../modules/Schedule/getDateIsInSchedule");
51
+ var _clientDataVariants = require("../../modules/ProductList/clientDataVariants");
38
52
  var _ResourcePlanner = require("../../modules/ResourcePlanner");
39
53
  var _types = require("./types");
40
54
  Object.keys(_types).forEach(function (key) {
@@ -55,7 +69,7 @@ var _localClock = require("../../modules/ResourcePlanner/localClock");
55
69
  var _platform = require("../../utils/platform");
56
70
  var _itemRule = require("../../model/strategy/adapter/itemRule");
57
71
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
58
- const OPEN_DATA_SECTION_CODES = ['sale', 'reservation', 'fulfillment', 'menu', 'workflow', 'documents', 'basic', 'checkout', 'availability'];
72
+ const OPEN_DATA_SECTION_CODES = ['sale', 'reservation', 'fulfillment', 'menu', 'workflow', 'documents', 'basic', 'checkout', 'availability', 'interface'];
59
73
  function normalizePositiveInteger(value) {
60
74
  const normalized = Number(value);
61
75
  if (!Number.isInteger(normalized) || normalized <= 0) return undefined;
@@ -1045,6 +1059,11 @@ function buildBookingFromAvailabilitySelection(params) {
1045
1059
  unified_booking_sales: true,
1046
1060
  availability_candidate_key: candidate.key,
1047
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
+ } : {}),
1048
1067
  availability_slice_start_at: candidate.startAt,
1049
1068
  availability_slice_end_at: candidate.endAt,
1050
1069
  availability_schedule_refs: candidate.scheduleRefs,
@@ -1879,6 +1898,121 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1879
1898
  async getOpenData() {
1880
1899
  return this.loadOpenDataConfig();
1881
1900
  }
1901
+
1902
+ /** One policy snapshot for all Sales 2.0 consumers. Network errors must reach the caller. */
1903
+ async getSalesSettings() {
1904
+ const config = await this.getOpenData();
1905
+ if (!config) throw new Error('Sales settings are unavailable without a business context.');
1906
+ return (0, _OpenData.normalizeSalesSettings)(config, this.otherParams?.platform);
1907
+ }
1908
+ getLoadedSalesSettings() {
1909
+ if (!this.runtimeOpenDataSnapshot) {
1910
+ throw new Error('Sales settings are not loaded. Call getSalesSettings before preparing a booking.');
1911
+ }
1912
+ return (0, _OpenData.normalizeSalesSettings)(this.runtimeOpenDataSnapshot, this.otherParams?.platform);
1913
+ }
1914
+ getProductBookingsForScheduling() {
1915
+ const seen = new Set();
1916
+ return (this.getTempOrder()?.products || []).flatMap(product => {
1917
+ if (product.metadata?.product_add_schedule_time != null || product.deleted_at) return [];
1918
+ const booking = this.findLinkedBooking(product);
1919
+ if (!booking || (0, _pickupTiming.isFulfillmentTimingBooking)(booking) || seen.has(booking)) return [];
1920
+ seen.add(booking);
1921
+ return [booking];
1922
+ });
1923
+ }
1924
+ shouldApplyMultipleBookingScheduling() {
1925
+ const platform = (0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform);
1926
+ return platform === 'pos' || platform === 'webpos';
1927
+ }
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);
1932
+ const settings = this.getLoadedSalesSettings();
1933
+ return (0, _salesSettings.resolveDefaultBookingStart)({
1934
+ bookings: this.getProductBookingsForScheduling(),
1935
+ holderIds,
1936
+ mode: settings.reservation.multipleBookingScheduling,
1937
+ fallback
1938
+ });
1939
+ }
1940
+
1941
+ /** Used by the SKU flow after Holder changes, without changing an explicit user-selected time. */
1942
+ async resolveDefaultBookingStart(params) {
1943
+ if (!this.shouldApplyMultipleBookingScheduling()) return (0, _salesSettings.normalizeBookingDateTime)(params.fallback);
1944
+ await this.getSalesSettings();
1945
+ return this.resolveLoadedDefaultBookingStart(params.holderIds, params.fallback);
1946
+ }
1947
+ buildBookingCalcContext(extra) {
1948
+ return {
1949
+ ...super.buildBookingCalcContext(extra),
1950
+ resolveDefaultBookingStart: (cacheItem, fallback) => this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
1951
+ };
1952
+ }
1953
+ buildAddProductCtx(extra) {
1954
+ return {
1955
+ ...super.buildAddProductCtx(extra),
1956
+ resolveDefaultBookingStart: (cacheItem, fallback) => this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
1957
+ };
1958
+ }
1959
+
1960
+ /** Re-evaluate an automatic default after Holder enrichment, or restore a known explicit TimeBar start. */
1961
+ async applyDefaultBookingStart(cacheItem, options = {}) {
1962
+ if (!this.shouldApplyMultipleBookingScheduling()) return cacheItem;
1963
+ if (!cacheItem?.new || !(0, _utils.isBookingProduct)(cacheItem) || (0, _utils.isSessionProduct)(cacheItem) || cacheItem?._extend?.other?.session) return cacheItem;
1964
+ const extend = cacheItem._extend || {};
1965
+ const currentStart = (0, _salesSettings.getBookingBoundary)(extend, 'start');
1966
+ const automaticStart = (0, _salesSettings.normalizeBookingDateTime)(cacheItem._data?.salesDefaultBookingStart);
1967
+ if (extend.start_time && (!automaticStart || !currentStart || (0, _dayjs.default)(currentStart).valueOf() !== (0, _dayjs.default)(automaticStart).valueOf())) return cacheItem;
1968
+ const explicitStart = (0, _salesSettings.normalizeBookingDateTime)(options.explicitStart);
1969
+ if (options.explicitStart !== undefined && !explicitStart) {
1970
+ throw new Error('The explicit booking start must be a valid date and time.');
1971
+ }
1972
+ const holderIds = options.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem);
1973
+ const fallback = (0, _salesSettings.normalizeBookingDateTime)(cacheItem._data?.salesDefaultBookingFallback) ?? currentStart ?? (0, _salesSettings.normalizeBookingDateTime)(String(this.getBookingDate() || ''));
1974
+ const nextStart = explicitStart ?? (await this.resolveDefaultBookingStart({
1975
+ holderIds,
1976
+ fallback
1977
+ }));
1978
+ if (!nextStart) return cacheItem;
1979
+ if (currentStart && (0, _dayjs.default)(nextStart).valueOf() === (0, _dayjs.default)(currentStart).valueOf()) {
1980
+ if (!explicitStart) return cacheItem;
1981
+ const data = {
1982
+ ...cacheItem._data
1983
+ };
1984
+ delete data.salesDefaultBookingStart;
1985
+ delete data.salesDefaultBookingFallback;
1986
+ return {
1987
+ ...cacheItem,
1988
+ _data: data
1989
+ };
1990
+ }
1991
+ const nextExtend = {
1992
+ ...extend,
1993
+ start_date: nextStart.slice(0, 10),
1994
+ start_time: nextStart.slice(11)
1995
+ };
1996
+ for (const key of ['startDate', 'endDate', 'end_time', 'resource', 'resources', 'availabilitySelection']) {
1997
+ delete nextExtend[key];
1998
+ }
1999
+ if ((0, _utils.isMultiDayProduct)(cacheItem) && currentStart && extend.end_date) {
2000
+ const shiftDays = (0, _dayjs.default)(nextStart.slice(0, 10)).diff((0, _dayjs.default)(currentStart.slice(0, 10)), 'day');
2001
+ nextExtend.end_date = (0, _dayjs.default)(extend.end_date).add(shiftDays, 'day').format('YYYY-MM-DD');
2002
+ } else {
2003
+ delete nextExtend.end_date;
2004
+ }
2005
+ return this.getProductExtend({
2006
+ ...cacheItem,
2007
+ _extend: nextExtend,
2008
+ _data: explicitStart ? {} : {
2009
+ salesDefaultBookingStart: nextStart,
2010
+ salesDefaultBookingFallback: fallback
2011
+ }
2012
+ }, {
2013
+ holderIds
2014
+ });
2015
+ }
1882
2016
  async loadPickupTimingOpenData(_force) {
1883
2017
  const scope = this.getPickupTimingScope();
1884
2018
  const businessCode = String(this.otherParams?.businessCode ?? this.otherParams?.business_code ?? '').trim();
@@ -2028,6 +2162,128 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2028
2162
  * product because session products carry their fixed intervals there.
2029
2163
  */
2030
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) {
2031
2287
  if (!this.store.products) throw new Error('[UnifiedBookingSales] products 模块未初始化');
2032
2288
  const catalogScope = this.otherParams.catalogScopeKey;
2033
2289
  const schedule_date = params.schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD');
@@ -2045,8 +2301,6 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2045
2301
  name: 'AbortError'
2046
2302
  });
2047
2303
  }
2048
- this.unifiedProductCatalog = Array.isArray(result) ? [...result] : [];
2049
- await this.core.effects.emit(`${this.name}:onProductsLoaded`, result);
2050
2304
  return result;
2051
2305
  }
2052
2306
  async queryProducts(params = {}) {
@@ -2239,10 +2493,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2239
2493
  sourceProduct
2240
2494
  });
2241
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]]));
2242
2497
  // BaseSales may rebuild metadata from its price source. Stamp ownership and the selected
2243
2498
  // quotation shelf after that transform so neither booking adds nor edits lose quote identity.
2244
2499
  orderProduct.metadata = {
2245
2500
  ...(orderProduct.metadata || {}),
2501
+ ...venueMetadata,
2246
2502
  [ownershipKey]: true,
2247
2503
  ...(quotationShelfId !== undefined ? {
2248
2504
  quotation_shelf_id: quotationShelfId
@@ -2324,7 +2580,38 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2324
2580
  if (!orderProduct) {
2325
2581
  throw new Error('[UnifiedBookingSales] 无法生成零售商品订单行');
2326
2582
  }
2327
- 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
+ });
2328
2615
  }
2329
2616
  normalizeAvailabilityDateRange(params, timezone) {
2330
2617
  const today = (0, _localClock.formatLocalDate)((0, _localClock.localDateToScalar)(new Date()));
@@ -2379,8 +2666,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2379
2666
  params
2380
2667
  });
2381
2668
  }
2382
- if (!hasProductAnchor && !params.catalogScope) {
2383
- 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', {
2384
2671
  params
2385
2672
  });
2386
2673
  }
@@ -2483,12 +2770,15 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2483
2770
  dateRange
2484
2771
  } = params;
2485
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);
2486
2775
  let rawProducts = [];
2487
2776
  if (Array.isArray(prepare.rawProducts)) {
2488
2777
  rawProducts = prepare.rawProducts;
2489
- this.unifiedProductCatalog = [...rawProducts];
2778
+ if (publishCatalog) this.unifiedProductCatalog = [...rawProducts];
2490
2779
  } else if (explicitProductIds.length > 0) {
2491
- rawProducts = await this.loadProducts({
2780
+ rawProducts = await loadProducts({
2781
+ ...(!publishCatalog && prepare.catalogScope?.type === 'productList' ? prepare.catalogScope.params : {}),
2492
2782
  product_ids: explicitProductIds,
2493
2783
  schedule_date: dateRange.startDate
2494
2784
  });
@@ -2504,15 +2794,15 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2504
2794
  const productIds = uniqueAvailabilityIds([...scheduleProductIds, ...(this.store.schedule.getOtherProductsIds?.() || [])]);
2505
2795
  if (productIds.length > 0) {
2506
2796
  assertAvailabilityCatalogProductIds(productIds, 'prepare.catalogScope.scheduleProductIds');
2507
- rawProducts = await this.loadProducts({
2797
+ rawProducts = await loadProducts({
2508
2798
  product_ids: productIds,
2509
2799
  schedule_date: dateRange.startDate
2510
2800
  });
2511
2801
  } else {
2512
- this.unifiedProductCatalog = [];
2802
+ if (publishCatalog) this.unifiedProductCatalog = [];
2513
2803
  }
2514
2804
  } else if (prepare.catalogScope?.type === 'productList') {
2515
- rawProducts = await this.loadProducts({
2805
+ rawProducts = await loadProducts({
2516
2806
  ...prepare.catalogScope.params,
2517
2807
  schedule_date: prepare.catalogScope.params.schedule_date || dateRange.startDate
2518
2808
  });
@@ -2623,7 +2913,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2623
2913
  resourceOccupancies: []
2624
2914
  };
2625
2915
  }
2626
- if (Array.isArray(params.rawResources)) {
2916
+ if (Array.isArray(params.rawResources) && params.fetchPolicy !== 'refresh') {
2627
2917
  return buildAvailabilityResourcesFromV2({
2628
2918
  rawResources: params.rawResources,
2629
2919
  scheduleList: params.scheduleList,
@@ -2650,10 +2940,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2650
2940
  resourceOccupancies: []
2651
2941
  };
2652
2942
  }
2653
- const rawResources = await this.fetchAndPublishAvailabilityResourcesV2({
2943
+ const remoteQuery = {
2654
2944
  timezone: params.timezone,
2655
2945
  dateRange: params.dateRange,
2656
- resourceIds,
2946
+ resourceIds
2947
+ };
2948
+ const rawResources = params.fetchPolicy === 'refresh' ? await this.refreshAvailabilityRemoteResourceQuery(remoteQuery) : await this.fetchAndPublishAvailabilityResourcesV2({
2949
+ ...remoteQuery,
2657
2950
  useCacheOnHit: true
2658
2951
  });
2659
2952
  return buildAvailabilityResourcesFromV2({
@@ -2878,7 +3171,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2878
3171
  products,
2879
3172
  rawResources: normalizedPrepareParams.rawResources,
2880
3173
  scheduleList,
2881
- fetchPolicy: options.resourceFetchPolicy || 'default',
3174
+ // An explicit internal policy (notably commit's cache_only) remains authoritative.
3175
+ fetchPolicy: options.resourceFetchPolicy || (normalizedPrepareParams.refreshOccupancies ? 'refresh' : 'default'),
2882
3176
  fallbackResources: options.fallbackResources
2883
3177
  });
2884
3178
  const tempOrder = this.getTempOrder();
@@ -3163,18 +3457,22 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3163
3457
  projectionEntry
3164
3458
  } = await this.ensureAvailabilityContextProjection(contextId, 'get_product_time_ranges');
3165
3459
  const contextVersion = context.activeVersion;
3460
+ const strictAvailability = context.prepareParams.strictAvailability === true;
3166
3461
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3167
- 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);
3168
3463
  return (0, _ResourcePlanner.getProductTimeRanges)(projectionEntry.projection, {
3169
3464
  ...request,
3170
3465
  ...(allowOutsideOperatingHoursForRequestedStartTimes ? {
3171
3466
  allowOutsideOperatingHoursForRequestedStartTimes: true
3467
+ } : {}),
3468
+ ...(strictAvailability ? {
3469
+ allowOutsideOperatingHoursForRequestedStartTimes: false
3172
3470
  } : {})
3173
3471
  }, {
3174
3472
  evaluatedAt: this.getAvailabilityRuntimeDateTime(),
3175
- useExactDurationCandidateMinute: isPosAvailabilityRequest,
3176
- allowSessionCustomRanges: isPosAvailabilityRequest,
3177
- allowExcludedScheduleDateOverride: isPosAvailabilityRequest
3473
+ useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
3474
+ allowSessionCustomRanges: isPosAvailabilityRequest && !strictAvailability,
3475
+ allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
3178
3476
  }).map(group => ({
3179
3477
  ...group,
3180
3478
  ranges: group.ranges.map(candidate => this.decorateAvailabilityCandidate(context.contextId, contextVersion, candidate))
@@ -3189,10 +3487,11 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3189
3487
  refreshed
3190
3488
  } = await this.ensureAvailabilityContextProjection(contextId, 'query_booking_availability');
3191
3489
  this.assertContextualQueryFreshness(context, request);
3490
+ const strictAvailability = context.prepareParams.strictAvailability === true;
3192
3491
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3193
3492
  const result = (0, _ResourcePlanner.queryAvailabilityProjection)(projectionEntry.projection, request, {
3194
- useExactDurationCandidateMinute: isPosAvailabilityRequest,
3195
- allowExcludedScheduleDateOverride: isPosAvailabilityRequest
3493
+ useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
3494
+ allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
3196
3495
  });
3197
3496
  const contextVersion = context.activeVersion;
3198
3497
  const contextualResult = result.target === 'time' ? {
@@ -3226,6 +3525,20 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3226
3525
  refreshed
3227
3526
  };
3228
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
+ }
3229
3542
  releaseAvailabilityContext(contextId) {
3230
3543
  const context = this.availabilityContextRegistry.get(contextId);
3231
3544
  if (!context) return;
@@ -3279,6 +3592,27 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3279
3592
  candidate: params.candidate
3280
3593
  });
3281
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;
3282
3616
  await this.tryAcquireAvailabilityCommitLock(normalizedContextId);
3283
3617
  try {
3284
3618
  const bookingCount = Number(params.bookingCount ?? 1);
@@ -3287,7 +3621,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3287
3621
  bookingCount: params.bookingCount
3288
3622
  });
3289
3623
  }
3290
- if (params.mode === 'edit' && bookingCount !== 1) {
3624
+ if (isEditingSelection && bookingCount !== 1) {
3291
3625
  throw new _ResourcePlanner.AvailabilityError('INVALID_RESERVATION_QUANTITY', '编辑预约商品时 bookingCount 必须为 1', {
3292
3626
  bookingCount
3293
3627
  });
@@ -3318,7 +3652,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3318
3652
  });
3319
3653
  }
3320
3654
  const boundEditingUids = context.prepareParams.editingProductLineUids || [];
3321
- if (params.mode === 'edit') {
3655
+ if (isEditingSelection) {
3322
3656
  if (!params.productLineUid || !boundEditingUids.includes(String(params.productLineUid))) {
3323
3657
  throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'edit context 与当前商品行不匹配,请重新 prepare 编辑上下文', {
3324
3658
  contextId: normalizedContextId,
@@ -3362,16 +3696,16 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3362
3696
  candidateProductId: params.candidate.productId
3363
3697
  });
3364
3698
  }
3365
- if (params.mode === 'edit' && !params.productLineUid) {
3699
+ if (isEditingSelection && !params.productLineUid) {
3366
3700
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', 'edit 模式必须提供 productLineUid');
3367
3701
  }
3368
- const editingLine = params.mode === 'edit' ? this.findProductLineByUid(String(params.productLineUid)) : undefined;
3369
- if (params.mode === 'edit' && !editingLine) {
3702
+ const editingLine = isEditingSelection ? this.findProductLineByUid(String(params.productLineUid)) : undefined;
3703
+ if (isEditingSelection && !editingLine) {
3370
3704
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', '找不到要编辑的预约商品行', {
3371
3705
  productLineUid: params.productLineUid
3372
3706
  });
3373
3707
  }
3374
- 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)) {
3375
3709
  throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '编辑商品行与 candidate 商品不一致', {
3376
3710
  productLineUid: params.productLineUid,
3377
3711
  productLineProductId: editingLine.product_id ?? editingLine.id,
@@ -3402,7 +3736,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3402
3736
  };
3403
3737
  const commitSnapshot = await this.buildAvailabilityProjectionSnapshot({
3404
3738
  ...this.cloneAvailabilityPrepareParams(prepareParams),
3405
- editingProductLineUids: params.mode === 'edit' && params.productLineUid ? [params.productLineUid] : []
3739
+ editingProductLineUids: isEditingSelection && params.productLineUid ? [params.productLineUid] : []
3406
3740
  }, {
3407
3741
  resourceFetchPolicy: 'cache_only',
3408
3742
  fallbackResources,
@@ -3429,7 +3763,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3429
3763
  this.assertAvailabilityCommitWriteCAS(commitWriteGuard);
3430
3764
  const candidateDurationMinutes = getCandidateDurationMinutes(params.candidate);
3431
3765
  const candidateStartTime = getCandidateStartTime(params.candidate);
3432
- const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
3766
+ const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !strictAvailability;
3433
3767
  const refreshedRanges = (0, _ResourcePlanner.getProductTimeRanges)(refreshedProjection, {
3434
3768
  productIds: [params.candidate.productId],
3435
3769
  dateRange: {
@@ -3450,6 +3784,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3450
3784
  } : {})
3451
3785
  } : {})
3452
3786
  }, {
3787
+ ...(strictAvailability ? {
3788
+ evaluatedAt: this.getAvailabilityRuntimeDateTime()
3789
+ } : {}),
3453
3790
  useExactDurationCandidateMinute: allowPosAvailabilityOverride,
3454
3791
  allowSessionCustomRanges: allowPosAvailabilityOverride,
3455
3792
  allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
@@ -3534,9 +3871,30 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3534
3871
  expectedOrderRevision: revalidationEntry.orderRevision
3535
3872
  };
3536
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;
3537
3895
  const existingBooking = editingLine ? this.findLinkedBooking(editingLine) : undefined;
3538
3896
  const existingBookingUid = existingBooking ? getBookingUid(existingBooking) : '';
3539
- if (params.mode === 'edit' && !existingBookingUid) {
3897
+ if (isEditingSelection && !existingBookingUid) {
3540
3898
  throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', '编辑商品行缺少关联 booking', {
3541
3899
  productLineUid: params.productLineUid
3542
3900
  });
@@ -3548,9 +3906,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3548
3906
  product,
3549
3907
  resources: refreshedProjection.resources,
3550
3908
  bookingUid: existingBookingUid || undefined,
3551
- holder: params.orderProduct?._extend?.holder ?? existingBooking?.holder ?? existingBooking?.metadata?.holder,
3552
- 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)
3553
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
+ }
3554
3917
  const transformed = this.buildUnifiedOrderProduct({
3555
3918
  ...params.orderProduct,
3556
3919
  num: bookingCount,
@@ -3567,13 +3930,43 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3567
3930
  unified_booking_sales: true,
3568
3931
  availability_candidate_key: refreshedCandidate.key,
3569
3932
  availability_context_id: normalizedContextId,
3570
- 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
+ } : {})
3571
3937
  };
3572
3938
  let productLineUid = '';
3573
3939
  let bookingUid = '';
3574
3940
  let productLineUids = [];
3575
3941
  let bookingUids = [];
3576
- 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) {
3577
3970
  transformed.product_sku = transformed.product_sku ?? editingLine.product_sku;
3578
3971
  transformed.product_bundle = transformed.product_bundle ?? editingLine.product_bundle;
3579
3972
  transformed.booking_uid = existingBookingUid;
@@ -3583,7 +3976,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3583
3976
  unique_identification_number: params.productLineUid,
3584
3977
  booking_uid: existingBookingUid
3585
3978
  };
3586
- await this.updateOrderProduct({
3979
+ const update = {
3587
3980
  product_id: transformed.product_id ?? editingLine.product_id,
3588
3981
  product_variant_id: transformed.product_variant_id ?? editingLine.product_variant_id ?? 0,
3589
3982
  unique_identification_number: params.productLineUid,
@@ -3595,7 +3988,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3595
3988
  ...(params.allowBookingDiscountReapply !== undefined ? {
3596
3989
  allow_booking_discount_reapply: params.allowBookingDiscountReapply
3597
3990
  } : {})
3598
- });
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);
3599
3999
  productLineUid = params.productLineUid;
3600
4000
  bookingUid = existingBookingUid;
3601
4001
  productLineUids = [productLineUid];
@@ -3603,12 +4003,20 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3603
4003
  } else {
3604
4004
  const beforeProductLineUids = new Set((this.getTempOrder()?.products || []).map(line => getProductLineUid(line)).filter(Boolean));
3605
4005
  const beforeBookingUids = new Set((this.getTempOrder()?.bookings || []).map(item => getBookingUid(item)).filter(Boolean));
3606
- const products = await this.addProductToOrder(transformed, booking, params.salesNotes?.length ? {
3607
- 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
+ } : {})
3608
4015
  } : undefined);
4016
+ guardedCommitPublished = hasCommitGuard;
3609
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)));
3610
4018
  productLineUids = addedLines.map(line => getProductLineUid(line)).filter(Boolean);
3611
- 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)));
3612
4020
  bookingUids = addedBookings.map(item => getBookingUid(item)).filter(Boolean);
3613
4021
  if (bookingUids.length === 0) {
3614
4022
  bookingUids = addedLines.map(line => String(line.booking_uid ?? line.metadata?.booking_uid ?? '')).filter(Boolean);
@@ -3616,12 +4024,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3616
4024
  productLineUid = productLineUids[productLineUids.length - 1] || '';
3617
4025
  bookingUid = bookingUids[bookingUids.length - 1] || '';
3618
4026
  }
3619
- this.invalidateAvailabilityContextsAfterCommit();
3620
- 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);
3621
4030
  const result = {
3622
4031
  contextId: normalizedContextId,
3623
- contextVersion: nextContext.activeVersion,
3624
- tempOrder: this.getTempOrder(),
4032
+ contextVersion: nextContext?.activeVersion ?? refreshedCandidate.availabilityContextVersion,
4033
+ tempOrder: hasCommitGuard ? guardedOrder : this.getTempOrder(),
3625
4034
  validation,
3626
4035
  candidate: refreshedCandidate,
3627
4036
  productLineUid,
@@ -3629,10 +4038,19 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3629
4038
  productLineUids,
3630
4039
  bookingUids
3631
4040
  };
3632
- 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
+ }
3633
4050
  return result;
3634
4051
  } finally {
3635
- await this.releaseAvailabilityCommitLock(normalizedContextId);
4052
+ const release = this.releaseAvailabilityCommitLock(normalizedContextId);
4053
+ if (guardedCommitPublished) await release.catch(() => undefined);else await release;
3636
4054
  }
3637
4055
  }
3638
4056
  }