@pisell/pisellos 2.2.322 → 2.2.324
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.
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/inventory/index.d.ts +92 -0
- package/dist/inventory/index.js +509 -0
- package/dist/model/strategy/adapter/promotion/index.js +0 -9
- package/dist/modules/BookingContext/index.d.ts +2 -2
- package/dist/modules/BookingContext/index.js +55 -25
- package/dist/modules/BookingContext/types.d.ts +2 -0
- package/dist/modules/BookingContext/utils/calendarBooking.d.ts +15 -0
- package/dist/modules/BookingContext/utils/calendarBooking.js +207 -0
- package/dist/modules/BookingContext/utils/index.d.ts +1 -0
- package/dist/modules/BookingContext/utils/index.js +1 -0
- package/dist/modules/BookingContext/utils/productExtend.d.ts +20 -1
- package/dist/modules/BookingContext/utils/productExtend.js +122 -29
- package/dist/modules/Date/index.d.ts +1 -1
- package/dist/modules/Date/index.js +60 -14
- package/dist/modules/Date/types.d.ts +5 -0
- package/dist/modules/Discount/index.js +1 -0
- package/dist/modules/OpenData/index.d.ts +1 -0
- package/dist/modules/OpenData/index.js +1 -0
- package/dist/modules/OpenData/salesSettings.d.ts +32 -0
- package/dist/modules/OpenData/salesSettings.js +80 -0
- package/dist/modules/OpenData/types.d.ts +16 -0
- package/dist/modules/OpenData/utils.d.ts +1 -1
- package/dist/modules/OpenData/utils.js +3 -2
- package/dist/modules/Order/index.d.ts +54 -11
- package/dist/modules/Order/index.js +2699 -1411
- package/dist/modules/Order/types.d.ts +43 -5
- package/dist/modules/Order/types.js +4 -0
- package/dist/modules/Order/unpaidAmountGap.d.ts +6 -0
- package/dist/modules/Order/unpaidAmountGap.js +72 -0
- package/dist/modules/Order/utils/discountProductLineIdentity.js +2 -2
- package/dist/modules/Order/utils/productVoucherGroups.d.ts +15 -0
- package/dist/modules/Order/utils/productVoucherGroups.js +115 -0
- package/dist/modules/Order/utils.d.ts +3 -1
- package/dist/modules/Order/utils.js +18 -3
- package/dist/modules/Product/index.d.ts +1 -1
- package/dist/modules/Product/types.d.ts +5 -0
- package/dist/modules/ProductList/clientDataVariants.js +6 -2
- package/dist/modules/ProductList/index.d.ts +2 -0
- package/dist/modules/ProductList/index.js +161 -51
- package/dist/modules/ResourcePlanner/planner.js +58 -2
- package/dist/modules/ResourcePlanner/types.d.ts +13 -0
- package/dist/modules/Rules/index.d.ts +2 -0
- package/dist/modules/Rules/index.js +58 -39
- package/dist/modules/Schedule/index.d.ts +7 -1
- package/dist/modules/Schedule/index.js +155 -39
- package/dist/modules/Schedule/types.d.ts +2 -0
- package/dist/modules/bookingReadValidation.d.ts +6 -0
- package/dist/modules/bookingReadValidation.js +72 -0
- package/dist/plugins/request.d.ts +2 -0
- package/dist/server/index.d.ts +5 -0
- package/dist/server/index.js +1312 -1154
- package/dist/server/modules/order/index.js +2 -1
- package/dist/shared/receipt/customerInvoiceLanguages.d.ts +1 -1
- package/dist/shared/receipt/customerInvoiceLanguages.js +5 -3
- package/dist/shared/receipt/small-ticket.d.ts +4 -0
- package/dist/shared/receipt/small-ticket.js +70 -12
- package/dist/solution/BaseSales/index.d.ts +40 -5
- package/dist/solution/BaseSales/index.js +1939 -1484
- package/dist/solution/BaseSales/types.d.ts +4 -0
- package/dist/solution/BaseSales/types.js +1 -0
- package/dist/solution/BaseSales/utils/posDurationPricing.d.ts +21 -0
- package/dist/solution/BaseSales/utils/posDurationPricing.js +174 -0
- package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +2 -0
- package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +8 -8
- package/dist/solution/BookingByStep/index.d.ts +16 -2
- package/dist/solution/BookingByStep/index.js +676 -361
- package/dist/solution/BookingByStep/utils/resources.d.ts +10 -0
- package/dist/solution/BookingByStep/utils/resources.js +117 -76
- package/dist/solution/BookingTicket/index.d.ts +2 -2
- package/dist/solution/BookingTicket/index.js +249 -135
- package/dist/solution/BookingTicket/types.d.ts +14 -2
- package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +3 -1
- package/dist/solution/BookingTicket/utils/addProductDecision.js +39 -11
- package/dist/solution/BookingTicket/utils/resolveUniqueCartDetail.d.ts +8 -0
- package/dist/solution/BookingTicket/utils/resolveUniqueCartDetail.js +188 -0
- package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +8 -0
- package/dist/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +88 -0
- package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +1 -0
- package/dist/solution/BookingTicket/utils/scan/handleScan.js +2 -1
- package/dist/solution/OrderInvoicePreview/index.js +14 -8
- package/dist/solution/ScanOrder/index.d.ts +2 -0
- package/dist/solution/ScanOrder/index.js +166 -67
- package/dist/solution/ScanOrder/menuAvailability.d.ts +24 -0
- package/dist/solution/ScanOrder/menuAvailability.js +363 -0
- package/dist/solution/UnifiedBookingSales/catalogQueryBatch.d.ts +21 -0
- package/dist/solution/UnifiedBookingSales/catalogQueryBatch.js +202 -0
- package/dist/solution/UnifiedBookingSales/index.d.ts +96 -4
- package/dist/solution/UnifiedBookingSales/index.js +3391 -1176
- package/dist/solution/UnifiedBookingSales/remoteOccupancyCache.d.ts +2 -0
- package/dist/solution/UnifiedBookingSales/remoteOccupancyCache.js +4 -0
- package/dist/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
- package/dist/solution/UnifiedBookingSales/salesSettings.js +81 -0
- package/dist/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
- package/dist/solution/UnifiedBookingSales/sessionResourceCache.js +271 -0
- package/dist/solution/UnifiedBookingSales/types.d.ts +71 -2
- package/dist/solution/UnifiedBookingSales/types.js +7 -1
- package/dist/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
- package/dist/solution/UnifiedBookingSales/venueCatalogSession.js +283 -0
- package/dist/utils/platform.d.ts +2 -0
- package/dist/utils/platform.js +6 -0
- package/dist/utils/pos-receipt-auto-print.d.ts +4 -0
- package/dist/utils/pos-receipt-auto-print.js +14 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +12 -0
- package/lib/inventory/index.d.ts +92 -0
- package/lib/inventory/index.js +287 -0
- package/lib/model/strategy/adapter/promotion/index.js +1 -46
- package/lib/modules/BookingContext/index.d.ts +2 -2
- package/lib/modules/BookingContext/index.js +42 -10
- package/lib/modules/BookingContext/types.d.ts +2 -0
- package/lib/modules/BookingContext/utils/calendarBooking.d.ts +15 -0
- package/lib/modules/BookingContext/utils/calendarBooking.js +156 -0
- package/lib/modules/BookingContext/utils/index.d.ts +1 -0
- package/lib/modules/BookingContext/utils/index.js +11 -0
- package/lib/modules/BookingContext/utils/productExtend.d.ts +20 -1
- package/lib/modules/BookingContext/utils/productExtend.js +96 -7
- package/lib/modules/Date/index.d.ts +1 -1
- package/lib/modules/Date/index.js +28 -5
- package/lib/modules/Date/types.d.ts +5 -0
- package/lib/modules/Discount/index.js +1 -0
- package/lib/modules/OpenData/index.d.ts +1 -0
- package/lib/modules/OpenData/index.js +12 -0
- package/lib/modules/OpenData/salesSettings.d.ts +32 -0
- package/lib/modules/OpenData/salesSettings.js +70 -0
- package/lib/modules/OpenData/types.d.ts +16 -0
- package/lib/modules/OpenData/utils.d.ts +1 -1
- package/lib/modules/OpenData/utils.js +3 -2
- package/lib/modules/Order/index.d.ts +54 -11
- package/lib/modules/Order/index.js +659 -80
- package/lib/modules/Order/types.d.ts +43 -5
- package/lib/modules/Order/types.js +2 -0
- package/lib/modules/Order/unpaidAmountGap.d.ts +6 -0
- package/lib/modules/Order/unpaidAmountGap.js +60 -0
- package/lib/modules/Order/utils/discountProductLineIdentity.js +1 -1
- package/lib/modules/Order/utils/productVoucherGroups.d.ts +15 -0
- package/lib/modules/Order/utils/productVoucherGroups.js +64 -0
- package/lib/modules/Order/utils.d.ts +3 -1
- package/lib/modules/Order/utils.js +19 -2
- package/lib/modules/Product/index.d.ts +1 -1
- package/lib/modules/Product/types.d.ts +5 -0
- package/lib/modules/ProductList/clientDataVariants.js +6 -2
- package/lib/modules/ProductList/index.d.ts +2 -0
- package/lib/modules/ProductList/index.js +74 -0
- package/lib/modules/ResourcePlanner/planner.js +52 -1
- package/lib/modules/ResourcePlanner/types.d.ts +13 -0
- package/lib/modules/Rules/index.d.ts +2 -0
- package/lib/modules/Rules/index.js +25 -9
- package/lib/modules/Schedule/index.d.ts +7 -1
- package/lib/modules/Schedule/index.js +68 -4
- package/lib/modules/Schedule/types.d.ts +2 -0
- package/lib/modules/bookingReadValidation.d.ts +6 -0
- package/lib/modules/bookingReadValidation.js +56 -0
- package/lib/plugins/request.d.ts +2 -0
- package/lib/server/index.d.ts +5 -0
- package/lib/server/index.js +124 -16
- package/lib/server/modules/order/index.js +2 -1
- package/lib/shared/receipt/customerInvoiceLanguages.d.ts +1 -1
- package/lib/shared/receipt/customerInvoiceLanguages.js +5 -3
- package/lib/shared/receipt/small-ticket.d.ts +4 -0
- package/lib/shared/receipt/small-ticket.js +63 -8
- package/lib/solution/BaseSales/index.d.ts +40 -5
- package/lib/solution/BaseSales/index.js +296 -43
- package/lib/solution/BaseSales/types.d.ts +4 -0
- package/lib/solution/BaseSales/types.js +1 -0
- package/lib/solution/BaseSales/utils/posDurationPricing.d.ts +21 -0
- package/lib/solution/BaseSales/utils/posDurationPricing.js +133 -0
- package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +2 -0
- package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +1 -1
- package/lib/solution/BookingByStep/index.d.ts +16 -2
- package/lib/solution/BookingByStep/index.js +222 -14
- package/lib/solution/BookingByStep/utils/resources.d.ts +10 -0
- package/lib/solution/BookingByStep/utils/resources.js +25 -15
- package/lib/solution/BookingTicket/index.d.ts +2 -2
- package/lib/solution/BookingTicket/index.js +47 -4
- package/lib/solution/BookingTicket/types.d.ts +14 -2
- package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +3 -1
- package/lib/solution/BookingTicket/utils/addProductDecision.js +37 -6
- package/lib/solution/BookingTicket/utils/resolveUniqueCartDetail.d.ts +8 -0
- package/lib/solution/BookingTicket/utils/resolveUniqueCartDetail.js +136 -0
- package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.d.ts +8 -0
- package/lib/solution/BookingTicket/utils/scan/applyProductVoucherCollectionScan.js +54 -0
- package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +1 -0
- package/lib/solution/BookingTicket/utils/scan/handleScan.js +2 -1
- package/lib/solution/OrderInvoicePreview/index.js +7 -1
- package/lib/solution/ScanOrder/index.d.ts +2 -0
- package/lib/solution/ScanOrder/index.js +72 -2
- package/lib/solution/ScanOrder/menuAvailability.d.ts +24 -0
- package/lib/solution/ScanOrder/menuAvailability.js +203 -0
- package/lib/solution/UnifiedBookingSales/catalogQueryBatch.d.ts +21 -0
- package/lib/solution/UnifiedBookingSales/catalogQueryBatch.js +109 -0
- package/lib/solution/UnifiedBookingSales/index.d.ts +96 -4
- package/lib/solution/UnifiedBookingSales/index.js +1339 -74
- package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.d.ts +2 -0
- package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.js +2 -0
- package/lib/solution/UnifiedBookingSales/salesSettings.d.ts +16 -0
- package/lib/solution/UnifiedBookingSales/salesSettings.js +72 -0
- package/lib/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
- package/lib/solution/UnifiedBookingSales/sessionResourceCache.js +199 -0
- package/lib/solution/UnifiedBookingSales/types.d.ts +71 -2
- package/lib/solution/UnifiedBookingSales/types.js +4 -1
- package/lib/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
- package/lib/solution/UnifiedBookingSales/venueCatalogSession.js +155 -0
- package/lib/utils/platform.d.ts +2 -0
- package/lib/utils/platform.js +7 -0
- package/lib/utils/pos-receipt-auto-print.d.ts +4 -0
- package/lib/utils/pos-receipt-auto-print.js +13 -0
- package/package.json +1 -1
|
@@ -36,7 +36,20 @@ var _pickupTiming = require("../../modules/Order/pickupTiming");
|
|
|
36
36
|
var _cacheItemToBookingInput = require("../../modules/BookingContext/utils/cacheItemToBookingInput");
|
|
37
37
|
var _utils = require("../../modules/BookingContext/utils");
|
|
38
38
|
var _OpenData = require("../../modules/OpenData");
|
|
39
|
+
var _salesSettings = require("./salesSettings");
|
|
40
|
+
Object.keys(_salesSettings).forEach(function (key) {
|
|
41
|
+
if (key === "default" || key === "__esModule") return;
|
|
42
|
+
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
43
|
+
if (key in exports && exports[key] === _salesSettings[key]) return;
|
|
44
|
+
Object.defineProperty(exports, key, {
|
|
45
|
+
enumerable: true,
|
|
46
|
+
get: function () {
|
|
47
|
+
return _salesSettings[key];
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
});
|
|
39
51
|
var _getDateIsInSchedule = require("../../modules/Schedule/getDateIsInSchedule");
|
|
52
|
+
var _clientDataVariants = require("../../modules/ProductList/clientDataVariants");
|
|
40
53
|
var _ResourcePlanner = require("../../modules/ResourcePlanner");
|
|
41
54
|
var _types = require("./types");
|
|
42
55
|
Object.keys(_types).forEach(function (key) {
|
|
@@ -51,13 +64,17 @@ Object.keys(_types).forEach(function (key) {
|
|
|
51
64
|
});
|
|
52
65
|
});
|
|
53
66
|
var _remoteOccupancyCache = require("./remoteOccupancyCache");
|
|
67
|
+
var _sessionResourceCache = require("./sessionResourceCache");
|
|
54
68
|
var _businessAvailability = require("./businessAvailability");
|
|
69
|
+
var _catalogQueryBatch = require("./catalogQueryBatch");
|
|
70
|
+
var _venueCatalogSession = require("./venueCatalogSession");
|
|
55
71
|
var _BookingTicket = require("../BookingTicket");
|
|
56
72
|
var _localClock = require("../../modules/ResourcePlanner/localClock");
|
|
57
73
|
var _platform = require("../../utils/platform");
|
|
74
|
+
var _posReceiptAutoPrint = require("../../utils/pos-receipt-auto-print");
|
|
58
75
|
var _itemRule = require("../../model/strategy/adapter/itemRule");
|
|
59
76
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
60
|
-
const OPEN_DATA_SECTION_CODES = ['sale', 'reservation', 'fulfillment', 'menu', 'workflow', 'documents', 'basic', 'checkout', 'availability'];
|
|
77
|
+
const OPEN_DATA_SECTION_CODES = ['sale', 'reservation', 'fulfillment', 'menu', 'workflow', 'documents', 'basic', 'checkout', 'availability', 'interface'];
|
|
61
78
|
function normalizePositiveInteger(value) {
|
|
62
79
|
const normalized = Number(value);
|
|
63
80
|
if (!Number.isInteger(normalized) || normalized <= 0) return undefined;
|
|
@@ -219,6 +236,7 @@ const MAX_AVAILABILITY_RANGE_DAYS = 90;
|
|
|
219
236
|
const MAX_AVAILABILITY_CONTEXT_REGISTRY = 128;
|
|
220
237
|
const MAX_AVAILABILITY_PROJECTION_POOL = 16;
|
|
221
238
|
const MAX_REMOTE_OCCUPANCY_RESOURCE_DATE_CELLS = 4096;
|
|
239
|
+
const PREVIEW_OCCUPANCY_CACHE_MAX_AGE_MS = 30 * 1000;
|
|
222
240
|
function isValidClockTime(value) {
|
|
223
241
|
const match = /^(\d{2}):(\d{2})$/.exec(value);
|
|
224
242
|
if (!match) return false;
|
|
@@ -1061,6 +1079,11 @@ function buildBookingFromAvailabilitySelection(params) {
|
|
|
1061
1079
|
unified_booking_sales: true,
|
|
1062
1080
|
availability_candidate_key: candidate.key,
|
|
1063
1081
|
availability_source: candidate.source,
|
|
1082
|
+
availability_business_date: candidate.businessDate || candidate.date,
|
|
1083
|
+
availability_timezone: candidate.timezone,
|
|
1084
|
+
...(candidate.primaryScheduleRef ? {
|
|
1085
|
+
availability_primary_schedule_ref: (0, _lodashEs.cloneDeep)(candidate.primaryScheduleRef)
|
|
1086
|
+
} : {}),
|
|
1064
1087
|
availability_slice_start_at: candidate.startAt,
|
|
1065
1088
|
availability_slice_end_at: candidate.endAt,
|
|
1066
1089
|
availability_schedule_refs: candidate.scheduleRefs,
|
|
@@ -1221,8 +1244,13 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1221
1244
|
runtimeOpenDataModule = null;
|
|
1222
1245
|
runtimeOpenDataCore;
|
|
1223
1246
|
runtimeOpenDataGeneration = 0;
|
|
1247
|
+
runtimeInitializationGeneration = 0;
|
|
1224
1248
|
runtimeOpenDataDestroyed = false;
|
|
1225
1249
|
unifiedProductCatalog = [];
|
|
1250
|
+
venueCatalogSessions = new Set();
|
|
1251
|
+
venueCatalogSessionKey;
|
|
1252
|
+
venueCatalogMenus;
|
|
1253
|
+
venueVariantDetails = new Map();
|
|
1226
1254
|
availabilityRuntimeOffsetMinutes = null;
|
|
1227
1255
|
availabilityScheduleCatalog = null;
|
|
1228
1256
|
availabilityProjectionSequence = 0;
|
|
@@ -1233,6 +1261,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1233
1261
|
availabilityPrepareInFlight = new Map();
|
|
1234
1262
|
availabilityProjectionRefreshInFlight = new Map();
|
|
1235
1263
|
availabilityRemoteOccupancyCache = new _remoteOccupancyCache.AvailabilityRemoteOccupancyCache(MAX_REMOTE_OCCUPANCY_RESOURCE_DATE_CELLS);
|
|
1264
|
+
availabilitySessionResourceCache = new _sessionResourceCache.AvailabilitySessionResourceCache();
|
|
1236
1265
|
availabilityRemoteResourceQueryInFlight = new Map();
|
|
1237
1266
|
availabilityRemoteResourceQuerySequence = 0;
|
|
1238
1267
|
availabilityRemoteResourceEpoch = 0;
|
|
@@ -1241,15 +1270,24 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1241
1270
|
allergyItemRuleConfigs = [];
|
|
1242
1271
|
allergyItemRuleConfigsPromise = null;
|
|
1243
1272
|
async initialize(core, options = {}) {
|
|
1273
|
+
const initializationGeneration = ++this.runtimeInitializationGeneration;
|
|
1244
1274
|
this.resetRuntimeOpenData();
|
|
1245
1275
|
this.runtimeOpenDataDestroyed = false;
|
|
1246
|
-
const openDataGeneration = this.runtimeOpenDataGeneration;
|
|
1247
1276
|
this.availabilityScheduleCatalog = null;
|
|
1248
1277
|
this.availabilityRuntimeOffsetMinutes = (0, _localClock.captureRuntimeOffsetMinutes)();
|
|
1249
1278
|
this.clearAvailabilityRemoteResourceState();
|
|
1250
1279
|
this.resetAllergyItemRuleState();
|
|
1251
|
-
await
|
|
1252
|
-
|
|
1280
|
+
// BaseSales synchronously installs this runtime before its first await. Cache
|
|
1281
|
+
// refreshes during that await are valid; they are not a new initialization.
|
|
1282
|
+
const initialization = super.initialize(core, options);
|
|
1283
|
+
const scope = this.getRuntimeOpenDataScope();
|
|
1284
|
+
const openDataModule = this.store.openData;
|
|
1285
|
+
await initialization;
|
|
1286
|
+
if (this.runtimeOpenDataDestroyed || initializationGeneration !== this.runtimeInitializationGeneration) {
|
|
1287
|
+
// A destroyed/reinitialized instance must not publish a ready snapshot.
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
if (core !== this.core || openDataModule !== this.store.openData || scope !== this.getRuntimeOpenDataScope()) {
|
|
1253
1291
|
throw new Error('Store settings changed. Please try again.');
|
|
1254
1292
|
}
|
|
1255
1293
|
this.captureAvailabilityScheduleCatalog();
|
|
@@ -1469,6 +1507,96 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1469
1507
|
}
|
|
1470
1508
|
};
|
|
1471
1509
|
}
|
|
1510
|
+
|
|
1511
|
+
/** Reuse an approved calendar cache; only the final commit may mutate the order. */
|
|
1512
|
+
async prepareDirectAddCalendarBooking(cacheItem, options = {}) {
|
|
1513
|
+
if ((0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform) !== 'pos' || cacheItem?._data?.calendarManualBooking || cacheItem?.duration?.type === 'days') return null;
|
|
1514
|
+
if (!cacheItem?._data?.calendarBookingPreparationKey || (0, _utils.calendarBookingNeedsInput)(cacheItem)) {
|
|
1515
|
+
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Calendar booking still requires product input.');
|
|
1516
|
+
}
|
|
1517
|
+
const productId = Number(cacheItem.product_id ?? cacheItem.id);
|
|
1518
|
+
const bookingCount = Number(options.bookingCount ?? cacheItem._extend?.quantity ?? 1);
|
|
1519
|
+
const capacity = cacheItem._extend?.capacity || [];
|
|
1520
|
+
const partySize = Array.isArray(capacity) ? Math.max(1, capacity.reduce((sum, item) => sum + Number(item.value), 0)) : NaN;
|
|
1521
|
+
if (!Number.isSafeInteger(productId) || productId <= 0 || !Number.isInteger(bookingCount) || bookingCount <= 0 || !Array.isArray(capacity) || !capacity.every(item => Number.isInteger(Number(item.value)) && Number(item.value) >= 0) || !Number.isInteger(partySize)) throw new _ResourcePlanner.AvailabilityError('INVALID_RESERVATION_QUANTITY', 'Invalid calendar booking quantity.');
|
|
1522
|
+
const product = normalizeProductForAvailability(cacheItem, this.getAvailabilityScheduleCatalog(), this.getAvailabilityRuntimeOffsetMinutes());
|
|
1523
|
+
if (product.kind !== 'duration' && product.kind !== 'session') return null;
|
|
1524
|
+
const range = {
|
|
1525
|
+
startAt: `${(0, _dayjs.default)(cacheItem._extend.start_date).format('YYYY-MM-DD')}T${cacheItem._extend.start_time}:00${(0, _localClock.formatFixedOffset)(this.getAvailabilityRuntimeOffsetMinutes())}`,
|
|
1526
|
+
endAt: `${(0, _dayjs.default)(cacheItem._extend.end_date).format('YYYY-MM-DD')}T${cacheItem._extend.end_time}:00${(0, _localClock.formatFixedOffset)(this.getAvailabilityRuntimeOffsetMinutes())}`
|
|
1527
|
+
};
|
|
1528
|
+
const requirementSelections = [];
|
|
1529
|
+
for (const [formId, rows] of Object.entries(cacheItem._extend?.resource || {})) {
|
|
1530
|
+
if (!Array.isArray(rows)) throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Invalid selected calendar resources.');
|
|
1531
|
+
if (!rows.length) continue;
|
|
1532
|
+
const groups = (product.requirementGroups || []).filter(group => String(group.formId) === formId);
|
|
1533
|
+
if (groups.length !== 1 || rows.some(row => row.form_id != null && String(row.form_id) !== formId)) {
|
|
1534
|
+
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Calendar resource group does not belong to this product.');
|
|
1535
|
+
}
|
|
1536
|
+
requirementSelections.push({
|
|
1537
|
+
requirementGroupId: groups[0].id,
|
|
1538
|
+
formId: groups[0].formId,
|
|
1539
|
+
resourceIds: rows.map(row => row.relation_id ?? row.resource_id)
|
|
1540
|
+
});
|
|
1541
|
+
}
|
|
1542
|
+
const order = this.getTempOrder();
|
|
1543
|
+
const calendarOrderSessionId = this.getOrderSessionId();
|
|
1544
|
+
const scope = JSON.stringify(this.getAvailabilityScopeDescriptor());
|
|
1545
|
+
const assertCurrent = () => {
|
|
1546
|
+
options.availabilityCommitGuard?.();
|
|
1547
|
+
if (calendarOrderSessionId && !this.isOrderSessionCurrent(calendarOrderSessionId) || this.getTempOrder() !== order || JSON.stringify(this.getAvailabilityScopeDescriptor()) !== scope) {
|
|
1548
|
+
throw new _ResourcePlanner.AvailabilityError('AVAILABILITY_SELECTION_STALE', 'Calendar booking order changed.');
|
|
1549
|
+
}
|
|
1550
|
+
};
|
|
1551
|
+
let contextId;
|
|
1552
|
+
try {
|
|
1553
|
+
assertCurrent();
|
|
1554
|
+
const context = await this.prepareAvailabilityProjection({
|
|
1555
|
+
productIds: [productId],
|
|
1556
|
+
dateRange: {
|
|
1557
|
+
startDate: range.startAt.slice(0, 10),
|
|
1558
|
+
endDate: range.endAt.slice(0, 10)
|
|
1559
|
+
},
|
|
1560
|
+
rawProducts: [...this.unifiedProductCatalog.filter(item => String(item.id) !== String(productId)), cacheItem]
|
|
1561
|
+
});
|
|
1562
|
+
contextId = context.contextId;
|
|
1563
|
+
assertCurrent();
|
|
1564
|
+
const groups = await this.getProductTimeRanges(contextId, {
|
|
1565
|
+
productIds: [productId],
|
|
1566
|
+
requestedRangesByProductId: {
|
|
1567
|
+
[String(productId)]: range
|
|
1568
|
+
}
|
|
1569
|
+
});
|
|
1570
|
+
assertCurrent();
|
|
1571
|
+
const ranges = groups.find(group => String(group.productId) === String(productId))?.ranges || [];
|
|
1572
|
+
if (ranges.length !== 1) throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', 'Calendar booking requires one exact interval.');
|
|
1573
|
+
const candidate = ranges[0];
|
|
1574
|
+
const contextEntry = this.getAvailabilityContextEntry(contextId);
|
|
1575
|
+
contextEntry.calendarOrderSessionId = calendarOrderSessionId ?? undefined;
|
|
1576
|
+
const projection = this.getActiveAvailabilityProjectionEntry(contextEntry).projection;
|
|
1577
|
+
const forced = buildPosForcedAvailabilityAssignments({
|
|
1578
|
+
product,
|
|
1579
|
+
resources: projection.resources,
|
|
1580
|
+
candidate,
|
|
1581
|
+
requirementSelections,
|
|
1582
|
+
partySize
|
|
1583
|
+
});
|
|
1584
|
+
if (forced.conflicts.length) throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', 'Invalid calendar resource selection.', {
|
|
1585
|
+
validation: forced
|
|
1586
|
+
});
|
|
1587
|
+
return {
|
|
1588
|
+
cacheItem,
|
|
1589
|
+
contextId,
|
|
1590
|
+
candidate,
|
|
1591
|
+
requirementSelections,
|
|
1592
|
+
partySize,
|
|
1593
|
+
bookingCount
|
|
1594
|
+
};
|
|
1595
|
+
} catch (error) {
|
|
1596
|
+
if (contextId) this.releaseAvailabilityContext(contextId);
|
|
1597
|
+
throw error;
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1472
1600
|
async resolveAvailabilityPrepareDefaults(params) {
|
|
1473
1601
|
const needsOperatingHours = params.businessHours === undefined;
|
|
1474
1602
|
const needsTimeSlice = params.slotStepMinutes === undefined;
|
|
@@ -1525,6 +1653,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1525
1653
|
clearAvailabilityRemoteResourceState() {
|
|
1526
1654
|
this.availabilityRemoteResourceEpoch += 1;
|
|
1527
1655
|
this.availabilityRemoteOccupancyCache.clear();
|
|
1656
|
+
this.availabilitySessionResourceCache.clear();
|
|
1528
1657
|
this.availabilityRemoteResourceQueryInFlight.clear();
|
|
1529
1658
|
this.availabilityRemoteResourceQuerySequence = 0;
|
|
1530
1659
|
}
|
|
@@ -1546,6 +1675,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1546
1675
|
cover = false
|
|
1547
1676
|
} = {}) {
|
|
1548
1677
|
const previousScope = this.getAvailabilityScopeDescriptor(this.otherParams || {});
|
|
1678
|
+
const previousCatalogScope = this.otherParams?.catalogScopeKey;
|
|
1549
1679
|
const previousItemRuleConfig = this.otherParams?.itemRule;
|
|
1550
1680
|
const explicitlySetsOpenData = Object.prototype.hasOwnProperty.call(params, 'openData');
|
|
1551
1681
|
const nextParams = cover ? params : {
|
|
@@ -1558,6 +1688,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1558
1688
|
await super.setOtherParams(params, {
|
|
1559
1689
|
cover
|
|
1560
1690
|
});
|
|
1691
|
+
if (previousCatalogScope !== this.otherParams?.catalogScopeKey && (previousCatalogScope || this.otherParams?.catalogScopeKey)) {
|
|
1692
|
+
this.unifiedProductCatalog = [];
|
|
1693
|
+
await this.core.effects.emit(`${this.name}:onProductsLoaded`, []);
|
|
1694
|
+
}
|
|
1561
1695
|
const nextScope = this.getAvailabilityScopeDescriptor(this.otherParams || {});
|
|
1562
1696
|
if (explicitlySetsOpenData) {
|
|
1563
1697
|
this.openDataTarget = this.otherParams?.openData && nextScope.businessCode && nextScope.channel ? `${nextScope.businessCode}+${nextScope.channel}` : null;
|
|
@@ -1571,6 +1705,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1571
1705
|
}
|
|
1572
1706
|
}
|
|
1573
1707
|
async destroy() {
|
|
1708
|
+
this.runtimeInitializationGeneration += 1;
|
|
1574
1709
|
this.runtimeOpenDataDestroyed = true;
|
|
1575
1710
|
this.clearOpenDataCache();
|
|
1576
1711
|
this.availabilityScheduleCatalog = null;
|
|
@@ -1634,12 +1769,48 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1634
1769
|
contextId: context.contextId,
|
|
1635
1770
|
...(projection && this.usesDurationTimeGrid(projection) ? {
|
|
1636
1771
|
durationTimeSelection: {
|
|
1637
|
-
version:
|
|
1638
|
-
currentBusinessDate: this.getCurrentAvailabilityBusinessDate(projection)
|
|
1772
|
+
version: 2,
|
|
1773
|
+
currentBusinessDate: this.getCurrentAvailabilityBusinessDate(projection),
|
|
1774
|
+
orderSessionId: this.getOrderSessionId()
|
|
1639
1775
|
}
|
|
1640
1776
|
} : {})
|
|
1641
1777
|
};
|
|
1642
1778
|
}
|
|
1779
|
+
|
|
1780
|
+
/** Accept the v2 interval only within the POS order that recorded it. */
|
|
1781
|
+
resolveOrderRememberedTimes(context, projection, ranges, orderSessionId) {
|
|
1782
|
+
if (ranges === undefined) return undefined;
|
|
1783
|
+
if (String(this.otherParams?.platform ?? '').trim().toLowerCase() !== 'pos' || context.prepareParams.editingProductLineUids?.length || !this.usesDurationTimeGrid(projection)) return undefined;
|
|
1784
|
+
this.assertRememberedOrderSession(orderSessionId);
|
|
1785
|
+
if (!isRecord(ranges) || !Object.keys(ranges).length) {
|
|
1786
|
+
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间区间不能为空');
|
|
1787
|
+
}
|
|
1788
|
+
const offset = (0, _localClock.extractFixedOffsetMinutes)(projection.meta.now) ?? this.getAvailabilityRuntimeOffsetMinutes();
|
|
1789
|
+
return Object.fromEntries(Object.entries(ranges).map(([productId, range]) => {
|
|
1790
|
+
try {
|
|
1791
|
+
const normalize = value => {
|
|
1792
|
+
if (typeof value !== 'string') throw new Error('Missing interval boundary');
|
|
1793
|
+
const scalar = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(value));
|
|
1794
|
+
const inputOffset = (0, _localClock.extractFixedOffsetMinutes)(value) ?? offset;
|
|
1795
|
+
return (0, _localClock.formatLocalDateTime)(scalar + (offset - inputOffset) * 60000, offset);
|
|
1796
|
+
};
|
|
1797
|
+
const startAt = normalize(range.startAt);
|
|
1798
|
+
const endAt = normalize(range.endAt);
|
|
1799
|
+
if (endAt <= startAt) throw new Error('Invalid interval');
|
|
1800
|
+
return [productId, {
|
|
1801
|
+
startAt,
|
|
1802
|
+
endAt
|
|
1803
|
+
}];
|
|
1804
|
+
} catch {
|
|
1805
|
+
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间必须包含有效且递增的开始和结束时间');
|
|
1806
|
+
}
|
|
1807
|
+
}));
|
|
1808
|
+
}
|
|
1809
|
+
assertRememberedOrderSession(orderSessionId) {
|
|
1810
|
+
if (!orderSessionId || !this.isOrderSessionCurrent(orderSessionId)) {
|
|
1811
|
+
throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '记忆时间所属订单已变化,请重新选择');
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1643
1814
|
async emitAvailabilityDiagnostic(payload) {
|
|
1644
1815
|
await this.core?.effects?.emit?.(`${this.name}:${_types.UnifiedBookingSalesHooks.onAvailabilityProjectionDiagnostic}`, {
|
|
1645
1816
|
...payload,
|
|
@@ -1812,14 +1983,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
1812
1983
|
}
|
|
1813
1984
|
|
|
1814
1985
|
/**
|
|
1815
|
-
* PC/H5
|
|
1986
|
+
* PC/H5 及自助终端结账默认直接等待云端 checkout;POS/WebPOS 仍保持本地待同步。
|
|
1816
1987
|
* 显式传 checkoutSyncTaskEnabled: true 时仍可回退到本地同步模式。
|
|
1817
1988
|
*/
|
|
1818
1989
|
shouldUseCheckoutSyncTask() {
|
|
1819
1990
|
const configured = this.otherParams?.checkoutSyncTaskEnabled;
|
|
1820
1991
|
if (configured === true) return true;
|
|
1821
1992
|
const platform = (0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform);
|
|
1822
|
-
return !(0, _platform.isCustomerUserPlatform)(platform) && platform
|
|
1993
|
+
return !(0, _platform.isCustomerUserPlatform)(platform) && !(0, _platform.isSelfServicePlatform)(platform);
|
|
1823
1994
|
}
|
|
1824
1995
|
|
|
1825
1996
|
/** UnifiedBookingSales 的真实结账默认请求收据数据,供云端确认后再本地打印。 */
|
|
@@ -2038,6 +2209,121 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2038
2209
|
async getOpenData() {
|
|
2039
2210
|
return this.loadOpenDataConfig();
|
|
2040
2211
|
}
|
|
2212
|
+
|
|
2213
|
+
/** One policy snapshot for all Sales 2.0 consumers. Network errors must reach the caller. */
|
|
2214
|
+
async getSalesSettings() {
|
|
2215
|
+
const config = await this.getOpenData();
|
|
2216
|
+
if (!config) throw new Error('Sales settings are unavailable without a business context.');
|
|
2217
|
+
return (0, _OpenData.normalizeSalesSettings)(config, this.otherParams?.platform);
|
|
2218
|
+
}
|
|
2219
|
+
getLoadedSalesSettings() {
|
|
2220
|
+
if (!this.runtimeOpenDataSnapshot) {
|
|
2221
|
+
throw new Error('Sales settings are not loaded. Call getSalesSettings before preparing a booking.');
|
|
2222
|
+
}
|
|
2223
|
+
return (0, _OpenData.normalizeSalesSettings)(this.runtimeOpenDataSnapshot, this.otherParams?.platform);
|
|
2224
|
+
}
|
|
2225
|
+
getProductBookingsForScheduling() {
|
|
2226
|
+
const seen = new Set();
|
|
2227
|
+
return (this.getTempOrder()?.products || []).flatMap(product => {
|
|
2228
|
+
if (product.metadata?.product_add_schedule_time != null || product.deleted_at) return [];
|
|
2229
|
+
const booking = this.findLinkedBooking(product);
|
|
2230
|
+
if (!booking || (0, _pickupTiming.isFulfillmentTimingBooking)(booking) || seen.has(booking)) return [];
|
|
2231
|
+
seen.add(booking);
|
|
2232
|
+
return [booking];
|
|
2233
|
+
});
|
|
2234
|
+
}
|
|
2235
|
+
shouldApplyMultipleBookingScheduling() {
|
|
2236
|
+
const platform = (0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform);
|
|
2237
|
+
return platform === 'pos' || platform === 'webpos';
|
|
2238
|
+
}
|
|
2239
|
+
resolveLoadedDefaultBookingStart(holderIds, fallback) {
|
|
2240
|
+
// Customer channels keep their entry default instead of following cart bookings.
|
|
2241
|
+
// Keep this callback installed so BookingContext cannot fall back to Board.
|
|
2242
|
+
if (!this.shouldApplyMultipleBookingScheduling()) return (0, _salesSettings.normalizeBookingDateTime)(fallback);
|
|
2243
|
+
const settings = this.getLoadedSalesSettings();
|
|
2244
|
+
return (0, _salesSettings.resolveDefaultBookingStart)({
|
|
2245
|
+
bookings: this.getProductBookingsForScheduling(),
|
|
2246
|
+
holderIds,
|
|
2247
|
+
mode: settings.reservation.multipleBookingScheduling,
|
|
2248
|
+
fallback
|
|
2249
|
+
});
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
/** Used by the SKU flow after Holder changes, without changing an explicit user-selected time. */
|
|
2253
|
+
async resolveDefaultBookingStart(params) {
|
|
2254
|
+
if (!this.shouldApplyMultipleBookingScheduling()) return (0, _salesSettings.normalizeBookingDateTime)(params.fallback);
|
|
2255
|
+
await this.getSalesSettings();
|
|
2256
|
+
return this.resolveLoadedDefaultBookingStart(params.holderIds, params.fallback);
|
|
2257
|
+
}
|
|
2258
|
+
buildBookingCalcContext(extra) {
|
|
2259
|
+
return {
|
|
2260
|
+
...super.buildBookingCalcContext(extra),
|
|
2261
|
+
resolveDefaultBookingStart: (cacheItem, fallback) => extra?.useCurrentTimeAfterRememberedExpiry ? (0, _salesSettings.normalizeBookingDateTime)(fallback) : this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
|
|
2262
|
+
};
|
|
2263
|
+
}
|
|
2264
|
+
buildAddProductCtx(extra) {
|
|
2265
|
+
return {
|
|
2266
|
+
...super.buildAddProductCtx(extra),
|
|
2267
|
+
resolveDefaultBookingStart: (cacheItem, fallback) => extra?.useCurrentTimeAfterRememberedExpiry ? (0, _salesSettings.normalizeBookingDateTime)(fallback) : this.resolveLoadedDefaultBookingStart(extra?.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem), fallback)
|
|
2268
|
+
};
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
/** Re-evaluate an automatic default after Holder enrichment, or restore a known explicit TimeBar start. */
|
|
2272
|
+
async applyDefaultBookingStart(cacheItem, options = {}) {
|
|
2273
|
+
if (!this.shouldApplyMultipleBookingScheduling()) return cacheItem;
|
|
2274
|
+
if (!cacheItem?.new || !(0, _utils.isBookingProduct)(cacheItem) || (0, _utils.isSessionProduct)(cacheItem) || cacheItem?._extend?.other?.session) return cacheItem;
|
|
2275
|
+
const extend = cacheItem._extend || {};
|
|
2276
|
+
const currentStart = (0, _salesSettings.getBookingBoundary)(extend, 'start');
|
|
2277
|
+
const automaticStart = (0, _salesSettings.normalizeBookingDateTime)(cacheItem._data?.salesDefaultBookingStart);
|
|
2278
|
+
if (extend.start_time && (!automaticStart || !currentStart || (0, _dayjs.default)(currentStart).valueOf() !== (0, _dayjs.default)(automaticStart).valueOf())) return cacheItem;
|
|
2279
|
+
const explicitStart = (0, _salesSettings.normalizeBookingDateTime)(options.explicitStart);
|
|
2280
|
+
if (options.explicitStart !== undefined && !explicitStart) {
|
|
2281
|
+
throw new Error('The explicit booking start must be a valid date and time.');
|
|
2282
|
+
}
|
|
2283
|
+
const holderIds = options.holderIds ?? (0, _salesSettings.getBookingHolderIds)(cacheItem);
|
|
2284
|
+
const fallback = (0, _salesSettings.normalizeBookingDateTime)(cacheItem._data?.salesDefaultBookingFallback) ?? currentStart ?? (0, _salesSettings.normalizeBookingDateTime)(String(this.getBookingDate() || ''));
|
|
2285
|
+
const nextStart = explicitStart ?? (await this.resolveDefaultBookingStart({
|
|
2286
|
+
holderIds,
|
|
2287
|
+
fallback
|
|
2288
|
+
}));
|
|
2289
|
+
if (!nextStart) return cacheItem;
|
|
2290
|
+
if (currentStart && (0, _dayjs.default)(nextStart).valueOf() === (0, _dayjs.default)(currentStart).valueOf()) {
|
|
2291
|
+
if (!explicitStart) return cacheItem;
|
|
2292
|
+
const data = {
|
|
2293
|
+
...cacheItem._data
|
|
2294
|
+
};
|
|
2295
|
+
delete data.salesDefaultBookingStart;
|
|
2296
|
+
delete data.salesDefaultBookingFallback;
|
|
2297
|
+
return {
|
|
2298
|
+
...cacheItem,
|
|
2299
|
+
_data: data
|
|
2300
|
+
};
|
|
2301
|
+
}
|
|
2302
|
+
const nextExtend = {
|
|
2303
|
+
...extend,
|
|
2304
|
+
start_date: nextStart.slice(0, 10),
|
|
2305
|
+
start_time: nextStart.slice(11)
|
|
2306
|
+
};
|
|
2307
|
+
for (const key of ['startDate', 'endDate', 'end_time', 'resource', 'resources', 'availabilitySelection']) {
|
|
2308
|
+
delete nextExtend[key];
|
|
2309
|
+
}
|
|
2310
|
+
if ((0, _utils.isMultiDayProduct)(cacheItem) && currentStart && extend.end_date) {
|
|
2311
|
+
const shiftDays = (0, _dayjs.default)(nextStart.slice(0, 10)).diff((0, _dayjs.default)(currentStart.slice(0, 10)), 'day');
|
|
2312
|
+
nextExtend.end_date = (0, _dayjs.default)(extend.end_date).add(shiftDays, 'day').format('YYYY-MM-DD');
|
|
2313
|
+
} else {
|
|
2314
|
+
delete nextExtend.end_date;
|
|
2315
|
+
}
|
|
2316
|
+
return this.getProductExtend({
|
|
2317
|
+
...cacheItem,
|
|
2318
|
+
_extend: nextExtend,
|
|
2319
|
+
_data: explicitStart ? {} : {
|
|
2320
|
+
salesDefaultBookingStart: nextStart,
|
|
2321
|
+
salesDefaultBookingFallback: fallback
|
|
2322
|
+
}
|
|
2323
|
+
}, {
|
|
2324
|
+
holderIds
|
|
2325
|
+
});
|
|
2326
|
+
}
|
|
2041
2327
|
async loadPickupTimingOpenData(_force) {
|
|
2042
2328
|
const scope = this.getPickupTimingScope();
|
|
2043
2329
|
const businessCode = String(this.otherParams?.businessCode ?? this.otherParams?.business_code ?? '').trim();
|
|
@@ -2076,6 +2362,82 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2076
2362
|
throw error;
|
|
2077
2363
|
}
|
|
2078
2364
|
}
|
|
2365
|
+
|
|
2366
|
+
/** Required products currently apply only to the online venue-ticket entry. */
|
|
2367
|
+
async validateRequiredProducts() {
|
|
2368
|
+
const businessCode = String(this.otherParams?.businessCode ?? this.otherParams?.business_code ?? '').trim();
|
|
2369
|
+
const channel = String(this.otherParams?.channel ?? '').trim();
|
|
2370
|
+
if (businessCode !== 'venue_ticket' || channel !== 'online_ordering') return;
|
|
2371
|
+
const scope = this.getPickupTimingScope();
|
|
2372
|
+
const order = this.getTempOrder();
|
|
2373
|
+
const runtimeConfig = this.otherParams?.itemRule || {};
|
|
2374
|
+
let configs = normalizeItemRuleStrategyConfigs(runtimeConfig.strategyConfigs);
|
|
2375
|
+
if (!configs.length) {
|
|
2376
|
+
const openData = await this.getOpenData();
|
|
2377
|
+
if (!toConfiguredBoolean(openData?.['sale.enable_item_rules'])) return;
|
|
2378
|
+
const ids = normalizePositiveIntegerList(openData?.['sale.enabled_item_rules']);
|
|
2379
|
+
if (!ids.length) return;
|
|
2380
|
+
|
|
2381
|
+
// Checkout must not use the allergy loader's fail-open fallback.
|
|
2382
|
+
const response = await this.request.get('/promotion', {
|
|
2383
|
+
skip: 1,
|
|
2384
|
+
num: 99,
|
|
2385
|
+
status: 'active',
|
|
2386
|
+
ids
|
|
2387
|
+
});
|
|
2388
|
+
if (response?.code !== 200 || !Array.isArray(response?.data?.list)) {
|
|
2389
|
+
throw new Error('Unable to load required product rules. Please try again.');
|
|
2390
|
+
}
|
|
2391
|
+
// Configured IDs can include disabled or deleted rules; only active results participate.
|
|
2392
|
+
configs = normalizeItemRuleStrategyConfigs(response.data.list.filter(item => ids.includes(Number(item?.id))).map(item => item?.metadata));
|
|
2393
|
+
}
|
|
2394
|
+
if (scope !== this.getPickupTimingScope() || order !== this.getTempOrder()) {
|
|
2395
|
+
throw new Error('The order changed. Please try again.');
|
|
2396
|
+
}
|
|
2397
|
+
const strategyConfigs = configs.filter(config => Array.isArray(config.actions)).map(config => ({
|
|
2398
|
+
...config,
|
|
2399
|
+
actions: config.actions.filter(action => {
|
|
2400
|
+
const rules = action.config?.quantityRules;
|
|
2401
|
+
return action.type === 'QUANTITY_CHECK' && action.config?.targetType === 'product' && Array.isArray(rules) && rules.length > 0 && rules.every(rule => rule.source === 'fixed' && (rule.comparison === 'minimum' || rule.comparison === 'must_include'));
|
|
2402
|
+
})
|
|
2403
|
+
})).filter(config => config.actions.length > 0);
|
|
2404
|
+
if (!strategyConfigs.length) return;
|
|
2405
|
+
const cartItems = this.getOrderProducts().map(item => ({
|
|
2406
|
+
product_id: Number(item.product_id),
|
|
2407
|
+
quantity: Number(item.num)
|
|
2408
|
+
})).filter(item => Number.isFinite(item.product_id) && item.product_id > 0 && Number.isFinite(item.quantity) && item.quantity > 0);
|
|
2409
|
+
const result = new _itemRule.ItemRuleEvaluator().evaluate({
|
|
2410
|
+
strategyConfigs,
|
|
2411
|
+
cartItems,
|
|
2412
|
+
// Fixed-quantity rules do not consume pax; no customer headcount is collected.
|
|
2413
|
+
pax: {
|
|
2414
|
+
total: 0,
|
|
2415
|
+
adult: 0,
|
|
2416
|
+
child: 0
|
|
2417
|
+
},
|
|
2418
|
+
channel,
|
|
2419
|
+
submissionIndex: 0,
|
|
2420
|
+
custom: {
|
|
2421
|
+
...runtimeConfig.custom,
|
|
2422
|
+
businessCode
|
|
2423
|
+
}
|
|
2424
|
+
});
|
|
2425
|
+
if (result.rawResults.some(evaluation => !evaluation.success)) {
|
|
2426
|
+
throw new Error('Unable to validate required product rules. Please try again.');
|
|
2427
|
+
}
|
|
2428
|
+
if (!result.allPassed) {
|
|
2429
|
+
const error = new Error(result.failedChecks[0]?.validationMessage || 'Please select the required product before checkout.');
|
|
2430
|
+
Object.assign(error, {
|
|
2431
|
+
code: 'REQUIRED_PRODUCT_MISSING',
|
|
2432
|
+
failures: result.failedChecks
|
|
2433
|
+
});
|
|
2434
|
+
throw error;
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
async submitSalesOrder(params) {
|
|
2438
|
+
await this.validateRequiredProducts();
|
|
2439
|
+
return super.submitSalesOrder(params);
|
|
2440
|
+
}
|
|
2079
2441
|
async ensureAllergyItemRuleConfigsLoaded() {
|
|
2080
2442
|
if (this.allergyItemRuleConfigs.length > 0) {
|
|
2081
2443
|
return this.allergyItemRuleConfigs;
|
|
@@ -2160,6 +2522,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2160
2522
|
}
|
|
2161
2523
|
return this.store.openData.getInvoiceTemplateSettings();
|
|
2162
2524
|
}
|
|
2525
|
+
getPosReceiptAutoPrintPaymentStatuses() {
|
|
2526
|
+
const platform = (0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform);
|
|
2527
|
+
if (platform !== 'pos' && platform !== 'webpos') return undefined;
|
|
2528
|
+
if (!this.isInvoiceOpenDataCacheCurrent() || this.runtimeOpenDataModule !== this.store.openData || this.runtimeOpenDataCore !== this.core) return undefined;
|
|
2529
|
+
return (0, _posReceiptAutoPrint.normalizePosReceiptAutoPrintPaymentStatuses)(this.runtimeOpenDataSnapshot?.['documents.pos_receipt_auto_print_payment_statuses']);
|
|
2530
|
+
}
|
|
2163
2531
|
isInvoiceOpenDataCacheCurrent() {
|
|
2164
2532
|
const businessCode = String(this.otherParams?.businessCode || '').trim();
|
|
2165
2533
|
const channel = String(this.otherParams?.channel || '').trim();
|
|
@@ -2176,7 +2544,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2176
2544
|
throw new Error('[UnifiedBookingSales] getProtocol 需要 policyId');
|
|
2177
2545
|
}
|
|
2178
2546
|
let policyUrl = 'shop-policy';
|
|
2179
|
-
if (this.otherParams.platform
|
|
2547
|
+
if ((0, _platform.isSelfServicePlatform)(this.otherParams.platform) || this.otherParams.platform === 'pos' || this.otherParams.platform === 'shop') {
|
|
2180
2548
|
policyUrl = 'policy';
|
|
2181
2549
|
}
|
|
2182
2550
|
return this.request.get(`/${policyUrl}/${encodeURIComponent(normalizedPolicyId)}`);
|
|
@@ -2187,7 +2555,540 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2187
2555
|
* product because session products carry their fixed intervals there.
|
|
2188
2556
|
*/
|
|
2189
2557
|
async loadProducts(params = {}, options) {
|
|
2558
|
+
const result = await this.loadCatalogProducts(params, options);
|
|
2559
|
+
this.unifiedProductCatalog = Array.isArray(result) ? [...result] : [];
|
|
2560
|
+
await this.core.effects.emit(`${this.name}:onProductsLoaded`, result);
|
|
2561
|
+
return result;
|
|
2562
|
+
}
|
|
2563
|
+
|
|
2564
|
+
/**
|
|
2565
|
+
* Queries one explicitly configured menu scope without publishing the sales catalog.
|
|
2566
|
+
* The returned graph is detached from ProductList's shared ID cache. Callers own its
|
|
2567
|
+
* membership and must requery/reprice with the service datetime after a context change.
|
|
2568
|
+
* Missing/invalid menu configuration fails closed instead of querying every product.
|
|
2569
|
+
*/
|
|
2570
|
+
async queryCatalogSnapshot(params) {
|
|
2571
|
+
if (!Array.isArray(params.menu_list_ids) || params.menu_list_ids.length === 0 || params.menu_list_ids.some(id => !Number.isInteger(id) || id <= 0)) {
|
|
2572
|
+
return [];
|
|
2573
|
+
}
|
|
2574
|
+
const {
|
|
2575
|
+
product_ids,
|
|
2576
|
+
...scopeParams
|
|
2577
|
+
} = (0, _lodashEs.cloneDeep)(params);
|
|
2578
|
+
// The OS Server ID-query branch intentionally bypasses menus. Apply IDs only after
|
|
2579
|
+
// querying the configured menu so an isolated scope cannot leak other products.
|
|
2580
|
+
const result = await this.loadCatalogProducts({
|
|
2581
|
+
...scopeParams,
|
|
2582
|
+
menu_list_ids: [...new Set(params.menu_list_ids)]
|
|
2583
|
+
});
|
|
2584
|
+
const list = Array.isArray(result) ? result : [];
|
|
2585
|
+
return (0, _lodashEs.cloneDeep)(product_ids?.length ? list.filter(product => product_ids.some(id => Number(id) === Number(product.id))) : list);
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2588
|
+
/** Full SKU/bundle detail, after verifying membership in the explicit day/menu scope. */
|
|
2589
|
+
async queryCatalogProductDetail(params) {
|
|
2590
|
+
return this.loadCatalogProductDetail(params, query => this.queryCatalogSnapshot(query));
|
|
2591
|
+
}
|
|
2592
|
+
isVenueCatalogLocalPricingActive() {
|
|
2593
|
+
return this.venueCatalogSessions.size > 0;
|
|
2594
|
+
}
|
|
2595
|
+
getVenueCatalogLocalPriceSource(productId, selectedProduct) {
|
|
2596
|
+
const scope = this.getRuntimeOpenDataScope();
|
|
2597
|
+
const role = selectedProduct?.metadata?.venue_booking_role;
|
|
2598
|
+
const poolRole = role === 'party_extra' || role === 'tickets_extra' ? 'extras' : role === 'party_main' || role === 'tickets' ? 'main' : undefined;
|
|
2599
|
+
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));
|
|
2600
|
+
if (!matches.length) return undefined;
|
|
2601
|
+
const pool = matches[0].pool;
|
|
2602
|
+
const product = this.getVenueCatalogHydratedProduct(pool.products.find(row => Number(row.id) === productId));
|
|
2603
|
+
// Legacy promotion/gift inputs may have no venue role. Equivalent complete
|
|
2604
|
+
// sources are unambiguous; different pool snapshots must never use Set order.
|
|
2605
|
+
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;
|
|
2606
|
+
return {
|
|
2607
|
+
product: (0, _lodashEs.cloneDeep)(product),
|
|
2608
|
+
menuList: (0, _lodashEs.cloneDeep)(pool.pricingMenus)
|
|
2609
|
+
};
|
|
2610
|
+
}
|
|
2611
|
+
async getProductByIds(ids, options) {
|
|
2612
|
+
const active = this.isVenueCatalogLocalPricingActive();
|
|
2613
|
+
const products = await super.getProductByIds(ids, active ? {
|
|
2614
|
+
loadMissing: false
|
|
2615
|
+
} : options);
|
|
2616
|
+
return active ? products.map(product => this.getVenueCatalogHydratedProduct(product)) : products;
|
|
2617
|
+
}
|
|
2618
|
+
getVenueCatalogHydratedProduct(product) {
|
|
2619
|
+
const variants = this.venueVariantDetails.get(Number(product.id ?? product.product_id))?.data;
|
|
2620
|
+
return variants ? {
|
|
2621
|
+
...(0, _lodashEs.cloneDeep)(product),
|
|
2622
|
+
variant: (0, _lodashEs.cloneDeep)(variants)
|
|
2623
|
+
} : (0, _lodashEs.cloneDeep)(product);
|
|
2624
|
+
}
|
|
2625
|
+
|
|
2626
|
+
/** Explicit user opening for legacy promotion/gift SKU hosts. Pure readers never call this. */
|
|
2627
|
+
async prepareVenueCatalogProductDetail(params) {
|
|
2628
|
+
if (!this.isVenueCatalogLocalPricingActive()) throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_REQUIRED', 'Open a venue catalog before configuring this product.');
|
|
2629
|
+
const owner = this.venueCatalogSessionKey;
|
|
2630
|
+
const scope = this.getRuntimeOpenDataScope();
|
|
2631
|
+
const generation = this.runtimeInitializationGeneration;
|
|
2632
|
+
const source = this.getVenueCatalogLocalPriceSource(params.product_id);
|
|
2633
|
+
if (!source) return undefined;
|
|
2634
|
+
await this.hydrateVenueVariantDetail(source.product, params);
|
|
2635
|
+
if (this.runtimeOpenDataDestroyed || !this.isVenueCatalogLocalPricingActive() || owner !== this.venueCatalogSessionKey || scope !== this.getRuntimeOpenDataScope() || generation !== this.runtimeInitializationGeneration) {
|
|
2636
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_STALE', 'The venue catalog changed while loading product options.');
|
|
2637
|
+
}
|
|
2638
|
+
return this.getVenueCatalogHydratedProduct(source.product);
|
|
2639
|
+
}
|
|
2640
|
+
async hydrateVenueVariantDetail(raw, params) {
|
|
2641
|
+
// is_variant is the backend's explicit gate. Ordinary retail never requests detail.
|
|
2642
|
+
if (Number(raw.is_variant) !== 1) return;
|
|
2643
|
+
const count = Number(raw.variant_count) || 0;
|
|
2644
|
+
if (Array.isArray(raw.variant) && raw.variant.length > 0 && raw.variant.length >= count) return;
|
|
2645
|
+
const productId = Number(raw.id ?? raw.product_id);
|
|
2646
|
+
let entry = this.venueVariantDetails.get(productId);
|
|
2647
|
+
if (entry?.failed && params.retry === true) {
|
|
2648
|
+
this.venueVariantDetails.delete(productId);
|
|
2649
|
+
entry = undefined;
|
|
2650
|
+
}
|
|
2651
|
+
if (!entry) {
|
|
2652
|
+
const owner = this.venueCatalogSessionKey;
|
|
2653
|
+
const scope = this.getRuntimeOpenDataScope();
|
|
2654
|
+
const generation = this.runtimeInitializationGeneration;
|
|
2655
|
+
const core = this.core;
|
|
2656
|
+
const request = this.request;
|
|
2657
|
+
const next = {
|
|
2658
|
+
promise: Promise.resolve([])
|
|
2659
|
+
};
|
|
2660
|
+
const assertCurrent = () => {
|
|
2661
|
+
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) {
|
|
2662
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_STALE', 'The venue catalog changed while loading product options.');
|
|
2663
|
+
}
|
|
2664
|
+
};
|
|
2665
|
+
this.venueVariantDetails.set(productId, next);
|
|
2666
|
+
next.promise = Promise.resolve().then(async () => {
|
|
2667
|
+
assertCurrent();
|
|
2668
|
+
const response = await request.get(`/product/show/${productId}`, {
|
|
2669
|
+
open_bundle: 1,
|
|
2670
|
+
with_schedule: 1,
|
|
2671
|
+
is_eject: 1,
|
|
2672
|
+
with: [..._clientDataVariants.PRODUCT_QUERY_DATA_VARIANT_RELATIONS]
|
|
2673
|
+
}, {
|
|
2674
|
+
useCache: false,
|
|
2675
|
+
customToast: () => {}
|
|
2676
|
+
});
|
|
2677
|
+
assertCurrent();
|
|
2678
|
+
if (response?.status === false || response?.code != null && Number(response.code) !== 200) {
|
|
2679
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_VARIANT_DETAIL_FAILED', response?.message || 'Product options could not be loaded.');
|
|
2680
|
+
}
|
|
2681
|
+
const detail = response?.data?.item ?? response?.data;
|
|
2682
|
+
if (Number(detail?.id ?? detail?.product_id) !== productId || !Array.isArray(detail?.variant) || !detail.variant.length || detail.variant.length < count) {
|
|
2683
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_VARIANT_DETAIL_INCOMPLETE', 'Complete product variants are unavailable. Please retry.');
|
|
2684
|
+
}
|
|
2685
|
+
const variants = detail.variant.map(value => {
|
|
2686
|
+
const variant = (0, _lodashEs.cloneDeep)(value);
|
|
2687
|
+
const original = variant._dataVariant?.original;
|
|
2688
|
+
const evaluated = variant._dataVariant || Array.isArray(variant.metadata?.data_variant_ids);
|
|
2689
|
+
const basePrice = original?.price ?? original?.base_price ?? variant.base_price ?? (evaluated ? undefined : variant.price);
|
|
2690
|
+
if (!Number.isSafeInteger(Number(variant.id)) || Number(variant.id) <= 0 || basePrice === undefined || basePrice === null || basePrice === '' || !Number.isFinite(Number(basePrice))) {
|
|
2691
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_VARIANT_DETAIL_INCOMPLETE', 'The base price for a product variant is unavailable.');
|
|
2692
|
+
}
|
|
2693
|
+
// Copy only combination SKU data. The pool's price/data_variants and
|
|
2694
|
+
// pricing metadata remain its original baseline for every later context.
|
|
2695
|
+
variant.price = basePrice;
|
|
2696
|
+
variant.base_price = basePrice;
|
|
2697
|
+
if (variant.selling_price !== undefined) variant.selling_price = basePrice;
|
|
2698
|
+
delete variant._dataVariant;
|
|
2699
|
+
if (variant.metadata) delete variant.metadata.data_variant_ids;
|
|
2700
|
+
return variant;
|
|
2701
|
+
});
|
|
2702
|
+
next.data = variants;
|
|
2703
|
+
for (const pool of this.venueCatalogSessions) {
|
|
2704
|
+
if (pool.scope !== scope || !pool.pool) continue;
|
|
2705
|
+
const product = pool.pool.products.find(row => Number(row.id) === productId);
|
|
2706
|
+
if (!product) continue;
|
|
2707
|
+
const hydrated = this.getVenueCatalogHydratedProduct(product);
|
|
2708
|
+
this.store.products?.rememberRawProductQueryResult?.([(0, _lodashEs.cloneDeep)(hydrated)]);
|
|
2709
|
+
this.store.products?.addProduct?.([(0, _lodashEs.cloneDeep)(hydrated)]);
|
|
2710
|
+
}
|
|
2711
|
+
return variants;
|
|
2712
|
+
}).catch(error => {
|
|
2713
|
+
next.failed = true;
|
|
2714
|
+
throw error;
|
|
2715
|
+
});
|
|
2716
|
+
entry = next;
|
|
2717
|
+
}
|
|
2718
|
+
await entry.promise;
|
|
2719
|
+
}
|
|
2720
|
+
|
|
2721
|
+
/** One complete raw product query per explicitly configured pool for this page lifetime. */
|
|
2722
|
+
createVenueCatalogSession(params) {
|
|
2723
|
+
if (!(0, _platform.isCustomerUserPlatform)(this.otherParams?.platform)) {
|
|
2724
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_PLATFORM_UNSUPPORTED', 'Venue catalog sessions require a customer platform.');
|
|
2725
|
+
}
|
|
2726
|
+
const ids = params.menu_list_ids;
|
|
2727
|
+
if (!Array.isArray(ids) || !ids.length || ids.some(id => !Number.isSafeInteger(id) || id <= 0)) {
|
|
2728
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_MENU_REQUIRED', 'Choose an explicit menu for this venue product pool.');
|
|
2729
|
+
}
|
|
2730
|
+
const menuIds = [...new Set(ids)].sort((a, b) => a - b);
|
|
2731
|
+
const scope = this.getRuntimeOpenDataScope();
|
|
2732
|
+
const generation = this.runtimeInitializationGeneration;
|
|
2733
|
+
const core = this.core;
|
|
2734
|
+
const request = this.request;
|
|
2735
|
+
const entry = {
|
|
2736
|
+
scope,
|
|
2737
|
+
generation,
|
|
2738
|
+
role: params.poolRole
|
|
2739
|
+
};
|
|
2740
|
+
const sessionKey = JSON.stringify([scope, generation, params.sessionKey ?? null]);
|
|
2741
|
+
if (!this.venueCatalogSessions.size || sessionKey !== this.venueCatalogSessionKey) {
|
|
2742
|
+
// React may create new page pools before disposing the old page's pools.
|
|
2743
|
+
// The explicit session identity prevents reusing old-order occupancy then.
|
|
2744
|
+
this.venueCatalogSessions.clear();
|
|
2745
|
+
this.venueCatalogSessionKey = sessionKey;
|
|
2746
|
+
this.venueCatalogMenus = undefined;
|
|
2747
|
+
this.venueVariantDetails.clear();
|
|
2748
|
+
this.availabilitySessionResourceCache.clear();
|
|
2749
|
+
}
|
|
2750
|
+
this.venueCatalogSessions.add(entry);
|
|
2751
|
+
const assertCurrent = () => {
|
|
2752
|
+
if (!this.venueCatalogSessions.has(entry)) {
|
|
2753
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_DISPOSED', 'The venue catalog session is closed.');
|
|
2754
|
+
}
|
|
2755
|
+
if (this.runtimeOpenDataDestroyed || this.core !== core || this.request !== request || generation !== this.runtimeInitializationGeneration || scope !== this.getRuntimeOpenDataScope()) {
|
|
2756
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_STALE', 'The venue store context changed. Reopen the booking page.');
|
|
2757
|
+
}
|
|
2758
|
+
};
|
|
2759
|
+
const now = () => {
|
|
2760
|
+
const timezone = String(this.otherParams?.businessTimezone || this.getPickupTimingContextData('timezone') || '').trim();
|
|
2761
|
+
if (!timezone) throw (0, _venueCatalogSession.venueCatalogError)('VENUE_TIMEZONE_REQUIRED', 'The venue timezone is not ready.');
|
|
2762
|
+
const parts = new Intl.DateTimeFormat('en-GB', {
|
|
2763
|
+
timeZone: timezone,
|
|
2764
|
+
year: 'numeric',
|
|
2765
|
+
month: '2-digit',
|
|
2766
|
+
day: '2-digit',
|
|
2767
|
+
hour: '2-digit',
|
|
2768
|
+
minute: '2-digit',
|
|
2769
|
+
second: '2-digit',
|
|
2770
|
+
hourCycle: 'h23'
|
|
2771
|
+
}).formatToParts(new Date());
|
|
2772
|
+
const part = type => parts.find(item => item.type === type)?.value;
|
|
2773
|
+
return `${part('year')}-${part('month')}-${part('day')} ${part('hour')}:${part('minute')}:${part('second')}`;
|
|
2774
|
+
};
|
|
2775
|
+
const snapshot = (pool, input) => {
|
|
2776
|
+
assertCurrent();
|
|
2777
|
+
if (input.menu_list_ids && JSON.stringify([...new Set(input.menu_list_ids)].sort((a, b) => a - b)) !== JSON.stringify(menuIds)) {
|
|
2778
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_MENU_SCOPE_CHANGED', 'This catalog session belongs to another menu.');
|
|
2779
|
+
}
|
|
2780
|
+
const current = now();
|
|
2781
|
+
const datetime = input.schedule_datetime || (input.schedule_date ? `${input.schedule_date} ${current.slice(11)}` : current);
|
|
2782
|
+
if (!(0, _localClock.parseLocalDateTime)(datetime.replace('T', ' ')) || input.schedule_date && datetime.slice(0, 10) !== input.schedule_date) {
|
|
2783
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_DATETIME_INVALID', 'Choose a valid venue catalog date and time.');
|
|
2784
|
+
}
|
|
2785
|
+
const menus = (0, _venueCatalogSession.activeVenueMenus)(pool.menus, this.getAvailabilityScheduleCatalog(), datetime, Boolean(input.schedule_date && !input.schedule_datetime));
|
|
2786
|
+
let products = pool.products.filter(product => menus.some(menu => (0, _venueCatalogSession.productMatchesVenueMenu)(product, menu))).map(product => this.getVenueCatalogHydratedProduct(product));
|
|
2787
|
+
if (input.product_ids?.length) products = products.filter(product => input.product_ids.some(id => Number(id) === Number(product.id)));
|
|
2788
|
+
const user = this.core.getPlugin?.('user');
|
|
2789
|
+
const queryPayload = {
|
|
2790
|
+
schedule_date: datetime.slice(0, 10),
|
|
2791
|
+
schedule_datetime: datetime,
|
|
2792
|
+
customer_id: input.customer_id ?? this.getTempOrder()?.customer_id ?? user?.get?.()?.id,
|
|
2793
|
+
strategy_context: {
|
|
2794
|
+
...this.getPriceQueryStrategyContext(),
|
|
2795
|
+
...(input.strategy_context || {})
|
|
2796
|
+
}
|
|
2797
|
+
};
|
|
2798
|
+
const result = (0, _clientDataVariants.tryResolveClientDataVariants)({
|
|
2799
|
+
core: this.core,
|
|
2800
|
+
otherParams: this.otherParams,
|
|
2801
|
+
products: (0, _lodashEs.cloneDeep)(products),
|
|
2802
|
+
queryPayload,
|
|
2803
|
+
handledByOsServer: false,
|
|
2804
|
+
scheduleList: this.getAvailabilityScheduleCatalog(),
|
|
2805
|
+
menuList: pool.pricingMenus
|
|
2806
|
+
});
|
|
2807
|
+
if (result.status !== 'resolved' && result.status !== 'empty') {
|
|
2808
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_LOCAL_PRICE_UNAVAILABLE', 'Complete product pricing rules are not ready. Please retry.');
|
|
2809
|
+
}
|
|
2810
|
+
return result.products.slice().sort((a, b) => Number(b.sort || 0) - Number(a.sort || 0));
|
|
2811
|
+
};
|
|
2812
|
+
return (0, _venueCatalogSession.createVenueCatalogSessionAdapter)({
|
|
2813
|
+
assertCurrent,
|
|
2814
|
+
load: async () => {
|
|
2815
|
+
if (!this.venueCatalogMenus || this.venueCatalogMenus.scope !== scope) {
|
|
2816
|
+
const promise = request.get('/form/data/v1', {
|
|
2817
|
+
skip: 1,
|
|
2818
|
+
num: 999,
|
|
2819
|
+
code: 'menu_list'
|
|
2820
|
+
}, {
|
|
2821
|
+
useCache: false,
|
|
2822
|
+
customToast: () => {}
|
|
2823
|
+
}).then(response => (0, _venueCatalogSession.readVenueCatalogList)(response, 'Venue menus'));
|
|
2824
|
+
this.venueCatalogMenus = {
|
|
2825
|
+
scope,
|
|
2826
|
+
promise
|
|
2827
|
+
};
|
|
2828
|
+
void promise.catch(() => {
|
|
2829
|
+
if (this.venueCatalogMenus?.promise === promise) this.venueCatalogMenus = undefined;
|
|
2830
|
+
});
|
|
2831
|
+
}
|
|
2832
|
+
const menuCache = this.venueCatalogMenus;
|
|
2833
|
+
const pricingMenus = await menuCache.promise;
|
|
2834
|
+
assertCurrent();
|
|
2835
|
+
let menus;
|
|
2836
|
+
try {
|
|
2837
|
+
menus = (0, _venueCatalogSession.validateVenueMenus)(pricingMenus, menuIds);
|
|
2838
|
+
} catch (error) {
|
|
2839
|
+
// A malformed selected menu must be fetched again on explicit retry.
|
|
2840
|
+
if (this.venueCatalogMenus === menuCache) this.venueCatalogMenus = undefined;
|
|
2841
|
+
throw error;
|
|
2842
|
+
}
|
|
2843
|
+
// A menu query with a date may exclude future members. Read the raw ID union
|
|
2844
|
+
// without menu/time/customer pricing filters, then filter collection/all menus locally.
|
|
2845
|
+
const onlyIds = menus.every(menu => menu.partyroom_package.type === 'products');
|
|
2846
|
+
const onlyCollections = menus.every(menu => menu.partyroom_package.type === 'product_collection');
|
|
2847
|
+
const productIds = onlyIds ? [...new Set(menus.flatMap(menu => menu.partyroom_package.products.map(product => Number(product.product_id))))] : undefined;
|
|
2848
|
+
const collections = onlyCollections ? [...new Set(menus.flatMap(menu => menu.partyroom_package.products.map(product => String(product.product_collection_id))))] : undefined;
|
|
2849
|
+
const emptySelection = productIds?.length === 0 || collections?.length === 0;
|
|
2850
|
+
const products = emptySelection ? [] : await this.store.products.loadVenueCatalogPool({
|
|
2851
|
+
product_ids: productIds,
|
|
2852
|
+
collection: collections,
|
|
2853
|
+
category_ids: params.category_ids,
|
|
2854
|
+
extension_type: params.extension_type,
|
|
2855
|
+
cacheId: this.cacheId
|
|
2856
|
+
});
|
|
2857
|
+
assertCurrent();
|
|
2858
|
+
const pool = {
|
|
2859
|
+
menus,
|
|
2860
|
+
pricingMenus: (0, _lodashEs.cloneDeep)(pricingMenus),
|
|
2861
|
+
products: products.filter(product => !('deleted_at' in product && product.deleted_at) && (!product.status || product.status === 'published') && menus.some(menu => (0, _venueCatalogSession.productMatchesVenueMenu)(product, menu)))
|
|
2862
|
+
};
|
|
2863
|
+
entry.pool = (0, _lodashEs.cloneDeep)(pool);
|
|
2864
|
+
// Legacy marketing lookups can reuse complete records without changing
|
|
2865
|
+
// either pool's membership or publishing a replacement sales catalog.
|
|
2866
|
+
this.store.products.rememberRawProductQueryResult((0, _lodashEs.cloneDeep)(pool.products));
|
|
2867
|
+
this.store.products.addProduct((0, _lodashEs.cloneDeep)(pool.products));
|
|
2868
|
+
return pool;
|
|
2869
|
+
},
|
|
2870
|
+
snapshot,
|
|
2871
|
+
prepareDetail: async (pool, query) => {
|
|
2872
|
+
const raw = pool.products.find(product => Number(product.id) === Number(query.product_id));
|
|
2873
|
+
if (raw) await this.hydrateVenueVariantDetail(raw, query);
|
|
2874
|
+
assertCurrent();
|
|
2875
|
+
},
|
|
2876
|
+
quote: async (pool, query) => {
|
|
2877
|
+
const product = query.product;
|
|
2878
|
+
const productId = Number(product?.product_id ?? product?.id);
|
|
2879
|
+
const booking = query.booking;
|
|
2880
|
+
const datetime = booking?.start_date ? `${booking.start_date} ${booking.start_time || '00:00:00'}` : query.datetime || now();
|
|
2881
|
+
if (!snapshot(pool, {
|
|
2882
|
+
product_ids: [productId],
|
|
2883
|
+
schedule_datetime: datetime,
|
|
2884
|
+
customer_id: query.customer_id == null ? undefined : Number(query.customer_id)
|
|
2885
|
+
}).length) {
|
|
2886
|
+
throw (0, _venueCatalogSession.venueCatalogError)('VENUE_PRODUCT_UNAVAILABLE', 'This product is unavailable in the selected menu at this time.');
|
|
2887
|
+
}
|
|
2888
|
+
const raw = pool.products.find(row => Number(row.id) === productId);
|
|
2889
|
+
if (!raw) throw (0, _venueCatalogSession.venueCatalogError)('VENUE_PRODUCT_UNAVAILABLE', 'This product is not in the venue catalog.');
|
|
2890
|
+
const result = await this.calculateVenueCatalogProductBookingPrice({
|
|
2891
|
+
...query,
|
|
2892
|
+
datetime
|
|
2893
|
+
}, {
|
|
2894
|
+
product: this.getVenueCatalogHydratedProduct(raw),
|
|
2895
|
+
menuList: pool.pricingMenus
|
|
2896
|
+
});
|
|
2897
|
+
assertCurrent();
|
|
2898
|
+
return result;
|
|
2899
|
+
},
|
|
2900
|
+
onRetry: () => {
|
|
2901
|
+
for (const [id, detail] of this.venueVariantDetails) if (detail.failed) this.venueVariantDetails.delete(id);
|
|
2902
|
+
},
|
|
2903
|
+
onDispose: () => {
|
|
2904
|
+
this.venueCatalogSessions.delete(entry);
|
|
2905
|
+
if (!this.venueCatalogSessions.size) {
|
|
2906
|
+
this.venueCatalogSessionKey = undefined;
|
|
2907
|
+
this.venueCatalogMenus = undefined;
|
|
2908
|
+
this.venueVariantDetails.clear();
|
|
2909
|
+
this.availabilitySessionResourceCache.clear();
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
});
|
|
2913
|
+
}
|
|
2914
|
+
|
|
2915
|
+
/**
|
|
2916
|
+
* Opt-in calendar/card preview batching. Results expire after sixty seconds or a
|
|
2917
|
+
* runtime change; the next read starts a fresh clock/cache. Selection and submit
|
|
2918
|
+
* must keep using the ordinary fresh query methods. Call dispose on owner cleanup.
|
|
2919
|
+
*/
|
|
2920
|
+
createCatalogQueryBatch() {
|
|
2921
|
+
return (0, _catalogQueryBatch.createCatalogQueryBatchAdapter)({
|
|
2922
|
+
runtime: () => {
|
|
2923
|
+
if (this.runtimeOpenDataDestroyed) throw new Error('The booking service is closed.');
|
|
2924
|
+
const user = this.core.getPlugin?.('user');
|
|
2925
|
+
const productParams = this.store.products?.otherParams || this.otherParams || {};
|
|
2926
|
+
const fatherModule = String(productParams.fatherModule || '').trim();
|
|
2927
|
+
const schedule = (fatherModule ? this.core.getModule?.(`${fatherModule}_schedule`) : null) || this.core.getModule?.('schedule');
|
|
2928
|
+
const evaluator = this.core.context?.dataVariantEvaluator;
|
|
2929
|
+
// OpenData hydration is not a catalog input. Its temporary null/reload cycle
|
|
2930
|
+
// must not expire a batch while a parallel preview reads sales settings.
|
|
2931
|
+
const {
|
|
2932
|
+
openData: _openData,
|
|
2933
|
+
...otherParams
|
|
2934
|
+
} = this.otherParams || {};
|
|
2935
|
+
const {
|
|
2936
|
+
openData: _productOpenData,
|
|
2937
|
+
...productOtherParams
|
|
2938
|
+
} = productParams;
|
|
2939
|
+
return {
|
|
2940
|
+
references: [this.core, this.request, this.store.products, this.core.server, user, this.appPlugin, this.core.getPlugin?.('request'), this.core.getPlugin?.('app'), schedule, evaluator],
|
|
2941
|
+
values: {
|
|
2942
|
+
initialization: this.runtimeInitializationGeneration,
|
|
2943
|
+
scope: this.getRuntimeOpenDataScope(),
|
|
2944
|
+
requestBaseUrl: this.request.baseUrl,
|
|
2945
|
+
customerId: user?.get?.()?.id,
|
|
2946
|
+
otherParams,
|
|
2947
|
+
productOtherParams
|
|
2948
|
+
},
|
|
2949
|
+
refreshValues: {
|
|
2950
|
+
scheduleList: schedule?.getScheduleList?.(),
|
|
2951
|
+
contextScheduleList: this.core.context?.scheduleList,
|
|
2952
|
+
contextMenuList: this.core.context?.menuList,
|
|
2953
|
+
strategyConfigs: evaluator?.getStrategyConfigs?.()
|
|
2954
|
+
}
|
|
2955
|
+
};
|
|
2956
|
+
},
|
|
2957
|
+
normalize: (params, now) => {
|
|
2958
|
+
const date = params.schedule_date || (0, _dayjs.default)(now).format('YYYY-MM-DD');
|
|
2959
|
+
const user = this.core.getPlugin?.('user');
|
|
2960
|
+
const explicitCustomer = params.customer_id;
|
|
2961
|
+
if (explicitCustomer != null && (!Number.isSafeInteger(Number(explicitCustomer)) || Number(explicitCustomer) <= 0)) {
|
|
2962
|
+
throw new Error('Catalog query customer_id must be a positive integer.');
|
|
2963
|
+
}
|
|
2964
|
+
const fallbackCustomer = user?.get?.()?.id;
|
|
2965
|
+
const customer = explicitCustomer ?? (Number.isSafeInteger(Number(fallbackCustomer)) && Number(fallbackCustomer) > 0 ? Number(fallbackCustomer) : undefined);
|
|
2966
|
+
const productParams = this.store.products?.otherParams || this.otherParams || {};
|
|
2967
|
+
const channelMap = {
|
|
2968
|
+
online_store: 'online-store',
|
|
2969
|
+
scan_to_order: 'online-store',
|
|
2970
|
+
'scan-to-order': 'online-store',
|
|
2971
|
+
scan_to_order_2: 'online-store',
|
|
2972
|
+
scan_to_order_3: 'scantoorder3'
|
|
2973
|
+
};
|
|
2974
|
+
const channel = channelMap[productParams.channel] || productParams.channel;
|
|
2975
|
+
const businessCode = productParams.businessCode ?? productParams.business_code;
|
|
2976
|
+
const sorted = items => [...new Set(items)].sort((a, b) => String(a).localeCompare(String(b)));
|
|
2977
|
+
return {
|
|
2978
|
+
...params,
|
|
2979
|
+
menu_list_ids: Array.isArray(params.menu_list_ids) ? sorted(params.menu_list_ids) : params.menu_list_ids,
|
|
2980
|
+
category_ids: sorted(params.category_ids || []),
|
|
2981
|
+
collection: Array.isArray(params.collection) ? sorted(params.collection) : params.collection,
|
|
2982
|
+
extension_type: params.extension_type ? sorted(params.extension_type) : undefined,
|
|
2983
|
+
with_count: sorted(params.with_count ?? ['bundleGroup', 'optionGroup']),
|
|
2984
|
+
with_schedule: params.with_schedule ?? 1,
|
|
2985
|
+
status: params.status ?? 'published',
|
|
2986
|
+
schedule_date: date,
|
|
2987
|
+
schedule_datetime: params.schedule_datetime || `${date} ${(0, _dayjs.default)(now).format('HH:mm:ss')}`,
|
|
2988
|
+
customer_id: customer == null ? undefined : Number(customer),
|
|
2989
|
+
strategy_context: {
|
|
2990
|
+
...(channel ? {
|
|
2991
|
+
channel
|
|
2992
|
+
} : {}),
|
|
2993
|
+
...(businessCode ? {
|
|
2994
|
+
business_code: businessCode
|
|
2995
|
+
} : {}),
|
|
2996
|
+
...(params.strategy_context || {})
|
|
2997
|
+
}
|
|
2998
|
+
};
|
|
2999
|
+
},
|
|
3000
|
+
key: params => JSON.stringify(stableValue(params)),
|
|
3001
|
+
snapshot: params => this.queryCatalogSnapshot(params),
|
|
3002
|
+
detail: (params, snapshot) => this.loadCatalogProductDetail(params, snapshot)
|
|
3003
|
+
});
|
|
3004
|
+
}
|
|
3005
|
+
async loadCatalogProductDetail(params, loadSnapshot) {
|
|
3006
|
+
const {
|
|
3007
|
+
product_id,
|
|
3008
|
+
product_ids: _ignoredIds,
|
|
3009
|
+
...catalogParams
|
|
3010
|
+
} = (0, _lodashEs.cloneDeep)(params);
|
|
3011
|
+
if (!Number.isInteger(product_id) || product_id <= 0) return undefined;
|
|
3012
|
+
const schedule_date = catalogParams.schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD');
|
|
3013
|
+
const schedule_datetime = catalogParams.schedule_datetime || `${schedule_date} ${(0, _dayjs.default)().format('HH:mm:ss')}`;
|
|
3014
|
+
const scopedParams = {
|
|
3015
|
+
...catalogParams,
|
|
3016
|
+
schedule_date,
|
|
3017
|
+
schedule_datetime
|
|
3018
|
+
};
|
|
3019
|
+
const member = (await loadSnapshot(scopedParams)).find(item => Number(item.id) === product_id);
|
|
3020
|
+
if (!member) return undefined;
|
|
3021
|
+
const baseUrl = String(this.request.baseUrl || ((0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) ? '/h5' : '/shop')).replace(/\/+$/, '');
|
|
3022
|
+
const localPath = `/product/query/${product_id}`;
|
|
3023
|
+
const handledByOsServer = this.core.server?.hasRoute?.('get', `${baseUrl}${localPath}`) === true;
|
|
3024
|
+
const channelMap = {
|
|
3025
|
+
online_store: 'online-store',
|
|
3026
|
+
scan_to_order: 'online-store',
|
|
3027
|
+
'scan-to-order': 'online-store',
|
|
3028
|
+
scan_to_order_2: 'online-store',
|
|
3029
|
+
scan_to_order_3: 'scantoorder3'
|
|
3030
|
+
};
|
|
3031
|
+
const channel = channelMap[this.otherParams?.channel] || this.otherParams?.channel;
|
|
3032
|
+
const businessCode = this.otherParams?.businessCode ?? this.otherParams?.business_code;
|
|
3033
|
+
const strategy_context = {
|
|
3034
|
+
...(channel ? {
|
|
3035
|
+
channel
|
|
3036
|
+
} : {}),
|
|
3037
|
+
...(businessCode ? {
|
|
3038
|
+
business_code: businessCode
|
|
3039
|
+
} : {}),
|
|
3040
|
+
...(scopedParams.strategy_context || {})
|
|
3041
|
+
};
|
|
3042
|
+
let customerId = scopedParams.customer_id;
|
|
3043
|
+
if (customerId == null) customerId = this.core.getPlugin?.('user')?.get?.()?.id;
|
|
3044
|
+
const queryPayload = {
|
|
3045
|
+
...scopedParams,
|
|
3046
|
+
customer_id: customerId,
|
|
3047
|
+
strategy_context,
|
|
3048
|
+
application_code: channel,
|
|
3049
|
+
is_eject: 1,
|
|
3050
|
+
open_bundle: 1,
|
|
3051
|
+
with_schedule: 1,
|
|
3052
|
+
with: [..._clientDataVariants.PRODUCT_QUERY_DATA_VARIANT_RELATIONS],
|
|
3053
|
+
...((0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) ? {} : {
|
|
3054
|
+
open_quotation: 1
|
|
3055
|
+
})
|
|
3056
|
+
};
|
|
3057
|
+
const response = await this.request.get(baseUrl === '/shop' ? localPath : `/product/show/${product_id}`, queryPayload, {
|
|
3058
|
+
osServer: true,
|
|
3059
|
+
useCache: false,
|
|
3060
|
+
customToast: () => {}
|
|
3061
|
+
});
|
|
3062
|
+
if (response?.status === false || Number(response?.code) >= 400) throw new Error('[UnifiedBookingSales] Product detail query failed');
|
|
3063
|
+
const raw = response?.data?.item ?? response?.data;
|
|
3064
|
+
if (!raw || Number(raw.id ?? raw.product_id) !== product_id) return undefined;
|
|
3065
|
+
if (raw.status && raw.status !== 'published') return undefined;
|
|
3066
|
+
if (!handledByOsServer) this.store.products?.rememberRawProductQueryResult?.([(0, _lodashEs.cloneDeep)(raw)]);
|
|
3067
|
+
const resolved = (0, _clientDataVariants.resolveClientDataVariants)({
|
|
3068
|
+
core: this.core,
|
|
3069
|
+
otherParams: this.otherParams,
|
|
3070
|
+
products: [(0, _lodashEs.cloneDeep)(raw)],
|
|
3071
|
+
queryPayload,
|
|
3072
|
+
handledByOsServer
|
|
3073
|
+
})[0];
|
|
3074
|
+
// Detail owns relation arrays. Never synthesize empty groups from list counts.
|
|
3075
|
+
if (!resolved) return undefined;
|
|
3076
|
+
const detail = {
|
|
3077
|
+
...member,
|
|
3078
|
+
...resolved,
|
|
3079
|
+
metadata: {
|
|
3080
|
+
...(member.metadata || {}),
|
|
3081
|
+
...(resolved.metadata || {})
|
|
3082
|
+
}
|
|
3083
|
+
};
|
|
3084
|
+
for (const key of ['bundle_group', 'bundle_groups', 'option_group', 'variant_group', 'variant']) {
|
|
3085
|
+
if (!Object.prototype.hasOwnProperty.call(resolved, key)) delete detail[key];
|
|
3086
|
+
}
|
|
3087
|
+
return (0, _lodashEs.cloneDeep)(detail);
|
|
3088
|
+
}
|
|
3089
|
+
async loadCatalogProducts(params = {}, options) {
|
|
2190
3090
|
if (!this.store.products) throw new Error('[UnifiedBookingSales] products 模块未初始化');
|
|
3091
|
+
const catalogScope = this.otherParams.catalogScopeKey;
|
|
2191
3092
|
const schedule_date = params.schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD');
|
|
2192
3093
|
const schedule_datetime = params.schedule_datetime || `${schedule_date} ${(0, _dayjs.default)().format('HH:mm:ss')}`;
|
|
2193
3094
|
const result = await this.store.products.loadProducts({
|
|
@@ -2198,8 +3099,11 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2198
3099
|
schedule_datetime,
|
|
2199
3100
|
cacheId: this.cacheId
|
|
2200
3101
|
}, options);
|
|
2201
|
-
|
|
2202
|
-
|
|
3102
|
+
if (catalogScope !== this.otherParams.catalogScopeKey) {
|
|
3103
|
+
throw Object.assign(new Error('Product scope changed'), {
|
|
3104
|
+
name: 'AbortError'
|
|
3105
|
+
});
|
|
3106
|
+
}
|
|
2203
3107
|
return result;
|
|
2204
3108
|
}
|
|
2205
3109
|
async queryProducts(params = {}) {
|
|
@@ -2375,6 +3279,17 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2375
3279
|
}
|
|
2376
3280
|
buildUnifiedOrderProduct(sourceProduct, ownershipKey, product) {
|
|
2377
3281
|
const normalizedProductRaw = product?.raw || {};
|
|
3282
|
+
const bookingQuote = sourceProduct._extend?.bookingPriceQuote;
|
|
3283
|
+
const isPos = (0, _platform.normalizeRuntimePlatform)(this.otherParams?.platform) === 'pos';
|
|
3284
|
+
const quoteMethod = isPos ? bookingQuote?.pricing_method?.type : undefined;
|
|
3285
|
+
const hasDurationQuote = quoteMethod === 'duration_based';
|
|
3286
|
+
const quoteSourcePrice = bookingQuote?.sourceUnitPrice;
|
|
3287
|
+
const quoteDuration = bookingQuote?.duration;
|
|
3288
|
+
if (hasDurationQuote && (quoteSourcePrice === undefined || quoteSourcePrice === null || quoteSourcePrice === '' || !Number.isFinite(Number(quoteSourcePrice)) || Number(quoteSourcePrice) < 0 || quoteDuration?.type !== 'minutes' || !Number.isFinite(Number(quoteDuration.value)) || Number(quoteDuration.value) <= 0)) {
|
|
3289
|
+
throw Object.assign(new Error('按时长计价结果无效,请重新选择预约时间。'), {
|
|
3290
|
+
code: 'DURATION_PRICING_UNAVAILABLE'
|
|
3291
|
+
});
|
|
3292
|
+
}
|
|
2378
3293
|
const quotationShelfId = sourceProduct._extend?.quotation_shelf_id ?? sourceProduct.quotation_shelf_id ?? sourceProduct.metadata?.quotation_shelf_id;
|
|
2379
3294
|
const orderProduct = this.transformBaseProductToOrderProduct({
|
|
2380
3295
|
payload: {
|
|
@@ -2389,18 +3304,47 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2389
3304
|
[ownershipKey]: true
|
|
2390
3305
|
}
|
|
2391
3306
|
},
|
|
2392
|
-
sourceProduct
|
|
3307
|
+
sourceProduct,
|
|
3308
|
+
...(hasDurationQuote ? {
|
|
3309
|
+
quotedSourceProductPrice: quoteSourcePrice
|
|
3310
|
+
} : {})
|
|
2393
3311
|
});
|
|
2394
3312
|
if (orderProduct && typeof orderProduct === 'object') {
|
|
3313
|
+
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]]));
|
|
3314
|
+
const isVenueExtra = ownershipKey === 'unified_booking_sales_retail' && ['tickets_extra', 'party_extra'].includes(venueMetadata.venue_booking_role);
|
|
3315
|
+
if (isVenueExtra && sourceProduct.metadata?.venue_extra_holder_variant_id !== undefined) {
|
|
3316
|
+
// null explicitly clears a previous SKU override. The adapter pairs the marker
|
|
3317
|
+
// with its resolved policy, independent of the product's original settings.
|
|
3318
|
+
venueMetadata.venue_extra_holder_variant_id = sourceProduct.metadata.venue_extra_holder_variant_id;
|
|
3319
|
+
const holderConfig = sourceProduct.holder_config ?? sourceProduct.metadata.holder_config;
|
|
3320
|
+
if (holderConfig) venueMetadata.holder_config = (0, _lodashEs.cloneDeep)(holderConfig);
|
|
3321
|
+
}
|
|
2395
3322
|
// BaseSales may rebuild metadata from its price source. Stamp ownership and the selected
|
|
2396
3323
|
// quotation shelf after that transform so neither booking adds nor edits lose quote identity.
|
|
2397
3324
|
orderProduct.metadata = {
|
|
2398
3325
|
...(orderProduct.metadata || {}),
|
|
3326
|
+
...venueMetadata,
|
|
2399
3327
|
[ownershipKey]: true,
|
|
3328
|
+
...(hasDurationQuote || quoteMethod === 'fixed_price' ? {
|
|
3329
|
+
pricing_method: {
|
|
3330
|
+
type: quoteMethod
|
|
3331
|
+
},
|
|
3332
|
+
duration: hasDurationQuote ? {
|
|
3333
|
+
...quoteDuration
|
|
3334
|
+
} : undefined
|
|
3335
|
+
} : {}),
|
|
2400
3336
|
...(quotationShelfId !== undefined ? {
|
|
2401
3337
|
quotation_shelf_id: quotationShelfId
|
|
2402
3338
|
} : {})
|
|
2403
3339
|
};
|
|
3340
|
+
// Extras use retail order-detail relations even when the catalog product
|
|
3341
|
+
// also has a bookable duration. Order binds the patch to the final line UID.
|
|
3342
|
+
if (isVenueExtra && Array.isArray(sourceProduct._extend?.holder_relations)) {
|
|
3343
|
+
orderProduct._extend = {
|
|
3344
|
+
...orderProduct._extend,
|
|
3345
|
+
holder_relations: (0, _lodashEs.cloneDeep)(sourceProduct._extend.holder_relations)
|
|
3346
|
+
};
|
|
3347
|
+
}
|
|
2404
3348
|
}
|
|
2405
3349
|
return orderProduct;
|
|
2406
3350
|
}
|
|
@@ -2445,6 +3389,16 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2445
3389
|
return this.stageProducts(params, 'unified_booking_sales_retail');
|
|
2446
3390
|
}
|
|
2447
3391
|
|
|
3392
|
+
/** Explicit capability: order-scoped Tickets extras use guarded writes without implicit SKU merging. */
|
|
3393
|
+
supportsVenueTicketExtras() {
|
|
3394
|
+
return true;
|
|
3395
|
+
}
|
|
3396
|
+
|
|
3397
|
+
/** The venue retail write path accepts per-line Holder relations for both templates. */
|
|
3398
|
+
supportsVenueExtraHolders() {
|
|
3399
|
+
return true;
|
|
3400
|
+
}
|
|
3401
|
+
|
|
2448
3402
|
/**
|
|
2449
3403
|
* Adds one retail line without replacing the cart's existing retail selection.
|
|
2450
3404
|
* This is intentionally separate from stageRetailProducts(), whose contract is
|
|
@@ -2477,7 +3431,65 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2477
3431
|
if (!orderProduct) {
|
|
2478
3432
|
throw new Error('[UnifiedBookingSales] 无法生成零售商品订单行');
|
|
2479
3433
|
}
|
|
2480
|
-
|
|
3434
|
+
if (orderProduct.metadata?.venue_booking_role === 'tickets_extra') {
|
|
3435
|
+
const order = this.getTempOrder();
|
|
3436
|
+
const meta = orderProduct.metadata;
|
|
3437
|
+
const scopeKey = String(meta.venue_booking_scope_key || '');
|
|
3438
|
+
const purchaseDatetime = String(meta.venue_booking_service_datetime || '');
|
|
3439
|
+
const identity = [order?.order_id, order?.external_sale_number, order?.customer_id];
|
|
3440
|
+
const isCurrentOrder = () => this.getTempOrder() === order && order?.order_id === identity[0] && order?.external_sale_number === identity[1] && order?.customer_id === identity[2];
|
|
3441
|
+
const guard = () => {
|
|
3442
|
+
params.availabilityCommitGuard?.();
|
|
3443
|
+
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)) {
|
|
3444
|
+
throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '门票订单或购买时间已变化,请重新确认附加商品');
|
|
3445
|
+
}
|
|
3446
|
+
};
|
|
3447
|
+
guard();
|
|
3448
|
+
// Retail extras are order-owned, with their own UID and no booking.
|
|
3449
|
+
delete orderProduct.unique_identification_number;
|
|
3450
|
+
delete meta.unique_identification_number;
|
|
3451
|
+
delete meta.venue_booking_parent_uid;
|
|
3452
|
+
return this.addProductToOrder(orderProduct, undefined, {
|
|
3453
|
+
disableMerge: true,
|
|
3454
|
+
availabilityCommitGuard: guard,
|
|
3455
|
+
availabilityCommitTargetGuard: isCurrentOrder,
|
|
3456
|
+
salesNotes: params.salesNotes
|
|
3457
|
+
});
|
|
3458
|
+
}
|
|
3459
|
+
if (orderProduct.metadata?.venue_booking_role === 'party_extra') {
|
|
3460
|
+
const order = this.getTempOrder();
|
|
3461
|
+
const meta = orderProduct.metadata;
|
|
3462
|
+
const parentUid = String(meta.venue_booking_parent_uid || '');
|
|
3463
|
+
const scopeKey = String(meta.venue_booking_scope_key || '');
|
|
3464
|
+
// The persisted legacy key holds this retail extra's venue-local purchase quote time.
|
|
3465
|
+
// Its parent UID owns the extra; the parent's appointment time does not price it.
|
|
3466
|
+
const purchaseDatetime = String(meta.venue_booking_service_datetime || '');
|
|
3467
|
+
const normalizedPurchaseDatetime = purchaseDatetime.length === 16 ? `${purchaseDatetime}:00` : purchaseDatetime;
|
|
3468
|
+
const identity = [order?.order_id, order?.external_sale_number, order?.customer_id];
|
|
3469
|
+
const isCurrentOrder = () => this.getTempOrder() === order && order?.order_id === identity[0] && order?.external_sale_number === identity[1] && order?.customer_id === identity[2];
|
|
3470
|
+
const guard = () => {
|
|
3471
|
+
params.availabilityCommitGuard?.();
|
|
3472
|
+
const parent = (order?.products || []).find(line => getProductLineUid(line) === parentUid);
|
|
3473
|
+
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 主商品或附加商品报价上下文已变化,请重新确认附加商品');
|
|
3474
|
+
};
|
|
3475
|
+
guard();
|
|
3476
|
+
delete orderProduct.unique_identification_number;
|
|
3477
|
+
delete orderProduct.metadata.unique_identification_number;
|
|
3478
|
+
return this.addProductToOrder(orderProduct, undefined, {
|
|
3479
|
+
disableMerge: true,
|
|
3480
|
+
availabilityCommitGuard: guard,
|
|
3481
|
+
availabilityCommitTargetGuard: isCurrentOrder,
|
|
3482
|
+
salesNotes: params.salesNotes
|
|
3483
|
+
});
|
|
3484
|
+
}
|
|
3485
|
+
return this.addProductToOrder(orderProduct, undefined, {
|
|
3486
|
+
...(params.availabilityCommitGuard ? {
|
|
3487
|
+
availabilityCommitGuard: params.availabilityCommitGuard
|
|
3488
|
+
} : {}),
|
|
3489
|
+
...(params.salesNotes ? {
|
|
3490
|
+
salesNotes: params.salesNotes
|
|
3491
|
+
} : {})
|
|
3492
|
+
});
|
|
2481
3493
|
}
|
|
2482
3494
|
normalizeAvailabilityDateRange(params, timezone) {
|
|
2483
3495
|
const today = (0, _localClock.formatLocalDate)((0, _localClock.localDateToScalar)(new Date()));
|
|
@@ -2523,6 +3535,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2523
3535
|
};
|
|
2524
3536
|
}
|
|
2525
3537
|
assertAvailabilityPrepareParams(params) {
|
|
3538
|
+
if (params.occupancyCachePolicy !== undefined && params.occupancyCachePolicy !== 'cache_first' && params.occupancyCachePolicy !== 'session') {
|
|
3539
|
+
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Unknown occupancyCachePolicy');
|
|
3540
|
+
}
|
|
2526
3541
|
assertAvailabilityCatalogProductIds(params.productIds, 'prepare.productIds');
|
|
2527
3542
|
const hasProductAnchor = Array.isArray(params.productIds) && params.productIds.length > 0;
|
|
2528
3543
|
const hasResourceAnchor = Array.isArray(params.resourceIds) && params.resourceIds.length > 0;
|
|
@@ -2532,8 +3547,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2532
3547
|
params
|
|
2533
3548
|
});
|
|
2534
3549
|
}
|
|
2535
|
-
if (!hasProductAnchor && !params.catalogScope) {
|
|
2536
|
-
throw new _ResourcePlanner.AvailabilityError('MISSING_CATALOG_SCOPE', '缺少 productIds 时必须提供 catalogScope', {
|
|
3550
|
+
if (!hasProductAnchor && !params.catalogScope && !Array.isArray(params.rawProducts)) {
|
|
3551
|
+
throw new _ResourcePlanner.AvailabilityError('MISSING_CATALOG_SCOPE', '缺少 productIds 时必须提供 catalogScope 或 rawProducts', {
|
|
2537
3552
|
params
|
|
2538
3553
|
});
|
|
2539
3554
|
}
|
|
@@ -2650,12 +3665,15 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2650
3665
|
dateRange
|
|
2651
3666
|
} = params;
|
|
2652
3667
|
const explicitProductIds = prepare.productIds || [];
|
|
3668
|
+
const publishCatalog = prepare.publishCatalog !== false;
|
|
3669
|
+
const loadProducts = query => publishCatalog ? this.loadProducts(query) : prepare.catalogScope?.type === 'productList' ? this.queryCatalogSnapshot(query) : this.loadCatalogProducts(query);
|
|
2653
3670
|
let rawProducts = [];
|
|
2654
3671
|
if (Array.isArray(prepare.rawProducts)) {
|
|
2655
3672
|
rawProducts = prepare.rawProducts;
|
|
2656
|
-
this.unifiedProductCatalog = [...rawProducts];
|
|
3673
|
+
if (publishCatalog) this.unifiedProductCatalog = [...rawProducts];
|
|
2657
3674
|
} else if (explicitProductIds.length > 0) {
|
|
2658
|
-
rawProducts = await
|
|
3675
|
+
rawProducts = await loadProducts({
|
|
3676
|
+
...(!publishCatalog && prepare.catalogScope?.type === 'productList' ? prepare.catalogScope.params : {}),
|
|
2659
3677
|
product_ids: explicitProductIds,
|
|
2660
3678
|
schedule_date: dateRange.startDate
|
|
2661
3679
|
});
|
|
@@ -2671,25 +3689,25 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2671
3689
|
const productIds = uniqueAvailabilityIds([...scheduleProductIds, ...(this.store.schedule.getOtherProductsIds?.() || [])]);
|
|
2672
3690
|
if (productIds.length > 0) {
|
|
2673
3691
|
assertAvailabilityCatalogProductIds(productIds, 'prepare.catalogScope.scheduleProductIds');
|
|
2674
|
-
rawProducts = await
|
|
3692
|
+
rawProducts = await loadProducts({
|
|
2675
3693
|
product_ids: productIds,
|
|
2676
3694
|
schedule_date: dateRange.startDate
|
|
2677
3695
|
});
|
|
2678
3696
|
} else {
|
|
2679
|
-
this.unifiedProductCatalog = [];
|
|
3697
|
+
if (publishCatalog) this.unifiedProductCatalog = [];
|
|
2680
3698
|
}
|
|
2681
3699
|
} else if (prepare.catalogScope?.type === 'productList') {
|
|
2682
|
-
rawProducts = await
|
|
3700
|
+
rawProducts = await loadProducts({
|
|
2683
3701
|
...prepare.catalogScope.params,
|
|
2684
3702
|
schedule_date: prepare.catalogScope.params.schedule_date || dateRange.startDate
|
|
2685
3703
|
});
|
|
2686
3704
|
}
|
|
2687
|
-
const
|
|
3705
|
+
const productIdSet = explicitProductIds.length ? new Set(explicitProductIds.map(String)) : null;
|
|
3706
|
+
const normalized = (productIdSet ? rawProducts.filter(product => productIdSet.has(String(product.id ?? product.product_id))) : rawProducts).map(product => normalizeProductForAvailability(product, params.scheduleList, this.getAvailabilityRuntimeOffsetMinutes()));
|
|
2688
3707
|
if (!explicitProductIds.length && prepare.resourceIds?.length) {
|
|
2689
3708
|
return normalized.filter(product => product.requirementGroups?.some(group => group.resourceIds?.some(resourceId => prepare.resourceIds.some(id => sameAvailabilityId(id, resourceId)))));
|
|
2690
3709
|
}
|
|
2691
|
-
|
|
2692
|
-
return productIdSet ? normalized.filter(product => productIdSet.has(String(product.id))) : normalized;
|
|
3710
|
+
return normalized;
|
|
2693
3711
|
}
|
|
2694
3712
|
|
|
2695
3713
|
/**
|
|
@@ -2707,10 +3725,72 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2707
3725
|
useCache: false
|
|
2708
3726
|
});
|
|
2709
3727
|
const data = response?.data;
|
|
3728
|
+
if (params.strictResponse && response?.status === false) {
|
|
3729
|
+
const message = response?.message;
|
|
3730
|
+
throw Object.assign(new Error(typeof message === 'string' && message.trim() ? message : 'Unable to load booking resource details.'), {
|
|
3731
|
+
code: response?.code
|
|
3732
|
+
});
|
|
3733
|
+
}
|
|
2710
3734
|
if (Array.isArray(data)) return data;
|
|
2711
3735
|
if (Array.isArray(data?.list)) return data.list;
|
|
3736
|
+
if (params.strictResponse) {
|
|
3737
|
+
throw new Error('Booking resource details returned an invalid response.');
|
|
3738
|
+
}
|
|
2712
3739
|
return [];
|
|
2713
3740
|
}
|
|
3741
|
+
|
|
3742
|
+
/** Fresh read-only metadata for confirmation forms/policies; does not create a projection or mutate BookingContext. */
|
|
3743
|
+
async queryBookingResourceDetails(params) {
|
|
3744
|
+
const date = params?.date;
|
|
3745
|
+
try {
|
|
3746
|
+
if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error('date');
|
|
3747
|
+
(0, _localClock.parseLocalDate)(date);
|
|
3748
|
+
} catch {
|
|
3749
|
+
throw this.createAvailabilityFacadeError('INVALID_DATE_RANGE', 'A valid booking date is required to load resource details.');
|
|
3750
|
+
}
|
|
3751
|
+
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)) {
|
|
3752
|
+
throw this.createAvailabilityFacadeError('INVALID_TARGET_FILTER', 'Selected resource IDs are required to load resource details.');
|
|
3753
|
+
}
|
|
3754
|
+
const resourceIds = [...new Set(params.resourceIds.map(id => String(Number(id))))];
|
|
3755
|
+
const core = this.core;
|
|
3756
|
+
const request = this.request;
|
|
3757
|
+
const generation = this.runtimeInitializationGeneration;
|
|
3758
|
+
const scope = this.getRuntimeOpenDataScope();
|
|
3759
|
+
const assertCurrent = () => {
|
|
3760
|
+
if (this.runtimeOpenDataDestroyed || !request || core !== this.core || request !== this.request || generation !== this.runtimeInitializationGeneration || scope !== this.getRuntimeOpenDataScope()) {
|
|
3761
|
+
throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'Booking settings changed. Please reload the resource details.');
|
|
3762
|
+
}
|
|
3763
|
+
};
|
|
3764
|
+
assertCurrent();
|
|
3765
|
+
const resourceQuery = {
|
|
3766
|
+
dateRange: {
|
|
3767
|
+
startDate: date,
|
|
3768
|
+
endDate: date
|
|
3769
|
+
},
|
|
3770
|
+
resourceIds
|
|
3771
|
+
};
|
|
3772
|
+
// Match normalizeAvailabilityPrepareDescriptor so confirmation reuses exactly
|
|
3773
|
+
// the same resource/date coverage as the selection projection.
|
|
3774
|
+
const timezone = String(this.otherParams?.businessTimezone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai').trim();
|
|
3775
|
+
const resources = this.isVenueCatalogLocalPricingActive() ? await this.availabilitySessionResourceCache.load({
|
|
3776
|
+
scopeKey: `${scope}:${this.buildAvailabilityRemoteResourceScopeKey(timezone)}`,
|
|
3777
|
+
timezoneName: timezone,
|
|
3778
|
+
...resourceQuery,
|
|
3779
|
+
fetch: query => this.fetchAvailabilityResourcesV2({
|
|
3780
|
+
...query,
|
|
3781
|
+
strictResponse: true
|
|
3782
|
+
})
|
|
3783
|
+
}) : await this.fetchAvailabilityResourcesV2({
|
|
3784
|
+
...resourceQuery,
|
|
3785
|
+
strictResponse: true
|
|
3786
|
+
});
|
|
3787
|
+
assertCurrent();
|
|
3788
|
+
const byId = new Map(resources.filter(isRecord).map(resource => [String(resource.id), resource]));
|
|
3789
|
+
if (resourceIds.some(id => !byId.has(id))) {
|
|
3790
|
+
throw this.createAvailabilityFacadeError('INVALID_TARGET_FILTER', 'A selected booking resource is no longer available.');
|
|
3791
|
+
}
|
|
3792
|
+
return (0, _lodashEs.cloneDeep)(resourceIds.map(id => byId.get(id)));
|
|
3793
|
+
}
|
|
2714
3794
|
async fetchAndPublishAvailabilityResourcesV2(params) {
|
|
2715
3795
|
const normalizedResourceIds = this.normalizeAvailabilityIdList(params.resourceIds) || [];
|
|
2716
3796
|
if (normalizedResourceIds.length === 0) return [];
|
|
@@ -2718,7 +3798,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2718
3798
|
const cacheParams = {
|
|
2719
3799
|
scopeKey,
|
|
2720
3800
|
resourceIds: normalizedResourceIds,
|
|
2721
|
-
dateRange: params.dateRange
|
|
3801
|
+
dateRange: params.dateRange,
|
|
3802
|
+
maxAgeMs: params.maxAgeMs
|
|
2722
3803
|
};
|
|
2723
3804
|
const cachedRawResources = this.availabilityRemoteOccupancyCache.read(cacheParams);
|
|
2724
3805
|
if (cachedRawResources) {
|
|
@@ -2733,6 +3814,22 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2733
3814
|
}
|
|
2734
3815
|
return cachedRawResources;
|
|
2735
3816
|
}
|
|
3817
|
+
if (params.maxAgeMs !== undefined) {
|
|
3818
|
+
// A visible-month request can cover a concurrent day/resource-subset preview.
|
|
3819
|
+
// Only share fully covering requests; partial overlaps keep the normal fetch path.
|
|
3820
|
+
const epoch = this.availabilityRemoteResourceEpoch;
|
|
3821
|
+
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))));
|
|
3822
|
+
if (covering) {
|
|
3823
|
+
await covering.promise;
|
|
3824
|
+
if (epoch !== this.availabilityRemoteResourceEpoch) {
|
|
3825
|
+
throw this.createAvailabilityFacadeError('AVAILABILITY_CONTEXT_NOT_FOUND', 'Resource settings changed while loading. Please prepare again.');
|
|
3826
|
+
}
|
|
3827
|
+
// Read a detached, correctly sliced graph after publication. A newer overlapping
|
|
3828
|
+
// response may have invalidated cells, in which case fetch this exact range below.
|
|
3829
|
+
const coveredResources = this.availabilityRemoteOccupancyCache.read(cacheParams);
|
|
3830
|
+
if (coveredResources) return coveredResources;
|
|
3831
|
+
}
|
|
3832
|
+
}
|
|
2736
3833
|
return await this.refreshAvailabilityRemoteResourceQuery({
|
|
2737
3834
|
timezone: params.timezone,
|
|
2738
3835
|
dateRange: params.dateRange,
|
|
@@ -2754,19 +3851,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2754
3851
|
}
|
|
2755
3852
|
this.availabilityRemoteResourceQuerySequence += 1;
|
|
2756
3853
|
const writeVersion = this.availabilityRemoteResourceQuerySequence;
|
|
3854
|
+
const scopeKey = this.buildAvailabilityRemoteResourceScopeKey(params.timezone);
|
|
2757
3855
|
const promise = this.fetchAvailabilityResourcesV2({
|
|
2758
3856
|
dateRange: params.dateRange,
|
|
2759
3857
|
resourceIds: normalizedResourceIds
|
|
2760
|
-
})
|
|
2761
|
-
this.availabilityRemoteResourceQueryInFlight.set(queryKey, {
|
|
2762
|
-
epoch,
|
|
2763
|
-
promise
|
|
2764
|
-
});
|
|
2765
|
-
try {
|
|
2766
|
-
const rawResources = await promise;
|
|
3858
|
+
}).then(rawResources => {
|
|
2767
3859
|
if (epoch === this.availabilityRemoteResourceEpoch) {
|
|
2768
3860
|
this.availabilityRemoteOccupancyCache.publish({
|
|
2769
|
-
scopeKey
|
|
3861
|
+
scopeKey,
|
|
2770
3862
|
timezoneName: params.timezone,
|
|
2771
3863
|
resourceIds: normalizedResourceIds,
|
|
2772
3864
|
dateRange: params.dateRange,
|
|
@@ -2775,6 +3867,18 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2775
3867
|
});
|
|
2776
3868
|
}
|
|
2777
3869
|
return rawResources;
|
|
3870
|
+
});
|
|
3871
|
+
this.availabilityRemoteResourceQueryInFlight.set(queryKey, {
|
|
3872
|
+
epoch,
|
|
3873
|
+
scopeKey,
|
|
3874
|
+
dateRange: {
|
|
3875
|
+
...params.dateRange
|
|
3876
|
+
},
|
|
3877
|
+
resourceIds: [...normalizedResourceIds],
|
|
3878
|
+
promise
|
|
3879
|
+
});
|
|
3880
|
+
try {
|
|
3881
|
+
return await promise;
|
|
2778
3882
|
} finally {
|
|
2779
3883
|
const current = this.availabilityRemoteResourceQueryInFlight.get(queryKey);
|
|
2780
3884
|
if (current?.promise === promise) {
|
|
@@ -2790,7 +3894,25 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2790
3894
|
resourceOccupancies: []
|
|
2791
3895
|
};
|
|
2792
3896
|
}
|
|
2793
|
-
if (
|
|
3897
|
+
if (params.fetchPolicy === 'session') {
|
|
3898
|
+
const rawResources = await this.availabilitySessionResourceCache.load({
|
|
3899
|
+
scopeKey: `${this.getRuntimeOpenDataScope()}:${this.buildAvailabilityRemoteResourceScopeKey(params.timezone)}`,
|
|
3900
|
+
timezoneName: params.timezone,
|
|
3901
|
+
resourceIds,
|
|
3902
|
+
dateRange: params.dateRange,
|
|
3903
|
+
fetch: query => this.fetchAvailabilityResourcesV2({
|
|
3904
|
+
...query,
|
|
3905
|
+
strictResponse: true
|
|
3906
|
+
})
|
|
3907
|
+
});
|
|
3908
|
+
return buildAvailabilityResourcesFromV2({
|
|
3909
|
+
rawResources,
|
|
3910
|
+
scheduleList: params.scheduleList,
|
|
3911
|
+
dateRange: params.dateRange,
|
|
3912
|
+
fixedOffsetMinutes: this.getAvailabilityRuntimeOffsetMinutes()
|
|
3913
|
+
});
|
|
3914
|
+
}
|
|
3915
|
+
if (Array.isArray(params.rawResources) && params.fetchPolicy !== 'refresh') {
|
|
2794
3916
|
return buildAvailabilityResourcesFromV2({
|
|
2795
3917
|
rawResources: params.rawResources,
|
|
2796
3918
|
scheduleList: params.scheduleList,
|
|
@@ -2817,11 +3939,17 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2817
3939
|
resourceOccupancies: []
|
|
2818
3940
|
};
|
|
2819
3941
|
}
|
|
2820
|
-
const
|
|
3942
|
+
const remoteQuery = {
|
|
2821
3943
|
timezone: params.timezone,
|
|
2822
3944
|
dateRange: params.dateRange,
|
|
2823
|
-
resourceIds
|
|
2824
|
-
|
|
3945
|
+
resourceIds
|
|
3946
|
+
};
|
|
3947
|
+
const rawResources = params.fetchPolicy === 'refresh' ? await this.refreshAvailabilityRemoteResourceQuery(remoteQuery) : await this.fetchAndPublishAvailabilityResourcesV2({
|
|
3948
|
+
...remoteQuery,
|
|
3949
|
+
useCacheOnHit: params.fetchPolicy !== 'cache_first',
|
|
3950
|
+
...(params.fetchPolicy === 'cache_first' ? {
|
|
3951
|
+
maxAgeMs: PREVIEW_OCCUPANCY_CACHE_MAX_AGE_MS
|
|
3952
|
+
} : {})
|
|
2825
3953
|
});
|
|
2826
3954
|
return buildAvailabilityResourcesFromV2({
|
|
2827
3955
|
rawResources,
|
|
@@ -3012,6 +4140,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3012
4140
|
lastPreparedAt: params.projection.meta.preparedAt,
|
|
3013
4141
|
lastSnapshotId: params.projection.meta.snapshotId,
|
|
3014
4142
|
durationCandidateAnchorAt: previousContext?.durationCandidateAnchorAt ?? this.getAvailabilityDurationCandidateAnchorAt(params.projection),
|
|
4143
|
+
calendarOrderSessionId: previousContext?.calendarOrderSessionId,
|
|
3015
4144
|
refreshNonce: previousContext?.refreshNonce ?? 0,
|
|
3016
4145
|
lifecycleGeneration: this.availabilityLifecycleGeneration
|
|
3017
4146
|
};
|
|
@@ -3055,7 +4184,9 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3055
4184
|
products,
|
|
3056
4185
|
rawResources: normalizedPrepareParams.rawResources,
|
|
3057
4186
|
scheduleList,
|
|
3058
|
-
|
|
4187
|
+
// Explicit Venue sessions retain physical occupancy coverage across preview,
|
|
4188
|
+
// selection and commit. Cart-derived occupancy is still rebuilt below.
|
|
4189
|
+
fetchPolicy: normalizedPrepareParams.occupancyCachePolicy === 'session' ? 'session' : options.resourceFetchPolicy || (normalizedPrepareParams.refreshOccupancies ? 'refresh' : normalizedPrepareParams.occupancyCachePolicy === 'cache_first' ? 'cache_first' : 'default'),
|
|
3059
4190
|
fallbackResources: options.fallbackResources
|
|
3060
4191
|
});
|
|
3061
4192
|
const tempOrder = this.getTempOrder();
|
|
@@ -3340,9 +4471,31 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3340
4471
|
projectionEntry
|
|
3341
4472
|
} = await this.ensureAvailabilityContextProjection(contextId, 'get_product_time_ranges');
|
|
3342
4473
|
const contextVersion = context.activeVersion;
|
|
4474
|
+
const strictAvailability = context.prepareParams.strictAvailability === true;
|
|
3343
4475
|
const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
|
|
3344
4476
|
const isEditingContext = Boolean(context.prepareParams.editingProductLineUids?.length);
|
|
3345
4477
|
const editingOffset = (0, _localClock.extractFixedOffsetMinutes)(projectionEntry.projection.meta.now) ?? this.getAvailabilityRuntimeOffsetMinutes();
|
|
4478
|
+
const hasRequestedRanges = Object.keys(request.requestedRangesByProductId || {}).length > 0;
|
|
4479
|
+
if (hasRequestedRanges && (!isPosAvailabilityRequest || strictAvailability || request.rememberedStartAtByProductId || request.rememberedTimeByProductId)) {
|
|
4480
|
+
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '明确预约范围仅支持 POS 手工选择');
|
|
4481
|
+
}
|
|
4482
|
+
// Calendar entry carries absolute instants. Convert both endpoints once to
|
|
4483
|
+
// the projection clock; never reinterpret their HH:mm as a business date.
|
|
4484
|
+
const requestedRangesByProductId = hasRequestedRanges ? Object.fromEntries(Object.entries(request.requestedRangesByProductId).map(([productId, range]) => {
|
|
4485
|
+
try {
|
|
4486
|
+
const normalizeEndpoint = value => {
|
|
4487
|
+
const scalar = (0, _localClock.localDateTimeToScalar)((0, _localClock.parseLocalDateTime)(value));
|
|
4488
|
+
const inputOffset = (0, _localClock.extractFixedOffsetMinutes)(value) ?? editingOffset;
|
|
4489
|
+
return (0, _localClock.formatLocalDateTime)(scalar + (editingOffset - inputOffset) * 60000, editingOffset);
|
|
4490
|
+
};
|
|
4491
|
+
return [productId, {
|
|
4492
|
+
startAt: normalizeEndpoint(range.startAt),
|
|
4493
|
+
endAt: normalizeEndpoint(range.endAt)
|
|
4494
|
+
}];
|
|
4495
|
+
} catch {
|
|
4496
|
+
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '手工预约范围必须包含完整有效起止日期时间');
|
|
4497
|
+
}
|
|
4498
|
+
})) : undefined;
|
|
3346
4499
|
// This new editing input represents an absolute instant. Normalize it once
|
|
3347
4500
|
// to the projection's fixed business clock before the wall-clock planner.
|
|
3348
4501
|
const editingStartAtByProductId = isEditingContext && request.editingStartAtByProductId ? Object.fromEntries(Object.entries(request.editingStartAtByProductId).map(([productId, startAt]) => {
|
|
@@ -3365,26 +4518,34 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3365
4518
|
endDate: businessDate
|
|
3366
4519
|
};
|
|
3367
4520
|
}
|
|
3368
|
-
const
|
|
3369
|
-
const
|
|
4521
|
+
const rememberedTimeByProductId = this.resolveOrderRememberedTimes(context, projectionEntry.projection, request.rememberedTimeByProductId, request.orderSessionId);
|
|
4522
|
+
const rememberedStartAtByProductId = !rememberedTimeByProductId && isPosAvailabilityRequest && !isEditingContext ? request.rememberedStartAtByProductId : undefined;
|
|
4523
|
+
const allowOutsideOperatingHoursForRequestedStartTimes = isPosAvailabilityRequest && !strictAvailability && !rememberedStartAtByProductId && !rememberedTimeByProductId && (editingStarts.length > 0 || Object.values(request.durationStartTimesByProductId || {}).some(startTimes => Array.isArray(startTimes) && startTimes.length > 0));
|
|
3370
4524
|
return (0, _ResourcePlanner.getProductTimeRanges)(projectionEntry.projection, {
|
|
3371
4525
|
...request,
|
|
3372
4526
|
dateRange,
|
|
3373
4527
|
editingStartAtByProductId,
|
|
4528
|
+
requestedRangesByProductId,
|
|
3374
4529
|
rememberedStartAtByProductId,
|
|
3375
|
-
|
|
4530
|
+
rememberedTimeByProductId,
|
|
4531
|
+
...(rememberedStartAtByProductId || rememberedTimeByProductId ? {
|
|
3376
4532
|
allowOutsideOperatingHoursForRequestedStartTimes: false
|
|
3377
4533
|
} : {}),
|
|
3378
4534
|
...(allowOutsideOperatingHoursForRequestedStartTimes ? {
|
|
3379
4535
|
allowOutsideOperatingHoursForRequestedStartTimes: true
|
|
4536
|
+
} : {}),
|
|
4537
|
+
...(strictAvailability ? {
|
|
4538
|
+
allowOutsideOperatingHoursForRequestedStartTimes: false
|
|
3380
4539
|
} : {})
|
|
3381
4540
|
}, {
|
|
3382
4541
|
evaluatedAt: this.getAvailabilityRuntimeDateTime(),
|
|
3383
4542
|
useDurationTimeGrid: this.usesDurationTimeGrid(projectionEntry.projection),
|
|
3384
|
-
enforceSaleCutoff: Boolean(rememberedStartAtByProductId),
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
4543
|
+
enforceSaleCutoff: strictAvailability || Boolean(rememberedStartAtByProductId || rememberedTimeByProductId),
|
|
4544
|
+
rememberedTimeByProductId,
|
|
4545
|
+
useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
|
|
4546
|
+
allowSessionCustomRanges: isPosAvailabilityRequest && !strictAvailability,
|
|
4547
|
+
allowRequestedRanges: isPosAvailabilityRequest && !strictAvailability && !rememberedStartAtByProductId && !rememberedTimeByProductId,
|
|
4548
|
+
allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
|
|
3388
4549
|
}).map(group => ({
|
|
3389
4550
|
...group,
|
|
3390
4551
|
ranges: group.ranges.map(candidate => this.decorateAvailabilityCandidate(context.contextId, contextVersion, candidate))
|
|
@@ -3399,16 +4560,19 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3399
4560
|
refreshed
|
|
3400
4561
|
} = await this.ensureAvailabilityContextProjection(contextId, 'query_booking_availability');
|
|
3401
4562
|
this.assertContextualQueryFreshness(context, request);
|
|
4563
|
+
const strictAvailability = context.prepareParams.strictAvailability === true;
|
|
3402
4564
|
const isPosAvailabilityRequest = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos';
|
|
4565
|
+
const rememberedTimeByProductId = request.selectionIntent === 'remembered' ? this.resolveOrderRememberedTimes(context, projectionEntry.projection, request.rememberedTimeByProductId, request.orderSessionId) : undefined;
|
|
3403
4566
|
const queryRequest = request.target === 'date' || request.target === 'product' ? {
|
|
3404
4567
|
...request,
|
|
3405
4568
|
dateRange: request.dateRange || this.getAvailabilityBusinessDateRange(projectionEntry.projection)
|
|
3406
4569
|
} : request;
|
|
3407
4570
|
const result = (0, _ResourcePlanner.queryAvailabilityProjection)(projectionEntry.projection, queryRequest, {
|
|
3408
4571
|
useDurationTimeGrid: this.usesDurationTimeGrid(projectionEntry.projection),
|
|
3409
|
-
enforceSaleCutoff: isPosAvailabilityRequest && !context.prepareParams.editingProductLineUids?.length && request.selectionIntent === 'remembered',
|
|
3410
|
-
|
|
3411
|
-
|
|
4572
|
+
enforceSaleCutoff: strictAvailability || isPosAvailabilityRequest && !context.prepareParams.editingProductLineUids?.length && request.selectionIntent === 'remembered',
|
|
4573
|
+
rememberedTimeByProductId,
|
|
4574
|
+
useExactDurationCandidateMinute: isPosAvailabilityRequest && !strictAvailability,
|
|
4575
|
+
allowExcludedScheduleDateOverride: isPosAvailabilityRequest && !strictAvailability
|
|
3412
4576
|
});
|
|
3413
4577
|
const contextVersion = context.activeVersion;
|
|
3414
4578
|
const contextualResult = result.target === 'time' ? {
|
|
@@ -3442,6 +4606,20 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3442
4606
|
refreshed
|
|
3443
4607
|
};
|
|
3444
4608
|
}
|
|
4609
|
+
|
|
4610
|
+
/** Reads detached resource metadata from the current context; never refreshes or performs I/O. */
|
|
4611
|
+
getAvailabilityResources(contextId, expectedVersion) {
|
|
4612
|
+
const context = this.getAvailabilityContextEntry(contextId);
|
|
4613
|
+
const entry = this.getActiveAvailabilityProjectionEntry(context);
|
|
4614
|
+
if (!entry || entry.contextVersion !== context.activeVersion || entry.orderRevision !== this.getCurrentOrderRevision() || expectedVersion !== undefined && context.activeVersion !== expectedVersion) {
|
|
4615
|
+
throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '资源上下文已变化,请重新查询当前候选', {
|
|
4616
|
+
contextId,
|
|
4617
|
+
expectedVersion,
|
|
4618
|
+
currentContextVersion: context.activeVersion
|
|
4619
|
+
});
|
|
4620
|
+
}
|
|
4621
|
+
return (0, _lodashEs.cloneDeep)([...entry.projection.resources]);
|
|
4622
|
+
}
|
|
3445
4623
|
releaseAvailabilityContext(contextId) {
|
|
3446
4624
|
const context = this.availabilityContextRegistry.get(contextId);
|
|
3447
4625
|
if (!context) return;
|
|
@@ -3513,24 +4691,49 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3513
4691
|
candidate: params.candidate
|
|
3514
4692
|
});
|
|
3515
4693
|
}
|
|
4694
|
+
const calendarOrderSessionId = this.availabilityContextRegistry.get(normalizedContextId)?.calendarOrderSessionId;
|
|
4695
|
+
if (calendarOrderSessionId) {
|
|
4696
|
+
const callerGuard = params.availabilityCommitGuard;
|
|
4697
|
+
params = {
|
|
4698
|
+
...params,
|
|
4699
|
+
availabilityCommitGuard: () => {
|
|
4700
|
+
callerGuard?.();
|
|
4701
|
+
if (!this.isOrderSessionCurrent(calendarOrderSessionId)) {
|
|
4702
|
+
throw new _ResourcePlanner.AvailabilityError('AVAILABILITY_SELECTION_STALE', 'Calendar booking order session changed.');
|
|
4703
|
+
}
|
|
4704
|
+
}
|
|
4705
|
+
};
|
|
4706
|
+
}
|
|
4707
|
+
const isEditingSelection = params.mode === 'edit' || params.mode === 'replace';
|
|
4708
|
+
const isPartyReplacement = params.mode === 'replace' || params.relatedRetailProducts !== undefined;
|
|
4709
|
+
if (isPartyReplacement && (!isEditingSelection || !Array.isArray(params.relatedRetailProducts))) {
|
|
4710
|
+
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', 'Party replacement requires edit/replace mode and the confirmed complete extras array');
|
|
4711
|
+
}
|
|
3516
4712
|
const isRememberedSelection = params.selectionIntent === 'remembered';
|
|
4713
|
+
const isOrderRememberedSelection = isRememberedSelection && params.orderSessionId !== undefined;
|
|
3517
4714
|
if (isRememberedSelection && (String(this.otherParams?.platform ?? '').trim().toLowerCase() !== 'pos' || params.mode !== 'add')) {
|
|
3518
4715
|
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '记忆时间自动提交仅支持 POS 新增 duration 商品');
|
|
3519
4716
|
}
|
|
3520
|
-
const
|
|
4717
|
+
const strictAvailability = this.availabilityContextRegistry.get(normalizedContextId)?.prepareParams.strictAvailability === true;
|
|
4718
|
+
const hasCommitGuard = strictAvailability || isRememberedSelection || isPartyReplacement || Boolean(params.availabilityCommitGuard);
|
|
3521
4719
|
params.availabilityCommitGuard?.();
|
|
3522
4720
|
// Stabilize the locally generated sale identity before taking the guard snapshot.
|
|
3523
4721
|
if (hasCommitGuard) this.store.order?.ensureTempOrder?.();
|
|
3524
|
-
|
|
4722
|
+
if (isOrderRememberedSelection) this.assertRememberedOrderSession(params.orderSessionId);
|
|
4723
|
+
let rememberedOrder = hasCommitGuard ? this.getTempOrder() : null;
|
|
3525
4724
|
const getRememberedCommitIdentity = () => JSON.stringify(stableValue({
|
|
3526
4725
|
scope: this.getAvailabilityScopeDescriptor(),
|
|
3527
4726
|
shopId: this.otherParams?.shop_id ?? this.otherParams?.shopId,
|
|
3528
4727
|
contextShopId: this.core?.context?.shop_id,
|
|
3529
|
-
|
|
3530
|
-
|
|
4728
|
+
...(isOrderRememberedSelection ? {
|
|
4729
|
+
orderSessionId: this.getOrderSessionId()
|
|
4730
|
+
} : {
|
|
4731
|
+
orderId: this.getTempOrder()?.order_id,
|
|
4732
|
+
externalSaleNumber: this.getTempOrder()?.external_sale_number
|
|
4733
|
+
})
|
|
3531
4734
|
}));
|
|
3532
4735
|
const rememberedCommitIdentity = hasCommitGuard ? getRememberedCommitIdentity() : '';
|
|
3533
|
-
const availabilityCommitTargetGuard = () => this.getTempOrder() === rememberedOrder && getRememberedCommitIdentity() === rememberedCommitIdentity;
|
|
4736
|
+
const availabilityCommitTargetGuard = () => (isOrderRememberedSelection ? this.isOrderSessionCurrent(params.orderSessionId) : this.getTempOrder() === rememberedOrder) && getRememberedCommitIdentity() === rememberedCommitIdentity;
|
|
3534
4737
|
let guardedCommitPublished = false;
|
|
3535
4738
|
await this.tryAcquireAvailabilityCommitLock(normalizedContextId);
|
|
3536
4739
|
try {
|
|
@@ -3540,7 +4743,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3540
4743
|
bookingCount: params.bookingCount
|
|
3541
4744
|
});
|
|
3542
4745
|
}
|
|
3543
|
-
if (
|
|
4746
|
+
if (isEditingSelection && bookingCount !== 1) {
|
|
3544
4747
|
throw new _ResourcePlanner.AvailabilityError('INVALID_RESERVATION_QUANTITY', '编辑预约商品时 bookingCount 必须为 1', {
|
|
3545
4748
|
bookingCount
|
|
3546
4749
|
});
|
|
@@ -3571,7 +4774,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3571
4774
|
});
|
|
3572
4775
|
}
|
|
3573
4776
|
const boundEditingUids = context.prepareParams.editingProductLineUids || [];
|
|
3574
|
-
if (
|
|
4777
|
+
if (isEditingSelection) {
|
|
3575
4778
|
if (!params.productLineUid || !boundEditingUids.includes(String(params.productLineUid))) {
|
|
3576
4779
|
throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', 'edit context 与当前商品行不匹配,请重新 prepare 编辑上下文', {
|
|
3577
4780
|
contextId: normalizedContextId,
|
|
@@ -3615,16 +4818,16 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3615
4818
|
candidateProductId: params.candidate.productId
|
|
3616
4819
|
});
|
|
3617
4820
|
}
|
|
3618
|
-
if (
|
|
4821
|
+
if (isEditingSelection && !params.productLineUid) {
|
|
3619
4822
|
throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', 'edit 模式必须提供 productLineUid');
|
|
3620
4823
|
}
|
|
3621
|
-
const editingLine =
|
|
3622
|
-
if (
|
|
4824
|
+
const editingLine = isEditingSelection ? this.findProductLineByUid(String(params.productLineUid)) : undefined;
|
|
4825
|
+
if (isEditingSelection && !editingLine) {
|
|
3623
4826
|
throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', '找不到要编辑的预约商品行', {
|
|
3624
4827
|
productLineUid: params.productLineUid
|
|
3625
4828
|
});
|
|
3626
4829
|
}
|
|
3627
|
-
if (editingLine && !sameAvailabilityId(editingLine.product_id ?? editingLine.id, params.candidate.productId)) {
|
|
4830
|
+
if (editingLine && params.mode !== 'replace' && !sameAvailabilityId(editingLine.product_id ?? editingLine.id, params.candidate.productId)) {
|
|
3628
4831
|
throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '编辑商品行与 candidate 商品不一致', {
|
|
3629
4832
|
productLineUid: params.productLineUid,
|
|
3630
4833
|
productLineProductId: editingLine.product_id ?? editingLine.id,
|
|
@@ -3659,7 +4862,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3659
4862
|
};
|
|
3660
4863
|
const commitSnapshot = await this.buildAvailabilityProjectionSnapshot({
|
|
3661
4864
|
...this.cloneAvailabilityPrepareParams(prepareParams),
|
|
3662
|
-
editingProductLineUids:
|
|
4865
|
+
editingProductLineUids: isEditingSelection && params.productLineUid ? [params.productLineUid] : []
|
|
3663
4866
|
}, {
|
|
3664
4867
|
resourceFetchPolicy: 'cache_only',
|
|
3665
4868
|
fallbackResources,
|
|
@@ -3686,15 +4889,31 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3686
4889
|
this.assertAvailabilityCommitWriteCAS(commitWriteGuard);
|
|
3687
4890
|
const candidateDurationMinutes = getCandidateDurationMinutes(params.candidate);
|
|
3688
4891
|
const candidateStartTime = getCandidateStartTime(params.candidate);
|
|
3689
|
-
const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !isRememberedSelection;
|
|
4892
|
+
const allowPosAvailabilityOverride = String(this.otherParams?.platform ?? '').trim().toLowerCase() === 'pos' && !isRememberedSelection && !strictAvailability;
|
|
3690
4893
|
const candidateBusinessDate = params.candidate.businessDate || (selectedProduct?.kind === 'duration' && this.usesDurationTimeGrid(refreshedProjection) ? (0, _ResourcePlanner.getDurationBusinessDate)(refreshedProjection, params.candidate.startAt) : params.candidate.startAt.slice(0, 10));
|
|
4894
|
+
const rememberedTimeByProductId = isOrderRememberedSelection ? this.resolveOrderRememberedTimes(context, refreshedProjection, {
|
|
4895
|
+
[String(params.candidate.productId)]: {
|
|
4896
|
+
startAt: params.candidate.bookingStartAt,
|
|
4897
|
+
endAt: params.candidate.bookingEndAt
|
|
4898
|
+
}
|
|
4899
|
+
}, params.orderSessionId) : undefined;
|
|
3691
4900
|
const refreshedRanges = (0, _ResourcePlanner.getProductTimeRanges)(refreshedProjection, {
|
|
3692
4901
|
productIds: [params.candidate.productId],
|
|
3693
4902
|
dateRange: {
|
|
3694
4903
|
startDate: candidateBusinessDate,
|
|
3695
4904
|
endDate: candidateBusinessDate
|
|
3696
4905
|
},
|
|
3697
|
-
...(
|
|
4906
|
+
...(allowPosAvailabilityOverride && params.candidate.source === 'duration_window' ? {
|
|
4907
|
+
requestedRangesByProductId: {
|
|
4908
|
+
[String(params.candidate.productId)]: {
|
|
4909
|
+
startAt: params.candidate.bookingStartAt,
|
|
4910
|
+
endAt: params.candidate.bookingEndAt
|
|
4911
|
+
}
|
|
4912
|
+
}
|
|
4913
|
+
} : {}),
|
|
4914
|
+
...(rememberedTimeByProductId ? {
|
|
4915
|
+
rememberedTimeByProductId
|
|
4916
|
+
} : isRememberedSelection ? {
|
|
3698
4917
|
rememberedStartAtByProductId: {
|
|
3699
4918
|
[String(params.candidate.productId)]: params.candidate.bookingStartAt
|
|
3700
4919
|
},
|
|
@@ -3707,7 +4926,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3707
4926
|
durationMinutesByProductId: {
|
|
3708
4927
|
[String(params.candidate.productId)]: candidateDurationMinutes
|
|
3709
4928
|
},
|
|
3710
|
-
...(
|
|
4929
|
+
...(isEditingSelection && selectedProduct?.kind === 'duration' ? {
|
|
3711
4930
|
editingStartAtByProductId: {
|
|
3712
4931
|
[String(params.candidate.productId)]: params.candidate.bookingStartAt
|
|
3713
4932
|
}
|
|
@@ -3724,9 +4943,11 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3724
4943
|
}, {
|
|
3725
4944
|
evaluatedAt: this.getAvailabilityRuntimeDateTime(),
|
|
3726
4945
|
useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
|
|
3727
|
-
enforceSaleCutoff: isRememberedSelection,
|
|
4946
|
+
enforceSaleCutoff: strictAvailability || isRememberedSelection,
|
|
4947
|
+
rememberedTimeByProductId,
|
|
3728
4948
|
useExactDurationCandidateMinute: allowPosAvailabilityOverride,
|
|
3729
4949
|
allowSessionCustomRanges: allowPosAvailabilityOverride,
|
|
4950
|
+
allowRequestedRanges: allowPosAvailabilityOverride,
|
|
3730
4951
|
allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
|
|
3731
4952
|
}).flatMap(group => group.ranges);
|
|
3732
4953
|
const refreshedCandidateBase = refreshedRanges.find(candidate => candidate.startAt === params.candidate.startAt && candidate.endAt === params.candidate.endAt && candidate.bookingStartAt === params.candidate.bookingStartAt && candidate.bookingEndAt === params.candidate.bookingEndAt);
|
|
@@ -3750,7 +4971,8 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3750
4971
|
bookingCount
|
|
3751
4972
|
}, {
|
|
3752
4973
|
useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
|
|
3753
|
-
enforceSaleCutoff: isRememberedSelection,
|
|
4974
|
+
enforceSaleCutoff: strictAvailability || isRememberedSelection,
|
|
4975
|
+
rememberedTimeByProductId,
|
|
3754
4976
|
useExactDurationCandidateMinute: allowPosAvailabilityOverride,
|
|
3755
4977
|
allowExcludedScheduleDateOverride: allowPosAvailabilityOverride
|
|
3756
4978
|
});
|
|
@@ -3819,25 +5041,29 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3819
5041
|
if (!availabilityCommitTargetGuard()) {
|
|
3820
5042
|
throw this.createAvailabilityFacadeError('AVAILABILITY_SELECTION_STALE', '记忆时间加购期间订单或业务已变化');
|
|
3821
5043
|
}
|
|
3822
|
-
|
|
5044
|
+
// Same-order immutable snapshots and generated sale IDs preserve the session.
|
|
5045
|
+
// Capture the actual object Order is about to publish, not an earlier snapshot.
|
|
5046
|
+
if (isOrderRememberedSelection) rememberedOrder = this.getTempOrder();
|
|
5047
|
+
if (!isRememberedSelection && !strictAvailability) return;
|
|
3823
5048
|
const currentValidation = (0, _ResourcePlanner.validateAvailabilitySelection)(refreshedProjection, {
|
|
3824
5049
|
candidate: refreshedCandidateBase,
|
|
3825
5050
|
requirementSelections: params.requirementSelections,
|
|
3826
5051
|
partySize,
|
|
3827
5052
|
bookingCount
|
|
3828
5053
|
}, {
|
|
3829
|
-
useDurationTimeGrid:
|
|
3830
|
-
enforceSaleCutoff: true
|
|
5054
|
+
useDurationTimeGrid: this.usesDurationTimeGrid(refreshedProjection),
|
|
5055
|
+
enforceSaleCutoff: true,
|
|
5056
|
+
rememberedTimeByProductId
|
|
3831
5057
|
});
|
|
3832
5058
|
if (!currentValidation.ok) {
|
|
3833
|
-
throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '
|
|
5059
|
+
throw new _ResourcePlanner.AvailabilityError('REVALIDATION_FAILED', '所选时间在加购前已不可用,请重新选择', {
|
|
3834
5060
|
validation: currentValidation
|
|
3835
5061
|
});
|
|
3836
5062
|
}
|
|
3837
5063
|
} : undefined;
|
|
3838
5064
|
const existingBooking = editingLine ? this.findLinkedBooking(editingLine) : undefined;
|
|
3839
5065
|
const existingBookingUid = existingBooking ? getBookingUid(existingBooking) : '';
|
|
3840
|
-
if (
|
|
5066
|
+
if (isEditingSelection && !existingBookingUid) {
|
|
3841
5067
|
throw new _ResourcePlanner.AvailabilityError('PRODUCT_LINE_NOT_FOUND', '编辑商品行缺少关联 booking', {
|
|
3842
5068
|
productLineUid: params.productLineUid
|
|
3843
5069
|
});
|
|
@@ -3849,9 +5075,14 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3849
5075
|
product,
|
|
3850
5076
|
resources: refreshedProjection.resources,
|
|
3851
5077
|
bookingUid: existingBookingUid || undefined,
|
|
3852
|
-
holder: params.orderProduct?._extend?.holder ?? existingBooking?.holder ?? existingBooking?.metadata?.holder,
|
|
3853
|
-
holderIds: params.orderProduct?._extend?.holder_id ?? params.orderProduct?._extend?.holder?.form_record ?? existingBooking?.metadata?.holder_id ?? existingBooking?.holder?.form_record
|
|
5078
|
+
holder: params.orderProduct?._extend?.holder ?? (params.mode === 'replace' ? undefined : existingBooking?.holder ?? existingBooking?.metadata?.holder),
|
|
5079
|
+
holderIds: params.orderProduct?._extend?.holder_id ?? params.orderProduct?._extend?.holder?.form_record ?? (params.mode === 'replace' ? undefined : existingBooking?.metadata?.holder_id ?? existingBooking?.holder?.form_record)
|
|
3854
5080
|
});
|
|
5081
|
+
if (params.mode === 'replace') {
|
|
5082
|
+
// A different product must not inherit the previous product/resource's completed forms.
|
|
5083
|
+
booking.holder = booking.holder || null;
|
|
5084
|
+
booking.relation_forms = [];
|
|
5085
|
+
}
|
|
3855
5086
|
if (isRememberedSelection && params.orderProduct?._extend?.resource) {
|
|
3856
5087
|
// AutoClose 与编辑共用旧资源协议。仅复用其结构,实际资源及每份容量
|
|
3857
5088
|
// 必须与本次严格校验结果一致;时间、Holder 和校验元数据仍使用上面的结果。
|
|
@@ -3885,13 +5116,43 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3885
5116
|
unified_booking_sales: true,
|
|
3886
5117
|
availability_candidate_key: refreshedCandidate.key,
|
|
3887
5118
|
availability_context_id: normalizedContextId,
|
|
3888
|
-
availability_context_version: refreshedCandidate.availabilityContextVersion
|
|
5119
|
+
availability_context_version: refreshedCandidate.availabilityContextVersion,
|
|
5120
|
+
...(['tickets', 'party_main'].includes(transformed.metadata?.venue_booking_role) ? {
|
|
5121
|
+
venue_booking_service_datetime: `${booking.start_date} ${booking.start_time}`
|
|
5122
|
+
} : {})
|
|
3889
5123
|
};
|
|
3890
5124
|
let productLineUid = '';
|
|
3891
5125
|
let bookingUid = '';
|
|
3892
5126
|
let productLineUids = [];
|
|
3893
5127
|
let bookingUids = [];
|
|
3894
|
-
if (
|
|
5128
|
+
if (isPartyReplacement && editingLine && params.productLineUid) {
|
|
5129
|
+
const relatedRetailProducts = params.relatedRetailProducts.map(source => {
|
|
5130
|
+
const line = this.buildUnifiedOrderProduct(source, 'unified_booking_sales_retail');
|
|
5131
|
+
if (!line) throw new _ResourcePlanner.AvailabilityError('INVALID_TARGET_FILTER', '无法生成附加商品订单行');
|
|
5132
|
+
// This is the only replacement-specific UID restore. Order checks ownership/collisions.
|
|
5133
|
+
const sourceUid = getProductLineUid(source);
|
|
5134
|
+
if (sourceUid) {
|
|
5135
|
+
line.metadata = {
|
|
5136
|
+
...(line.metadata || {}),
|
|
5137
|
+
unique_identification_number: sourceUid
|
|
5138
|
+
};
|
|
5139
|
+
}
|
|
5140
|
+
return line;
|
|
5141
|
+
});
|
|
5142
|
+
await this.store.order.replaceBookingProductWithRelatedRetail({
|
|
5143
|
+
productLineUid: params.productLineUid,
|
|
5144
|
+
product: transformed,
|
|
5145
|
+
booking,
|
|
5146
|
+
relatedRetailProducts: relatedRetailProducts,
|
|
5147
|
+
availabilityCommitGuard: availabilityCommitGuard,
|
|
5148
|
+
availabilityCommitTargetGuard
|
|
5149
|
+
});
|
|
5150
|
+
guardedCommitPublished = true;
|
|
5151
|
+
productLineUid = params.productLineUid;
|
|
5152
|
+
bookingUid = existingBookingUid;
|
|
5153
|
+
productLineUids = [productLineUid];
|
|
5154
|
+
bookingUids = [bookingUid];
|
|
5155
|
+
} else if (params.mode === 'edit' && editingLine && params.productLineUid) {
|
|
3895
5156
|
transformed.product_sku = transformed.product_sku ?? editingLine.product_sku;
|
|
3896
5157
|
transformed.product_bundle = transformed.product_bundle ?? editingLine.product_bundle;
|
|
3897
5158
|
transformed.booking_uid = existingBookingUid;
|
|
@@ -3932,8 +5193,12 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
3932
5193
|
availabilityCommitTargetGuard
|
|
3933
5194
|
} : {})
|
|
3934
5195
|
} : undefined);
|
|
3935
|
-
products = await this.removeBookingProductsOutsideStartDate(booking.start_date);
|
|
3936
5196
|
guardedCommitPublished = hasCommitGuard;
|
|
5197
|
+
// A completed add can publish before a different order becomes current.
|
|
5198
|
+
// Keep its returned lines and never clean up products on that next order.
|
|
5199
|
+
if (!hasCommitGuard || availabilityCommitTargetGuard()) {
|
|
5200
|
+
products = await this.removeBookingProductsOutsideStartDate(booking.start_date);
|
|
5201
|
+
}
|
|
3937
5202
|
const addedLines = products.filter(line => sameAvailabilityId(line.product_id ?? line.id, refreshedCandidate.productId) && line.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeProductLineUids.has(getProductLineUid(line)));
|
|
3938
5203
|
productLineUids = addedLines.map(line => getProductLineUid(line)).filter(Boolean);
|
|
3939
5204
|
const addedBookings = ((hasCommitGuard ? rememberedOrder : this.getTempOrder())?.bookings || []).filter(item => item.metadata?.availability_candidate_key === refreshedCandidate.key && !beforeBookingUids.has(getBookingUid(item)));
|