@pisell/pisellos 0.10.83 → 0.10.88

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.
@@ -100,6 +100,9 @@ export interface OpenDataConfig {
100
100
  'sale.short_number_prefix'?: string | null;
101
101
  'sale.sale_number_prefix'?: string | null;
102
102
  'sale.enabled_item_rules'?: number[];
103
+ 'fulfillment.enable_adjust_session_on_arrival'?: boolean | 0 | 1;
104
+ 'fulfillment.max_earlier_shift_minutes'?: number | string;
105
+ 'fulfillment.max_later_shift_minutes'?: number | string;
103
106
  'fulfillment.enable_pickup'?: boolean;
104
107
  'fulfillment.handover_mode'?: string[];
105
108
  'fulfillment.pickup.timing_mode'?: 'asap_only' | 'scheduled_only' | 'asap_and_scheduled';
@@ -4740,6 +4740,9 @@ class OrderModule extends _BaseModule.BaseModule {
4740
4740
  metadata: {
4741
4741
  ...(targetBooking.metadata || {}),
4742
4742
  ...(updates.metadata || {}),
4743
+ ...(Number(targetBooking.metadata?.is_change_by_redeem) === 1 ? {
4744
+ is_change_by_redeem: 1
4745
+ } : {}),
4743
4746
  unique_identification_number: bookingUid
4744
4747
  }
4745
4748
  };
@@ -5919,7 +5922,7 @@ class OrderModule extends _BaseModule.BaseModule {
5919
5922
  if (options?.ensureIdentity !== false) {
5920
5923
  this.ensureExternalSaleNumber(nextTempOrder);
5921
5924
  }
5922
- nextTempOrder.vouchers = raw.vouchers || [];
5925
+ nextTempOrder.vouchers = (0, _utils.restoreRedeemVoucherTimes)(nextTempOrder, raw.vouchers || []);
5923
5926
  return nextTempOrder;
5924
5927
  }
5925
5928
  isSyntheticDraftOrderIdForRuntime(record, options) {
@@ -644,7 +644,7 @@ export interface SubmitSalesOrderParams {
644
644
  holder_relations?: OrderHolderRelation[];
645
645
  bookings: OrderSubmitBooking[];
646
646
  payments: any[];
647
- vouchers: any[];
647
+ vouchers?: any[];
648
648
  surcharges?: any[];
649
649
  relation_forms: any[];
650
650
  form_record_ids?: OrderSubmitFormRecord[];
@@ -208,6 +208,10 @@ export declare const getAllDiscountList: (cartItem: CartItem) => any;
208
208
  export { createUuidV4 };
209
209
  export declare function isTempOrder(data: any): data is OrderTempOrder;
210
210
  export declare function formatDateTime(date: Date): string;
211
+ /** 旧票券可能没有事件 ID;缺失或占位值不能用于关联预约。 */
212
+ export declare function redeemEventKey(value: unknown): string | undefined;
213
+ /** checkout 提交子预约的标记;重新加载订单时,从已调时的子预约恢复关联票券的票面时段。 */
214
+ export declare function restoreRedeemVoucherTimes(order: Pick<OrderTempOrder, 'bookings'>, vouchers: any[]): any[];
211
215
  export declare function normalizeBookingIsAll(booking: Record<string, any>): 0 | 1;
212
216
  export declare function normalizeBookingSubType(booking: Record<string, any>): string;
213
217
  export declare function normalizeSubmitBooking<T extends {
@@ -79,6 +79,7 @@ exports.normalizeSubmitBooking = normalizeSubmitBooking;
79
79
  exports.normalizeSubmitCollectPaxValue = normalizeSubmitCollectPaxValue;
80
80
  exports.normalizeVirtualCurrencySnapshotItem = normalizeVirtualCurrencySnapshotItem;
81
81
  exports.productRequiresFormSubject = productRequiresFormSubject;
82
+ exports.redeemEventKey = redeemEventKey;
82
83
  exports.resolveEffectivePerUnitDiscount = resolveEffectivePerUnitDiscount;
83
84
  exports.resolveIsFormSubject = resolveIsFormSubject;
84
85
  Object.defineProperty(exports, "resolveManualDiscountMessage", {
@@ -109,6 +110,7 @@ Object.defineProperty(exports, "resolveSafeProductNum", {
109
110
  });
110
111
  exports.resolveSubmitCollectPax = resolveSubmitCollectPax;
111
112
  exports.resolveSubmitOrderType = resolveSubmitOrderType;
113
+ exports.restoreRedeemVoucherTimes = restoreRedeemVoucherTimes;
112
114
  Object.defineProperty(exports, "shouldBuildManualProductDiscount", {
113
115
  enumerable: true,
114
116
  get: function () {
@@ -1324,7 +1326,49 @@ function normalizeSubmitProduct(product, formatOptions = {}) {
1324
1326
  payment_price: formatOptions.virtualSettlementMode ? virtualPrice : submitProduct.payment_price ?? submitProduct.selling_price
1325
1327
  };
1326
1328
  }
1327
- const SUBMIT_BOOKING_METADATA_WHITELIST = ['unique_identification_number', 'collect_pax', 'capacity', 'holder_id', 'resource_select_type', 'holder', 'is_fulfillment_timing', 'fulfillment_timing'];
1329
+
1330
+ /** 旧票券可能没有事件 ID;缺失或占位值不能用于关联预约。 */
1331
+ function redeemEventKey(value) {
1332
+ if (typeof value !== 'number' && typeof value !== 'string') return;
1333
+ const key = String(value).trim();
1334
+ return /^[1-9]\d*$/.test(key) ? key : undefined;
1335
+ }
1336
+
1337
+ /** checkout 提交子预约的标记;重新加载订单时,从已调时的子预约恢复关联票券的票面时段。 */
1338
+ function restoreRedeemVoucherTimes(order, vouchers) {
1339
+ if (!Array.isArray(vouchers) || !vouchers.length) return vouchers;
1340
+ const markedBookings = new Map();
1341
+ for (const booking of order.bookings || []) {
1342
+ const event = redeemEventKey(booking?.schedule_event_id);
1343
+ if (event && Number(booking.metadata?.is_change_by_redeem) === 1) markedBookings.set(event, booking);
1344
+ }
1345
+ if (!markedBookings.size) return vouchers;
1346
+ let restored = vouchers;
1347
+ vouchers.forEach((voucher, index) => {
1348
+ const event = redeemEventKey(voucher?.schedule_event_id);
1349
+ const booking = event && markedBookings.get(event);
1350
+ if (!booking || !booking.start_time || !booking.end_time) return;
1351
+ const times = {
1352
+ start_time: booking.start_time,
1353
+ end_time: booking.end_time,
1354
+ ...(booking.start_date && {
1355
+ start_date: booking.start_date
1356
+ }),
1357
+ ...(booking.end_date && {
1358
+ expire_date: booking.end_date
1359
+ })
1360
+ };
1361
+ const timeChanged = Object.entries(times).some(([key, value]) => voucher[key] !== value);
1362
+ if (!timeChanged) return;
1363
+ if (restored === vouchers) restored = vouchers.slice();
1364
+ restored[index] = {
1365
+ ...voucher,
1366
+ ...times
1367
+ };
1368
+ });
1369
+ return restored;
1370
+ }
1371
+ const SUBMIT_BOOKING_METADATA_WHITELIST = ['is_change_by_redeem', 'unique_identification_number', 'collect_pax', 'capacity', 'holder_id', 'resource_select_type', 'holder', 'is_fulfillment_timing', 'fulfillment_timing'];
1328
1372
  function normalizeBookingIsAll(booking) {
1329
1373
  return booking.is_all === true || booking.is_all === 1 || booking.is_all === '1' || booking.is_all === 'true' ? 1 : 0;
1330
1374
  }
@@ -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(): "duration" | "session" | "normal";
52
+ getProductType(): "normal" | "duration" | "session";
53
53
  }
@@ -310,6 +310,9 @@ class ProductList extends _BaseModule.BaseModule {
310
310
  } : {}),
311
311
  front_end_cache_id: params.cacheId
312
312
  }, {
313
+ // Core dispatches Kiosk to its local product query; PC/H5 without that
314
+ // route keep using HTTP. open_quotation: 0 preserves the raw venue pool.
315
+ osServer: true,
313
316
  useCache: false,
314
317
  customToast: () => {}
315
318
  });
@@ -319,7 +322,7 @@ class ProductList extends _BaseModule.BaseModule {
319
322
  code: 'VENUE_CATALOG_LOAD_FAILED'
320
323
  });
321
324
  }
322
- const total = data.total ?? data.total_count ?? data.total_num;
325
+ const total = data.total ?? data.total_count ?? data.total_num ?? data.count;
323
326
  if (total != null && Number.isFinite(Number(total)) && Number(total) > data.list.length || total == null && data.list.length >= 500) {
324
327
  throw Object.assign(new Error('The venue product pool is incomplete. A single complete catalog response is required.'), {
325
328
  code: 'VENUE_CATALOG_INCOMPLETE'
@@ -286,6 +286,7 @@ declare class Server {
286
286
  * 存储订阅者信息,便于数据变更时推送最新结果
287
287
  */
288
288
  private handleProductQuery;
289
+ private queryRawKioskProductPool;
289
290
  /**
290
291
  * ProductList callers such as standalone retail pages do not always have a selected schedule.
291
292
  * In that case query against the current local time so menu availability can still be evaluated.
@@ -1655,6 +1655,11 @@ class Server {
1655
1655
  data,
1656
1656
  config
1657
1657
  }) => {
1658
+ // Venue previews seed one complete raw Kiosk pool. Quoting or applying the
1659
+ // current schedule here would remove members needed by other preview dates.
1660
+ if (data?.open_quotation === 0 && data?.application_code === 'kiosk') {
1661
+ return this.queryRawKioskProductPool(data);
1662
+ }
1658
1663
  const {
1659
1664
  menu_list_ids,
1660
1665
  customer_id,
@@ -1720,6 +1725,40 @@ class Server {
1720
1725
  }
1721
1726
  return result;
1722
1727
  };
1728
+ async queryRawKioskProductPool(data) {
1729
+ const preload = this.startupModulePreloadInFlight;
1730
+ if (preload) await preload;
1731
+ if (!this.products?.getProducts) {
1732
+ throw new Error('The local product catalog is not ready.');
1733
+ }
1734
+ const products = await this.products.getProducts();
1735
+ if (!Array.isArray(products)) {
1736
+ throw new Error('The local product catalog is unavailable.');
1737
+ }
1738
+ const filterSet = value => Array.isArray(value) && value.length ? new Set(value.filter(item => typeof item === 'string' || typeof item === 'number').map(item => String(item).trim()).filter(Boolean)) : undefined;
1739
+ const ids = filterSet(data.ids);
1740
+ const collections = filterSet(typeof data.collection === 'number' ? [data.collection] : data.collection);
1741
+ const categories = filterSet(data.category_ids);
1742
+ const extensionTypes = filterSet(data.extension_type);
1743
+ const list = products.filter(product => {
1744
+ if ((product.status || 'published') !== 'published' || 'deleted_at' in product && product.deleted_at) return false;
1745
+ if (!Array.isArray(product.channel_application) || !product.channel_application.includes('kiosk')) return false;
1746
+ if (ids && !ids.has(String(product.id))) return false;
1747
+ if (collections && !product.collection?.some(collection => collections.has(String(collection.id)))) return false;
1748
+ if (categories && !product.categories?.some(category => categories.has(String(category.id)) || categories.has(String(category.pivot?.product_category_id)))) return false;
1749
+ return !extensionTypes || extensionTypes.has(String(product.extension_type));
1750
+ });
1751
+ return {
1752
+ code: 200,
1753
+ status: true,
1754
+ message: '',
1755
+ data: {
1756
+ list,
1757
+ count: list.length,
1758
+ schedule_time_points: []
1759
+ }
1760
+ };
1761
+ }
1723
1762
 
1724
1763
  /**
1725
1764
  * ProductList callers such as standalone retail pages do not always have a selected schedule.
@@ -373,7 +373,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
373
373
  };
374
374
  setOtherData(key: string, value: any): void;
375
375
  getOtherData(key: string): any;
376
- getProductTypeById(id: number): Promise<"duration" | "session" | "normal">;
376
+ getProductTypeById(id: number): Promise<"normal" | "duration" | "session">;
377
377
  /**
378
378
  * 提供给 UI 的方法,减轻 UI 层的计算压力,UI 层只需要传递 cartItemId 和 resourceCode 即返回对应的 renderList
379
379
  *
@@ -479,7 +479,19 @@ export declare class BookingTicketImpl extends BaseSalesImpl implements Module {
479
479
  * 加车两阶段主决策(规格弹窗 / 资源编辑 / 直接加车)。
480
480
  * 与 ticketBooking `handleSelectProduct` + `handleBooking4Service` 等价。
481
481
  */
482
- decideAddProduct(item: any, options?: Partial<AddProductDecideContext>): import("./utils/addProductDecision").AddProductDecision;
482
+ decideAddProduct(item: any, options?: Partial<AddProductDecideContext>): {
483
+ action: "reloadCatalog";
484
+ } | {
485
+ action: "add";
486
+ cacheItem: any;
487
+ } | {
488
+ action: "requiresDetail";
489
+ payload: AddProductRequiresDetailPayload;
490
+ } | {
491
+ action: "requiresBookingEdit";
492
+ cacheItem: any;
493
+ payload: import("./utils/addProductDecision").AddProductRequiresBookingEditPayload;
494
+ };
483
495
  /** 规格弹窗 callback 后的第二段决策。 */
484
496
  decideAfterDetail(cacheItem: any, options?: Partial<AddProductDecideContext>): import("./utils/addProductDecision").AddProductDecision;
485
497
  /**
@@ -583,10 +595,15 @@ export declare class BookingTicketImpl extends BaseSalesImpl implements Module {
583
595
  handlePrintWristband(params: {
584
596
  voucher_ids: number[];
585
597
  }): Promise<void>;
598
+ private redeemStatusWrite?;
599
+ private arrivalQueue;
600
+ private getRedeemArrivalWindow;
601
+ isRedeemArrivalEnabled(): boolean;
586
602
  handleRedeem(params: {
587
603
  voucher_ids: number[];
588
604
  is_checkin: boolean;
589
605
  }): Promise<any>;
606
+ updateTicketArrival(voucherIds: Array<string | number>): Promise<any>;
590
607
  /**
591
608
  * 销毁模块:先调用父类(销毁所有 store 内子模块 + emit destroy + super.destroy()),
592
609
  * 再清理 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"));
@@ -2092,6 +2093,14 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
2092
2093
  source_id: idempotencyKey
2093
2094
  });
2094
2095
  }
2096
+ redeemStatusWrite;
2097
+ arrivalQueue = Promise.resolve();
2098
+ getRedeemArrivalWindow() {
2099
+ return (0, _redeemArrival.readArrivalWindow)(this.store.openData?.getOpenData?.() ?? this.getInjectedOpenDataConfig());
2100
+ }
2101
+ isRedeemArrivalEnabled() {
2102
+ return Boolean(this.getRedeemArrivalWindow());
2103
+ }
2095
2104
 
2096
2105
  // 触发核销
2097
2106
  async handleRedeem(params) {
@@ -2118,10 +2127,16 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
2118
2127
  };
2119
2128
  });
2120
2129
  if (tempOrder && hasUpdatedVoucher) {
2121
- await this.replaceTempOrder({
2130
+ const write = this.replaceTempOrder({
2122
2131
  ...tempOrder,
2123
2132
  vouchers: nextVouchers
2124
2133
  });
2134
+ this.redeemStatusWrite = write;
2135
+ try {
2136
+ await write;
2137
+ } finally {
2138
+ if (this.redeemStatusWrite === write) this.redeemStatusWrite = undefined;
2139
+ }
2125
2140
  }
2126
2141
  this.core.effects.emit(`${this.name}:onVouchersChange`, {});
2127
2142
  if (voucherIds.length === 0) {
@@ -2146,6 +2161,92 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
2146
2161
  osServer: true
2147
2162
  });
2148
2163
  }
2164
+ async updateTicketArrival(voucherIds) {
2165
+ const window = this.getRedeemArrivalWindow();
2166
+ const tempOrder = this.store.order?.getTempOrder?.();
2167
+ const log = (0, _redeemArrival.createArrivalLogger)(this.logger, tempOrder, voucherIds);
2168
+ if (!window || !tempOrder) {
2169
+ log('skipped', {
2170
+ reason: !window ? 'no_effective_window' : 'missing_order'
2171
+ });
2172
+ return;
2173
+ }
2174
+ log('started', {
2175
+ early_minutes: window.earlyMinutes,
2176
+ late_minutes: window.lateMinutes
2177
+ });
2178
+ let operation = 'prepare';
2179
+ const arrivalTime = new Date();
2180
+ const updateArrival = async () => {
2181
+ // 本地核销状态写入期间读到的是旧快照。等写入完成再调时,batch 请求仍独立执行。
2182
+ if (this.redeemStatusWrite) await this.redeemStatusWrite.catch(() => {});
2183
+ const current = this.store.order?.getTempOrder?.();
2184
+ const sameOrder = () => {
2185
+ const active = this.store.order?.getTempOrder?.();
2186
+ return active && active.order_id === tempOrder.order_id && active.external_sale_number === tempOrder.external_sale_number;
2187
+ };
2188
+ const order = current && sameOrder() ? current : tempOrder;
2189
+ const arrival = (0, _redeemArrival.applyRedeemArrival)(order, new Set(voucherIds.map(String)), arrivalTime, window, reason => log('skipped', {
2190
+ reason
2191
+ }));
2192
+ if (!arrival) return;
2193
+ const next = {
2194
+ ...order,
2195
+ ...arrival
2196
+ };
2197
+ const query = (0, _redeemArrival.buildArrivalCheckoutQuery)(next, next.summary ?? (sameOrder() ? await this.getSummary() : undefined));
2198
+ operation = 'checkout';
2199
+ log('checkout_requested', {
2200
+ bookings: (0, _redeemArrival.describeChangedBookings)(order.bookings, arrival.bookings)
2201
+ });
2202
+ const checkout = await this.store.order.submitSalesOrder({
2203
+ query
2204
+ });
2205
+ if (checkout?.status === false || checkout?.code != null && checkout.code !== 200) {
2206
+ log('checkout_rejected', {
2207
+ code: checkout.code,
2208
+ status: checkout.status,
2209
+ message: checkout.message
2210
+ }, true);
2211
+ return checkout;
2212
+ }
2213
+ log('checkout_accepted', {
2214
+ code: checkout?.code
2215
+ });
2216
+ operation = 'local_update';
2217
+ if (this.redeemStatusWrite) await this.redeemStatusWrite.catch(() => {});
2218
+ if (sameOrder()) {
2219
+ const latest = this.store.order.getTempOrder();
2220
+ const patch = (0, _redeemArrival.applyRedeemArrival)(latest, new Set(voucherIds.map(String)), arrivalTime, window);
2221
+ if (patch) {
2222
+ await this.replaceTempOrder({
2223
+ ...latest,
2224
+ ...patch
2225
+ });
2226
+ log('local_updated');
2227
+ this.core.effects.emit(`${this.name}:onVouchersChange`, {});
2228
+ } else {
2229
+ log('local_skipped', {
2230
+ reason: 'no_pending_change'
2231
+ });
2232
+ }
2233
+ } else {
2234
+ log('local_skipped', {
2235
+ reason: 'order_changed'
2236
+ });
2237
+ }
2238
+ return checkout;
2239
+ };
2240
+ const completion = this.arrivalQueue.then(updateArrival).catch(error => {
2241
+ log('failed', {
2242
+ operation,
2243
+ message: error instanceof Error ? error.message : String(error)
2244
+ }, true);
2245
+ throw error;
2246
+ });
2247
+ this.arrivalQueue = completion.then(() => {}, () => {});
2248
+ return completion;
2249
+ }
2149
2250
 
2150
2251
  /**
2151
2252
  * 销毁模块:先调用父类(销毁所有 store 内子模块 + emit destroy + super.destroy()),
@@ -0,0 +1,77 @@
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
+ small_ticket_data_flag: number;
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
+ status: string;
28
+ metadata: Record<string, any>;
29
+ business_code?: string | undefined;
30
+ customer_id: number | null;
31
+ type: string;
32
+ holder: Record<string, any> | null;
33
+ email: string;
34
+ phone: string;
35
+ note: string;
36
+ relation_forms: any[];
37
+ holder_relations?: import("../../../modules/Order/types").OrderHolderRelation[] | undefined;
38
+ country_calling_code: string;
39
+ contacts_info: Record<string, any> | null;
40
+ order_id: number | null;
41
+ external_sale_number: string;
42
+ order_number: string | null;
43
+ shop_order_number: string | null;
44
+ shop_full_order_number: string | null;
45
+ sales_channel: string;
46
+ order_sales_channel: string;
47
+ shipping_status: string;
48
+ customer_name: string;
49
+ is_price_include_tax: number;
50
+ tax_title: string;
51
+ tax_country_code: string;
52
+ currency_code: string;
53
+ currency_symbol: string;
54
+ currency_format: string;
55
+ is_deposit: number;
56
+ deposit_amount: string;
57
+ shop_discount: string;
58
+ surcharge_fee: string;
59
+ buzzer?: string | undefined;
60
+ delivery_type?: string | undefined;
61
+ table_number?: Record<string, any> | undefined;
62
+ schedule_date: string;
63
+ bookings: any[];
64
+ payments: any[];
65
+ order_meta_list?: import("../../../modules/Order/types").OrderMetaList | undefined;
66
+ refunds?: any[] | undefined;
67
+ surcharges: any[];
68
+ contacts: any[];
69
+ };
70
+ export declare function describeChangedBookings(before: OrderTempOrder['bookings'], after: OrderTempOrder['bookings']): {
71
+ schedule_event_id: any;
72
+ previous_start: any;
73
+ previous_end: any;
74
+ start: any;
75
+ end: any;
76
+ }[];
77
+ export {};
@@ -0,0 +1,149 @@
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 _utils = require("../../../modules/Order/utils");
13
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
+ function readArrivalWindow(config) {
15
+ const enabled = config?.['fulfillment.enable_adjust_session_on_arrival'];
16
+ if (enabled !== true && enabled !== 1 && enabled !== '1') return;
17
+ const minutes = value => {
18
+ const number = Number(value);
19
+ return Number.isFinite(number) ? Math.max(0, Math.floor(number)) : 0;
20
+ };
21
+ const earlyMinutes = minutes(config?.['fulfillment.max_earlier_shift_minutes']);
22
+ const lateMinutes = minutes(config?.['fulfillment.max_later_shift_minutes']);
23
+ // 两个方向都没有可调整的分钟数时,核销和打印沿用关闭开关时的流程。
24
+ if (earlyMinutes === 0 && lateMinutes === 0) return;
25
+ return {
26
+ earlyMinutes,
27
+ lateMinutes
28
+ };
29
+ }
30
+ function shiftedSession(booking, now, window) {
31
+ if (!window || !booking.start_date || !booking.start_time || !booking.end_time) return;
32
+ const start = (0, _dayjs.default)(`${booking.start_date} ${booking.start_time}`);
33
+ const end = (0, _dayjs.default)(`${booking.end_date || booking.start_date} ${booking.end_time}`);
34
+ if (!start.isValid() || !end.isValid() || end.isBefore(start)) return;
35
+ const delta = (0, _dayjs.default)(now).startOf('minute').diff(start, 'minute');
36
+ const minutes = Math.max(-window.earlyMinutes, Math.min(window.lateMinutes, delta));
37
+ if (!Number.isFinite(minutes) || !minutes) return;
38
+ const shiftedStart = start.add(minutes, 'minute');
39
+ const shiftedEnd = end.add(minutes, 'minute');
40
+ return {
41
+ start_date: shiftedStart.format('YYYY-MM-DD'),
42
+ start_time: shiftedStart.format(booking.start_time.length > 5 ? 'HH:mm:ss' : 'HH:mm'),
43
+ end_date: shiftedEnd.format('YYYY-MM-DD'),
44
+ end_time: shiftedEnd.format(booking.end_time.length > 5 ? 'HH:mm:ss' : 'HH:mm')
45
+ };
46
+ }
47
+ function applyRedeemArrival(order, ids, now, window, onSkip) {
48
+ if (!window || !order.bookings?.length || !order.vouchers?.length) {
49
+ onSkip?.('missing_window_or_booking_data');
50
+ return;
51
+ }
52
+ const selected = new Set();
53
+ for (const voucher of order.vouchers) {
54
+ const event = (0, _utils.redeemEventKey)(voucher?.schedule_event_id);
55
+ if (event && ids.has(String(voucher.voucher_id))) selected.add(event);
56
+ }
57
+ let alreadyMarked = false;
58
+ const changes = new Map();
59
+ const bookings = order.bookings.map(booking => {
60
+ const event = (0, _utils.redeemEventKey)(booking?.schedule_event_id);
61
+ if (!event || !selected.has(event) || booking.parent_id === 0) return booking;
62
+ if (Number(booking.metadata?.is_change_by_redeem) === 1) {
63
+ alreadyMarked = true;
64
+ return booking;
65
+ }
66
+ const shift = shiftedSession(booking, now, window);
67
+ // 准点核销的偏移量为零,也要打标,避免下一张票改变这个时段。
68
+ changes.set(event, shift);
69
+ return {
70
+ ...booking,
71
+ ...shift,
72
+ metadata: {
73
+ ...booking.metadata,
74
+ is_change_by_redeem: 1
75
+ }
76
+ };
77
+ });
78
+ if (!changes.size) {
79
+ onSkip?.(alreadyMarked ? 'already_marked' : 'no_linked_booking');
80
+ return;
81
+ }
82
+ const vouchers = order.vouchers.map(voucher => {
83
+ const event = (0, _utils.redeemEventKey)(voucher?.schedule_event_id);
84
+ const shift = event && changes.get(event);
85
+ if (!shift) return voucher;
86
+ return {
87
+ ...voucher,
88
+ start_date: shift.start_date,
89
+ expire_date: shift.end_date,
90
+ start_time: shift.start_time,
91
+ end_time: shift.end_time
92
+ };
93
+ });
94
+ return {
95
+ vouchers,
96
+ bookings
97
+ };
98
+ }
99
+ function createArrivalLogger(logger, order, voucherIds) {
100
+ return (stage, details = {}, failed = false) => {
101
+ try {
102
+ logger?.addLog({
103
+ type: failed ? 'error' : 'info',
104
+ title: '[BookingTicket] updateTicketArrival',
105
+ metadata: {
106
+ stage,
107
+ order_id: order?.order_id,
108
+ external_sale_number: order?.external_sale_number,
109
+ voucher_ids: voucherIds,
110
+ ...details
111
+ }
112
+ });
113
+ } catch {
114
+ // 日志不可用时,核销和预约调时仍按原流程执行。
115
+ }
116
+ };
117
+ }
118
+ function buildArrivalCheckoutQuery(order, summary) {
119
+ const {
120
+ vouchers: _localVouchers,
121
+ ...payload
122
+ } = (0, _utils.buildSubmitPayload)({
123
+ tempOrder: order,
124
+ platform: order.platform,
125
+ businessCode: order.business_code,
126
+ type: order.type,
127
+ summary
128
+ });
129
+ return {
130
+ ...payload,
131
+ // 调时提交无需自动打印整单小票;Redeem & Print 由票券按钮发起打印。
132
+ small_ticket_data_flag: 0
133
+ };
134
+ }
135
+ function describeChangedBookings(before, after) {
136
+ const changes = [];
137
+ for (const [index, booking] of after.entries()) {
138
+ const previous = before[index];
139
+ if (booking === previous) continue;
140
+ changes.push({
141
+ schedule_event_id: booking.schedule_event_id,
142
+ previous_start: previous.start_time,
143
+ previous_end: previous.end_time,
144
+ start: booking.start_time,
145
+ end: booking.end_time
146
+ });
147
+ }
148
+ return changes;
149
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "0.10.83",
4
+ "version": "0.10.88",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",