@pisell/pisellos 2.3.179 → 2.3.181
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/modules/Product/index.d.ts +1 -1
- package/dist/solution/BookingByStep/index.d.ts +2 -2
- package/dist/solution/BookingTicket/index.d.ts +1 -1
- package/dist/solution/ScanOrder/index.d.ts +2 -0
- package/dist/solution/ScanOrder/index.js +157 -63
- package/dist/solution/ScanOrder/menuAvailability.d.ts +24 -0
- package/dist/solution/ScanOrder/menuAvailability.js +363 -0
- package/dist/solution/UnifiedBookingSales/index.d.ts +4 -0
- package/dist/solution/UnifiedBookingSales/index.js +719 -554
- package/lib/modules/Product/index.d.ts +1 -1
- package/lib/solution/BookingByStep/index.d.ts +2 -2
- package/lib/solution/BookingTicket/index.d.ts +1 -1
- package/lib/solution/ScanOrder/index.d.ts +2 -0
- package/lib/solution/ScanOrder/index.js +67 -2
- package/lib/solution/ScanOrder/menuAvailability.d.ts +24 -0
- package/lib/solution/ScanOrder/menuAvailability.js +203 -0
- package/lib/solution/UnifiedBookingSales/index.d.ts +4 -0
- package/lib/solution/UnifiedBookingSales/index.js +76 -0
- package/package.json +1 -1
|
@@ -49,5 +49,5 @@ export declare class Product extends BaseModule implements Module {
|
|
|
49
49
|
getCategories(): ProductCategory[];
|
|
50
50
|
setOtherParams(key: string, value: any): void;
|
|
51
51
|
getOtherParams(): any;
|
|
52
|
-
getProductType(): "
|
|
52
|
+
getProductType(): "duration" | "normal" | "session";
|
|
53
53
|
}
|
|
@@ -328,7 +328,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
|
|
|
328
328
|
date: string;
|
|
329
329
|
status: string;
|
|
330
330
|
week: string;
|
|
331
|
-
weekNum: 0 |
|
|
331
|
+
weekNum: 0 | 2 | 1 | 3 | 4 | 5 | 6;
|
|
332
332
|
}[]>;
|
|
333
333
|
submitTimeSlot(timeSlots: TimeSliceItem): void;
|
|
334
334
|
private getScheduleDataByIds;
|
|
@@ -375,7 +375,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
|
|
|
375
375
|
};
|
|
376
376
|
setOtherData(key: string, value: any): void;
|
|
377
377
|
getOtherData(key: string): any;
|
|
378
|
-
getProductTypeById(id: number): Promise<"
|
|
378
|
+
getProductTypeById(id: number): Promise<"duration" | "normal" | "session">;
|
|
379
379
|
/**
|
|
380
380
|
* 提供给 UI 的方法,减轻 UI 层的计算压力,UI 层只需要传递 cartItemId 和 resourceCode 即返回对应的 renderList
|
|
381
381
|
*
|
|
@@ -366,7 +366,7 @@ export declare class BookingTicketImpl extends BaseSalesImpl implements Module {
|
|
|
366
366
|
* 获取当前的客户搜索条件
|
|
367
367
|
* @returns 当前搜索条件
|
|
368
368
|
*/
|
|
369
|
-
getCurrentCustomerSearchParams(): Omit<import("../../modules").ShopGetCustomerListParams, "
|
|
369
|
+
getCurrentCustomerSearchParams(): Omit<import("../../modules").ShopGetCustomerListParams, "num" | "skip">;
|
|
370
370
|
/**
|
|
371
371
|
* 获取客户列表状态(包含滚动加载相关状态)
|
|
372
372
|
* @returns 客户状态
|
|
@@ -101,6 +101,8 @@ export declare class ScanOrderImpl extends BaseSalesImpl implements Module {
|
|
|
101
101
|
private buildSubmitPayloadEnhancer;
|
|
102
102
|
private isScanOrderMoreMode;
|
|
103
103
|
private submitScanOrderMore;
|
|
104
|
+
/** Read both current and legacy cart snapshots without changing the product catalog. */
|
|
105
|
+
private getMenuAvailabilityProductSources;
|
|
104
106
|
submitScanOrder<T = any>(): Promise<T>;
|
|
105
107
|
addProductToOrder(product: Partial<ScanOrderOrderProduct> & ScanOrderOrderProductIdentity): Promise<import("../../modules/Order/types").OrderProduct[]>;
|
|
106
108
|
updateOrderProduct(params: UpdateOrderProductParams): Promise<import("../../modules/Order/types").OrderProduct[]>;
|
|
@@ -31,6 +31,7 @@ var _getDateIsInSchedule = require("../../modules/Schedule/getDateIsInSchedule")
|
|
|
31
31
|
var _utils2 = require("../../modules/Order/utils");
|
|
32
32
|
var _dayjs = _interopRequireDefault(require("dayjs"));
|
|
33
33
|
var _itemRule = require("../../model/strategy/adapter/itemRule");
|
|
34
|
+
var _menuAvailability = require("./menuAvailability");
|
|
34
35
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
35
36
|
function isItemRewardProductDiscount(discount) {
|
|
36
37
|
return discount?.type === 'product' && discount?.metadata?.source === 'promotion' && discount?.metadata?.actionType === 'ITEM_REWARD';
|
|
@@ -994,6 +995,27 @@ class ScanOrderImpl extends _BaseSales.BaseSalesImpl {
|
|
|
994
995
|
}
|
|
995
996
|
return result;
|
|
996
997
|
}
|
|
998
|
+
|
|
999
|
+
/** Read both current and legacy cart snapshots without changing the product catalog. */
|
|
1000
|
+
getMenuAvailabilityProductSources(tempOrder) {
|
|
1001
|
+
const products = tempOrder.products || [];
|
|
1002
|
+
const sources = [...this.enabledReservationRuleProducts];
|
|
1003
|
+
for (const product of products) {
|
|
1004
|
+
const uid = product.metadata?.unique_identification_number;
|
|
1005
|
+
const origins = [product._origin, product.metadata?.origin, uid ? tempOrder._extend?.productsByUid?.[String(uid)]?.origin : undefined];
|
|
1006
|
+
for (const origin of origins) {
|
|
1007
|
+
if (origin && typeof origin === 'object' && !Array.isArray(origin)) {
|
|
1008
|
+
sources.push({
|
|
1009
|
+
...origin,
|
|
1010
|
+
product_id: product.product_id
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
const cachedSources = this.store.products?.getRawProductPriceSources?.(products.map(product => Number(product.product_id)));
|
|
1016
|
+
if (cachedSources) sources.push(...cachedSources.values());
|
|
1017
|
+
return sources;
|
|
1018
|
+
}
|
|
997
1019
|
async submitScanOrder() {
|
|
998
1020
|
this.logMethodStart('submitScanOrder');
|
|
999
1021
|
try {
|
|
@@ -1016,8 +1038,51 @@ class ScanOrderImpl extends _BaseSales.BaseSalesImpl {
|
|
|
1016
1038
|
delete tempOrderForSubmit.table_number;
|
|
1017
1039
|
}
|
|
1018
1040
|
this.store.order.persistTempOrder();
|
|
1019
|
-
const
|
|
1020
|
-
const
|
|
1041
|
+
const isAdditionalOrder = this.isScanOrderMoreMode(tempOrderForSubmit);
|
|
1042
|
+
const enhanceBookingPayload = this.buildSubmitPayloadEnhancer();
|
|
1043
|
+
const ruleProduct = this.enabledReservationRuleProducts[0];
|
|
1044
|
+
const resource = this.store.resource;
|
|
1045
|
+
const willAppendRuleProduct = !tempOrderForSubmit.order_id && ruleProduct && String(resource?.relationId ?? '').trim() && resource?.tableFormId;
|
|
1046
|
+
const productsToPrepare = isAdditionalOrder ? tempOrderForSubmit.products.filter(product => product.metadata?.is_rule !== true) : [...tempOrderForSubmit.products, ...(willAppendRuleProduct ? [{
|
|
1047
|
+
product_id: ruleProduct.id,
|
|
1048
|
+
metadata: {
|
|
1049
|
+
is_rule: true
|
|
1050
|
+
}
|
|
1051
|
+
}] : [])];
|
|
1052
|
+
const associatedMenus = this.otherParams?.dineInConfig?.['menu.associated_menus'];
|
|
1053
|
+
if (!Array.isArray(associatedMenus)) {
|
|
1054
|
+
throw new _menuAvailability.ScanOrderMenuAvailabilityError('SCAN_ORDER_MENU_VALIDATION_FAILED');
|
|
1055
|
+
}
|
|
1056
|
+
const validateMenuAvailability = await (0, _menuAvailability.prepareScanOrderMenuAvailability)({
|
|
1057
|
+
request: this.request,
|
|
1058
|
+
menuIds: associatedMenus.map(menu => menu?.value),
|
|
1059
|
+
timezone: String(this.getPickupTimingContextData('timezone') ?? ''),
|
|
1060
|
+
products: productsToPrepare,
|
|
1061
|
+
productSources: this.getMenuAvailabilityProductSources(tempOrderForSubmit)
|
|
1062
|
+
});
|
|
1063
|
+
const enhancePayload = (payload, context) => {
|
|
1064
|
+
const enhancedPayload = enhanceBookingPayload(payload, context);
|
|
1065
|
+
const originalByUid = new Map(context.tempOrder.products.filter(product => product.metadata?.unique_identification_number).map(product => [String(product.metadata.unique_identification_number), product]));
|
|
1066
|
+
const outgoingProducts = isAdditionalOrder ? (0, _utils.filterProductsForScanOrderMore)(enhancedPayload.products) : enhancedPayload.products;
|
|
1067
|
+
// Serialization strips the prefill marker. Restore it only on validation
|
|
1068
|
+
// copies, by line UID, so a manually added row of the same product stays checked.
|
|
1069
|
+
const validationProducts = outgoingProducts.map(product => {
|
|
1070
|
+
const uid = product.metadata?.unique_identification_number;
|
|
1071
|
+
const original = uid ? originalByUid.get(String(uid)) : undefined;
|
|
1072
|
+
return original?.metadata?.item_rule_prefill === true ? {
|
|
1073
|
+
...product,
|
|
1074
|
+
metadata: {
|
|
1075
|
+
...product.metadata,
|
|
1076
|
+
item_rule_prefill: true
|
|
1077
|
+
}
|
|
1078
|
+
} : product;
|
|
1079
|
+
});
|
|
1080
|
+
// Both checkout and add-on build their payload after async quotation. Check
|
|
1081
|
+
// the actual outgoing lines using a fresh clock, never the draft schedule_date.
|
|
1082
|
+
validateMenuAvailability(validationProducts, this.getMenuAvailabilityProductSources(context.tempOrder));
|
|
1083
|
+
return enhancedPayload;
|
|
1084
|
+
};
|
|
1085
|
+
const result = isAdditionalOrder ? await this.submitScanOrderMore({
|
|
1021
1086
|
tempOrder: tempOrderForSubmit,
|
|
1022
1087
|
enhancePayload
|
|
1023
1088
|
}) : await this.submitSalesOrder({
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
type Product = Record<string, any>;
|
|
2
|
+
type Request = {
|
|
3
|
+
get: (url: string, data?: any, options?: any) => Promise<any>;
|
|
4
|
+
post: (url: string, data?: any, options?: any) => Promise<any>;
|
|
5
|
+
};
|
|
6
|
+
export type ScanOrderMenuAvailabilityErrorCode = 'SCAN_ORDER_MENU_UNAVAILABLE' | 'SCAN_ORDER_MENU_VALIDATION_FAILED';
|
|
7
|
+
export declare class ScanOrderMenuAvailabilityError extends Error {
|
|
8
|
+
readonly code: ScanOrderMenuAvailabilityErrorCode;
|
|
9
|
+
readonly productIds: number[];
|
|
10
|
+
constructor(code: ScanOrderMenuAvailabilityErrorCode, productIds?: number[]);
|
|
11
|
+
}
|
|
12
|
+
export type ScanOrderMenuAvailabilityValidator = (products: Product[], productSources?: Product[]) => void;
|
|
13
|
+
/**
|
|
14
|
+
* Prepare fresh menu definitions without changing ProductList or the cart. The
|
|
15
|
+
* returned validator reads the shop's current time again at the submission boundary.
|
|
16
|
+
*/
|
|
17
|
+
export declare function prepareScanOrderMenuAvailability({ request, menuIds, timezone, products, productSources, }: {
|
|
18
|
+
request: Request;
|
|
19
|
+
menuIds: Array<number | string>;
|
|
20
|
+
timezone: string;
|
|
21
|
+
products: Product[];
|
|
22
|
+
productSources?: Product[];
|
|
23
|
+
}): Promise<ScanOrderMenuAvailabilityValidator>;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.ScanOrderMenuAvailabilityError = void 0;
|
|
7
|
+
exports.prepareScanOrderMenuAvailability = prepareScanOrderMenuAvailability;
|
|
8
|
+
var _utils = require("../ShopDiscount/utils");
|
|
9
|
+
var _dayjs = _interopRequireDefault(require("dayjs"));
|
|
10
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
11
|
+
class ScanOrderMenuAvailabilityError extends Error {
|
|
12
|
+
code;
|
|
13
|
+
productIds;
|
|
14
|
+
constructor(code, productIds = []) {
|
|
15
|
+
super(code);
|
|
16
|
+
this.name = 'ScanOrderMenuAvailabilityError';
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.productIds = [...new Set(productIds)];
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.ScanOrderMenuAvailabilityError = ScanOrderMenuAvailabilityError;
|
|
22
|
+
const positiveId = value => {
|
|
23
|
+
const id = Number(value);
|
|
24
|
+
return Number.isInteger(id) && id > 0 ? id : undefined;
|
|
25
|
+
};
|
|
26
|
+
const productId = product => positiveId(product?.product_id ?? product?.id);
|
|
27
|
+
const fail = (ids = []) => {
|
|
28
|
+
throw new ScanOrderMenuAvailabilityError('SCAN_ORDER_MENU_VALIDATION_FAILED', ids);
|
|
29
|
+
};
|
|
30
|
+
function readList(response) {
|
|
31
|
+
if (!response || response.code !== undefined && Number(response.code) !== 200 || response.status === false || typeof response.status === 'number' && response.status >= 400 || response.success === false || !Array.isArray(response.data?.list)) fail();
|
|
32
|
+
return response.data.list;
|
|
33
|
+
}
|
|
34
|
+
function readIds(values) {
|
|
35
|
+
if (!Array.isArray(values)) return fail();
|
|
36
|
+
const ids = values.map(positiveId);
|
|
37
|
+
if (ids.some(id => id === undefined)) return fail();
|
|
38
|
+
return [...new Set(ids)];
|
|
39
|
+
}
|
|
40
|
+
function readMenu(record) {
|
|
41
|
+
const scope = record.partyroom_package?.type;
|
|
42
|
+
if (!['product_all', 'products', 'product_collection'].includes(scope)) return fail();
|
|
43
|
+
const items = record.partyroom_package?.products;
|
|
44
|
+
if (scope !== 'product_all' && !Array.isArray(items)) return fail();
|
|
45
|
+
return {
|
|
46
|
+
id: positiveId(record.form_record_id),
|
|
47
|
+
scheduleIds: readIds(record.schedule),
|
|
48
|
+
scope,
|
|
49
|
+
productIds: scope === 'products' ? readIds(items.map(item => item.product_id)) : [],
|
|
50
|
+
collectionIds: scope === 'product_collection' ? readIds(items.map(item => item.product_collection_id)) : []
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function validateSchedule(schedule) {
|
|
54
|
+
const validDate = value => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) && (0, _dayjs.default)(value).isValid() && (0, _dayjs.default)(value).format('YYYY-MM-DD') === value;
|
|
55
|
+
const validDateTime = value => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}(?:[ T](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?)?$/.test(value) && validDate(value.slice(0, 10)) && (0, _dayjs.default)(value).isValid();
|
|
56
|
+
const validTime = value => typeof value === 'string' && /^(?:(?:[01]\d|2[0-3]):[0-5]\d|24:00)$/.test(value);
|
|
57
|
+
if (!schedule || !['standard', 'time-slots', 'designation'].includes(schedule.type)) return fail();
|
|
58
|
+
if (schedule.type === 'designation') {
|
|
59
|
+
if (!Array.isArray(schedule.designation) || schedule.designation.some(item => !validDate(item?.start_date) || !validDate(item?.end_date) || !validTime(item?.start_time) || !validTime(item?.end_time))) return fail();
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (!validDateTime(schedule.start_time)) return fail();
|
|
63
|
+
if (schedule.type === 'standard' && !validDateTime(schedule.end_time)) return fail();
|
|
64
|
+
if (schedule.type === 'time-slots' && (!Array.isArray(schedule.time_slot) || schedule.time_slot.some(slot => !validTime(slot?.start_time) || !validTime(slot?.end_time)))) return fail();
|
|
65
|
+
if (schedule.repeat_type === 'none') return;
|
|
66
|
+
if (!['daily', 'weekly'].includes(schedule.repeat_type)) return fail();
|
|
67
|
+
const rule = schedule.repeat_rule;
|
|
68
|
+
if (!rule || !positiveId(rule.frequency) || !['never', 'date', 'occurrence'].includes(rule.end?.type) || rule.end.type === 'date' && !validDateTime(rule.end.end_date)) return fail();
|
|
69
|
+
for (const ranges of [rule.excluded_date, rule.included_date ?? []]) {
|
|
70
|
+
if (!Array.isArray(ranges) || ranges.some(range => !validDateTime(range?.start) || !validDateTime(range?.end))) return fail();
|
|
71
|
+
}
|
|
72
|
+
if (schedule.repeat_type === 'weekly' && (!Array.isArray(rule.frequency_date) || rule.frequency_date.some(day => typeof day !== 'number' || !Number.isInteger(day) || day < 0 || day > 6))) return fail();
|
|
73
|
+
}
|
|
74
|
+
function createShopClock(timezone) {
|
|
75
|
+
if (typeof timezone !== 'string' || !timezone.trim()) return fail();
|
|
76
|
+
const formatter = new Intl.DateTimeFormat('en-GB', {
|
|
77
|
+
timeZone: timezone.trim(),
|
|
78
|
+
year: 'numeric',
|
|
79
|
+
month: '2-digit',
|
|
80
|
+
day: '2-digit',
|
|
81
|
+
hour: '2-digit',
|
|
82
|
+
minute: '2-digit',
|
|
83
|
+
second: '2-digit',
|
|
84
|
+
hourCycle: 'h23'
|
|
85
|
+
});
|
|
86
|
+
return () => {
|
|
87
|
+
const parts = formatter.formatToParts(new Date());
|
|
88
|
+
const value = type => parts.find(part => part.type === type)?.value;
|
|
89
|
+
return `${value('year')}-${value('month')}-${value('day')} ${value('hour')}:${value('minute')}:${value('second')}`;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function collectSources(target, sources) {
|
|
93
|
+
for (const source of sources) {
|
|
94
|
+
const id = productId(source);
|
|
95
|
+
if (!id || !Array.isArray(source?.collection)) continue;
|
|
96
|
+
const ids = source.collection.map(item => positiveId(item?.id));
|
|
97
|
+
if (ids.every(value => value !== undefined)) {
|
|
98
|
+
target.set(id, [...new Set(ids)]);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Prepare fresh menu definitions without changing ProductList or the cart. The
|
|
105
|
+
* returned validator reads the shop's current time again at the submission boundary.
|
|
106
|
+
*/
|
|
107
|
+
async function prepareScanOrderMenuAvailability({
|
|
108
|
+
request,
|
|
109
|
+
menuIds,
|
|
110
|
+
timezone,
|
|
111
|
+
products,
|
|
112
|
+
productSources = []
|
|
113
|
+
}) {
|
|
114
|
+
const initialIds = products.map(productId).filter(id => id !== undefined);
|
|
115
|
+
try {
|
|
116
|
+
const now = createShopClock(timezone);
|
|
117
|
+
const configuredIds = readIds(menuIds);
|
|
118
|
+
const [menuResponse, scheduleResponse] = await Promise.all([request.get('/form/data/v1', {
|
|
119
|
+
skip: 1,
|
|
120
|
+
num: 999,
|
|
121
|
+
code: 'menu_list'
|
|
122
|
+
}, {
|
|
123
|
+
useCache: false
|
|
124
|
+
}), request.get('/schedule', {
|
|
125
|
+
num: 999
|
|
126
|
+
}, {
|
|
127
|
+
useCache: false
|
|
128
|
+
})]);
|
|
129
|
+
const menuRecords = readList(menuResponse);
|
|
130
|
+
const scheduleRecords = readList(scheduleResponse);
|
|
131
|
+
const menuById = new Map(menuRecords.map(menu => [positiveId(menu.form_record_id), menu]));
|
|
132
|
+
const menus = configuredIds.map(id => {
|
|
133
|
+
const record = menuById.get(id);
|
|
134
|
+
return record ? readMenu(record) : fail();
|
|
135
|
+
});
|
|
136
|
+
const scheduleById = new Map(scheduleRecords.map(schedule => [positiveId(schedule.id), schedule]));
|
|
137
|
+
// Only configured menus and their schedules are required. Other pages in a
|
|
138
|
+
// larger catalog cannot affect this business's menu availability.
|
|
139
|
+
const referencedScheduleIds = menus.reduce((ids, menu) => ids.concat(menu.scheduleIds), []);
|
|
140
|
+
for (const id of new Set(referencedScheduleIds)) {
|
|
141
|
+
validateSchedule(scheduleById.get(id));
|
|
142
|
+
}
|
|
143
|
+
const hasCollectionMenu = menus.some(menu => menu.scope === 'product_collection');
|
|
144
|
+
const collectionsByProduct = new Map();
|
|
145
|
+
collectSources(collectionsByProduct, [...products, ...productSources]);
|
|
146
|
+
if (hasCollectionMenu) {
|
|
147
|
+
const missingIds = [...new Set(initialIds.filter(id => !collectionsByProduct.has(id)))];
|
|
148
|
+
if (missingIds.length) {
|
|
149
|
+
const response = await request.post('/product/query', {
|
|
150
|
+
ids: missingIds,
|
|
151
|
+
with: ['collection'],
|
|
152
|
+
open_quotation: 0,
|
|
153
|
+
open_bundle: 0,
|
|
154
|
+
skip: 1,
|
|
155
|
+
num: missingIds.length
|
|
156
|
+
}, {
|
|
157
|
+
useCache: false
|
|
158
|
+
});
|
|
159
|
+
collectSources(collectionsByProduct, readList(response));
|
|
160
|
+
const unresolved = missingIds.filter(id => !collectionsByProduct.has(id));
|
|
161
|
+
if (unresolved.length) fail(unresolved);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return (currentProducts, currentSources = []) => {
|
|
165
|
+
try {
|
|
166
|
+
const currentTime = now();
|
|
167
|
+
const collections = new Map(collectionsByProduct);
|
|
168
|
+
collectSources(collections, [...currentProducts, ...currentSources]);
|
|
169
|
+
const unavailable = [];
|
|
170
|
+
const insufficient = [];
|
|
171
|
+
for (const product of currentProducts) {
|
|
172
|
+
const id = productId(product);
|
|
173
|
+
if (!id) return fail();
|
|
174
|
+
const matchesDirectly = menu => menu.scope === 'product_all' || menu.scope === 'products' && menu.productIds.includes(id);
|
|
175
|
+
const isAvailable = menu => (0, _utils.getDateIsInSchedule)(currentTime, menu.scheduleIds.map(scheduleId => scheduleById.get(scheduleId)));
|
|
176
|
+
// A known valid direct relation is sufficient regardless of missing
|
|
177
|
+
// collection data on a rule product appended after preparation.
|
|
178
|
+
if (menus.some(menu => matchesDirectly(menu) && isAvailable(menu))) continue;
|
|
179
|
+
if (hasCollectionMenu && !collections.has(id)) {
|
|
180
|
+
insufficient.push(id);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const productCollections = collections.get(id) || [];
|
|
184
|
+
const associated = menus.filter(menu => matchesDirectly(menu) || menu.scope === 'product_collection' && menu.collectionIds.some(collectionId => productCollections.includes(collectionId)));
|
|
185
|
+
if (associated.some(isAvailable)) continue;
|
|
186
|
+
const systemItem = product.metadata?.item_rule_prefill === true || product.metadata?.is_rule === true;
|
|
187
|
+
if (associated.length === 0 && systemItem) continue;
|
|
188
|
+
unavailable.push(id);
|
|
189
|
+
}
|
|
190
|
+
if (insufficient.length) fail(insufficient);
|
|
191
|
+
if (unavailable.length) {
|
|
192
|
+
throw new ScanOrderMenuAvailabilityError('SCAN_ORDER_MENU_UNAVAILABLE', unavailable);
|
|
193
|
+
}
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error instanceof ScanOrderMenuAvailabilityError) throw error;
|
|
196
|
+
return fail(currentProducts.map(productId).filter(id => id !== undefined));
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
} catch (error) {
|
|
200
|
+
if (error instanceof ScanOrderMenuAvailabilityError) throw error;
|
|
201
|
+
return fail(initialIds);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
@@ -9,6 +9,7 @@ import type { AvailabilityDateRange, AvailabilityOccupancy, AvailabilityProduct,
|
|
|
9
9
|
import type { AvailabilityContextRef, ContextualAvailabilityQuery, ContextualAvailabilityQueryResult, ContextualCommitAvailabilitySelectionParams, ContextualProductTimeRangeGroup, UnifiedBookingSalesAddRetailProductParams, UnifiedBookingSalesApplyPlannerDiscountsParams, UnifiedBookingSalesCommitAvailabilitySelectionResult, UnifiedBookingSalesDiscountResult, UnifiedBookingSalesLoadProductsByScheduleDateParams, UnifiedBookingSalesLoadOpenDataParams, UnifiedBookingSalesPrepareAvailabilityProjectionParams, UnifiedBookingSalesPolicyResponse, UnifiedBookingSalesResolveProductAllergyRequirementParams, UnifiedBookingSalesStageRetailProductsParams, UnifiedBookingSalesState } from './types';
|
|
10
10
|
import type { BusinessAvailability } from '../../modules/BusinessAvailability';
|
|
11
11
|
import { BookingTicket } from '../BookingTicket';
|
|
12
|
+
import type { BaseSalesSubmitSalesOrderParams } from '../BaseSales/types';
|
|
12
13
|
import type { AllergyRequirement } from '../../model/strategy/adapter/itemRule';
|
|
13
14
|
export * from './types';
|
|
14
15
|
export * from './salesSettings';
|
|
@@ -202,6 +203,9 @@ export declare class UnifiedBookingSalesImpl extends BookingTicket {
|
|
|
202
203
|
protected loadPickupTimingOpenData(_force: boolean): Promise<Record<string, unknown>>;
|
|
203
204
|
private resetAllergyItemRuleState;
|
|
204
205
|
private fetchAllergyItemRuleConfigs;
|
|
206
|
+
/** Required products currently apply only to the online venue-ticket entry. */
|
|
207
|
+
validateRequiredProducts(): Promise<void>;
|
|
208
|
+
submitSalesOrder<T = any>(params?: BaseSalesSubmitSalesOrderParams): Promise<T>;
|
|
205
209
|
private ensureAllergyItemRuleConfigsLoaded;
|
|
206
210
|
/**
|
|
207
211
|
* 评估当前渠道与商品是否命中 ALLERGY_CHECK。
|
|
@@ -2203,6 +2203,82 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
|
|
|
2203
2203
|
throw error;
|
|
2204
2204
|
}
|
|
2205
2205
|
}
|
|
2206
|
+
|
|
2207
|
+
/** Required products currently apply only to the online venue-ticket entry. */
|
|
2208
|
+
async validateRequiredProducts() {
|
|
2209
|
+
const businessCode = String(this.otherParams?.businessCode ?? this.otherParams?.business_code ?? '').trim();
|
|
2210
|
+
const channel = String(this.otherParams?.channel ?? '').trim();
|
|
2211
|
+
if (businessCode !== 'venue_ticket' || channel !== 'online_ordering') return;
|
|
2212
|
+
const scope = this.getPickupTimingScope();
|
|
2213
|
+
const order = this.getTempOrder();
|
|
2214
|
+
const runtimeConfig = this.otherParams?.itemRule || {};
|
|
2215
|
+
let configs = normalizeItemRuleStrategyConfigs(runtimeConfig.strategyConfigs);
|
|
2216
|
+
if (!configs.length) {
|
|
2217
|
+
const openData = await this.getOpenData();
|
|
2218
|
+
if (!toConfiguredBoolean(openData?.['sale.enable_item_rules'])) return;
|
|
2219
|
+
const ids = normalizePositiveIntegerList(openData?.['sale.enabled_item_rules']);
|
|
2220
|
+
if (!ids.length) return;
|
|
2221
|
+
|
|
2222
|
+
// Checkout must not use the allergy loader's fail-open fallback.
|
|
2223
|
+
const response = await this.request.get('/promotion', {
|
|
2224
|
+
skip: 1,
|
|
2225
|
+
num: 99,
|
|
2226
|
+
status: 'active',
|
|
2227
|
+
ids
|
|
2228
|
+
});
|
|
2229
|
+
if (response?.code !== 200 || !Array.isArray(response?.data?.list)) {
|
|
2230
|
+
throw new Error('Unable to load required product rules. Please try again.');
|
|
2231
|
+
}
|
|
2232
|
+
// Configured IDs can include disabled or deleted rules; only active results participate.
|
|
2233
|
+
configs = normalizeItemRuleStrategyConfigs(response.data.list.filter(item => ids.includes(Number(item?.id))).map(item => item?.metadata));
|
|
2234
|
+
}
|
|
2235
|
+
if (scope !== this.getPickupTimingScope() || order !== this.getTempOrder()) {
|
|
2236
|
+
throw new Error('The order changed. Please try again.');
|
|
2237
|
+
}
|
|
2238
|
+
const strategyConfigs = configs.filter(config => Array.isArray(config.actions)).map(config => ({
|
|
2239
|
+
...config,
|
|
2240
|
+
actions: config.actions.filter(action => {
|
|
2241
|
+
const rules = action.config?.quantityRules;
|
|
2242
|
+
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'));
|
|
2243
|
+
})
|
|
2244
|
+
})).filter(config => config.actions.length > 0);
|
|
2245
|
+
if (!strategyConfigs.length) return;
|
|
2246
|
+
const cartItems = this.getOrderProducts().map(item => ({
|
|
2247
|
+
product_id: Number(item.product_id),
|
|
2248
|
+
quantity: Number(item.num)
|
|
2249
|
+
})).filter(item => Number.isFinite(item.product_id) && item.product_id > 0 && Number.isFinite(item.quantity) && item.quantity > 0);
|
|
2250
|
+
const result = new _itemRule.ItemRuleEvaluator().evaluate({
|
|
2251
|
+
strategyConfigs,
|
|
2252
|
+
cartItems,
|
|
2253
|
+
// Fixed-quantity rules do not consume pax; no customer headcount is collected.
|
|
2254
|
+
pax: {
|
|
2255
|
+
total: 0,
|
|
2256
|
+
adult: 0,
|
|
2257
|
+
child: 0
|
|
2258
|
+
},
|
|
2259
|
+
channel,
|
|
2260
|
+
submissionIndex: 0,
|
|
2261
|
+
custom: {
|
|
2262
|
+
...runtimeConfig.custom,
|
|
2263
|
+
businessCode
|
|
2264
|
+
}
|
|
2265
|
+
});
|
|
2266
|
+
if (result.rawResults.some(evaluation => !evaluation.success)) {
|
|
2267
|
+
throw new Error('Unable to validate required product rules. Please try again.');
|
|
2268
|
+
}
|
|
2269
|
+
if (!result.allPassed) {
|
|
2270
|
+
const error = new Error(result.failedChecks[0]?.validationMessage || 'Please select the required product before checkout.');
|
|
2271
|
+
Object.assign(error, {
|
|
2272
|
+
code: 'REQUIRED_PRODUCT_MISSING',
|
|
2273
|
+
failures: result.failedChecks
|
|
2274
|
+
});
|
|
2275
|
+
throw error;
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
async submitSalesOrder(params) {
|
|
2279
|
+
await this.validateRequiredProducts();
|
|
2280
|
+
return super.submitSalesOrder(params);
|
|
2281
|
+
}
|
|
2206
2282
|
async ensureAllergyItemRuleConfigsLoaded() {
|
|
2207
2283
|
if (this.allergyItemRuleConfigs.length > 0) {
|
|
2208
2284
|
return this.allergyItemRuleConfigs;
|