@pisell/pisellos 2.3.129 → 2.3.131

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 (102) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +3 -1
  3. package/dist/modules/BusinessAvailability/index.d.ts +30 -0
  4. package/dist/modules/BusinessAvailability/index.js +204 -0
  5. package/dist/modules/FulfillmentTiming/index.d.ts +11 -0
  6. package/dist/modules/FulfillmentTiming/index.js +407 -0
  7. package/dist/modules/FulfillmentTiming/types.d.ts +67 -0
  8. package/dist/modules/FulfillmentTiming/types.js +1 -0
  9. package/dist/modules/OpenData/types.d.ts +8 -0
  10. package/dist/modules/Order/index.d.ts +11 -2
  11. package/dist/modules/Order/index.js +370 -253
  12. package/dist/modules/Order/pickupTiming.d.ts +46 -0
  13. package/dist/modules/Order/pickupTiming.js +53 -0
  14. package/dist/modules/Order/types.d.ts +13 -1
  15. package/dist/modules/Order/utils.js +16 -6
  16. package/dist/modules/Payment/index.js +9 -10
  17. package/dist/modules/Schedule/index.d.ts +8 -0
  18. package/dist/modules/Schedule/index.js +141 -39
  19. package/dist/modules/index.d.ts +1 -0
  20. package/dist/modules/index.js +1 -0
  21. package/dist/plugins/request.d.ts +7 -0
  22. package/dist/server/utils/small-ticket.d.ts +1 -85
  23. package/dist/server/utils/small-ticket.js +2 -2542
  24. package/dist/shared/payment/loadPaymentMethods.d.ts +9 -0
  25. package/dist/shared/payment/loadPaymentMethods.js +66 -0
  26. package/dist/shared/receipt/loadCustomerInvoiceLayout.d.ts +22 -0
  27. package/dist/shared/receipt/loadCustomerInvoiceLayout.js +142 -0
  28. package/dist/shared/receipt/small-ticket.d.ts +85 -0
  29. package/dist/shared/receipt/small-ticket.js +2576 -0
  30. package/dist/shared/sales/loadSalesOrderSnapshot.d.ts +9 -0
  31. package/dist/shared/sales/loadSalesOrderSnapshot.js +21 -0
  32. package/dist/solution/BaseSales/index.d.ts +28 -15
  33. package/dist/solution/BaseSales/index.js +1346 -1101
  34. package/dist/solution/BaseSales/pickupTiming.d.ts +43 -0
  35. package/dist/solution/BaseSales/pickupTiming.js +589 -0
  36. package/dist/solution/BaseSales/types.d.ts +11 -0
  37. package/dist/solution/BaseSales/utils/parseSalesResponse.js +3 -0
  38. package/dist/solution/BookingByStep/index.d.ts +1 -1
  39. package/dist/solution/BookingTicket/index.d.ts +2 -2
  40. package/dist/solution/BookingTicket/index.js +41 -13
  41. package/dist/solution/BookingTicket/utils/cartView.js +3 -1
  42. package/dist/solution/OrderInvoicePreview/index.d.ts +56 -0
  43. package/dist/solution/OrderInvoicePreview/index.js +269 -0
  44. package/dist/solution/UnifiedBookingSales/businessAvailability.d.ts +27 -0
  45. package/dist/solution/UnifiedBookingSales/businessAvailability.js +292 -0
  46. package/dist/solution/UnifiedBookingSales/index.d.ts +24 -4
  47. package/dist/solution/UnifiedBookingSales/index.js +953 -709
  48. package/dist/solution/UnifiedBookingSales/types.d.ts +2 -0
  49. package/dist/solution/index.d.ts +1 -0
  50. package/dist/solution/index.js +2 -1
  51. package/lib/index.d.ts +2 -0
  52. package/lib/index.js +21 -1
  53. package/lib/model/strategy/adapter/promotion/index.js +46 -1
  54. package/lib/modules/BusinessAvailability/index.d.ts +30 -0
  55. package/lib/modules/BusinessAvailability/index.js +146 -0
  56. package/lib/modules/FulfillmentTiming/index.d.ts +11 -0
  57. package/lib/modules/FulfillmentTiming/index.js +359 -0
  58. package/lib/modules/FulfillmentTiming/types.d.ts +67 -0
  59. package/lib/modules/FulfillmentTiming/types.js +5 -0
  60. package/lib/modules/OpenData/types.d.ts +8 -0
  61. package/lib/modules/Order/index.d.ts +11 -2
  62. package/lib/modules/Order/index.js +101 -14
  63. package/lib/modules/Order/pickupTiming.d.ts +46 -0
  64. package/lib/modules/Order/pickupTiming.js +61 -0
  65. package/lib/modules/Order/types.d.ts +13 -1
  66. package/lib/modules/Order/utils.js +12 -4
  67. package/lib/modules/Payment/index.js +3 -4
  68. package/lib/modules/Schedule/index.d.ts +8 -0
  69. package/lib/modules/Schedule/index.js +68 -12
  70. package/lib/modules/index.d.ts +1 -0
  71. package/lib/modules/index.js +11 -0
  72. package/lib/plugins/request.d.ts +7 -0
  73. package/lib/server/utils/small-ticket.d.ts +1 -85
  74. package/lib/server/utils/small-ticket.js +9 -2305
  75. package/lib/shared/payment/loadPaymentMethods.d.ts +9 -0
  76. package/lib/shared/payment/loadPaymentMethods.js +40 -0
  77. package/lib/shared/receipt/loadCustomerInvoiceLayout.d.ts +22 -0
  78. package/lib/shared/receipt/loadCustomerInvoiceLayout.js +86 -0
  79. package/lib/shared/receipt/small-ticket.d.ts +85 -0
  80. package/lib/shared/receipt/small-ticket.js +2342 -0
  81. package/lib/shared/sales/loadSalesOrderSnapshot.d.ts +9 -0
  82. package/lib/shared/sales/loadSalesOrderSnapshot.js +22 -0
  83. package/lib/solution/BaseSales/index.d.ts +28 -15
  84. package/lib/solution/BaseSales/index.js +161 -25
  85. package/lib/solution/BaseSales/pickupTiming.d.ts +43 -0
  86. package/lib/solution/BaseSales/pickupTiming.js +269 -0
  87. package/lib/solution/BaseSales/types.d.ts +11 -0
  88. package/lib/solution/BaseSales/utils/parseSalesResponse.js +3 -0
  89. package/lib/solution/BookingByStep/index.d.ts +1 -1
  90. package/lib/solution/BookingTicket/index.d.ts +2 -2
  91. package/lib/solution/BookingTicket/index.js +37 -4
  92. package/lib/solution/BookingTicket/utils/cartView.js +3 -1
  93. package/lib/solution/OrderInvoicePreview/index.d.ts +56 -0
  94. package/lib/solution/OrderInvoicePreview/index.js +192 -0
  95. package/lib/solution/UnifiedBookingSales/businessAvailability.d.ts +27 -0
  96. package/lib/solution/UnifiedBookingSales/businessAvailability.js +138 -0
  97. package/lib/solution/UnifiedBookingSales/index.d.ts +24 -4
  98. package/lib/solution/UnifiedBookingSales/index.js +184 -46
  99. package/lib/solution/UnifiedBookingSales/types.d.ts +2 -0
  100. package/lib/solution/index.d.ts +1 -0
  101. package/lib/solution/index.js +11 -0
  102. package/package.json +1 -1
@@ -0,0 +1,269 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.PickupTimingController = void 0;
7
+ var _lodashEs = require("lodash-es");
8
+ var _FulfillmentTiming = require("../../modules/FulfillmentTiming");
9
+ async function withTimeout(request) {
10
+ let timer;
11
+ try {
12
+ return await Promise.race([request, new Promise((_, reject) => {
13
+ timer = setTimeout(() => reject(new Error('Unable to load pickup times. Please try again.')), 30000);
14
+ })]);
15
+ } finally {
16
+ if (timer !== undefined) clearTimeout(timer);
17
+ }
18
+ }
19
+
20
+ /** Reuses runtime configuration and schedules; every calculation still uses the live clock. */
21
+ class PickupTimingController {
22
+ latest;
23
+ runtime;
24
+ writeSequence = 0;
25
+ constructor(host) {
26
+ this.host = host;
27
+ }
28
+ now() {
29
+ return this.host.now?.() ?? new Date();
30
+ }
31
+
32
+ /** A new solution context or an explicit settings refresh invalidates pending work too. */
33
+ invalidate() {
34
+ this.runtime = undefined;
35
+ this.latest = undefined;
36
+ this.writeSequence += 1;
37
+ }
38
+ assertCurrentRuntime(runtime) {
39
+ if (this.runtime !== runtime || runtime.scope !== this.host.getScope()) {
40
+ throw new Error('Store settings changed. Please try again.');
41
+ }
42
+ }
43
+ getRuntime() {
44
+ const scope = this.host.getScope();
45
+ if (this.runtime?.scope !== scope) {
46
+ this.latest = undefined;
47
+ this.runtime = {
48
+ scope
49
+ };
50
+ }
51
+ return this.runtime;
52
+ }
53
+ async loadConfig(runtime) {
54
+ if (runtime.config) return runtime.config;
55
+ if (!runtime.configRequest) {
56
+ const request = (async () => {
57
+ const config = (0, _FulfillmentTiming.normalizePickupTimingConfig)(await withTimeout(this.host.loadOpenData(false)));
58
+ this.assertCurrentRuntime(runtime);
59
+ runtime.config = config;
60
+ return config;
61
+ })();
62
+ runtime.configRequest = request;
63
+ }
64
+ const request = runtime.configRequest;
65
+ try {
66
+ return await request;
67
+ } finally {
68
+ if (runtime.configRequest === request) runtime.configRequest = undefined;
69
+ }
70
+ }
71
+ async loadSchedules(runtime, config) {
72
+ if (runtime.schedules) return runtime.schedules;
73
+ if (!runtime.scheduleRequest) {
74
+ const request = (async () => {
75
+ const schedule = this.host.getSchedule();
76
+ if (!schedule) throw new Error('Pickup schedule is unavailable. Please try again.');
77
+ // Reuse the catalog loaded by solution initialization, including its in-flight request.
78
+ await withTimeout(schedule.loadAllSchedule({
79
+ useCache: true
80
+ }));
81
+ this.assertCurrentRuntime(runtime);
82
+ const ids = [...new Set([...config.scheduleIds, ...(config.operatingHoursScheduleIds || [])])];
83
+ const schedules = (0, _lodashEs.cloneDeep)(schedule.getScheduleListByIds(ids) || []);
84
+ runtime.schedules = schedules;
85
+ return schedules;
86
+ })();
87
+ runtime.scheduleRequest = request;
88
+ }
89
+ const request = runtime.scheduleRequest;
90
+ try {
91
+ return await request;
92
+ } finally {
93
+ if (runtime.scheduleRequest === request) runtime.scheduleRequest = undefined;
94
+ }
95
+ }
96
+ async snapshot(includeSchedule, tolerateScheduleError = false) {
97
+ const runtime = this.getRuntime();
98
+ const config = await this.loadConfig(runtime);
99
+ this.assertCurrentRuntime(runtime);
100
+ let schedules = [];
101
+ let error;
102
+ if (includeSchedule && config.handoverModes.includes('pick_up') && config.timingMode !== 'asap_only' && config.scheduleIds.length) {
103
+ try {
104
+ schedules = await this.loadSchedules(runtime, config);
105
+ } catch (reason) {
106
+ if (!tolerateScheduleError) throw reason;
107
+ error = reason instanceof Error ? reason.message : 'Pickup schedule is unavailable. Please try again.';
108
+ }
109
+ }
110
+ this.assertCurrentRuntime(runtime);
111
+ const result = {
112
+ config,
113
+ timezone: this.host.getTimezone(),
114
+ schedules,
115
+ scope: runtime.scope,
116
+ error
117
+ };
118
+ this.latest = result;
119
+ return result;
120
+ }
121
+ async getAvailability(params = {}) {
122
+ // `force` remains accepted for older callers; refresh recomputes time using the runtime catalog.
123
+ const snapshot = await this.snapshot(true, true);
124
+ const now = this.now();
125
+ try {
126
+ return {
127
+ ...(0, _FulfillmentTiming.computePickupTimingAvailability)({
128
+ ...snapshot,
129
+ date: params.date,
130
+ now
131
+ }),
132
+ error: snapshot.error
133
+ };
134
+ } catch (reason) {
135
+ // Keep the handover selector usable when only Pickup's timezone is unavailable.
136
+ return {
137
+ config: snapshot.config,
138
+ timezone: snapshot.timezone,
139
+ now: now.toISOString(),
140
+ today: '',
141
+ maxDate: '',
142
+ date: params.date || '',
143
+ dates: [],
144
+ slots: [],
145
+ error: reason instanceof Error ? reason.message : 'Pickup times are unavailable. Please try again.'
146
+ };
147
+ }
148
+ }
149
+ getSelection() {
150
+ const order = this.host.getOrder();
151
+ const tempOrder = order.getTempOrder();
152
+ const booking = order.getPickupTimingBooking();
153
+ const config = this.latest?.scope === this.host.getScope() ? this.latest.config : undefined;
154
+ const storedServiceType = String(tempOrder?.metadata?.shop_service_data?.service_type || '');
155
+ const serviceType = config?.handoverModes.length ? config.handoverModes.includes(storedServiceType) ? storedServiceType : config.handoverModes[0] : storedServiceType;
156
+ const details = serviceType === 'pick_up' ? booking?.metadata.fulfillment_timing : undefined;
157
+ const mode = config?.timingMode === 'asap_only' ? 'asap' : config?.timingMode === 'scheduled_only' ? 'scheduled' : details?.mode ?? 'asap';
158
+ const sameMode = details?.mode === mode;
159
+ return {
160
+ serviceType,
161
+ mode,
162
+ source: mode === 'asap' ? 'asap' : sameMode && details?.source || 'schedule',
163
+ ...(sameMode && booking ? {
164
+ date: booking.start_date,
165
+ time: booking.start_time,
166
+ instant: details?.instant
167
+ } : {})
168
+ };
169
+ }
170
+ async validateSnapshot(selection) {
171
+ const snapshot = await this.snapshot(selection.serviceType === 'pick_up' && selection.mode === 'scheduled' && selection.source !== 'pos_manual');
172
+ const now = this.now();
173
+ const result = (0, _FulfillmentTiming.validatePickupTimingSelection)(selection, {
174
+ ...snapshot,
175
+ now,
176
+ allowManualOverride: this.host.isPos()
177
+ });
178
+ return {
179
+ snapshot,
180
+ now,
181
+ result
182
+ };
183
+ }
184
+ async validate(selection) {
185
+ return (await this.validateSnapshot(selection)).result;
186
+ }
187
+ async setSelection(selection, options = {}) {
188
+ const order = this.host.getOrder();
189
+ const tempOrder = order.ensureTempOrder();
190
+ const sequence = ++this.writeSequence;
191
+ const {
192
+ snapshot,
193
+ now,
194
+ result
195
+ } = await this.validateSnapshot(selection);
196
+ if (sequence !== this.writeSequence || order.getTempOrder() !== tempOrder || snapshot.scope !== this.host.getScope()) {
197
+ throw new Error('The order changed. Please choose the pickup time again.');
198
+ }
199
+ if (!result.valid) throw new Error(result.message || 'Please choose a valid pickup time.');
200
+ if (!snapshot.config.handoverModes.length) {
201
+ order.clearPickupTimingBooking();
202
+ return this.getSelection();
203
+ }
204
+ if (selection.serviceType !== 'pick_up') {
205
+ order.updateTempOrderServiceType(selection.serviceType);
206
+ return this.getSelection();
207
+ }
208
+ const slot = selection.mode === 'asap' ? (0, _FulfillmentTiming.getAsapPickupTiming)({
209
+ ...snapshot,
210
+ now
211
+ }) : result.slot;
212
+ if (!slot) throw new Error('Please choose a pickup time.');
213
+ // Validate everything before either field is changed; notify once after the combined update.
214
+ tempOrder.metadata = {
215
+ ...(tempOrder.metadata || {}),
216
+ shop_service_data: {
217
+ ...(tempOrder.metadata?.shop_service_data || {}),
218
+ service_type: 'pick_up'
219
+ }
220
+ };
221
+ order.setPickupTimingBooking({
222
+ mode: selection.mode,
223
+ source: selection.mode === 'asap' ? 'asap' : selection.source === 'pos_manual' ? 'pos_manual' : 'schedule',
224
+ date: slot.date,
225
+ time: slot.time,
226
+ instant: slot.instant,
227
+ timezone: snapshot.timezone,
228
+ frozen: options.frozen ?? false
229
+ });
230
+ return this.getSelection();
231
+ }
232
+
233
+ /** Called before a new checkout/payment; payment callbacks keep their already prepared appointment. */
234
+ async prepare(options = {}) {
235
+ const order = this.host.getOrder();
236
+ const tempOrder = order.getTempOrder();
237
+ const sequence = this.writeSequence;
238
+ if (order.getOrderIdentity()?.isSubmitted) return this.getSelection();
239
+ const booking = order.getPickupTimingBooking();
240
+ if (booking?.metadata.fulfillment_timing?.frozen) return this.getSelection();
241
+ // An actual payment callback must never revalidate or move the time after funds have been taken.
242
+ const paymentStatus = order.getTempOrder()?.payment_status;
243
+ if (paymentStatus === 'paid' || paymentStatus === 'partially_paid') {
244
+ if (booking?.metadata.fulfillment_timing) {
245
+ const detail = booking.metadata.fulfillment_timing;
246
+ order.setPickupTimingBooking({
247
+ ...detail,
248
+ date: booking.start_date,
249
+ time: booking.start_time,
250
+ frozen: true
251
+ });
252
+ }
253
+ return this.getSelection();
254
+ }
255
+ const snapshot = await this.snapshot(false);
256
+ if (order !== this.host.getOrder() || order.getTempOrder() !== tempOrder || sequence !== this.writeSequence) {
257
+ throw new Error('The order changed. Please choose the pickup time again.');
258
+ }
259
+ const selection = this.getSelection();
260
+ if (!snapshot.config.handoverModes.length) {
261
+ order.clearPickupTimingBooking();
262
+ return selection;
263
+ }
264
+ return this.setSelection(selection, {
265
+ frozen: options.freeze ?? false
266
+ });
267
+ }
268
+ }
269
+ exports.PickupTimingController = PickupTimingController;
@@ -4,6 +4,8 @@ import type { ScanOrderLogInput as BaseSalesLogInput, ScanOrderLoggerProviderCon
4
4
  import type { QuantityCheckResult, QuantityLimitResult } from '../../model/strategy/adapter/itemRule';
5
5
  import type { QuotationCustomerScopeInfo } from '../../modules/Quotation/types';
6
6
  import type { PaymentMethod } from '../../modules/Payment/types';
7
+ import type { OrderPaymentSource } from '../../modules/Order/types';
8
+ import type { SubmitPayloadEnhancer } from '../../modules/Order/utils';
7
9
  /**
8
10
  * BaseSales 流程 hook 后缀。
9
11
  * 完整事件名应由当前模块名动态拼接,避免多个实例共享固定事件 key。
@@ -27,6 +29,15 @@ export interface BaseSalesCashPaymentOptions {
27
29
  /** 指定现金支付方式;省略时使用默认 CASHMANUAL。 */
28
30
  paymentMethodId?: number | string;
29
31
  }
32
+ export interface BaseSalesSubmitSalesOrderParams {
33
+ payments?: OrderPaymentSource[];
34
+ paymentStatus?: BaseSalesPaymentStatus;
35
+ smallTicketDataFlag?: number;
36
+ confirmPendingVoucherPayments?: boolean;
37
+ enhancePayload?: SubmitPayloadEnhancer;
38
+ /** Create the order without executing payment; payment status comes from the server. */
39
+ paymentExecution?: 'deferred';
40
+ }
30
41
  export interface BaseSalesCashPaymentConfig {
31
42
  available: boolean;
32
43
  paymentMethod?: PaymentMethod;
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.parseSalesResponse = parseSalesResponse;
7
7
  var _orderCollectionIdentity = require("../../../modules/Order/utils/orderCollectionIdentity");
8
+ var _pickupTiming = require("../../../modules/Order/pickupTiming");
8
9
  /**
9
10
  * 把 `/order/sales/{id}` 响应(OrderData)解析为 ISalesDetail。
10
11
  *
@@ -64,6 +65,7 @@ function pickCustomer(raw) {
64
65
  */
65
66
  function isRootBooking(booking) {
66
67
  if (!booking || typeof booking !== 'object') return false;
68
+ if ((0, _pickupTiming.isFulfillmentTimingBooking)(booking)) return false;
67
69
  const parentId = booking.parent_id;
68
70
  if (parentId === 0 || parentId === null || parentId === undefined) return true;
69
71
  return false;
@@ -71,6 +73,7 @@ function isRootBooking(booking) {
71
73
  function indexBookingsByProductUid(bookings) {
72
74
  const result = {};
73
75
  for (const b of bookings) {
76
+ if ((0, _pickupTiming.isFulfillmentTimingBooking)(b)) continue;
74
77
  const uid = b && (b.product_uid || b.metadata?.product_uid) || '';
75
78
  if (!uid) continue;
76
79
  const key = String(uid);
@@ -326,7 +326,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
326
326
  date: string;
327
327
  status: string;
328
328
  week: string;
329
- weekNum: 0 | 2 | 1 | 3 | 4 | 5 | 6;
329
+ weekNum: 0 | 1 | 2 | 3 | 5 | 4 | 6;
330
330
  }[]>;
331
331
  submitTimeSlot(timeSlots: TimeSliceItem): void;
332
332
  private getScheduleDataByIds;
@@ -53,10 +53,10 @@ export declare class BookingTicketImpl extends BaseSalesImpl implements Module {
53
53
  * 在解决方案对外 ready 前准备 Invoice Document;失败只降级模板,不阻断销售。
54
54
  * 已由页面取得的 OpenData 直接交给模块接管,没有注入数据时再走 target-scoped 加载。
55
55
  */
56
- private prepareInvoiceTemplateAtSolutionReady;
56
+ protected prepareInvoiceTemplateAtSolutionReady(injectedOpenData?: OpenDataConfig): Promise<void>;
57
57
  protected getBookingTicketBusinessCode(): string | null;
58
58
  private getIdGeneratorPlugin;
59
- private loadOpenDataConfig;
59
+ protected loadOpenDataConfig(): Promise<OpenDataConfig | null>;
60
60
  getOpenData(): Promise<OpenDataConfig | null>;
61
61
  getInvoiceLayoutConfig(): Promise<InvoiceLayoutConfig>;
62
62
  getInvoiceTemplateSettings(): Promise<InvoiceTemplateSettings>;
@@ -1672,6 +1672,30 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
1672
1672
  };
1673
1673
  }
1674
1674
  try {
1675
+ // Capture before lookup/UI awaits, so a result cannot land in a new cart.
1676
+ // Unscoped POS Order modules return a no-op guard.
1677
+ const beforeScanCommit = this.store.order.createCartIntentCommitGuard('add_product');
1678
+ const beforeScanDialog = this.store.order.createCartIntentCommitGuard('add_product');
1679
+ const guardCallback = callback => callback ? (...args) => {
1680
+ beforeScanCommit();
1681
+ return callback(...args);
1682
+ } : undefined;
1683
+ const guardedBridge = bridge ? {
1684
+ ...bridge,
1685
+ confirmDetail: guardCallback(bridge.confirmDetail),
1686
+ confirmBookingEdit: guardCallback(bridge.confirmBookingEdit),
1687
+ applyPromotionCode: guardCallback(bridge.applyPromotionCode),
1688
+ openOrder: guardCallback(bridge.openOrder),
1689
+ requestCustomerSwitch: guardCallback(bridge.requestCustomerSwitch),
1690
+ openProductDetail: bridge.openProductDetail ? payload => {
1691
+ beforeScanDialog();
1692
+ return bridge.openProductDetail(payload);
1693
+ } : undefined,
1694
+ openBookingEdit: bridge.openBookingEdit ? payload => {
1695
+ beforeScanDialog();
1696
+ return bridge.openBookingEdit(payload);
1697
+ } : undefined
1698
+ } : undefined;
1675
1699
  const localSearch = v => this.store.products.findProductsByCodeOrBarcode(v);
1676
1700
  const scanCallback = (0, _handleScan.handleGlobalScan)(this.request, localSearch, this.getSubmitOrderSalesChannel());
1677
1701
  const raw = await scanCallback({
@@ -1687,7 +1711,10 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
1687
1711
  };
1688
1712
  }
1689
1713
  const result = await (0, _applyGlobalScan.applyGlobalScan)({
1690
- setOrderCustomer: customer => this.setOrderCustomer(customer),
1714
+ setOrderCustomer: customer => {
1715
+ beforeScanCommit();
1716
+ this.setOrderCustomer(customer);
1717
+ },
1691
1718
  getOrderCustomerSnapshot: () => this.getOrderCustomerSnapshot(),
1692
1719
  resolveCustomerById: customerId => this.resolveCustomerById(customerId),
1693
1720
  getBusinessCode: () => this.otherParams?.businessCode,
@@ -1695,10 +1722,16 @@ class BookingTicketImpl extends _BaseSales.BaseSalesImpl {
1695
1722
  decideAddProduct: (item, options) => this.decideAddProduct(item, options),
1696
1723
  decideAfterDetail: (cacheItem, options) => this.decideAfterDetail(cacheItem, options),
1697
1724
  transformDetailToProductAndBooking: input => this.transformDetailToProductAndBooking(input),
1698
- addProductToOrder: (product, booking) => this.addProductToOrder(product, booking),
1725
+ addProductToOrder: (product, booking) => {
1726
+ beforeScanCommit();
1727
+ return this.addProductToOrder(product, booking);
1728
+ },
1699
1729
  refreshWalletAssets: params => this.refreshWalletAssets(params),
1700
- scanWalletAsset: scanCode => this.scanWalletAsset(scanCode)
1701
- }, formatted, bridge);
1730
+ scanWalletAsset: scanCode => {
1731
+ beforeScanCommit();
1732
+ return this.scanWalletAsset(scanCode);
1733
+ }
1734
+ }, formatted, guardedBridge);
1702
1735
  bridge?.refresh?.();
1703
1736
  return result;
1704
1737
  } catch (error) {
@@ -8,12 +8,14 @@ exports.buildCustomerView = buildCustomerView;
8
8
  exports.indexBookingsByProductUid = indexBookingsByProductUid;
9
9
  exports.isWalkInCustomer = isWalkInCustomer;
10
10
  var _addTimeAvailability = require("./addTimeAvailability");
11
+ var _pickupTiming = require("../../../modules/Order/pickupTiming");
11
12
  /**
12
13
  * 仅按 booking.product_uid 建索引,避免发明 booking 与商品行之间的其它等价关系。
13
14
  */
14
15
  function indexBookingsByProductUid(bookings) {
15
16
  if (!Array.isArray(bookings) || bookings.length === 0) return {};
16
17
  return bookings.reduce((acc, booking) => {
18
+ if ((0, _pickupTiming.isFulfillmentTimingBooking)(booking)) return acc;
17
19
  const uid = booking?.product_uid;
18
20
  if (uid === undefined || uid === null || uid === '') return acc;
19
21
  const key = String(uid);
@@ -105,7 +107,7 @@ function isGiftProductLine(line) {
105
107
  function buildCartView(lines, bookings, options = {}) {
106
108
  const productLines = Array.isArray(lines) ? lines : [];
107
109
  const bookingList = Array.isArray(bookings) ? bookings : [];
108
- const childBookings = bookingList.filter(booking => booking.parent_id !== 0);
110
+ const childBookings = bookingList.filter(booking => booking.parent_id !== 0 && !(0, _pickupTiming.isFulfillmentTimingBooking)(booking));
109
111
  const bookingsByProductUid = indexBookingsByProductUid(childBookings);
110
112
  const linesByUid = indexProductsByUid(productLines);
111
113
  const addTimeLinesByBookingUid = indexAddTimeProductsByBookingUid(productLines);
@@ -0,0 +1,56 @@
1
+ import type { Module, ModuleOptions, PisellCore } from '../../types';
2
+ import { BaseModule } from '../../modules/BaseModule';
3
+ import type { InvoiceLayoutConfig } from '../../modules/OpenData';
4
+ import { type SmallTicketData } from '../../shared/receipt/small-ticket';
5
+ export interface OrderInvoicePreviewInput {
6
+ orderId: string | number;
7
+ tenantId: string | number;
8
+ shopId: string | number;
9
+ /** Changes on login/logout, without exposing credentials in state or cache keys. */
10
+ identity: string;
11
+ businessCode: string;
12
+ channel: string;
13
+ locale: string;
14
+ sourceRevision: string;
15
+ shop?: Record<string, any>;
16
+ }
17
+ export interface OrderInvoicePreviewResult {
18
+ identity: string;
19
+ sourceRevision: string;
20
+ generatedAt: string;
21
+ locale: string;
22
+ orderId: string | number;
23
+ source: Record<string, any>;
24
+ shop: Record<string, any>;
25
+ layout: InvoiceLayoutConfig;
26
+ smallTicketData: SmallTicketData;
27
+ }
28
+ export interface OrderInvoicePreviewState {
29
+ status: 'idle' | 'loading' | 'ready' | 'error';
30
+ result: OrderInvoicePreviewResult | null;
31
+ error: string | null;
32
+ }
33
+ /** Read-only, page-owned solution. No Order, Schedule, quotation or payment modules. */
34
+ export declare class OrderInvoicePreviewImpl extends BaseModule implements Module {
35
+ isSolution: boolean;
36
+ private request;
37
+ private state;
38
+ private listeners;
39
+ private generation;
40
+ private disposed;
41
+ private input?;
42
+ private activeKey;
43
+ private pending?;
44
+ private snapshotCache;
45
+ constructor(name?: string);
46
+ initialize(core: PisellCore, _options: ModuleOptions): void;
47
+ getState: () => OrderInvoicePreviewState;
48
+ subscribe: (listener: () => void) => (() => void);
49
+ private publish;
50
+ private getScope;
51
+ private loadContext;
52
+ private loadSource;
53
+ prepare(input: OrderInvoicePreviewInput): Promise<OrderInvoicePreviewResult>;
54
+ retry(): Promise<OrderInvoicePreviewResult>;
55
+ destroy(): void;
56
+ }
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.OrderInvoicePreviewImpl = void 0;
7
+ var _BaseModule = require("../../modules/BaseModule");
8
+ var _loadCustomerInvoiceLayout = require("../../shared/receipt/loadCustomerInvoiceLayout");
9
+ var _smallTicket = require("../../shared/receipt/small-ticket");
10
+ var _loadSalesOrderSnapshot = require("../../shared/sales/loadSalesOrderSnapshot");
11
+ var _loadPaymentMethods = require("../../shared/payment/loadPaymentMethods");
12
+ // Page-runtime cache shared by preview instances, scoped to host, shop and identity.
13
+ const contextCaches = new WeakMap();
14
+ /** Read-only, page-owned solution. No Order, Schedule, quotation or payment modules. */
15
+ class OrderInvoicePreviewImpl extends _BaseModule.BaseModule {
16
+ isSolution = true;
17
+ request;
18
+ state = {
19
+ status: 'idle',
20
+ result: null,
21
+ error: null
22
+ };
23
+ listeners = new Set();
24
+ generation = 0;
25
+ disposed = false;
26
+ input;
27
+ activeKey = '';
28
+ pending;
29
+ snapshotCache = new Map();
30
+ constructor(name = 'orderInvoicePreview') {
31
+ super(name);
32
+ }
33
+ initialize(core, _options) {
34
+ this.core = core;
35
+ const request = core.getPlugin('request');
36
+ if (!request) throw new Error('OrderInvoicePreview requires request plugin');
37
+ this.request = request;
38
+ }
39
+ getState = () => this.state;
40
+ subscribe = listener => {
41
+ this.listeners.add(listener);
42
+ return () => {
43
+ this.listeners.delete(listener);
44
+ };
45
+ };
46
+ publish(state) {
47
+ this.state = state;
48
+ this.listeners.forEach(listener => listener());
49
+ }
50
+ getScope(input) {
51
+ return JSON.stringify([input.tenantId, input.shopId, input.identity, input.businessCode, input.channel]);
52
+ }
53
+ loadContext(input) {
54
+ let cache = contextCaches.get(this.request);
55
+ if (!cache) {
56
+ cache = new Map();
57
+ contextCaches.set(this.request, cache);
58
+ }
59
+ const key = JSON.stringify([input.tenantId, input.shopId, input.identity, input.locale]);
60
+ const cached = cache.get(key);
61
+ if (cached) return cached;
62
+ const task = Promise.all([this.request.get('/shop/show', {}, {
63
+ manualErrorHandling: true,
64
+ skipErrorHandler: true
65
+ }), (0, _loadPaymentMethods.loadPaymentMethods)(this.request, {
66
+ transport: 'remote',
67
+ filterPaymentMethods: false
68
+ })]).then(([response, methods]) => {
69
+ const shop = response?.data;
70
+ if (!shop || typeof shop !== 'object' || Array.isArray(shop)) throw new Error('Invoice shop information is unavailable');
71
+ if (String(shop.id) !== String(input.shopId)) throw new Error('Invoice shop identity mismatch');
72
+ return {
73
+ shop,
74
+ methods
75
+ };
76
+ }).catch(error => {
77
+ if (cache.get(key) === task) cache.delete(key);
78
+ throw error;
79
+ });
80
+ cache.set(key, task);
81
+ return task;
82
+ }
83
+ loadSource(input) {
84
+ const key = JSON.stringify([this.getScope(input), input.orderId, input.sourceRevision]);
85
+ const cached = this.snapshotCache.get(key);
86
+ if (cached) return cached;
87
+ const task = (0, _loadSalesOrderSnapshot.loadSalesOrderSnapshot)(this.request, {
88
+ lookup: input.orderId,
89
+ transport: 'remote'
90
+ }).then(response => {
91
+ if (response?.code !== 200 || !response.data || typeof response.data !== 'object' || Array.isArray(response.data)) {
92
+ throw new Error(response?.message || 'Invoice order is unavailable');
93
+ }
94
+ const source = response.data;
95
+ if (source.order_id != null && String(source.order_id) !== String(input.orderId)) {
96
+ throw new Error('Invoice order identity mismatch');
97
+ }
98
+ return source;
99
+ }).catch(error => {
100
+ if (this.snapshotCache.get(key) === task) this.snapshotCache.delete(key);
101
+ throw error;
102
+ });
103
+ this.snapshotCache.set(key, task);
104
+ return task;
105
+ }
106
+ prepare(input) {
107
+ if (this.disposed) return Promise.reject(new Error('Invoice preview disposed'));
108
+ const currentShop = this.core.getPlugin('app')?.getData?.()?.('shop_id');
109
+ if (currentShop != null && String(currentShop) !== String(input.shopId)) {
110
+ return Promise.reject(new Error('Invoice shop changed'));
111
+ }
112
+ const key = JSON.stringify([this.getScope(input), input.orderId, input.sourceRevision, input.locale]);
113
+ if (key === this.activeKey) {
114
+ if (this.pending) return this.pending;
115
+ if (this.state.status === 'ready' && this.state.result) return Promise.resolve(this.state.result);
116
+ }
117
+ if (this.input && this.getScope(this.input) !== this.getScope(input)) this.snapshotCache.clear();
118
+ this.input = input;
119
+ this.activeKey = key;
120
+ const generation = ++this.generation;
121
+ this.publish({
122
+ status: 'loading',
123
+ result: null,
124
+ error: null
125
+ });
126
+ const task = (async () => {
127
+ const [snapshot, context, layout] = await Promise.all([this.loadSource(input), this.loadContext(input), (0, _loadCustomerInvoiceLayout.loadCustomerInvoiceLayout)(this.request, input)]);
128
+ const source = (0, _loadPaymentMethods.withPaymentMethodNames)(snapshot, context.methods);
129
+ const getData = this.core.getPlugin('app')?.getData?.();
130
+ if (getData?.('shop_id') != null && String(getData('shop_id')) !== String(input.shopId)) throw new Error('Invoice shop changed');
131
+ const coreData = getData?.('core');
132
+ const shop = {
133
+ ...(coreData?.core?.shop || coreData?.shop || {}),
134
+ ...(getData?.('shop_info') || {}),
135
+ ...input.shop,
136
+ ...context.shop,
137
+ ...(getData?.('tax_country_code') ? {
138
+ tax_country_code: getData('tax_country_code')
139
+ } : {})
140
+ };
141
+ if (generation !== this.generation || this.disposed) throw new Error('Invoice request superseded');
142
+ const requestedLocale = input.locale.toLowerCase().replace(/_/g, '-');
143
+ const locale = requestedLocale.startsWith('zh-tw') || requestedLocale.startsWith('zh-hk') ? 'zh_HK' : requestedLocale.startsWith('zh') ? 'zh_CN' : requestedLocale.startsWith('ja') ? 'ja' : requestedLocale.startsWith('pt') ? 'pt' : 'en';
144
+ const result = {
145
+ identity: key,
146
+ orderId: input.orderId,
147
+ sourceRevision: input.sourceRevision,
148
+ generatedAt: new Date().toISOString(),
149
+ locale,
150
+ source,
151
+ shop,
152
+ layout,
153
+ smallTicketData: (0, _smallTicket.buildSmallTicketData)({
154
+ order: source,
155
+ shopInfo: shop,
156
+ locales: [locale]
157
+ })
158
+ };
159
+ this.publish({
160
+ status: 'ready',
161
+ result,
162
+ error: null
163
+ });
164
+ return result;
165
+ })().catch(error => {
166
+ if (generation === this.generation && !this.disposed) {
167
+ this.publish({
168
+ status: 'error',
169
+ result: null,
170
+ error: error instanceof Error ? error.message : String(error)
171
+ });
172
+ }
173
+ throw error;
174
+ }).finally(() => {
175
+ if (this.pending === task) this.pending = undefined;
176
+ });
177
+ this.pending = task;
178
+ return task;
179
+ }
180
+ retry() {
181
+ if (!this.input) return Promise.reject(new Error('Invoice input is missing'));
182
+ return this.prepare(this.input);
183
+ }
184
+ destroy() {
185
+ this.disposed = true;
186
+ this.generation++;
187
+ this.listeners.clear();
188
+ this.snapshotCache.clear();
189
+ if (this.core.getModule(this.name) === this) super.destroy();
190
+ }
191
+ }
192
+ exports.OrderInvoicePreviewImpl = OrderInvoicePreviewImpl;