@pisell/pisellos 0.10.94 → 0.10.96

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 (39) hide show
  1. package/dist/modules/OpenData/index.d.ts +13 -0
  2. package/dist/modules/OpenData/index.js +243 -93
  3. package/dist/modules/Product/index.d.ts +1 -1
  4. package/dist/modules/SalesSummary/index.d.ts +3 -0
  5. package/dist/modules/SalesSummary/index.js +104 -56
  6. package/dist/server/index.d.ts +7 -0
  7. package/dist/server/index.js +1036 -598
  8. package/dist/server/modules/order/index.d.ts +1 -0
  9. package/dist/server/modules/order/index.js +51 -51
  10. package/dist/solution/BookingByStep/index.d.ts +2 -2
  11. package/dist/solution/BookingTicket/utils/redeemArrival.d.ts +8 -8
  12. package/dist/solution/Sales/index.d.ts +2 -1
  13. package/dist/solution/Sales/index.js +154 -48
  14. package/dist/solution/Sales/types.d.ts +12 -0
  15. package/dist/solution/Sales/types.js +2 -0
  16. package/dist/solution/UnifiedBookingSales/index.d.ts +1 -0
  17. package/dist/solution/UnifiedBookingSales/index.js +48 -49
  18. package/dist/solution/UnifiedBookingSales/sessionResourceCache.d.ts +4 -0
  19. package/dist/solution/UnifiedBookingSales/sessionResourceCache.js +91 -14
  20. package/lib/modules/OpenData/index.d.ts +13 -0
  21. package/lib/modules/OpenData/index.js +97 -18
  22. package/lib/modules/Product/index.d.ts +1 -1
  23. package/lib/modules/SalesSummary/index.d.ts +3 -0
  24. package/lib/modules/SalesSummary/index.js +36 -15
  25. package/lib/server/index.d.ts +7 -0
  26. package/lib/server/index.js +240 -18
  27. package/lib/server/modules/order/index.d.ts +1 -0
  28. package/lib/server/modules/order/index.js +4 -3
  29. package/lib/solution/BookingByStep/index.d.ts +2 -2
  30. package/lib/solution/BookingTicket/utils/redeemArrival.d.ts +8 -8
  31. package/lib/solution/Sales/index.d.ts +2 -1
  32. package/lib/solution/Sales/index.js +53 -0
  33. package/lib/solution/Sales/types.d.ts +12 -0
  34. package/lib/solution/Sales/types.js +1 -0
  35. package/lib/solution/UnifiedBookingSales/index.d.ts +1 -0
  36. package/lib/solution/UnifiedBookingSales/index.js +11 -10
  37. package/lib/solution/UnifiedBookingSales/sessionResourceCache.d.ts +4 -0
  38. package/lib/solution/UnifiedBookingSales/sessionResourceCache.js +69 -4
  39. package/package.json +1 -1
@@ -120,6 +120,13 @@ function isLegacyInvoiceTemplate(value) {
120
120
  const numericLike = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
121
121
  return !numericLike.test(normalized);
122
122
  }
123
+ function readInvoiceShopScope(app) {
124
+ const getData = app?.getData?.();
125
+ return {
126
+ shopId: String(getData?.('shop_id') ?? '').trim(),
127
+ tenantId: String(getData?.('tenant_id') ?? '').trim()
128
+ };
129
+ }
123
130
  class OpenDataModule extends _BaseModule.BaseModule {
124
131
  defaultName = 'openData';
125
132
  defaultVersion = '1.0.0';
@@ -133,6 +140,9 @@ class OpenDataModule extends _BaseModule.BaseModule {
133
140
  otherParams = {};
134
141
  fetchRevision = 0;
135
142
  invoiceTemplateCacheRevision = 0;
143
+ // Cloud printing only caches successful resolutions. Regular sales screens
144
+ // deliberately retain DEFAULT after a failed Document lookup.
145
+ cloudInvoiceTemplates = new Map();
136
146
  invoiceTemplateDocumentCache = new Map();
137
147
  invoiceTemplateDocumentInFlight = new Map();
138
148
  constructor(name, version) {
@@ -182,22 +192,7 @@ class OpenDataModule extends _BaseModule.BaseModule {
182
192
  }
183
193
  async fetchOpenData(params) {
184
194
  const fetchRevision = ++this.fetchRevision;
185
- const getData = this.appPlugin?.getData?.();
186
- const shopId = getData?.('shop_id');
187
- if (!shopId) throw new Error('[OpenDataModule] 无法获取 shop_id');
188
- const tenantId = getData?.('tenant_id');
189
- const headers = {};
190
- if (tenantId) headers['Tenant-Id'] = String(tenantId);
191
- const response = await this.request.post(`/open/my-pisell/${shopId}/setting`, {
192
- scope: params.scope,
193
- target: params.target,
194
- section_code: params.section_code
195
- }, {
196
- pisell2: true,
197
- isPisell2: true,
198
- prefix: false,
199
- headers
200
- });
195
+ const response = await this.requestOpenData(params, readInvoiceShopScope(this.appPlugin));
201
196
  if (response?.status === false) {
202
197
  throw new Error(response?.message || '获取 OpenData 配置失败');
203
198
  }
@@ -211,6 +206,82 @@ class OpenDataModule extends _BaseModule.BaseModule {
211
206
  }
212
207
  return data;
213
208
  }
209
+ requestOpenData(params, scope, background = false) {
210
+ if (!scope.shopId) throw new Error('[OpenDataModule] 无法获取 shop_id');
211
+ return this.request.post(`/open/my-pisell/${encodeURIComponent(scope.shopId)}/setting`, {
212
+ scope: params.scope,
213
+ target: params.target,
214
+ section_code: params.section_code
215
+ }, {
216
+ pisell2: true,
217
+ isPisell2: true,
218
+ prefix: false,
219
+ headers: scope.tenantId ? {
220
+ 'Tenant-Id': scope.tenantId
221
+ } : {},
222
+ ...(background ? {
223
+ customToast: () => {},
224
+ manualErrorHandling: true,
225
+ skipErrorHandler: true
226
+ } : {})
227
+ });
228
+ }
229
+
230
+ /** Bind every stage of a cloud print to the same authenticated shop and cache generation. */
231
+ captureCloudInvoiceScope(expectedShopId) {
232
+ const scope = readInvoiceShopScope(this.appPlugin);
233
+ if (!scope.shopId || scope.shopId !== String(expectedShopId).trim()) {
234
+ throw new Error('Cloud Invoice shop does not match the active shop');
235
+ }
236
+ const revision = this.invoiceTemplateCacheRevision;
237
+ return {
238
+ ...scope,
239
+ assertCurrent: () => {
240
+ const current = readInvoiceShopScope(this.appPlugin);
241
+ if (revision !== this.invoiceTemplateCacheRevision || current.shopId !== scope.shopId || current.tenantId !== scope.tenantId) {
242
+ throw new Error('Cloud Invoice shop context changed');
243
+ }
244
+ }
245
+ };
246
+ }
247
+ async loadCloudInvoiceTemplate(target, scope) {
248
+ scope.assertCurrent();
249
+ const key = JSON.stringify([scope.tenantId, scope.shopId, target]);
250
+ const existing = this.cloudInvoiceTemplates.get(key);
251
+ if (existing && existing.expiresAt > Date.now()) return existing.request;
252
+ const request = this.fetchCloudInvoiceTemplate(target, scope);
253
+ const entry = {
254
+ request,
255
+ expiresAt: Infinity
256
+ };
257
+ this.cloudInvoiceTemplates.set(key, entry);
258
+ try {
259
+ const settings = await request;
260
+ scope.assertCurrent();
261
+ entry.expiresAt = Date.now() + 5 * 60 * 1000;
262
+ return settings;
263
+ } catch (error) {
264
+ if (this.cloudInvoiceTemplates.get(key) === entry) this.cloudInvoiceTemplates.delete(key);
265
+ throw error;
266
+ }
267
+ }
268
+ async fetchCloudInvoiceTemplate(target, scope) {
269
+ const response = await this.requestOpenData({
270
+ scope: 'board',
271
+ target,
272
+ section_code: ['documents']
273
+ }, scope, true);
274
+ scope.assertCurrent();
275
+ if (response?.status !== true || response.code !== 200 || !isRecord(response.data)) {
276
+ throw new Error(response?.message || 'Cloud Invoice settings unavailable');
277
+ }
278
+ const raw = response.data['documents.invoice_template'];
279
+ const documentId = resolveInvoiceDocumentId(raw);
280
+ if (documentId) return this.fetchInvoiceTemplateDocument(documentId, true);
281
+ if (raw == null || typeof raw === 'string' && !raw.trim()) return (0, _utils.getDefaultInvoiceTemplateSettings)();
282
+ if (isLegacyInvoiceTemplate(raw)) return (0, _utils.normalizeInvoiceTemplateSettings)(response.data);
283
+ throw new Error('Cloud Invoice template identifier is invalid');
284
+ }
214
285
  getOpenData() {
215
286
  return this.store.data;
216
287
  }
@@ -326,14 +397,18 @@ class OpenDataModule extends _BaseModule.BaseModule {
326
397
  const getData = this.appPlugin?.getData?.();
327
398
  return JSON.stringify([getData?.('tenant_id') ?? null, getData?.('shop_id') ?? null, target, documentId]);
328
399
  }
329
- async fetchInvoiceTemplateDocument(documentId) {
400
+ async fetchInvoiceTemplateDocument(documentId, strict = false) {
330
401
  const response = await this.request.get(`/document:get?filterByTk=${encodeURIComponent(documentId)}`, {}, {
331
402
  isNocobase: true,
332
403
  prefix: false,
333
404
  headers: {
334
405
  'x-data-source': 'pisell2'
335
406
  },
336
- customToast: () => {}
407
+ customToast: () => {},
408
+ ...(strict ? {
409
+ manualErrorHandling: true,
410
+ skipErrorHandler: true
411
+ } : {})
337
412
  });
338
413
  const document = response?.data;
339
414
  if (!document || resolveInvoiceDocumentId(document.id) !== documentId) {
@@ -345,6 +420,9 @@ class OpenDataModule extends _BaseModule.BaseModule {
345
420
  if (!isRecord(document.data) || !isRecord(document.data.template_settings)) {
346
421
  throw new Error(`Invoice Document ${documentId} 缺少 template_settings`);
347
422
  }
423
+ if (strict && (typeof document.data.template_settings.template !== 'string' || !document.data.template_settings.template.trim())) {
424
+ throw new Error(`Invoice Document ${documentId} 缺少 template`);
425
+ }
348
426
  return (0, _utils.normalizeRawInvoiceTemplateSettings)(document.data.template_settings);
349
427
  }
350
428
  logInvoiceTemplateDocumentFallback(error, target, documentId) {
@@ -362,6 +440,7 @@ class OpenDataModule extends _BaseModule.BaseModule {
362
440
  clearCache() {
363
441
  this.fetchRevision += 1;
364
442
  this.invoiceTemplateCacheRevision += 1;
443
+ this.cloudInvoiceTemplates.clear();
365
444
  this.invoiceTemplateDocumentCache.clear();
366
445
  this.invoiceTemplateDocumentInFlight.clear();
367
446
  this.store.data = null;
@@ -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" | "normal" | "session";
52
+ getProductType(): "normal" | "duration" | "session";
53
53
  }
@@ -11,6 +11,7 @@ export declare class SalesSummaryModule extends BaseModule implements Module, Sa
11
11
  private surchargeListModuleName;
12
12
  private otherParams;
13
13
  private surchargeListChannel;
14
+ private surchargeLoads;
14
15
  constructor(name?: string, version?: string);
15
16
  initialize(core: PisellCore, options: ModuleOptions): Promise<void>;
16
17
  /**
@@ -22,6 +23,8 @@ export declare class SalesSummaryModule extends BaseModule implements Module, Sa
22
23
  updateOtherParams(params: Record<string, any>): Promise<void>;
23
24
  private resolveChannel;
24
25
  getSurchargeList(channel?: string): Promise<void>;
26
+ private loadSurcharges;
27
+ private fetchSurcharges;
25
28
  private getAppData;
26
29
  private getTaxConfig;
27
30
  getSummary(params: {
@@ -38,6 +38,7 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
38
38
  surchargeListModuleName = 'surchargeList';
39
39
  otherParams = {};
40
40
  surchargeListChannel = DEFAULT_SURCHARGE_CHANNEL;
41
+ surchargeLoads = new Map();
41
42
  constructor(name, version) {
42
43
  super(name, version);
43
44
  }
@@ -47,6 +48,7 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
47
48
  this.appPlugin = this.core.getPlugin('app');
48
49
  this.request = this.core.getPlugin('request');
49
50
  this.otherParams = options.otherParams || {};
51
+ this.surchargeLoads = new Map();
50
52
  this.store.surchargeList = options.initialState?.surchargeList || [];
51
53
  this.store.summary = options.initialState?.summary || (0, _utils.createEmptySalesSummary)();
52
54
  this.surchargeListModuleName = this.otherParams?.surchargeListModuleName || 'surchargeList';
@@ -70,10 +72,11 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
70
72
  const previousChannel = this.resolveChannel();
71
73
  const nextSurchargeListModuleName = params?.surchargeListModuleName || 'surchargeList';
72
74
  const nextChannel = this.resolveChannel(params);
73
- const shouldReload = nextSurchargeListModuleName !== this.surchargeListModuleName || nextChannel !== previousChannel;
75
+ const sourceChanged = nextSurchargeListModuleName !== this.surchargeListModuleName || (params?.shopId ?? params?.shop_id) !== (this.otherParams.shopId ?? this.otherParams.shop_id) || (params?.tenantId ?? params?.tenant_id) !== (this.otherParams.tenantId ?? this.otherParams.tenant_id);
74
76
  this.otherParams = params || {};
75
77
  this.surchargeListModuleName = nextSurchargeListModuleName;
76
- if (shouldReload) {
78
+ if (sourceChanged) this.surchargeLoads = new Map();
79
+ if (sourceChanged || nextChannel !== previousChannel) {
77
80
  await this.getSurchargeList(nextChannel);
78
81
  }
79
82
  }
@@ -81,14 +84,33 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
81
84
  return params?.channel || DEFAULT_SURCHARGE_CHANNEL;
82
85
  }
83
86
  async getSurchargeList(channel = this.resolveChannel()) {
87
+ await this.loadSurcharges(channel);
88
+ }
89
+ loadSurcharges(channel) {
90
+ this.surchargeListChannel = channel;
91
+ const loads = this.surchargeLoads;
92
+ const pending = loads.get(channel);
93
+ if (pending) return pending;
94
+
95
+ // The core exposes the summary module while initialization is still pending.
96
+ // All calculations for this channel must wait for the same configuration, even when it is empty.
97
+ const load = this.fetchSurcharges(channel).then(list => {
98
+ loads.delete(channel);
99
+ if (loads === this.surchargeLoads && channel === this.surchargeListChannel) {
100
+ this.store.surchargeList = list;
101
+ }
102
+ return list;
103
+ });
104
+ loads.set(channel, load);
105
+ return load;
106
+ }
107
+ async fetchSurcharges(channel) {
84
108
  try {
85
109
  const surchargeListModule = this.core.getModule(this.surchargeListModuleName);
86
110
  if (surchargeListModule?.getSurchargeList) {
87
- this.store.surchargeList = await surchargeListModule.getSurchargeList({
111
+ return await surchargeListModule.getSurchargeList({
88
112
  channel
89
113
  });
90
- this.surchargeListChannel = channel;
91
- return;
92
114
  }
93
115
  const surchargeList = await this.request.get('/order/custom-surcharge/available/v2', {
94
116
  channel,
@@ -96,12 +118,10 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
96
118
  is_assemble_schedule_data: 1,
97
119
  with: ['relationSchedule']
98
120
  });
99
- this.store.surchargeList = surchargeList?.data || [];
100
- this.surchargeListChannel = channel;
121
+ return surchargeList?.data || [];
101
122
  } catch (error) {
102
123
  console.warn('[SalesSummaryModule] 加载附加费配置失败', error);
103
- this.store.surchargeList = [];
104
- this.surchargeListChannel = channel;
124
+ return [];
105
125
  }
106
126
  }
107
127
  getAppData(key) {
@@ -130,14 +150,13 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
130
150
  virtualSettlementMode = false
131
151
  } = params;
132
152
  const summaryChannel = channel || this.resolveChannel();
133
- if (summaryChannel !== this.surchargeListChannel) {
134
- await this.getSurchargeList(summaryChannel);
135
- }
153
+ const loads = this.surchargeLoads;
154
+ const surchargeList = loads.has(summaryChannel) || summaryChannel !== this.surchargeListChannel ? await this.loadSurcharges(summaryChannel) : this.store.surchargeList;
136
155
  const taxConfig = this.getTaxConfig();
137
156
  const fatherModuleName = this.otherParams?.fatherModule || this.name.replace(/_salesSummary$/, '');
138
157
  const scheduleModuleName = `${fatherModuleName}_schedule`;
139
158
  const summarySchedule = this.core.getModule(scheduleModuleName);
140
- const needScheduleIds = (this.store.surchargeList?.map(item => item.available_schedule_ids)?.flat() || []).filter(id => id !== undefined && id !== null && id !== '');
159
+ const needScheduleIds = (surchargeList?.map(item => item.available_schedule_ids)?.flat() || []).filter(id => id !== undefined && id !== null && id !== '');
141
160
  const scheduleList = needScheduleIds.length > 0 ? summarySchedule?.getScheduleListByIds(needScheduleIds) : [];
142
161
  const scheduleById = {};
143
162
  if (Array.isArray(scheduleList)) {
@@ -149,7 +168,7 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
149
168
  products,
150
169
  isPriceIncludeTax: isPriceIncludeTax ?? taxConfig.isPriceIncludeTax ?? 1,
151
170
  taxRate: taxRate ?? taxConfig.taxRate,
152
- surchargeList: this.store.surchargeList,
171
+ surchargeList,
153
172
  scheduleById,
154
173
  isInScheduleByDate: _Schedule.ScheduleModule.isInScheduleByDate,
155
174
  shopDiscount,
@@ -161,7 +180,9 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
161
180
  tax_rate: taxRate ?? taxConfig.taxRate,
162
181
  tax_country_code: taxConfig.taxCountryCode || ''
163
182
  };
164
- this.store.summary = summaryWithTaxMeta;
183
+ if (loads === this.surchargeLoads && summaryChannel === this.surchargeListChannel) {
184
+ this.store.summary = summaryWithTaxMeta;
185
+ }
165
186
  return summaryWithTaxMeta;
166
187
  }
167
188
  }
@@ -66,6 +66,7 @@ declare class Server {
66
66
  private localPaymentUpdateQueues;
67
67
  private paymentIdentityRefreshes;
68
68
  private receiptFulfillmentConfigInFlight;
69
+ private cloudInvoiceSubmissions;
69
70
  private floorPlanQuerySubscribers;
70
71
  private moduleRegistry;
71
72
  constructor(core: PisellCore);
@@ -547,8 +548,14 @@ declare class Server {
547
548
  private shouldLookupLocalPrintOrder;
548
549
  private getLocalPrintOrderLookup;
549
550
  private mergeLocalPrintOrderInput;
551
+ private getCloudInvoiceDevice;
552
+ private assertCloudInvoiceContext;
553
+ private loadCloudInvoiceOrder;
554
+ private resolveCloudOrderInvoice;
555
+ private handleCloudOrderInvoice;
550
556
  private handleLocalPrintOrder;
551
557
  private normalizeRequestedReceiptLocales;
558
+ private rebuildOrderReceipt;
552
559
  private handleLocalOrderReceiptSnapshot;
553
560
  private handleMachinecodeBatchMeta;
554
561
  private resolveMachinecodeBatchMetadataLookup;
@@ -126,6 +126,7 @@ class Server {
126
126
  localPaymentUpdateQueues = new Map();
127
127
  paymentIdentityRefreshes = new Map();
128
128
  receiptFulfillmentConfigInFlight = new Map();
129
+ cloudInvoiceSubmissions = new Map();
129
130
  floorPlanQuerySubscribers = new Map();
130
131
 
131
132
  // 模块注册表 - 定义所有可用的模块配置
@@ -1387,6 +1388,18 @@ class Server {
1387
1388
  method: 'post',
1388
1389
  path: '/shop/local/print-order',
1389
1390
  handler: this.handleLocalPrintOrder.bind(this)
1391
+ }, {
1392
+ method: 'post',
1393
+ path: '/shop/local/cloud-order-invoice/lookup',
1394
+ handler: ({
1395
+ data
1396
+ }) => this.handleCloudOrderInvoice(data, false)
1397
+ }, {
1398
+ method: 'post',
1399
+ path: '/shop/local/cloud-order-invoice/submit',
1400
+ handler: ({
1401
+ data
1402
+ }) => this.handleCloudOrderInvoice(data, true)
1390
1403
  }, {
1391
1404
  method: 'post',
1392
1405
  path: '/shop/local/order-receipt-snapshot',
@@ -4133,6 +4146,209 @@ class Server {
4133
4146
  external_sale_number: localOrder.external_sale_number ?? definedInput.external_sale_number ?? definedInput.externalSaleNumber
4134
4147
  };
4135
4148
  }
4149
+ async getCloudInvoiceDevice(shopId) {
4150
+ const readDevice = this.getAppData('async_iot_device_info');
4151
+ const iot = await readDevice?.();
4152
+ if (iot?.shop_id != null && String(iot.shop_id) !== shopId) {
4153
+ throw new Error('Cloud invoice device belongs to another shop');
4154
+ }
4155
+ const iotId = String(iot?.id || '').trim();
4156
+ const fullNumber = String(iot?.number || !iotId && this.getAppData('device_id') || '').trim();
4157
+ if (fullNumber && fullNumber !== '0') {
4158
+ return {
4159
+ id: fullNumber,
4160
+ target: iot?.short_number || fullNumber.slice(-2)
4161
+ };
4162
+ }
4163
+ if (iotId && iotId !== '0') return {
4164
+ id: 'iot-id:' + iotId,
4165
+ target: iot?.short_number || iotId
4166
+ };
4167
+ throw new Error('Cloud invoice device is unavailable');
4168
+ }
4169
+ assertCloudInvoiceContext(context) {
4170
+ if (String(this.getAppData('shop_id') ?? '') !== context.shopId || String(this.getAppData('tenant_id') ?? '') !== context.tenantId) {
4171
+ throw new Error('Cloud invoice shop context changed');
4172
+ }
4173
+ }
4174
+ async loadCloudInvoiceOrder(context) {
4175
+ if (!this.order) throw new Error('Cloud invoice order service is unavailable');
4176
+ const {
4177
+ orderId,
4178
+ shopId
4179
+ } = context;
4180
+ const hasReceiptDetail = order => {
4181
+ // Use the same amount fields as the receipt builder, including historical
4182
+ // top-level amounts. Zero is a valid total; a missing total in a list row is not.
4183
+ const total = [order.summary?.expect_amount, order.expect_amount, order.summary?.total_amount, order.total_amount].find(value => value != null && value !== '');
4184
+ return typeof order.business_code === 'string' && !!order.business_code.trim() && (typeof total === 'number' || typeof total === 'string' && !!total.trim()) && Number.isFinite(Number(total)) && (Array.isArray(order.products) || Array.isArray(order.bookings));
4185
+ };
4186
+ const local = await this.order.getLocalOrderByLookup(orderId, {
4187
+ exactOrderId: true
4188
+ });
4189
+ this.assertCloudInvoiceContext(context);
4190
+ if (local && String(local.order_id) === orderId) {
4191
+ if (local.shop_id != null && String(local.shop_id) !== shopId) {
4192
+ throw new Error('Cloud invoice order belongs to another shop');
4193
+ }
4194
+ if (String(local.shop_id) === shopId && hasReceiptDetail(local)) return local;
4195
+ }
4196
+
4197
+ // The generic detail route also matches short receipt numbers. Validate the
4198
+ // backend identity and live shop BEFORE its result enters the shared store.
4199
+ const result = await this.fetchAndPersistSalesOrderByLookup(orderId, {
4200
+ with: ['all']
4201
+ }, 'cloudOrderInvoice', undefined, fresh => {
4202
+ this.assertCloudInvoiceContext(context);
4203
+ if (String(fresh.order_id) !== orderId || fresh.shop_id != null && String(fresh.shop_id) !== shopId || !hasReceiptDetail(fresh)) {
4204
+ throw new Error('Cloud invoice order identity or detail is invalid');
4205
+ }
4206
+ // Some older shop-authenticated detail responses omit shop_id.
4207
+ return fresh.shop_id == null ? {
4208
+ ...fresh,
4209
+ shop_id: Number(shopId)
4210
+ } : fresh;
4211
+ });
4212
+ this.assertCloudInvoiceContext(context);
4213
+ const saved = result.order;
4214
+ if (!saved || String(saved.order_id) !== orderId || String(saved.shop_id) !== shopId || !hasReceiptDetail(saved)) {
4215
+ throw new Error(result.message || 'Cloud invoice order detail is unavailable');
4216
+ }
4217
+ return saved;
4218
+ }
4219
+ async resolveCloudOrderInvoice(context, input, submit) {
4220
+ const deviceTask = this.getDeviceTaskPlugin();
4221
+ if (!deviceTask?.findByIdempotencyKey || !deviceTask.dispatch) {
4222
+ throw new Error('Cloud invoice task service is unavailable');
4223
+ }
4224
+ const prior = await deviceTask.findByIdempotencyKey(context.taskKey);
4225
+ this.assertCloudInvoiceContext(context);
4226
+ if (prior) {
4227
+ if (!prior.uuid || String(prior.payload?.data?.order_id) !== context.orderId || prior.payload?.channel !== context.channel) {
4228
+ throw new Error('Cloud invoice message UUID conflicts with another task');
4229
+ }
4230
+ // Acceptance transfers ownership to DeviceTask, including its retry lifecycle.
4231
+ return {
4232
+ task_uuid: prior.uuid
4233
+ };
4234
+ }
4235
+ const order = await this.loadCloudInvoiceOrder(context);
4236
+ const businessCode = order.business_code.trim();
4237
+ if (!submit) return {
4238
+ business_code: businessCode,
4239
+ device_id: context.deviceId
4240
+ };
4241
+ if (input.business_code !== businessCode || typeof input.template_settings?.template !== 'string' || !input.template_settings.template.trim() || !Array.isArray(input.template_settings.modules)) {
4242
+ throw new Error('Cloud invoice template is missing or belongs to another business');
4243
+ }
4244
+ const settings = this.normalizePrintInvoiceTemplateSettings(input.template_settings);
4245
+ const receipt = await this.rebuildOrderReceipt(order, settings);
4246
+ const smallTicketData = receipt.payment_info?.small_ticket_data;
4247
+ if (!(0, _smallTicket.hasSmallTicketData)(smallTicketData)) throw new Error('Cloud invoice snapshot is unavailable');
4248
+ const device = await this.getCloudInvoiceDevice(context.shopId);
4249
+ if (device.id !== context.deviceId) throw new Error('Cloud invoice device changed');
4250
+ this.assertCloudInvoiceContext(context);
4251
+ const task = await deviceTask.dispatch({
4252
+ action: 'print_all',
4253
+ device_id: device.target,
4254
+ name: 'PRINT_V1',
4255
+ source: 'server',
4256
+ source_type: 'cloud_order_invoice',
4257
+ source_id: order.order_id,
4258
+ durability: 'durable',
4259
+ idempotency_key: context.taskKey,
4260
+ payload: {
4261
+ type: '0',
4262
+ shop_id: context.shopId,
4263
+ device_id: context.deviceId,
4264
+ message_uuid: context.messageUuid,
4265
+ channel: context.channel,
4266
+ template_settings: settings,
4267
+ data: {
4268
+ order_id: order.order_id,
4269
+ small_ticket_data: smallTicketData
4270
+ }
4271
+ }
4272
+ });
4273
+ if (!task?.uuid) throw new Error('Cloud invoice task was not accepted');
4274
+ return {
4275
+ task_uuid: task.uuid
4276
+ };
4277
+ }
4278
+ async handleCloudOrderInvoice(input, submit) {
4279
+ const orderId = String(input?.order_id ?? '').trim();
4280
+ const shopId = String(input?.shop_id ?? '').trim();
4281
+ const messageUuid = typeof input?.message_uuid === 'string' ? input.message_uuid.trim() : '';
4282
+ const channel = typeof input?.channel === 'string' ? input.channel.trim() : '';
4283
+ if (!/^[1-9]\d*$/.test(orderId) || !/^[1-9]\d*$/.test(shopId) || !Number.isSafeInteger(Number(shopId)) || typeof input.order_id === 'number' && !Number.isSafeInteger(input.order_id) || !messageUuid || !channel) {
4284
+ return {
4285
+ code: 400,
4286
+ status: false,
4287
+ message: 'Invalid cloud invoice command',
4288
+ data: null
4289
+ };
4290
+ }
4291
+ try {
4292
+ const tenantId = String(this.getAppData('tenant_id') ?? '');
4293
+ const {
4294
+ id: deviceId
4295
+ } = await this.getCloudInvoiceDevice(shopId);
4296
+ if (submit && input.device_id !== deviceId) throw new Error('Cloud invoice device changed');
4297
+ const taskKey = 'cloud_order_invoice:' + JSON.stringify([shopId, deviceId, messageUuid]);
4298
+ const context = {
4299
+ taskKey,
4300
+ shopId,
4301
+ tenantId,
4302
+ deviceId,
4303
+ orderId,
4304
+ messageUuid,
4305
+ channel
4306
+ };
4307
+ this.assertCloudInvoiceContext(context);
4308
+ let result;
4309
+ const pending = this.cloudInvoiceSubmissions.get(taskKey);
4310
+ if (pending) {
4311
+ if (pending.context.orderId !== orderId || pending.context.channel !== channel || pending.context.tenantId !== tenantId) {
4312
+ throw new Error('Cloud invoice message UUID conflicts with an in-flight order');
4313
+ }
4314
+ result = await pending.result;
4315
+ } else if (submit) {
4316
+ const submission = this.resolveCloudOrderInvoice(context, input, true);
4317
+ this.cloudInvoiceSubmissions.set(taskKey, {
4318
+ context,
4319
+ result: submission
4320
+ });
4321
+ try {
4322
+ result = await submission;
4323
+ } finally {
4324
+ this.cloudInvoiceSubmissions.delete(taskKey);
4325
+ }
4326
+ } else {
4327
+ result = await this.resolveCloudOrderInvoice(context, input, false);
4328
+ }
4329
+ return {
4330
+ code: 200,
4331
+ status: true,
4332
+ message: '',
4333
+ data: result
4334
+ };
4335
+ } catch (error) {
4336
+ const message = this.getUnknownErrorMessage(error);
4337
+ this.logWarning('Cloud invoice request failed', {
4338
+ shopId,
4339
+ orderId,
4340
+ messageUuid,
4341
+ channel,
4342
+ message
4343
+ });
4344
+ return {
4345
+ code: 500,
4346
+ status: false,
4347
+ message,
4348
+ data: null
4349
+ };
4350
+ }
4351
+ }
4136
4352
  handleLocalPrintOrder = async ({
4137
4353
  data
4138
4354
  }) => {
@@ -4265,6 +4481,23 @@ class Server {
4265
4481
  if (!Array.isArray(value)) return [];
4266
4482
  return Array.from(new Set(value.filter(locale => typeof locale === 'string').map(locale => locale.trim()).filter(Boolean)));
4267
4483
  }
4484
+ rebuildOrderReceipt(order, templateSettings, locales) {
4485
+ const paymentInfo = {
4486
+ ...order.payment_info
4487
+ };
4488
+ delete paymentInfo.small_ticket_data;
4489
+ return this.withLocalSmallTicketData({
4490
+ ...order,
4491
+ small_ticket_data_flag: 1,
4492
+ payment_info: paymentInfo
4493
+ }, {
4494
+ locales,
4495
+ invoiceTemplateSettings: templateSettings,
4496
+ applyTemplateVisibility: true,
4497
+ includeReceiptKeys: templateSettings !== undefined,
4498
+ refreshResourceReference: true
4499
+ });
4500
+ }
4268
4501
  handleLocalOrderReceiptSnapshot = async ({
4269
4502
  data
4270
4503
  }) => {
@@ -4308,21 +4541,7 @@ class Server {
4308
4541
  }
4309
4542
  sourceOrder = remoteResult.order;
4310
4543
  }
4311
- const paymentInfo = {
4312
- ...(sourceOrder.payment_info || {})
4313
- };
4314
- delete paymentInfo.small_ticket_data;
4315
- const rebuiltOrder = await this.withLocalSmallTicketData({
4316
- ...sourceOrder,
4317
- small_ticket_data_flag: 1,
4318
- payment_info: paymentInfo
4319
- }, {
4320
- locales: this.normalizeRequestedReceiptLocales(input.locales),
4321
- invoiceTemplateSettings: input.template_settings === undefined ? undefined : this.normalizePrintInvoiceTemplateSettings(input.template_settings),
4322
- applyTemplateVisibility: true,
4323
- includeReceiptKeys: input.template_settings !== undefined,
4324
- refreshResourceReference: true
4325
- });
4544
+ const rebuiltOrder = await this.rebuildOrderReceipt(sourceOrder, input.template_settings === undefined ? undefined : this.normalizePrintInvoiceTemplateSettings(input.template_settings), this.normalizeRequestedReceiptLocales(input.locales));
4326
4545
  const smallTicketData = rebuiltOrder.payment_info?.small_ticket_data;
4327
4546
  if (!(0, _smallTicket.hasSmallTicketData)(smallTicketData)) {
4328
4547
  return {
@@ -5274,7 +5493,7 @@ class Server {
5274
5493
  const code = typeof value === 'number' ? value : Number(value);
5275
5494
  return Number.isFinite(code) ? code : 500;
5276
5495
  }
5277
- async fetchAndPersistSalesOrderByLookup(lookup, data, title, paymentIdentityOrder) {
5496
+ async fetchAndPersistSalesOrderByLookup(lookup, data, title, paymentIdentityOrder, prepareExactOrderForPersist) {
5278
5497
  if (!this.order?.getLocalOrderByLookup || !this.order?.upsertOrdersFromRemote) {
5279
5498
  this.logError(`${title}: Order 模块未注册`);
5280
5499
  return {
@@ -5327,7 +5546,7 @@ class Server {
5327
5546
  order: null
5328
5547
  };
5329
5548
  }
5330
- const localBeforeRefresh = this.order.getLocalOrderFromMemoryByLookup?.(lookup) || (this.shouldForceRemoteSalesDetail(data) ? await this.order.getLocalOrderByLookup(lookup) : null);
5549
+ const localBeforeRefresh = prepareExactOrderForPersist ? this.order.getOrderByOrderId?.(lookup) : this.order.getLocalOrderFromMemoryByLookup?.(lookup) || (this.shouldForceRemoteSalesDetail(data) ? await this.order.getLocalOrderByLookup(lookup) : null);
5331
5550
  let orderToPersist = fresh;
5332
5551
  if (paymentIdentityOrder) {
5333
5552
  if (String(fresh.order_id) !== String(paymentIdentityOrder.order_id) || fresh.external_sale_number && paymentIdentityOrder.external_sale_number && fresh.external_sale_number !== paymentIdentityOrder.external_sale_number || !Array.isArray(fresh.payments)) {
@@ -5359,6 +5578,7 @@ class Server {
5359
5578
  })
5360
5579
  };
5361
5580
  }
5581
+ if (prepareExactOrderForPersist) orderToPersist = prepareExactOrderForPersist(orderToPersist);
5362
5582
  if ((0, _localEftposState.requiresLocalPaymentRefresh)(localBeforeRefresh)) {
5363
5583
  if (String(fresh.order_id) !== String(localBeforeRefresh.order_id)) {
5364
5584
  throw new Error('远端订单身份不匹配,请重新刷新');
@@ -5367,7 +5587,9 @@ class Server {
5367
5587
  } else {
5368
5588
  await this.order.upsertOrdersFromRemote([orderToPersist]);
5369
5589
  }
5370
- let savedOrder = await this.order.getLocalOrderByLookup(lookup);
5590
+ let savedOrder = prepareExactOrderForPersist ? await this.order.getLocalOrderByLookup(lookup, {
5591
+ exactOrderId: true
5592
+ }) : await this.order.getLocalOrderByLookup(lookup);
5371
5593
  if (!savedOrder && fresh.order_id !== undefined && fresh.order_id !== null && String(fresh.order_id) !== String(lookup)) {
5372
5594
  savedOrder = await this.order.getLocalOrderByLookup(fresh.order_id);
5373
5595
  }
@@ -109,6 +109,7 @@ export declare class OrderModule extends BaseModule implements Module {
109
109
  getLocalOrderForPaymentReadiness(lookup: OrderId): Promise<OrderData | null>;
110
110
  getLocalOrderByLookup(lookup: OrderId, options?: {
111
111
  operationId?: string;
112
+ exactOrderId?: boolean;
112
113
  }): Promise<OrderData | null>;
113
114
  getLocalPayment(params: {
114
115
  saleId: OrderId;