@pisell/pisellos 2.3.217 → 2.3.219

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  2. package/dist/modules/OpenData/types.d.ts +3 -0
  3. package/dist/modules/Order/index.js +6 -3
  4. package/dist/modules/Order/types.d.ts +1 -1
  5. package/dist/modules/Order/utils.d.ts +4 -0
  6. package/dist/modules/Order/utils.js +105 -53
  7. package/dist/solution/BookingByStep/index.d.ts +1 -1
  8. package/dist/solution/BookingTicket/index.d.ts +9 -0
  9. package/dist/solution/BookingTicket/index.js +241 -19
  10. package/dist/solution/BookingTicket/utils/redeemArrival.d.ts +78 -0
  11. package/dist/solution/BookingTicket/utils/redeemArrival.js +175 -0
  12. package/dist/solution/UnifiedBookingSales/index.d.ts +1 -0
  13. package/dist/solution/UnifiedBookingSales/index.js +42 -46
  14. package/dist/solution/UnifiedBookingSales/sessionResourceCache.d.ts +4 -0
  15. package/dist/solution/UnifiedBookingSales/sessionResourceCache.js +91 -14
  16. package/lib/modules/OpenData/types.d.ts +3 -0
  17. package/lib/modules/Order/index.js +4 -1
  18. package/lib/modules/Order/types.d.ts +1 -1
  19. package/lib/modules/Order/utils.d.ts +4 -0
  20. package/lib/modules/Order/utils.js +45 -1
  21. package/lib/solution/BookingByStep/index.d.ts +1 -1
  22. package/lib/solution/BookingTicket/index.d.ts +9 -0
  23. package/lib/solution/BookingTicket/index.js +121 -1
  24. package/lib/solution/BookingTicket/utils/redeemArrival.d.ts +78 -0
  25. package/lib/solution/BookingTicket/utils/redeemArrival.js +156 -0
  26. package/lib/solution/UnifiedBookingSales/index.d.ts +1 -0
  27. package/lib/solution/UnifiedBookingSales/index.js +6 -8
  28. package/lib/solution/UnifiedBookingSales/sessionResourceCache.d.ts +4 -0
  29. package/lib/solution/UnifiedBookingSales/sessionResourceCache.js +69 -4
  30. package/package.json +1 -1
@@ -600,11 +600,20 @@ export declare class BookingTicketImpl extends BaseSalesImpl implements Module {
600
600
  private getDeviceTaskPlugin;
601
601
  handlePrintWristband(params: {
602
602
  voucher_ids: number[];
603
+ voucher_times?: Record<string, {
604
+ start_time: string;
605
+ end_time: string;
606
+ }>;
603
607
  }): Promise<void>;
608
+ private redeemStatusWrite?;
609
+ private arrivalQueue;
610
+ private getRedeemArrivalWindow;
611
+ isRedeemArrivalEnabled(): boolean;
604
612
  handleRedeem(params: {
605
613
  voucher_ids: number[];
606
614
  is_checkin: boolean;
607
615
  }): Promise<any>;
616
+ updateTicketArrival(voucherIds: Array<string | number>): Promise<any>;
608
617
  /**
609
618
  * 销毁模块:先调用父类(销毁所有 store 内子模块 + emit destroy + super.destroy()),
610
619
  * 再清理 BookingTicket 自有资源(scan 监听 + scan 内存缓存)。
@@ -25,6 +25,7 @@ var _OpenData = require("../../modules/OpenData");
25
25
  var _BookingContext = require("../../modules/BookingContext");
26
26
  var _BaseSales = require("../BaseSales");
27
27
  var _scan = _interopRequireDefault(require("./utils/scan"));
28
+ var _redeemArrival = require("./utils/redeemArrival");
28
29
  var _orderCustomer = require("./utils/orderCustomer");
29
30
  var _handleScan = require("./utils/scan/handleScan");
30
31
  var _scanCache = _interopRequireDefault(require("./utils/scan/scanCache"));
@@ -2117,6 +2118,9 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
2117
2118
  type: 'WRISTBAND',
2118
2119
  data: {
2119
2120
  order_id: this.getOrderIdentity()?.orderId,
2121
+ ...(params.voucher_times && {
2122
+ voucher_times: params.voucher_times
2123
+ }),
2120
2124
  voucher_ids: Array.isArray(params.voucher_ids) ? params.voucher_ids : [params.voucher_ids]
2121
2125
  }
2122
2126
  },
@@ -2127,6 +2131,14 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
2127
2131
  source_id: idempotencyKey
2128
2132
  });
2129
2133
  }
2134
+ redeemStatusWrite;
2135
+ arrivalQueue = Promise.resolve();
2136
+ getRedeemArrivalWindow() {
2137
+ return (0, _redeemArrival.readArrivalWindow)(this.store.openData?.getOpenData?.() ?? this.getInjectedOpenDataConfig());
2138
+ }
2139
+ isRedeemArrivalEnabled() {
2140
+ return Boolean(this.getRedeemArrivalWindow());
2141
+ }
2130
2142
 
2131
2143
  // 触发核销
2132
2144
  async handleRedeem(params) {
@@ -2153,12 +2165,18 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
2153
2165
  };
2154
2166
  });
2155
2167
  if (tempOrder && hasUpdatedVoucher) {
2156
- await this.replaceTempOrder({
2168
+ const write = this.replaceTempOrder({
2157
2169
  ...tempOrder,
2158
2170
  vouchers: nextVouchers
2159
2171
  }, {
2160
2172
  preserveOrderSessionId: this.getOrderSessionId() || undefined
2161
2173
  });
2174
+ this.redeemStatusWrite = write;
2175
+ try {
2176
+ await write;
2177
+ } finally {
2178
+ if (this.redeemStatusWrite === write) this.redeemStatusWrite = undefined;
2179
+ }
2162
2180
  }
2163
2181
  this.core.effects.emit(`${this.name}:onVouchersChange`, {});
2164
2182
  if (voucherIds.length === 0) {
@@ -2183,6 +2201,108 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
2183
2201
  osServer: true
2184
2202
  });
2185
2203
  }
2204
+ async updateTicketArrival(voucherIds) {
2205
+ const window = this.getRedeemArrivalWindow();
2206
+ const tempOrder = this.store.order?.getTempOrder?.();
2207
+ const log = (0, _redeemArrival.createArrivalLogger)(this.logger, tempOrder, voucherIds);
2208
+ if (!window || !tempOrder) {
2209
+ log('skipped', {
2210
+ reason: !window ? 'no_effective_window' : 'missing_order'
2211
+ });
2212
+ return;
2213
+ }
2214
+ log('started', {
2215
+ early_minutes: window.earlyMinutes,
2216
+ late_minutes: window.lateMinutes
2217
+ });
2218
+ let operation = 'prepare';
2219
+ const arrivalTime = new Date();
2220
+ const session = this.getOrderSessionId();
2221
+ const updateArrival = async () => {
2222
+ // 本地核销状态写入期间读到的是旧快照。等写入完成再调时,batch 请求仍独立执行。
2223
+ if (this.redeemStatusWrite) await this.redeemStatusWrite.catch(() => {});
2224
+ const current = this.store.order?.getTempOrder?.();
2225
+ const sameOrder = () => {
2226
+ const active = this.store.order?.getTempOrder?.();
2227
+ return active && (session == null || this.getOrderSessionId() === session) && active.order_id === tempOrder.order_id && active.external_sale_number === tempOrder.external_sale_number;
2228
+ };
2229
+ const order = current && sameOrder() ? current : tempOrder;
2230
+ const arrival = (0, _redeemArrival.applyRedeemArrival)(order, new Set(voucherIds.map(String)), arrivalTime, window, reason => log('skipped', {
2231
+ reason
2232
+ }));
2233
+ if (!arrival) return;
2234
+ const next = {
2235
+ ...order,
2236
+ ...arrival
2237
+ };
2238
+ const query = (0, _redeemArrival.buildArrivalCheckoutQuery)(next, next.summary ?? (sameOrder() ? await this.getSummary() : undefined));
2239
+ operation = 'checkout';
2240
+ log('checkout_requested', {
2241
+ bookings: (0, _redeemArrival.describeChangedBookings)(order.bookings, arrival.bookings)
2242
+ });
2243
+ const checkout = await this.store.order.submitSalesOrder({
2244
+ query
2245
+ });
2246
+ if (checkout?.status === false || checkout?.code != null && checkout.code !== 200) {
2247
+ log('checkout_rejected', {
2248
+ code: checkout.code,
2249
+ status: checkout.status,
2250
+ message: checkout.message
2251
+ }, true);
2252
+ return checkout;
2253
+ }
2254
+ log('checkout_accepted', {
2255
+ code: checkout?.code
2256
+ });
2257
+ operation = 'local_update';
2258
+ if (this.redeemStatusWrite) await this.redeemStatusWrite.catch(() => {});
2259
+ if (sameOrder()) {
2260
+ const latest = this.store.order.getTempOrder();
2261
+ const patch = (0, _redeemArrival.applyRedeemArrival)(latest, new Set(voucherIds.map(String)), arrivalTime, window);
2262
+ if (patch) {
2263
+ await this.replaceTempOrder({
2264
+ ...latest,
2265
+ ...patch
2266
+ }, {
2267
+ preserveOrderSessionId: this.getOrderSessionId() || undefined
2268
+ });
2269
+ log('local_updated');
2270
+ this.core.effects.emit(`${this.name}:onVouchersChange`, {});
2271
+ } else {
2272
+ log('local_skipped', {
2273
+ reason: 'no_pending_change'
2274
+ });
2275
+ }
2276
+ } else {
2277
+ log('local_skipped', {
2278
+ reason: 'order_changed'
2279
+ });
2280
+ }
2281
+ // 从本次 checkout 已接受的快照取票面时间,避免打印接口短暂返回旧值。
2282
+ const voucherTimes = {};
2283
+ arrival.vouchers.forEach((voucher, index) => {
2284
+ if (voucher !== order.vouchers[index] && voucher.voucher_id != null && voucher.start_time && voucher.end_time) {
2285
+ voucherTimes[String(voucher.voucher_id)] = {
2286
+ start_time: voucher.start_time,
2287
+ end_time: voucher.end_time
2288
+ };
2289
+ }
2290
+ });
2291
+ return Object.keys(voucherTimes).length ? {
2292
+ ...checkout,
2293
+ voucher_times: voucherTimes
2294
+ } : checkout;
2295
+ };
2296
+ const completion = this.arrivalQueue.then(updateArrival).catch(error => {
2297
+ log('failed', {
2298
+ operation,
2299
+ message: error instanceof Error ? error.message : String(error)
2300
+ }, true);
2301
+ throw error;
2302
+ });
2303
+ this.arrivalQueue = completion.then(() => {}, () => {});
2304
+ return completion;
2305
+ }
2186
2306
 
2187
2307
  /**
2188
2308
  * 销毁模块:先调用父类(销毁所有 store 内子模块 + emit destroy + super.destroy()),
@@ -0,0 +1,78 @@
1
+ import type LoggerManager from '../../../plugins/app-types/logger';
2
+ import type { OrderTempOrder } from '../../../modules/Order/types';
3
+ export interface ArrivalWindow {
4
+ earlyMinutes: number;
5
+ lateMinutes: number;
6
+ }
7
+ export declare function readArrivalWindow(config?: Record<string, any> | null): ArrivalWindow | undefined;
8
+ type TicketOrder = Pick<OrderTempOrder, 'vouchers' | 'bookings'>;
9
+ export declare function applyRedeemArrival(order: TicketOrder, ids: Set<string>, now: Date, window?: ArrivalWindow, onSkip?: (reason: string) => void): {
10
+ vouchers: any[];
11
+ bookings: any[];
12
+ } | undefined;
13
+ export declare function createArrivalLogger(logger: Pick<LoggerManager, 'addLog'> | undefined, order: OrderTempOrder | null | undefined, voucherIds: Array<string | number>): (stage: string, details?: Record<string, unknown>, failed?: boolean) => void;
14
+ export declare function buildArrivalCheckoutQuery(order: OrderTempOrder, summary: OrderTempOrder['summary']): {
15
+ _os_pos_receipt_auto_print_payment_statuses: never[];
16
+ platform: string;
17
+ payment_status?: string | undefined;
18
+ created_at?: string | undefined;
19
+ request_unique_idempotency_token?: string | undefined;
20
+ form_record_ids?: {
21
+ form_id: string | number;
22
+ form_record_id: string | number;
23
+ }[] | undefined;
24
+ products: import("../../../modules/Order/types").OrderSubmitProduct[];
25
+ notes?: import("../../../modules/Order/types").SalesNote[] | undefined;
26
+ summary?: import("../../../modules/Order/types").OrderSummary | undefined;
27
+ small_ticket_data_flag?: number | undefined;
28
+ holder_relations?: import("../../../modules/Order/types").OrderHolderRelation[] | undefined;
29
+ metadata: Record<string, any>;
30
+ note: string;
31
+ order_id: number | null;
32
+ external_sale_number: string;
33
+ order_number: string | null;
34
+ shop_order_number: string | null;
35
+ shop_full_order_number: string | null;
36
+ type: string;
37
+ business_code?: string | undefined;
38
+ sales_channel: string;
39
+ order_sales_channel: string;
40
+ status: string;
41
+ shipping_status: string;
42
+ customer_id: number | null;
43
+ customer_name: string;
44
+ country_calling_code: string;
45
+ phone: string;
46
+ email: string;
47
+ is_price_include_tax: number;
48
+ tax_title: string;
49
+ tax_country_code: string;
50
+ currency_code: string;
51
+ currency_symbol: string;
52
+ currency_format: string;
53
+ is_deposit: number;
54
+ deposit_amount: string;
55
+ shop_discount: string;
56
+ surcharge_fee: string;
57
+ buzzer?: string | undefined;
58
+ delivery_type?: string | undefined;
59
+ table_number?: Record<string, any> | undefined;
60
+ schedule_date: string;
61
+ bookings: any[];
62
+ payments: any[];
63
+ refunds?: any[] | undefined;
64
+ surcharges: any[];
65
+ relation_forms: any[];
66
+ contacts: any[];
67
+ contacts_info: Record<string, any> | null;
68
+ holder: Record<string, any> | null;
69
+ order_meta_list?: import("../../../modules/Order/types").OrderMetaList | undefined;
70
+ };
71
+ export declare function describeChangedBookings(before: OrderTempOrder['bookings'], after: OrderTempOrder['bookings']): {
72
+ schedule_event_id: any;
73
+ previous_start: any;
74
+ previous_end: any;
75
+ start: any;
76
+ end: any;
77
+ }[];
78
+ export {};
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.applyRedeemArrival = applyRedeemArrival;
7
+ exports.buildArrivalCheckoutQuery = buildArrivalCheckoutQuery;
8
+ exports.createArrivalLogger = createArrivalLogger;
9
+ exports.describeChangedBookings = describeChangedBookings;
10
+ exports.readArrivalWindow = readArrivalWindow;
11
+ var _dayjs = _interopRequireDefault(require("dayjs"));
12
+ var _posReceiptAutoPrint = require("../../../utils/pos-receipt-auto-print");
13
+ var _utils = require("../../../modules/Order/utils");
14
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
+ function readArrivalWindow(config) {
16
+ const enabled = config?.['fulfillment.enable_adjust_session_on_arrival'];
17
+ if (enabled !== true && enabled !== 1 && enabled !== '1') return;
18
+ const minutes = value => {
19
+ const number = Number(value);
20
+ return Number.isFinite(number) ? Math.max(0, Math.floor(number)) : 0;
21
+ };
22
+ const earlyMinutes = minutes(config?.['fulfillment.max_earlier_shift_minutes']);
23
+ const lateMinutes = minutes(config?.['fulfillment.max_later_shift_minutes']);
24
+ // 两个方向都没有可调整的分钟数时,核销和打印沿用关闭开关时的流程。
25
+ if (earlyMinutes === 0 && lateMinutes === 0) return;
26
+ return {
27
+ earlyMinutes,
28
+ lateMinutes
29
+ };
30
+ }
31
+ function shiftedSession(booking, now, window) {
32
+ if (!window || !booking.start_date || !booking.start_time || !booking.end_time) return null;
33
+ const start = (0, _dayjs.default)(`${booking.start_date} ${booking.start_time}`);
34
+ const end = (0, _dayjs.default)(`${booking.end_date || booking.start_date} ${booking.end_time}`);
35
+ if (!start.isValid() || !end.isValid() || end.isBefore(start)) return null;
36
+ const delta = (0, _dayjs.default)(now).startOf('minute').diff(start, 'minute');
37
+ const minutes = Math.max(-window.earlyMinutes, Math.min(window.lateMinutes, delta));
38
+ if (!Number.isFinite(minutes)) return null;
39
+ if (!minutes) return;
40
+ const shiftedStart = start.add(minutes, 'minute');
41
+ const shiftedEnd = end.add(minutes, 'minute');
42
+ return {
43
+ start_date: shiftedStart.format('YYYY-MM-DD'),
44
+ start_time: shiftedStart.format(booking.start_time.length > 5 ? 'HH:mm:ss' : 'HH:mm'),
45
+ end_date: shiftedEnd.format('YYYY-MM-DD'),
46
+ end_time: shiftedEnd.format(booking.end_time.length > 5 ? 'HH:mm:ss' : 'HH:mm')
47
+ };
48
+ }
49
+ function applyRedeemArrival(order, ids, now, window, onSkip) {
50
+ if (!window || !order.bookings?.length || !order.vouchers?.length) {
51
+ onSkip?.('missing_window_or_booking_data');
52
+ return;
53
+ }
54
+ const selected = new Set();
55
+ for (const voucher of order.vouchers) {
56
+ const event = (0, _utils.redeemEventKey)(voucher?.schedule_event_id);
57
+ if (event && ids.has(String(voucher.voucher_id))) selected.add(event);
58
+ }
59
+ let alreadyMarked = false;
60
+ let invalidSession = false;
61
+ const changes = new Map();
62
+ const bookings = order.bookings.map(booking => {
63
+ const event = (0, _utils.redeemEventKey)(booking?.schedule_event_id);
64
+ if (!event || !selected.has(event) || String(booking.parent_id) === '0') return booking;
65
+ if (Number(booking.metadata?.is_change_by_redeem) === 1) {
66
+ alreadyMarked = true;
67
+ return booking;
68
+ }
69
+ const shift = shiftedSession(booking, now, window);
70
+ if (shift === null) {
71
+ invalidSession = true;
72
+ return booking;
73
+ }
74
+ // 准点核销的偏移量为零,也要打标,避免下一张票改变这个时段。
75
+ changes.set(event, shift);
76
+ return {
77
+ ...booking,
78
+ ...shift,
79
+ metadata: {
80
+ ...booking.metadata,
81
+ is_change_by_redeem: 1
82
+ }
83
+ };
84
+ });
85
+ if (!changes.size) {
86
+ onSkip?.(invalidSession ? 'invalid_booking_time' : alreadyMarked ? 'already_marked' : 'no_linked_booking');
87
+ return;
88
+ }
89
+ const vouchers = order.vouchers.map(voucher => {
90
+ const event = (0, _utils.redeemEventKey)(voucher?.schedule_event_id);
91
+ const shift = event && changes.get(event);
92
+ if (!shift) return voucher;
93
+ return {
94
+ ...voucher,
95
+ start_date: shift.start_date,
96
+ expire_date: shift.end_date,
97
+ start_time: shift.start_time,
98
+ end_time: shift.end_time
99
+ };
100
+ });
101
+ return {
102
+ vouchers,
103
+ bookings
104
+ };
105
+ }
106
+ function createArrivalLogger(logger, order, voucherIds) {
107
+ return (stage, details = {}, failed = false) => {
108
+ try {
109
+ logger?.addLog({
110
+ type: failed ? 'error' : 'info',
111
+ title: '[BookingTicket] updateTicketArrival',
112
+ metadata: {
113
+ stage,
114
+ order_id: order?.order_id,
115
+ external_sale_number: order?.external_sale_number,
116
+ voucher_ids: voucherIds,
117
+ ...details
118
+ }
119
+ });
120
+ } catch {
121
+ // 日志不可用时,核销和预约调时仍按原流程执行。
122
+ }
123
+ };
124
+ }
125
+ function buildArrivalCheckoutQuery(order, summary) {
126
+ const {
127
+ vouchers: _localVouchers,
128
+ ...payload
129
+ } = (0, _utils.buildSubmitPayload)({
130
+ tempOrder: order,
131
+ platform: order.platform,
132
+ businessCode: order.business_code,
133
+ type: order.type,
134
+ summary
135
+ });
136
+ return {
137
+ ...payload,
138
+ // 调时提交无需自动打印整单小票;Redeem & Print 由票券按钮发起打印。
139
+ [_posReceiptAutoPrint.OS_POS_RECEIPT_AUTO_PRINT_PAYMENT_STATUSES_FIELD]: []
140
+ };
141
+ }
142
+ function describeChangedBookings(before, after) {
143
+ const changes = [];
144
+ for (const [index, booking] of after.entries()) {
145
+ const previous = before[index];
146
+ if (booking === previous) continue;
147
+ changes.push({
148
+ schedule_event_id: booking.schedule_event_id,
149
+ previous_start: previous.start_time,
150
+ previous_end: previous.end_time,
151
+ start: booking.start_time,
152
+ end: booking.end_time
153
+ });
154
+ }
155
+ return changes;
156
+ }
@@ -91,6 +91,7 @@ export declare class UnifiedBookingSalesImpl extends BookingTicket {
91
91
  private availabilityProjectionRefreshInFlight;
92
92
  private availabilityRemoteOccupancyCache;
93
93
  private availabilitySessionResourceCache;
94
+ private readonly fetchAvailabilitySessionResources;
94
95
  private availabilityRemoteResourceQueryInFlight;
95
96
  private availabilityRemoteResourceQuerySequence;
96
97
  private availabilityRemoteResourceEpoch;
@@ -1307,6 +1307,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1307
1307
  availabilityProjectionRefreshInFlight = new Map();
1308
1308
  availabilityRemoteOccupancyCache = new _remoteOccupancyCache.AvailabilityRemoteOccupancyCache(MAX_REMOTE_OCCUPANCY_RESOURCE_DATE_CELLS);
1309
1309
  availabilitySessionResourceCache = new _sessionResourceCache.AvailabilitySessionResourceCache();
1310
+ fetchAvailabilitySessionResources = query => this.fetchAvailabilityResourcesV2({
1311
+ ...query,
1312
+ strictResponse: true
1313
+ });
1310
1314
  availabilityRemoteResourceQueryInFlight = new Map();
1311
1315
  availabilityRemoteResourceQuerySequence = 0;
1312
1316
  availabilityRemoteResourceEpoch = 0;
@@ -3837,10 +3841,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3837
3841
  scopeKey: `${scope}:${this.buildAvailabilityRemoteResourceScopeKey(timezone)}`,
3838
3842
  timezoneName: timezone,
3839
3843
  ...resourceQuery,
3840
- fetch: query => this.fetchAvailabilityResourcesV2({
3841
- ...query,
3842
- strictResponse: true
3843
- })
3844
+ fetch: this.fetchAvailabilitySessionResources
3844
3845
  }) : await this.fetchAvailabilityResourcesV2({
3845
3846
  ...resourceQuery,
3846
3847
  strictResponse: true
@@ -3961,10 +3962,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3961
3962
  timezoneName: params.timezone,
3962
3963
  resourceIds,
3963
3964
  dateRange: params.dateRange,
3964
- fetch: query => this.fetchAvailabilityResourcesV2({
3965
- ...query,
3966
- strictResponse: true
3967
- })
3965
+ fetch: this.fetchAvailabilitySessionResources
3968
3966
  });
3969
3967
  return buildAvailabilityResourcesFromV2({
3970
3968
  rawResources,
@@ -21,7 +21,11 @@ export declare class AvailabilitySessionResourceCache {
21
21
  private readonly cells;
22
22
  private readonly pending;
23
23
  private generation;
24
+ private queuedBatches;
25
+ private batchFlushScheduled;
24
26
  clear(): void;
27
+ private enqueueFetch;
28
+ private flushFetchBatches;
25
29
  load(params: AvailabilitySessionResourceLoadParams): Promise<RawResource[]>;
26
30
  }
27
31
  export {};
@@ -6,6 +6,11 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.AvailabilitySessionResourceCache = void 0;
7
7
  var _lodashEs = require("lodash-es");
8
8
  var _localClock = require("../../modules/ResourcePlanner/localClock");
9
+ function sessionChangedError() {
10
+ return Object.assign(new Error('Resource session changed while loading. Please prepare again.'), {
11
+ code: 'AVAILABILITY_CONTEXT_NOT_FOUND'
12
+ });
13
+ }
9
14
  function datesInRange(range) {
10
15
  const count = (0, _localClock.dateOrdinalFromLocalDate)(range.endDate) - (0, _localClock.dateOrdinalFromLocalDate)(range.startDate) + 1;
11
16
  // A legal 90-business-day projection may include its preceding opening and overnight tail.
@@ -67,18 +72,78 @@ class AvailabilitySessionResourceCache {
67
72
  cells = new Map();
68
73
  pending = new Map();
69
74
  generation = 0;
75
+ queuedBatches = [];
76
+ batchFlushScheduled = false;
70
77
  clear() {
71
78
  this.generation += 1;
72
79
  this.cells.clear();
73
80
  this.pending.clear();
81
+ // A queued request has not reached the transport yet. Settle its waiters
82
+ // now, rather than leaving them pending or dispatching it in the new scope.
83
+ const queued = this.queuedBatches;
84
+ this.queuedBatches = [];
85
+ queued.forEach(batch => batch.reject(sessionChangedError()));
86
+ }
87
+ enqueueFetch(params, query, generation) {
88
+ let batch = this.queuedBatches.find(entry => entry.generation === generation && entry.scopeKey === params.scopeKey && entry.timezoneName === params.timezoneName && entry.fetch === params.fetch && entry.dateRange.startDate === query.dateRange.startDate && entry.dateRange.endDate === query.dateRange.endDate);
89
+ if (!batch) {
90
+ let resolve;
91
+ let reject;
92
+ const promise = new Promise((resolvePromise, rejectPromise) => {
93
+ resolve = resolvePromise;
94
+ reject = rejectPromise;
95
+ });
96
+ batch = {
97
+ generation,
98
+ scopeKey: params.scopeKey,
99
+ timezoneName: params.timezoneName,
100
+ dateRange: {
101
+ ...query.dateRange
102
+ },
103
+ fetch: params.fetch,
104
+ resourceIds: new Map(),
105
+ promise,
106
+ resolve,
107
+ reject
108
+ };
109
+ this.queuedBatches.push(batch);
110
+ }
111
+ query.resourceIds.forEach(id => batch.resourceIds.set(String(id), id));
112
+ if (!this.batchFlushScheduled) {
113
+ this.batchFlushScheduled = true;
114
+ // Fetching was already asynchronous. Collect requests from this turn only;
115
+ // do not add a timer or broaden their physical date coverage.
116
+ void Promise.resolve().then(() => this.flushFetchBatches());
117
+ }
118
+ return batch.promise;
119
+ }
120
+ flushFetchBatches() {
121
+ this.batchFlushScheduled = false;
122
+ const queued = this.queuedBatches;
123
+ this.queuedBatches = [];
124
+ queued.forEach(batch => {
125
+ if (batch.generation !== this.generation) {
126
+ batch.reject(sessionChangedError());
127
+ return;
128
+ }
129
+ const query = {
130
+ resourceIds: Array.from(batch.resourceIds.values()).sort((left, right) => String(left).localeCompare(String(right))),
131
+ dateRange: {
132
+ ...batch.dateRange
133
+ }
134
+ };
135
+ try {
136
+ Promise.resolve(batch.fetch((0, _lodashEs.cloneDeep)(query))).then(batch.resolve, batch.reject);
137
+ } catch (error) {
138
+ batch.reject(error);
139
+ }
140
+ });
74
141
  }
75
142
  async load(params) {
76
143
  const generation = this.generation;
77
144
  const assertCurrent = () => {
78
145
  if (generation !== this.generation) {
79
- throw Object.assign(new Error('Resource session changed while loading. Please prepare again.'), {
80
- code: 'AVAILABILITY_CONTEXT_NOT_FOUND'
81
- });
146
+ throw sessionChangedError();
82
147
  }
83
148
  };
84
149
  const resources = Array.from(new Map(params.resourceIds.filter(id => id !== undefined && id !== null && id !== '').map(id => [String(id), id])).values());
@@ -121,7 +186,7 @@ class AvailabilitySessionResourceCache {
121
186
  const cellKeys = query.resourceIds.flatMap(id => queryDates.map(date => key(id, date)));
122
187
  const promise = Promise.resolve().then(async () => {
123
188
  assertCurrent();
124
- const response = await params.fetch((0, _lodashEs.cloneDeep)(query));
189
+ const response = await this.enqueueFetch(params, query, generation);
125
190
  assertCurrent();
126
191
  if (!Array.isArray(response)) throw new Error('Booking resources returned an invalid response.');
127
192
  const byId = new Map();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "2.3.217",
4
+ "version": "2.3.219",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",