@pisell/pisellos 0.10.80 → 0.10.82

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/ProductList/index.js +5 -0
  2. package/dist/modules/ResourcePlanner/planner.js +2 -1
  3. package/dist/solution/BookingByStep/index.d.ts +1 -1
  4. package/dist/solution/BookingTicket/index.d.ts +1 -1
  5. package/dist/solution/BookingTicket/index.js +36 -31
  6. package/dist/solution/ScanOrder/index.d.ts +0 -1
  7. package/dist/solution/ScanOrder/index.js +62 -59
  8. package/dist/solution/ScanOrder/types.d.ts +2 -0
  9. package/dist/solution/ScanOrder/types.js +2 -0
  10. package/dist/solution/UnifiedBookingSales/index.d.ts +11 -1
  11. package/dist/solution/UnifiedBookingSales/index.js +1485 -1163
  12. package/dist/solution/UnifiedBookingSales/types.d.ts +5 -0
  13. package/dist/solution/UnifiedBookingSales/venueCatalogSession.js +11 -5
  14. package/dist/solution/VenueBooking/index.js +111 -104
  15. package/dist/solution/VenueBooking/types.d.ts +2 -0
  16. package/dist/solution/VenueBooking/types.js +3 -1
  17. package/dist/solution/VenueBooking/utils/smartPricing.d.ts +1 -0
  18. package/dist/solution/VenueBooking/utils/smartPricing.js +6 -1
  19. package/dist/utils/hostLogger.d.ts +10 -0
  20. package/dist/utils/hostLogger.js +20 -0
  21. package/lib/model/strategy/adapter/promotion/index.js +46 -1
  22. package/lib/modules/ProductList/index.js +5 -0
  23. package/lib/modules/ResourcePlanner/planner.js +2 -1
  24. package/lib/solution/BookingByStep/index.d.ts +1 -1
  25. package/lib/solution/BookingTicket/index.d.ts +1 -1
  26. package/lib/solution/BookingTicket/index.js +5 -4
  27. package/lib/solution/ScanOrder/index.d.ts +0 -1
  28. package/lib/solution/ScanOrder/index.js +47 -41
  29. package/lib/solution/ScanOrder/types.d.ts +2 -0
  30. package/lib/solution/ScanOrder/types.js +1 -0
  31. package/lib/solution/UnifiedBookingSales/index.d.ts +11 -1
  32. package/lib/solution/UnifiedBookingSales/index.js +269 -57
  33. package/lib/solution/UnifiedBookingSales/types.d.ts +5 -0
  34. package/lib/solution/UnifiedBookingSales/venueCatalogSession.js +9 -5
  35. package/lib/solution/VenueBooking/index.js +38 -47
  36. package/lib/solution/VenueBooking/types.d.ts +2 -0
  37. package/lib/solution/VenueBooking/types.js +3 -1
  38. package/lib/solution/VenueBooking/utils/smartPricing.d.ts +1 -0
  39. package/lib/solution/VenueBooking/utils/smartPricing.js +6 -1
  40. package/lib/utils/hostLogger.d.ts +10 -0
  41. package/lib/utils/hostLogger.js +25 -0
  42. package/package.json +1 -1
@@ -71,6 +71,7 @@ var _BookingTicket = require("../BookingTicket");
71
71
  var _localClock = require("../../modules/ResourcePlanner/localClock");
72
72
  var _platform = require("../../utils/platform");
73
73
  var _itemRule = require("../../model/strategy/adapter/itemRule");
74
+ var _hostLogger = require("../../utils/hostLogger");
74
75
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
75
76
  const OPEN_DATA_SECTION_CODES = ['sale', 'reservation', 'fulfillment', 'menu', 'workflow', 'documents', 'basic', 'checkout', 'availability', 'interface'];
76
77
  function normalizePositiveInteger(value) {
@@ -1171,6 +1172,12 @@ function buildPosForcedAvailabilityAssignments(params) {
1171
1172
  }
1172
1173
  selectedResourceIds.forEach(resourceId => {
1173
1174
  if (sameAvailabilityId(resourceId, POS_NO_RESOURCE_ID)) {
1175
+ if (params.allowNoResource === false) {
1176
+ addConflict('resource_unavailable', '必须选择当前商品的有效资源', {
1177
+ resourceId
1178
+ });
1179
+ return;
1180
+ }
1174
1181
  assignments.push({
1175
1182
  productId: product.id,
1176
1183
  resourceId: POS_NO_RESOURCE_ID,
@@ -1217,6 +1224,45 @@ function buildPosForcedAvailabilityAssignments(params) {
1217
1224
  conflicts
1218
1225
  };
1219
1226
  }
1227
+
1228
+ /** Structural conversion only. The customer has already picked a time and resources in the UI. */
1229
+ function acceptCustomerSelectionSnapshot(params) {
1230
+ const {
1231
+ candidate
1232
+ } = params;
1233
+ try {
1234
+ const start = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(candidate.startAt));
1235
+ const end = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(candidate.endAt));
1236
+ const bookingStart = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(candidate.bookingStartAt));
1237
+ const bookingEnd = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(candidate.bookingEndAt));
1238
+ if (end <= start || bookingEnd <= bookingStart) throw new Error('invalid interval');
1239
+ } catch {
1240
+ throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '所选时间必须是有效且递增的区间');
1241
+ }
1242
+ const {
1243
+ assignments,
1244
+ conflicts
1245
+ } = buildPosForcedAvailabilityAssignments({
1246
+ ...params,
1247
+ allowNoResource: false
1248
+ });
1249
+ // Preserve the original time-card snapshot for callers; do not query current availability here.
1250
+ const display = candidate;
1251
+ const availability = {
1252
+ ...candidate,
1253
+ status: display.status || 'available',
1254
+ maxPartySize: display.maxPartySize ?? params.partySize,
1255
+ reasonCodes: display.reasonCodes || [],
1256
+ requirementGroups: display.requirementGroups || []
1257
+ };
1258
+ return {
1259
+ ok: conflicts.length === 0,
1260
+ status: availability.status,
1261
+ assignments,
1262
+ conflicts,
1263
+ availability
1264
+ };
1265
+ }
1220
1266
  class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1221
1267
  defaultName = 'unifiedBookingSales';
1222
1268
  defaultVersion = '1.0.0';
@@ -1254,6 +1300,26 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1254
1300
  allergyItemRuleConfigs = [];
1255
1301
  allergyItemRuleConfigsPromise = null;
1256
1302
  async initialize(core, options = {}) {
1303
+ const startedAt = Date.now();
1304
+ const initializationGeneration = this.runtimeInitializationGeneration + 1;
1305
+ try {
1306
+ const initialized = await this.initializeUnifiedSalesRuntime(core, options);
1307
+ if (initialized && !this.runtimeOpenDataDestroyed && initializationGeneration === this.runtimeInitializationGeneration) {
1308
+ this.writeSolutionLog('info', 'initialize success', {
1309
+ action: 'initialize',
1310
+ durationMs: Date.now() - startedAt
1311
+ });
1312
+ }
1313
+ } catch (error) {
1314
+ if (!this.runtimeOpenDataDestroyed && initializationGeneration === this.runtimeInitializationGeneration) {
1315
+ this.logSolutionFailure('initialize', error, {
1316
+ durationMs: Date.now() - startedAt
1317
+ });
1318
+ }
1319
+ throw error;
1320
+ }
1321
+ }
1322
+ async initializeUnifiedSalesRuntime(core, options) {
1257
1323
  const initializationGeneration = ++this.runtimeInitializationGeneration;
1258
1324
  this.resetRuntimeOpenData();
1259
1325
  this.runtimeOpenDataDestroyed = false;
@@ -1269,12 +1335,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1269
1335
  await initialization;
1270
1336
  if (this.runtimeOpenDataDestroyed || initializationGeneration !== this.runtimeInitializationGeneration) {
1271
1337
  // A destroyed/reinitialized instance must not publish a ready snapshot.
1272
- return;
1338
+ return false;
1273
1339
  }
1274
1340
  if (core !== this.core || openDataModule !== this.store.openData || scope !== this.getRuntimeOpenDataScope()) {
1275
1341
  throw new Error('Store settings changed. Please try again.');
1276
1342
  }
1277
1343
  this.captureAvailabilityScheduleCatalog();
1344
+ return !this.runtimeOpenDataDestroyed && initializationGeneration === this.runtimeInitializationGeneration;
1278
1345
  }
1279
1346
  getSubmitOrderSalesChannel() {
1280
1347
  const channel = String(this.otherParams?.channel ?? '').trim();
@@ -1403,6 +1470,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1403
1470
  const currentTarget = businessCode && channel ? `${businessCode}+${channel}` : null;
1404
1471
  let openData = (!currentTarget || this.openDataTarget === currentTarget) && (this.runtimeOpenDataScope === null || this.runtimeOpenDataScope === this.getRuntimeOpenDataScope()) ? this.otherParams?.openData : null;
1405
1472
  if (!openData && this.store.openData) {
1473
+ const logContext = this.getSolutionLogContext();
1406
1474
  try {
1407
1475
  openData = await this.getOpenData();
1408
1476
  } catch (error) {
@@ -1413,7 +1481,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1413
1481
  cause: error instanceof Error ? error.message : String(error)
1414
1482
  });
1415
1483
  }
1416
- console.warn('[UnifiedBookingSales] OpenData 时间切片配置加载失败,回退为默认值', error);
1484
+ this.logSolutionFailure('resolveAvailabilityTimeSlice', error, {
1485
+ fallback: 'default'
1486
+ }, logContext, 'warning');
1417
1487
  }
1418
1488
  }
1419
1489
  const operatingScheduleIds = this.normalizeAvailabilityIdList(Array.isArray(openData?.['availability.operating_hours']) ? openData?.['availability.operating_hours'] : undefined) || [];
@@ -1557,7 +1627,83 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1557
1627
  contextId: context.contextId
1558
1628
  };
1559
1629
  }
1630
+ getSolutionLogContext() {
1631
+ const context = {};
1632
+ try {
1633
+ Object.assign(context, {
1634
+ solutionName: this.name,
1635
+ moduleName: this.defaultName,
1636
+ module: 'unifiedBookingSales',
1637
+ cacheId: this.cacheId,
1638
+ businessCode: this.otherParams?.businessCode ?? this.otherParams?.business_code,
1639
+ platform: this.otherParams?.platform,
1640
+ channel: this.otherParams?.channel
1641
+ });
1642
+ try {
1643
+ const order = this.getTempOrder();
1644
+ Object.assign(context, {
1645
+ orderId: order?.order_id,
1646
+ externalSaleNumber: order?.external_sale_number,
1647
+ shopOrderNumber: order?.shop_order_number
1648
+ });
1649
+ } catch {/* A partially initialized order must not hide the failure log. */}
1650
+ try {
1651
+ const order = this.store.order;
1652
+ context.orderSessionId = order?.getOrderSessionId?.() ?? null;
1653
+ } catch {/* Session context is optional during initialization and teardown. */}
1654
+ } catch {/* Basic context remains useful even when some runtime fields cannot be read. */}
1655
+ return context;
1656
+ }
1657
+ writeSolutionLog(type, title, metadata = {}, context = this.getSolutionLogContext()) {
1658
+ try {
1659
+ (0, _hostLogger.writeHostLog)(this.core, {
1660
+ type,
1661
+ title: `[UnifiedBookingSales] ${title}`,
1662
+ metadata: {
1663
+ ...context,
1664
+ ...metadata
1665
+ }
1666
+ });
1667
+ } catch {
1668
+ // Reading diagnostic context must not change the sales result.
1669
+ }
1670
+ }
1671
+ logSolutionFailure(method, error, metadata = {}, context, type) {
1672
+ try {
1673
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : undefined;
1674
+ const isBusinessFailure = error instanceof _ResourcePlanner.AvailabilityError && code !== 'OPERATING_HOURS_RESOLVE_FAILED' && code !== 'SELF_EXCLUSION_RESOLVE_FAILED';
1675
+ this.writeSolutionLog(type ?? (code === 'AVAILABILITY_COMMIT_IN_PROGRESS' ? 'debug' : isBusinessFailure || code === 'REQUIRED_PRODUCT_MISSING' ? 'warning' : 'error'), `${method} failed`, {
1676
+ ...metadata,
1677
+ action: method,
1678
+ errorCode: code,
1679
+ errorMessage: (error instanceof Error ? error.message : String(error)).slice(0, 500)
1680
+ }, context);
1681
+ } catch {
1682
+ // Error serialization is observational only.
1683
+ }
1684
+ }
1560
1685
  async emitAvailabilityDiagnostic(payload) {
1686
+ try {
1687
+ const projection = payload.projection;
1688
+ this.writeSolutionLog(payload.action === 'prepare' || payload.action === 'refresh' ? 'info' : 'debug', `availability ${payload.action}`, {
1689
+ action: payload.action,
1690
+ reason: payload.reason,
1691
+ contextId: payload.contextId,
1692
+ contextVersion: payload.contextVersion,
1693
+ snapshotId: payload.snapshotId,
1694
+ orderRevision: payload.orderRevision,
1695
+ previousOrderRevision: payload.previousOrderRevision,
1696
+ registrySize: this.availabilityContextRegistry.size,
1697
+ projectionPoolSize: this.availabilityProjectionPool.size,
1698
+ ...(projection ? {
1699
+ productCount: projection.products.length,
1700
+ resourceCount: projection.resources.length,
1701
+ occupancyCount: projection.resourceOccupancies.length
1702
+ } : {})
1703
+ });
1704
+ } catch {
1705
+ // Diagnostic summaries must not change the existing effects event.
1706
+ }
1561
1707
  await this.core?.effects?.emit?.(`${this.name}:${_types.UnifiedBookingSalesHooks.onAvailabilityProjectionDiagnostic}`, {
1562
1708
  ...payload,
1563
1709
  registrySize: this.availabilityContextRegistry.size,
@@ -1725,6 +1871,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1725
1871
  });
1726
1872
  }
1727
1873
  const tempOrder = await super.addNewOrder();
1874
+ const logContext = this.getSolutionLogContext();
1728
1875
  if (sessionRecord) {
1729
1876
  this.store.order?.persistTempOrder();
1730
1877
  }
@@ -1735,13 +1882,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1735
1882
  await this.refreshLegacySessionCustomerDiscounts(tempOrder);
1736
1883
  }
1737
1884
  } catch (error) {
1738
- console.warn('[UnifiedBookingSales] Failed to sync authenticated order customer after addNewOrder', error);
1885
+ this.logSolutionFailure('syncAuthenticatedOrderCustomer', error, {}, logContext, 'warning');
1739
1886
  }
1740
1887
  } else if (sessionRecord) {
1741
1888
  try {
1742
1889
  await this.refreshLegacySessionCustomerDiscounts(tempOrder);
1743
1890
  } catch (error) {
1744
- console.warn('[UnifiedBookingSales] Failed to refresh cached customer discounts after addNewOrder', error);
1891
+ this.logSolutionFailure('refreshLegacySessionCustomerDiscounts', error, {}, logContext, 'warning');
1745
1892
  }
1746
1893
  }
1747
1894
  return this.store.order?.getTempOrder() || tempOrder;
@@ -1833,10 +1980,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1833
1980
  this.otherParams.openData = injectedOpenData;
1834
1981
  this.openDataTarget = `${businessCode}+${this.getSubmitOrderSalesChannel()}`;
1835
1982
  }
1983
+ const logContext = this.getSolutionLogContext();
1836
1984
  try {
1837
1985
  await this.loadOpenDataConfig();
1838
1986
  } catch (error) {
1839
- console.warn('[UnifiedBookingSales] Invoice 模板预加载失败,使用默认配置', error);
1987
+ this.logSolutionFailure('prepareInvoiceTemplateAtSolutionReady', error, {
1988
+ fallback: 'default'
1989
+ }, logContext, 'warning');
1840
1990
  }
1841
1991
  }
1842
1992
  async loadOpenDataConfig() {
@@ -2053,6 +2203,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2053
2203
  }
2054
2204
  async fetchAllergyItemRuleConfigs(strategyModelIds) {
2055
2205
  if (!strategyModelIds.length) return [];
2206
+ const logContext = this.getSolutionLogContext();
2056
2207
  try {
2057
2208
  const response = await this.request.get('/promotion', {
2058
2209
  skip: 1,
@@ -2066,9 +2217,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2066
2217
  const list = response.data.list;
2067
2218
  return normalizeItemRuleStrategyConfigs(list.map(item => item?.metadata));
2068
2219
  } catch (error) {
2069
- // this.logMethodError('fetchAllergyItemRuleConfigs', error, {
2070
- // strategyModelIds,
2071
- // });
2220
+ this.logSolutionFailure('fetchAllergyItemRuleConfigs', error, {
2221
+ strategyModelIds
2222
+ }, logContext);
2072
2223
  throw error;
2073
2224
  }
2074
2225
  }
@@ -2463,16 +2614,25 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2463
2614
  if (this.venueCatalogMenus?.promise === promise) this.venueCatalogMenus = undefined;
2464
2615
  });
2465
2616
  }
2466
- const pricingMenus = await this.venueCatalogMenus.promise;
2467
- const menus = (0, _venueCatalogSession.validateVenueMenus)(pricingMenus, menuIds);
2617
+ const menuCache = this.venueCatalogMenus;
2618
+ const pricingMenus = await menuCache.promise;
2468
2619
  assertCurrent();
2620
+ let menus;
2621
+ try {
2622
+ menus = (0, _venueCatalogSession.validateVenueMenus)(pricingMenus, menuIds);
2623
+ } catch (error) {
2624
+ // A malformed selected menu must be fetched again on explicit retry.
2625
+ if (this.venueCatalogMenus === menuCache) this.venueCatalogMenus = undefined;
2626
+ throw error;
2627
+ }
2469
2628
  // A menu query with a date may exclude future members. Read the raw ID union
2470
2629
  // without menu/time/customer pricing filters, then filter collection/all menus locally.
2471
2630
  const onlyIds = menus.every(menu => menu.partyroom_package.type === 'products');
2472
2631
  const onlyCollections = menus.every(menu => menu.partyroom_package.type === 'product_collection');
2473
2632
  const productIds = onlyIds ? [...new Set(menus.flatMap(menu => menu.partyroom_package.products.map(product => Number(product.product_id))))] : undefined;
2474
2633
  const collections = onlyCollections ? [...new Set(menus.flatMap(menu => menu.partyroom_package.products.map(product => String(product.product_collection_id))))] : undefined;
2475
- const products = onlyIds && !productIds?.length ? [] : await this.store.products.loadVenueCatalogPool({
2634
+ const emptySelection = productIds?.length === 0 || collections?.length === 0;
2635
+ const products = emptySelection ? [] : await this.store.products.loadVenueCatalogPool({
2476
2636
  product_ids: productIds,
2477
2637
  collection: collections,
2478
2638
  category_ids: params.category_ids,
@@ -2483,7 +2643,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2483
2643
  const pool = {
2484
2644
  menus,
2485
2645
  pricingMenus: (0, _lodashEs.cloneDeep)(pricingMenus),
2486
- products: products.filter(product => menus.some(menu => (0, _venueCatalogSession.productMatchesVenueMenu)(product, menu)))
2646
+ products: products.filter(product => !('deleted_at' in product && product.deleted_at) && (!product.status || product.status === 'published') && menus.some(menu => (0, _venueCatalogSession.productMatchesVenueMenu)(product, menu)))
2487
2647
  };
2488
2648
  entry.pool = (0, _lodashEs.cloneDeep)(pool);
2489
2649
  // Legacy marketing lookups can reuse complete records without changing
@@ -2922,6 +3082,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2922
3082
  });
2923
3083
  if (orderProduct && typeof orderProduct === 'object') {
2924
3084
  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]]));
3085
+ const isVenueExtra = ownershipKey === 'unified_booking_sales_retail' && ['tickets_extra', 'party_extra'].includes(venueMetadata.venue_booking_role);
3086
+ if (isVenueExtra && sourceProduct.metadata?.venue_extra_holder_variant_id !== undefined) {
3087
+ // null explicitly clears a previous SKU override. The adapter pairs the marker
3088
+ // with its resolved policy, independent of the product's original settings.
3089
+ venueMetadata.venue_extra_holder_variant_id = sourceProduct.metadata.venue_extra_holder_variant_id;
3090
+ const holderConfig = sourceProduct.holder_config ?? sourceProduct.metadata.holder_config;
3091
+ if (holderConfig) venueMetadata.holder_config = (0, _lodashEs.cloneDeep)(holderConfig);
3092
+ }
2925
3093
  // BaseSales may rebuild metadata from its price source. Stamp ownership and the selected
2926
3094
  // quotation shelf after that transform so neither booking adds nor edits lose quote identity.
2927
3095
  orderProduct.metadata = {
@@ -2932,6 +3100,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2932
3100
  quotation_shelf_id: quotationShelfId
2933
3101
  } : {})
2934
3102
  };
3103
+ // Extras use retail order-detail relations even when the catalog product
3104
+ // also has a bookable duration. Order binds the patch to the final line UID.
3105
+ if (isVenueExtra && Array.isArray(sourceProduct._extend?.holder_relations)) {
3106
+ orderProduct._extend = {
3107
+ ...orderProduct._extend,
3108
+ holder_relations: (0, _lodashEs.cloneDeep)(sourceProduct._extend.holder_relations)
3109
+ };
3110
+ }
2935
3111
  }
2936
3112
  return orderProduct;
2937
3113
  }
@@ -2981,6 +3157,11 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2981
3157
  return true;
2982
3158
  }
2983
3159
 
3160
+ /** The venue retail write path accepts per-line Holder relations for both templates. */
3161
+ supportsVenueExtraHolders() {
3162
+ return true;
3163
+ }
3164
+
2984
3165
  /**
2985
3166
  * Adds one retail line without replacing the cart's existing retail selection.
2986
3167
  * This is intentionally separate from stageRetailProducts(), whose contract is
@@ -3027,18 +3208,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3027
3208
  }
3028
3209
  };
3029
3210
  guard();
3030
- // Retail extras are order-owned, with their own UID and no Holder/booking.
3211
+ // Retail extras are order-owned, with their own UID and no booking.
3031
3212
  delete orderProduct.unique_identification_number;
3032
3213
  delete meta.unique_identification_number;
3033
3214
  delete meta.venue_booking_parent_uid;
3034
- orderProduct.holder_config = {
3035
- status: 'disable',
3036
- required: 0
3037
- };
3038
- meta.holder_config = {
3039
- status: 'disable',
3040
- required: 0
3041
- };
3042
3215
  return this.addProductToOrder(orderProduct, undefined, {
3043
3216
  disableMerge: true,
3044
3217
  availabilityCommitGuard: guard,
@@ -3055,8 +3228,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3055
3228
  // Its parent UID owns the extra; the parent's appointment time does not price it.
3056
3229
  const purchaseDatetime = String(meta.venue_booking_service_datetime || '');
3057
3230
  const normalizedPurchaseDatetime = purchaseDatetime.length === 16 ? `${purchaseDatetime}:00` : purchaseDatetime;
3058
- const identity = [order?.order_id, order?.external_sale_number];
3059
- const isCurrentOrder = () => this.getTempOrder() === order && order?.order_id === identity[0] && order?.external_sale_number === identity[1];
3231
+ const identity = [order?.order_id, order?.external_sale_number, order?.customer_id];
3232
+ const isCurrentOrder = () => this.getTempOrder() === order && order?.order_id === identity[0] && order?.external_sale_number === identity[1] && order?.customer_id === identity[2];
3060
3233
  const guard = () => {
3061
3234
  params.availabilityCommitGuard?.();
3062
3235
  const parent = (order?.products || []).find(line => getProductLineUid(line) === parentUid);
@@ -3065,14 +3238,6 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3065
3238
  guard();
3066
3239
  delete orderProduct.unique_identification_number;
3067
3240
  delete orderProduct.metadata.unique_identification_number;
3068
- orderProduct.holder_config = {
3069
- status: 'disable',
3070
- required: 0
3071
- };
3072
- orderProduct.metadata.holder_config = {
3073
- status: 'disable',
3074
- required: 0
3075
- };
3076
3241
  return this.addProductToOrder(orderProduct, undefined, {
3077
3242
  disableMerge: true,
3078
3243
  availabilityCommitGuard: guard,
@@ -3388,12 +3553,18 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3388
3553
  const cachedRawResources = this.availabilityRemoteOccupancyCache.read(cacheParams);
3389
3554
  if (cachedRawResources) {
3390
3555
  if (params.useCacheOnHit) {
3556
+ const logContext = this.getSolutionLogContext();
3391
3557
  void this.refreshAvailabilityRemoteResourceQuery({
3392
3558
  timezone: params.timezone,
3393
3559
  dateRange: params.dateRange,
3394
3560
  resourceIds: normalizedResourceIds
3395
3561
  }).catch(error => {
3396
- console.warn('[UnifiedBookingSales] Remote occupancy background refresh failed', error);
3562
+ this.logSolutionFailure('refreshAvailabilityRemoteResources', error, {
3563
+ resourceCount: normalizedResourceIds.length,
3564
+ dateRange: {
3565
+ ...params.dateRange
3566
+ }
3567
+ }, logContext, 'warning');
3397
3568
  });
3398
3569
  }
3399
3570
  return cachedRawResources;
@@ -3919,6 +4090,18 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3919
4090
  }
3920
4091
  }
3921
4092
  }
4093
+
4094
+ /** Read an existing customer selection without refreshing its clock or occupancy snapshot. */
4095
+ getCustomerSelectionProjection(contextId) {
4096
+ const context = this.getAvailabilityContextEntry(contextId);
4097
+ const projectionEntry = this.getActiveAvailabilityProjectionEntry(context);
4098
+ if (!projectionEntry) throw this.createAvailabilityFacadeError('AVAILABILITY_CONTEXT_NOT_FOUND', '所选商品上下文已关闭,请重新打开商品');
4099
+ return {
4100
+ context,
4101
+ projectionEntry,
4102
+ refreshed: false
4103
+ };
4104
+ }
3922
4105
  async ensureAvailabilityContextProjection(contextId, reason) {
3923
4106
  let retries = 0;
3924
4107
  while (retries < 3) {
@@ -4000,6 +4183,18 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4000
4183
 
4001
4184
  /** IO boundary: loads catalog, schedules, resources, occupancies, and registers one context. */
4002
4185
  async prepareAvailabilityProjection(params) {
4186
+ const logContext = this.getSolutionLogContext();
4187
+ try {
4188
+ return await this.prepareAvailabilityContext(params);
4189
+ } catch (error) {
4190
+ this.logSolutionFailure('prepareAvailabilityProjection', error, {
4191
+ productCount: params?.productIds?.length,
4192
+ resourceCount: params?.resourceIds?.length
4193
+ }, logContext);
4194
+ throw error;
4195
+ }
4196
+ }
4197
+ async prepareAvailabilityContext(params) {
4003
4198
  this.assertAvailabilityPrepareParams(params);
4004
4199
  const paramsWithDefaults = await this.resolveAvailabilityPrepareDefaults(params);
4005
4200
  const {
@@ -4068,15 +4263,19 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4068
4263
 
4069
4264
  /** Thin facade: auto-refresh on cart drift, then delegate to the pure projection query. */
4070
4265
  async queryBookingAvailability(contextId, request) {
4266
+ const customerSelectionSnapshot = request.target === 'resource' && request.customerSelectionSnapshot === true && (0, _platform.isCustomerUserPlatform)(this.otherParams?.platform);
4071
4267
  const {
4072
4268
  context,
4073
4269
  projectionEntry,
4074
4270
  refreshed
4075
- } = await this.ensureAvailabilityContextProjection(contextId, 'query_booking_availability');
4271
+ } = customerSelectionSnapshot ? this.getCustomerSelectionProjection(contextId) : await this.ensureAvailabilityContextProjection(contextId, 'query_booking_availability');
4076
4272
  this.assertContextualQueryFreshness(context, request);
4077
4273
  const strictAvailability = context.prepareParams.strictAvailability === true;
4078
4274
  const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
4079
4275
  const result = (0, _ResourcePlanner.queryAvailabilityProjection)(projectionEntry.projection, request, {
4276
+ ...(customerSelectionSnapshot ? {
4277
+ evaluatedAt: projectionEntry.projection.meta.now
4278
+ } : {}),
4080
4279
  useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
4081
4280
  allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
4082
4281
  });
@@ -4171,8 +4370,20 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4171
4370
  return (this.getTempOrder()?.bookings || []).find(booking => bookingUid && getBookingUid(booking) === bookingUid || productUid && String(booking.product_uid ?? '') === productUid);
4172
4371
  }
4173
4372
 
4174
- /** Revalidates against the latest landed occupancy cache, then mutates exactly one product line. */
4373
+ /** Customer snapshot writes defer availability to checkout; other callers retain cache revalidation. */
4175
4374
  async commitAvailabilitySelection(contextId, params) {
4375
+ const logContext = this.getSolutionLogContext();
4376
+ try {
4377
+ return await this.commitAvailabilitySelectionWithLock(contextId, params);
4378
+ } catch (error) {
4379
+ this.logSolutionFailure('commitAvailabilitySelection', error, {
4380
+ contextId,
4381
+ mode: params?.mode
4382
+ }, logContext);
4383
+ throw error;
4384
+ }
4385
+ }
4386
+ async commitAvailabilitySelectionWithLock(contextId, params) {
4176
4387
  const normalizedContextId = String(contextId || '').trim();
4177
4388
  if (!normalizedContextId) {
4178
4389
  throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'commitAvailabilitySelection 缺少 contextId', {
@@ -4184,8 +4395,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4184
4395
  if (isPartyReplacement && (!isEditingSelection || !Array.isArray(params.relatedRetailProducts))) {
4185
4396
  throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Party replacement requires edit/replace mode and the confirmed complete extras array');
4186
4397
  }
4398
+ const customerSelectionSnapshot = params.customerSelectionSnapshot === true && (0, _platform.isCustomerUserPlatform)(this.otherParams?.platform);
4187
4399
  const strictAvailability = this.availabilityContextRegistry.get(normalizedContextId)?.prepareParams.strictAvailability === true;
4188
- const hasCommitGuard = strictAvailability || isPartyReplacement || Boolean(params.availabilityCommitGuard);
4400
+ const hasCommitGuard = customerSelectionSnapshot || strictAvailability || isPartyReplacement || Boolean(params.availabilityCommitGuard);
4189
4401
  params.availabilityCommitGuard?.();
4190
4402
  // Stabilize the locally generated sale identity before taking the guard snapshot.
4191
4403
  if (hasCommitGuard) this.store.order?.ensureTempOrder?.();
@@ -4230,7 +4442,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4230
4442
  context,
4231
4443
  projectionEntry,
4232
4444
  refreshed
4233
- } = await this.ensureAvailabilityContextProjection(normalizedContextId, 'commit_precheck');
4445
+ } = customerSelectionSnapshot ? this.getCustomerSelectionProjection(normalizedContextId) : await this.ensureAvailabilityContextProjection(normalizedContextId, 'commit_precheck');
4234
4446
  if (refreshed) {
4235
4447
  throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'availability context 已刷新,请重新获取候选', {
4236
4448
  contextId: normalizedContextId,
@@ -4260,7 +4472,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4260
4472
  projectionContextVersion: projectionEntry.contextVersion
4261
4473
  });
4262
4474
  }
4263
- if (projectionEntry.orderRevision !== this.getCurrentOrderRevision()) {
4475
+ if (!customerSelectionSnapshot && projectionEntry.orderRevision !== this.getCurrentOrderRevision()) {
4264
4476
  throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '购物车已变化,请重新获取候选', {
4265
4477
  contextId: normalizedContextId,
4266
4478
  currentContextVersion: context.activeVersion,
@@ -4310,18 +4522,22 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4310
4522
  expectedVersion: context.activeVersion,
4311
4523
  expectedRefreshNonce: context.refreshNonce,
4312
4524
  expectedLifecycleGeneration: this.availabilityLifecycleGeneration,
4313
- expectedOrderRevision: String(baseProjection.meta.orderRevision ?? '')
4525
+ expectedOrderRevision: customerSelectionSnapshot ? this.getCurrentOrderRevision() : String(baseProjection.meta.orderRevision ?? '')
4314
4526
  };
4315
4527
  const prepareParams = baseProjection.meta.prepareParams;
4316
4528
  if (!prepareParams) {
4317
4529
  throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', 'projection 缺少 prepareParams,无法执行缓存重校验');
4318
4530
  }
4319
- const fallbackResources = {
4531
+ const fallbackResources = customerSelectionSnapshot ? undefined : {
4320
4532
  resources: (0, _lodashEs.cloneDeep)([...(baseProjection.resources || [])]),
4321
4533
  resourceOccupancies: (0, _lodashEs.cloneDeep)([...(baseProjection.resourceOccupancies || [])].filter(occupancy => occupancy.source !== 'cart')),
4322
4534
  includesInjectedRawOccupancies: true
4323
4535
  };
4324
- const commitSnapshot = await this.buildAvailabilityProjectionSnapshot({
4536
+ const commitSnapshot = customerSelectionSnapshot ? {
4537
+ projection: baseProjection,
4538
+ prepareParams,
4539
+ orderRevision: commitWriteGuard.expectedOrderRevision
4540
+ } : await this.buildAvailabilityProjectionSnapshot({
4325
4541
  ...this.cloneAvailabilityPrepareParams(prepareParams),
4326
4542
  editingProductLineUids: isEditingSelection && params.productLineUid ? [params.productLineUid] : []
4327
4543
  }, {
@@ -4330,7 +4546,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4330
4546
  durationCandidateAnchorAt: this.getAvailabilityDurationCandidateAnchorAt(baseProjection) || context.durationCandidateAnchorAt
4331
4547
  });
4332
4548
  const refreshedProjection = commitSnapshot.projection;
4333
- if (String(refreshedProjection.meta.orderRevision ?? '') !== String(baseProjection.meta.orderRevision ?? '')) {
4549
+ if (!customerSelectionSnapshot && String(refreshedProjection.meta.orderRevision ?? '') !== String(baseProjection.meta.orderRevision ?? '')) {
4334
4550
  await this.refreshAvailabilityContextProjection({
4335
4551
  contextId: normalizedContextId,
4336
4552
  reason: 'commit_order_revision_changed',
@@ -4351,7 +4567,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4351
4567
  const candidateDurationMinutes = getCandidateDurationMinutes(params.candidate);
4352
4568
  const candidateStartTime = getCandidateStartTime(params.candidate);
4353
4569
  const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !strictAvailability;
4354
- const refreshedRanges = (0, _ResourcePlanner.getProductTimeRanges)(refreshedProjection, {
4570
+ const refreshedRanges = customerSelectionSnapshot ? [params.candidate] : (0, _ResourcePlanner.getProductTimeRanges)(refreshedProjection, {
4355
4571
  productIds: [params.candidate.productId],
4356
4572
  dateRange: {
4357
4573
  startDate: params.candidate.startAt.slice(0, 10),
@@ -4392,7 +4608,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4392
4608
  productId: refreshedCandidateBase.productId
4393
4609
  });
4394
4610
  }
4395
- let validation = (0, _ResourcePlanner.validateAvailabilitySelection)(refreshedProjection, {
4611
+ let validation = customerSelectionSnapshot ? acceptCustomerSelectionSnapshot({
4612
+ candidate: params.candidate,
4613
+ product,
4614
+ resources: baseProjection.resources,
4615
+ requirementSelections: params.requirementSelections,
4616
+ partySize
4617
+ }) : (0, _ResourcePlanner.validateAvailabilitySelection)(refreshedProjection, {
4396
4618
  candidate: refreshedCandidateBase,
4397
4619
  requirementSelections: params.requirementSelections,
4398
4620
  partySize,
@@ -4431,7 +4653,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4431
4653
  // Revalidation failure must leave the caller's candidate reusable. Only publish the
4432
4654
  // refreshed projection/version after candidate and resource validation has passed;
4433
4655
  // otherwise a second Confirm from the still-open modal would incorrectly become stale.
4434
- const revalidationEntry = this.storeAvailabilityProjectionEntry({
4656
+ const revalidationEntry = customerSelectionSnapshot ? projectionEntry : this.storeAvailabilityProjectionEntry({
4435
4657
  contextId: normalizedContextId,
4436
4658
  prepareParams: commitSnapshot.prepareParams,
4437
4659
  prepareKey: context.prepareKey,
@@ -4440,7 +4662,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4440
4662
  incrementVersion: true
4441
4663
  });
4442
4664
  const revalidatedContext = this.getAvailabilityContextEntry(normalizedContextId);
4443
- await this.emitAvailabilityDiagnostic({
4665
+ if (!customerSelectionSnapshot) await this.emitAvailabilityDiagnostic({
4444
4666
  action: 'refresh',
4445
4667
  contextId: normalizedContextId,
4446
4668
  contextVersion: revalidatedContext.activeVersion,
@@ -4455,7 +4677,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4455
4677
  expectedVersion: revalidatedContext.activeVersion,
4456
4678
  expectedRefreshNonce: revalidatedContext.refreshNonce,
4457
4679
  expectedLifecycleGeneration: this.availabilityLifecycleGeneration,
4458
- expectedOrderRevision: revalidationEntry.orderRevision
4680
+ expectedOrderRevision: customerSelectionSnapshot ? commitWriteGuard.expectedOrderRevision : revalidationEntry.orderRevision
4459
4681
  };
4460
4682
  const refreshedCandidate = this.decorateAvailabilityCandidate(normalizedContextId, revalidatedContext.activeVersion, refreshedCandidateBase);
4461
4683
  // Order may await line/runtime setup. Its guarded transaction invokes this
@@ -4466,7 +4688,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4466
4688
  if (!availabilityCommitTargetGuard()) {
4467
4689
  throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '预约加购期间订单或业务已变化');
4468
4690
  }
4469
- if (!strictAvailability) return;
4691
+ if (customerSelectionSnapshot || !strictAvailability) return;
4470
4692
  const currentValidation = (0, _ResourcePlanner.validateAvailabilitySelection)(refreshedProjection, {
4471
4693
  candidate: refreshedCandidateBase,
4472
4694
  requirementSelections: params.requirementSelections,
@@ -4530,16 +4752,6 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
4530
4752
  const relatedRetailProducts = params.relatedRetailProducts.map(source => {
4531
4753
  const line = this.buildUnifiedOrderProduct(source, 'unified_booking_sales_retail');
4532
4754
  if (!line) throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '无法生成附加商品订单行');
4533
- if (line.metadata?.venue_booking_role === 'party_extra') {
4534
- line.holder_config = {
4535
- status: 'disable',
4536
- required: 0
4537
- };
4538
- line.metadata.holder_config = {
4539
- status: 'disable',
4540
- required: 0
4541
- };
4542
- }
4543
4755
  // This is the only replacement-specific UID restore. Order checks ownership/collisions.
4544
4756
  const sourceUid = getProductLineUid(source);
4545
4757
  if (sourceUid) {
@@ -145,6 +145,8 @@ export type ContextualAvailabilityQuery = Omit<Extract<AvailabilityQuery, {
145
145
  target: 'resource';
146
146
  }>, 'selectedRanges'> & {
147
147
  selectedRanges: ContextualProductTimeRange[];
148
+ /** PC/H5 only: retain the already-selected time while choosing resources in this snapshot. */
149
+ customerSelectionSnapshot?: boolean;
148
150
  });
149
151
  export type ContextualTimeAvailabilityItem = Omit<TimeAvailabilityItem, keyof ProductTimeRange> & ContextualProductTimeRange;
150
152
  export interface ContextualTimeAvailabilityGroup extends Omit<TimeAvailabilityGroup, 'times'> {
@@ -210,6 +212,8 @@ export interface UnifiedBookingSalesAddRetailProductParams {
210
212
  }
211
213
  export interface ContextualCommitAvailabilitySelectionParams {
212
214
  mode: 'add' | 'edit' | 'replace';
215
+ /** PC/H5 only: write the completed UI selection without re-querying availability; checkout is authoritative. */
216
+ customerSelectionSnapshot?: boolean;
213
217
  /** Local UI intent guard, checked again immediately before the Order mutation. */
214
218
  availabilityCommitGuard?: () => void;
215
219
  productLineUid?: string;
@@ -295,6 +299,7 @@ export interface UnifiedBookingSalesApi {
295
299
  loadProductsByScheduleDate: (params: UnifiedBookingSalesLoadProductsByScheduleDateParams) => Promise<unknown[]>;
296
300
  queryProducts: (params?: ProductListStoreQueryParams) => Promise<ProductData[]>;
297
301
  stageRetailProducts: (params: UnifiedBookingSalesStageRetailProductsParams) => Promise<Record<string, any> | null>;
302
+ supportsVenueExtraHolders: () => boolean;
298
303
  addRetailProduct: (params: UnifiedBookingSalesAddRetailProductParams) => Promise<Record<string, any>[]>;
299
304
  prepareAvailabilityProjection: (params: UnifiedBookingSalesPrepareAvailabilityProjectionParams) => Promise<AvailabilityContextRef>;
300
305
  getProductTimeRanges: (contextId: string, request?: GetProductTimeRangesRequest) => Promise<ContextualProductTimeRangeGroup[]>;