@pisell/pisellos 2.3.178 → 2.3.180

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.
@@ -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
+ }
@@ -49,7 +49,7 @@ function getBookingBoundary(booking, edge) {
49
49
  function resolveDefaultBookingStart({
50
50
  bookings,
51
51
  holderIds,
52
- mode = 'one_after_another',
52
+ mode = 'same_start_time',
53
53
  fallback
54
54
  }) {
55
55
  const holders = new Set(normalizeBookingHolderIds(holderIds));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "2.3.178",
4
+ "version": "2.3.180",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",