@pisell/pisellos 2.2.325 → 2.2.327

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 (44) hide show
  1. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  2. package/dist/model/strategy/adapter/walletPass/locales.js +9 -0
  3. package/dist/modules/OpenData/index.d.ts +8 -1
  4. package/dist/modules/OpenData/index.js +276 -95
  5. package/dist/modules/Payment/utils.d.ts +2 -0
  6. package/dist/modules/Payment/utils.js +6 -6
  7. package/dist/modules/Payment/walletpass.d.ts +2 -0
  8. package/dist/modules/Payment/walletpass.js +75 -34
  9. package/dist/server/index.d.ts +3 -0
  10. package/dist/server/index.js +883 -611
  11. package/dist/server/modules/order/index.d.ts +1 -0
  12. package/dist/server/modules/order/index.js +51 -51
  13. package/dist/server/modules/products/index.d.ts +6 -2
  14. package/dist/server/modules/products/index.js +476 -400
  15. package/dist/solution/BookingByStep/index.d.ts +1 -1
  16. package/dist/solution/BookingTicket/index.js +6 -5
  17. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +1 -1
  18. package/dist/solution/Sales/index.d.ts +2 -5
  19. package/dist/solution/Sales/index.js +117 -143
  20. package/dist/solution/Sales/types.d.ts +6 -0
  21. package/dist/solution/Sales/types.js +2 -0
  22. package/dist/solution/UnifiedBookingSales/index.js +34 -23
  23. package/lib/model/strategy/adapter/walletPass/locales.js +9 -0
  24. package/lib/modules/OpenData/index.d.ts +8 -1
  25. package/lib/modules/OpenData/index.js +123 -21
  26. package/lib/modules/Payment/utils.d.ts +2 -0
  27. package/lib/modules/Payment/utils.js +7 -7
  28. package/lib/modules/Payment/walletpass.d.ts +2 -0
  29. package/lib/modules/Payment/walletpass.js +42 -11
  30. package/lib/server/index.d.ts +3 -0
  31. package/lib/server/index.js +164 -22
  32. package/lib/server/modules/order/index.d.ts +1 -0
  33. package/lib/server/modules/order/index.js +4 -3
  34. package/lib/server/modules/products/index.d.ts +6 -2
  35. package/lib/server/modules/products/index.js +40 -7
  36. package/lib/solution/BookingByStep/index.d.ts +1 -1
  37. package/lib/solution/BookingTicket/index.js +2 -1
  38. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +1 -1
  39. package/lib/solution/Sales/index.d.ts +2 -5
  40. package/lib/solution/Sales/index.js +32 -66
  41. package/lib/solution/Sales/types.d.ts +6 -0
  42. package/lib/solution/Sales/types.js +1 -0
  43. package/lib/solution/UnifiedBookingSales/index.js +3 -2
  44. package/package.json +1 -1
@@ -19,6 +19,8 @@ export declare class OpenDataModule extends BaseModule implements Module {
19
19
  private otherParams;
20
20
  private fetchRevision;
21
21
  private invoiceTemplateCacheRevision;
22
+ private printInvoiceTemplates;
23
+ private lastManualPrintKey?;
22
24
  private invoiceTemplateDocumentCache;
23
25
  private invoiceTemplateDocumentInFlight;
24
26
  constructor(name?: string, version?: string);
@@ -32,13 +34,18 @@ export declare class OpenDataModule extends BaseModule implements Module {
32
34
  updateOtherParams(params: Record<string, any>): void;
33
35
  private shouldSkipInvoiceTemplateDocument;
34
36
  fetchOpenData(params: OpenDataFetchParams): Promise<OpenDataConfig>;
37
+ private requestOpenData;
38
+ loadCloudInvoiceTemplate(target: string): Promise<InvoiceTemplateSettings>;
39
+ /** 手动和云单打印共用已成功解析的模板及进行中的请求。每个订单仍单独派单。 */
40
+ loadPrintInvoiceTemplate(target: string, mode: 'manual' | 'cloud'): Promise<InvoiceTemplateSettings>;
41
+ private fetchPrintInvoiceTemplate;
35
42
  getOpenData(): OpenDataConfig | null;
36
43
  getInvoiceLayoutConfig(): InvoiceLayoutConfig;
37
44
  getInvoiceTemplateSettings(): InvoiceTemplateSettings;
38
45
  ensureInvoiceTemplateSettings(target: string, openDataConfig?: OpenDataConfig): Promise<InvoiceTemplateSettings>;
39
46
  private commitInvoiceTemplateSettings;
40
47
  private resolveInvoiceTemplateSettings;
41
- private buildInvoiceTemplateCacheKey;
48
+ private buildInvoiceCacheKey;
42
49
  private fetchInvoiceTemplateDocument;
43
50
  private logInvoiceTemplateDocumentFallback;
44
51
  getLastFetchedAt(): number | null;
@@ -63,6 +63,7 @@ Object.defineProperty(exports, "resolveInvoiceReceiptLocales", {
63
63
  return _utils.resolveInvoiceReceiptLocales;
64
64
  }
65
65
  });
66
+ var _lodashEs = require("lodash-es");
66
67
  var _BaseModule = require("../BaseModule");
67
68
  var _utils = require("./utils");
68
69
  var _types = require("./types");
@@ -120,6 +121,7 @@ function isLegacyInvoiceTemplate(value) {
120
121
  const numericLike = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
121
122
  return !numericLike.test(normalized);
122
123
  }
124
+ const INVOICE_OPEN_DATA_CACHE_TTL = 5 * 60 * 1000;
123
125
  class OpenDataModule extends _BaseModule.BaseModule {
124
126
  defaultName = 'openData';
125
127
  defaultVersion = '1.0.0';
@@ -133,6 +135,8 @@ class OpenDataModule extends _BaseModule.BaseModule {
133
135
  otherParams = {};
134
136
  fetchRevision = 0;
135
137
  invoiceTemplateCacheRevision = 0;
138
+ printInvoiceTemplates = new Map();
139
+ lastManualPrintKey;
136
140
  invoiceTemplateDocumentCache = new Map();
137
141
  invoiceTemplateDocumentInFlight = new Map();
138
142
  constructor(name, version) {
@@ -182,13 +186,26 @@ class OpenDataModule extends _BaseModule.BaseModule {
182
186
  }
183
187
  async fetchOpenData(params) {
184
188
  const fetchRevision = ++this.fetchRevision;
189
+ const response = await this.requestOpenData(params);
190
+ if (response?.status === false) {
191
+ throw new Error(response?.message || '获取 OpenData 配置失败');
192
+ }
193
+ const data = response?.data || {};
194
+ const resolvedInvoiceTemplate = await this.resolveInvoiceTemplateSettings(data, params.target);
195
+ // clearCache() 或后续请求发生后,旧响应不得复活已失效的 target 配置。
196
+ if (fetchRevision === this.fetchRevision) {
197
+ this.store.data = data;
198
+ this.store.lastFetchedAt = Date.now();
199
+ this.commitInvoiceTemplateSettings(params.target, resolvedInvoiceTemplate);
200
+ }
201
+ return data;
202
+ }
203
+ requestOpenData(params, background = false) {
185
204
  const getData = this.appPlugin?.getData?.();
186
205
  const shopId = getData?.('shop_id');
187
- if (!shopId) throw new Error('[OpenDataModule] 无法获取 shop_id');
188
206
  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`, {
207
+ if (!shopId) throw new Error('[OpenDataModule] 无法获取 shop_id');
208
+ return this.request.post(`/open/my-pisell/${encodeURIComponent(String(shopId))}/setting`, {
192
209
  scope: params.scope,
193
210
  target: params.target,
194
211
  section_code: params.section_code
@@ -196,20 +213,96 @@ class OpenDataModule extends _BaseModule.BaseModule {
196
213
  pisell2: true,
197
214
  isPisell2: true,
198
215
  prefix: false,
199
- headers
216
+ headers: tenantId ? {
217
+ 'Tenant-Id': String(tenantId)
218
+ } : {},
219
+ ...(background ? {
220
+ customToast: () => {},
221
+ manualErrorHandling: true,
222
+ skipErrorHandler: true
223
+ } : {})
200
224
  });
201
- if (response?.status === false) {
202
- throw new Error(response?.message || '获取 OpenData 配置失败');
225
+ }
226
+ loadCloudInvoiceTemplate(target) {
227
+ return this.loadPrintInvoiceTemplate(target, 'cloud');
228
+ }
229
+
230
+ /** 手动和云单打印共用已成功解析的模板及进行中的请求。每个订单仍单独派单。 */
231
+ async loadPrintInvoiceTemplate(target, mode) {
232
+ const skipDocument = mode === 'manual' && this.shouldSkipInvoiceTemplateDocument();
233
+ const key = this.buildInvoiceCacheKey(target, skipDocument);
234
+ const revision = this.invoiceTemplateCacheRevision;
235
+ const assertCurrent = () => {
236
+ if (revision !== this.invoiceTemplateCacheRevision || key !== this.buildInvoiceCacheKey(target, skipDocument)) {
237
+ throw new Error('Invoice 配置已失效');
238
+ }
239
+ };
240
+ // 手动切换打印入口时沿用原有行为,重新读取该入口的 Documents 选择。
241
+ const manualSwitch = mode === 'manual' && this.lastManualPrintKey !== undefined && this.lastManualPrintKey !== key;
242
+ if (mode === 'manual') this.lastManualPrintKey = key;
243
+ let entry = this.printInvoiceTemplates.get(key);
244
+ const refresh = entry?.expiresAt !== undefined && (Date.now() >= entry.expiresAt || manualSwitch || mode === 'cloud' && entry.manualFallback);
245
+ if (!entry || refresh) {
246
+ const next = {
247
+ manualFallback: false,
248
+ request: this.fetchPrintInvoiceTemplate(target, skipDocument, assertCurrent).then(result => {
249
+ assertCurrent();
250
+ next.expiresAt = Date.now() + INVOICE_OPEN_DATA_CACHE_TTL;
251
+ // 只有手动打印可复用文档读取失败后的 DEFAULT 回退。
252
+ if ('documentError' in result) {
253
+ if (mode === 'cloud') throw result.documentError;
254
+ next.manualFallback = true;
255
+ next.request = Promise.resolve({
256
+ settings: (0, _utils.getDefaultInvoiceTemplateSettings)()
257
+ });
258
+ }
259
+ return result;
260
+ }).catch(error => {
261
+ if (this.printInvoiceTemplates.get(key) === next) this.printInvoiceTemplates.delete(key);
262
+ throw error;
263
+ })
264
+ };
265
+ this.printInvoiceTemplates.set(key, next);
266
+ entry = next;
203
267
  }
204
- const data = response?.data || {};
205
- const resolvedInvoiceTemplate = await this.resolveInvoiceTemplateSettings(data, params.target);
206
- // clearCache() 或后续请求发生后,旧响应不得复活已失效的 target 配置。
207
- if (fetchRevision === this.fetchRevision) {
208
- this.store.data = data;
209
- this.store.lastFetchedAt = Date.now();
210
- this.commitInvoiceTemplateSettings(params.target, resolvedInvoiceTemplate);
268
+ const result = await entry.request;
269
+ assertCurrent();
270
+ if ('documentError' in result) throw result.documentError;
271
+ return (0, _lodashEs.cloneDeep)(result.settings);
272
+ }
273
+ async fetchPrintInvoiceTemplate(target, skipDocument, assertCurrent) {
274
+ const response = await this.requestOpenData({
275
+ scope: 'board',
276
+ target,
277
+ section_code: ['documents']
278
+ }, true);
279
+ assertCurrent();
280
+ if (response?.status !== true || response.code !== 200 || !isRecord(response.data)) {
281
+ throw new Error(response?.message || 'Cloud Invoice settings unavailable');
211
282
  }
212
- return data;
283
+ if (skipDocument) return {
284
+ settings: (0, _utils.getDefaultInvoiceTemplateSettings)()
285
+ };
286
+ const raw = response.data['documents.invoice_template'];
287
+ const documentId = resolveInvoiceDocumentId(raw);
288
+ if (documentId) {
289
+ try {
290
+ return {
291
+ settings: await this.fetchInvoiceTemplateDocument(documentId, true)
292
+ };
293
+ } catch (documentError) {
294
+ return {
295
+ documentError
296
+ };
297
+ }
298
+ }
299
+ if (raw == null || typeof raw === 'string' && !raw.trim()) return {
300
+ settings: (0, _utils.getDefaultInvoiceTemplateSettings)()
301
+ };
302
+ if (isLegacyInvoiceTemplate(raw)) return {
303
+ settings: (0, _utils.normalizeInvoiceTemplateSettings)(response.data)
304
+ };
305
+ throw new Error('Cloud Invoice template identifier is invalid');
213
306
  }
214
307
  getOpenData() {
215
308
  return this.store.data;
@@ -225,7 +318,7 @@ class OpenDataModule extends _BaseModule.BaseModule {
225
318
  const documentId = resolveInvoiceDocumentId(this.store.data?.['documents.invoice_template']);
226
319
  if (documentId) {
227
320
  const target = this.store.invoiceTemplateTarget;
228
- if (!target || this.store.invoiceTemplateCacheKey !== this.buildInvoiceTemplateCacheKey(target, documentId)) {
321
+ if (!target || this.store.invoiceTemplateCacheKey !== this.buildInvoiceCacheKey(target, documentId)) {
229
322
  return (0, _utils.getDefaultInvoiceTemplateSettings)();
230
323
  }
231
324
  }
@@ -281,7 +374,7 @@ class OpenDataModule extends _BaseModule.BaseModule {
281
374
  cacheKey: null
282
375
  };
283
376
  }
284
- const cacheKey = this.buildInvoiceTemplateCacheKey(target, documentId);
377
+ const cacheKey = this.buildInvoiceCacheKey(target, documentId);
285
378
  if (this.store.invoiceTemplateTarget === target && this.store.invoiceTemplateDocumentId === documentId && this.store.invoiceTemplateCacheKey === cacheKey && isRecord(this.store.invoiceTemplateSettings)) {
286
379
  return {
287
380
  settings: (0, _utils.normalizeRawInvoiceTemplateSettings)(this.store.invoiceTemplateSettings),
@@ -322,18 +415,22 @@ class OpenDataModule extends _BaseModule.BaseModule {
322
415
  cacheKey
323
416
  };
324
417
  }
325
- buildInvoiceTemplateCacheKey(target, documentId) {
418
+ buildInvoiceCacheKey(target, variant) {
326
419
  const getData = this.appPlugin?.getData?.();
327
- return JSON.stringify([getData?.('tenant_id') ?? null, getData?.('shop_id') ?? null, target, documentId]);
420
+ return JSON.stringify([getData?.('tenant_id') ?? null, getData?.('shop_id') ?? null, target, variant]);
328
421
  }
329
- async fetchInvoiceTemplateDocument(documentId) {
422
+ async fetchInvoiceTemplateDocument(documentId, strict = false) {
330
423
  const response = await this.request.get(`/document:get?filterByTk=${encodeURIComponent(documentId)}`, {}, {
331
424
  isNocobase: true,
332
425
  prefix: false,
333
426
  headers: {
334
427
  'x-data-source': 'pisell2'
335
428
  },
336
- customToast: () => {}
429
+ customToast: () => {},
430
+ ...(strict ? {
431
+ manualErrorHandling: true,
432
+ skipErrorHandler: true
433
+ } : {})
337
434
  });
338
435
  const document = response?.data;
339
436
  if (!document || resolveInvoiceDocumentId(document.id) !== documentId) {
@@ -345,6 +442,9 @@ class OpenDataModule extends _BaseModule.BaseModule {
345
442
  if (!isRecord(document.data) || !isRecord(document.data.template_settings)) {
346
443
  throw new Error(`Invoice Document ${documentId} 缺少 template_settings`);
347
444
  }
445
+ if (strict && (typeof document.data.template_settings.template !== 'string' || !document.data.template_settings.template.trim())) {
446
+ throw new Error(`Invoice Document ${documentId} 缺少 template`);
447
+ }
348
448
  return (0, _utils.normalizeRawInvoiceTemplateSettings)(document.data.template_settings);
349
449
  }
350
450
  logInvoiceTemplateDocumentFallback(error, target, documentId) {
@@ -362,6 +462,8 @@ class OpenDataModule extends _BaseModule.BaseModule {
362
462
  clearCache() {
363
463
  this.fetchRevision += 1;
364
464
  this.invoiceTemplateCacheRevision += 1;
465
+ this.printInvoiceTemplates.clear();
466
+ this.lastManualPrintKey = undefined;
365
467
  this.invoiceTemplateDocumentCache.clear();
366
468
  this.invoiceTemplateDocumentInFlight.clear();
367
469
  this.store.data = null;
@@ -10,6 +10,8 @@ export declare const formatWalletPassList2PreparePayments: (list?: any[]) => {
10
10
  wallet_pass_usage_unit: any;
11
11
  wallet_pass_use_value: any;
12
12
  }[];
13
+ /** 这两种不可用原因随订单内容变化,其他服务端错误需保留。 */
14
+ export declare const isWalletOrderAvailabilityError: (code: unknown) => boolean;
13
15
  /**
14
16
  * 对用户识别码列表进行排序
15
17
  * 排序规则:正常数据 -> unified_available_status===1 -> 500601/500602 -> unified_available_status===0
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.sortUserIdentificationCodeList = exports.getAvailableMaxAmount = exports.formatWalletPassList2PreparePayments = void 0;
6
+ exports.sortUserIdentificationCodeList = exports.isWalletOrderAvailabilityError = exports.getAvailableMaxAmount = exports.formatWalletPassList2PreparePayments = void 0;
7
7
  // 获取walletPass可用最大金额
8
8
  const getAvailableMaxAmount = data => {
9
9
  if (typeof data._available_max_amount === 'number') {
@@ -32,20 +32,21 @@ const formatWalletPassList2PreparePayments = list => {
32
32
  return formatted;
33
33
  };
34
34
 
35
+ /** 这两种不可用原因随订单内容变化,其他服务端错误需保留。 */
36
+ exports.formatWalletPassList2PreparePayments = formatWalletPassList2PreparePayments;
37
+ const isWalletOrderAvailabilityError = code => String(code) === '500601' || String(code) === '500602';
38
+
35
39
  /**
36
40
  * 对用户识别码列表进行排序
37
41
  * 排序规则:正常数据 -> unified_available_status===1 -> 500601/500602 -> unified_available_status===0
38
42
  * @param list 用户识别码列表
39
43
  * @returns 排序后的列表
40
44
  */
41
- exports.formatWalletPassList2PreparePayments = formatWalletPassList2PreparePayments;
45
+ exports.isWalletOrderAvailabilityError = isWalletOrderAvailabilityError;
42
46
  const sortUserIdentificationCodeList = list => {
43
47
  if (!Array.isArray(list) || list.length === 0) {
44
48
  return list;
45
49
  }
46
-
47
- // 定义中等优先级错误码
48
- const middlePriorityErrorCodes = ['500601', '500602'];
49
50
  return list.sort((a, b) => {
50
51
  // 确定每个项目的优先级
51
52
  // 0: 正常数据(没有特定错误码且available_status不是1或0)
@@ -53,11 +54,10 @@ const sortUserIdentificationCodeList = list => {
53
54
  // 2: 中等优先级错误码(500601、500602) 此订单内不可用 订单没有剩余金额
54
55
  // 3: unified_available_status === 0(最后)
55
56
  const getPriority = item => {
56
- const errorCode = item.unified_error_code?.toString();
57
57
  const availableStatus = item.unified_available_status;
58
58
 
59
59
  // 中等优先级错误码
60
- if (errorCode && middlePriorityErrorCodes.includes(errorCode)) return 2;
60
+ if (isWalletOrderAvailabilityError(item.unified_error_code)) return 2;
61
61
 
62
62
  // unified_available_status === 0 最后
63
63
  if (availableStatus === 0) return 3;
@@ -23,6 +23,8 @@ export declare class WalletPassPaymentImpl implements WalletPassPayment {
23
23
  */
24
24
  private emitEvent;
25
25
  private publishWalletAssetsState;
26
+ private get hasEmptyWalletCart();
27
+ private walletAssetForEmptyCart;
26
28
  private recalculateWalletAssets;
27
29
  /**
28
30
  * 搜索接口只返回后端 Wallet Pass 数据,不包含前端策略 config。
@@ -5,8 +5,12 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.WalletPassPaymentImpl = void 0;
7
7
  var _types = require("./types");
8
+ var _locales = require("../../model/strategy/adapter/walletPass/locales");
8
9
  var _utils = require("./utils");
9
10
  const WALLET_PAYMENT_ASSET_TAGS = new Set(['product_voucher', 'gift_card', 'point_card']);
11
+
12
+ // 旧版搜索响应可能只有订单不适用的提示文本,没有 unified_error_code。
13
+ const LEGACY_CART_MESSAGES = new Set(['Voucher not applicable to current cart', 'No eligible items in the cart', _locales.locales.en.exceeds_the_maximum_deduction_limit]);
10
14
  function isWalletPaymentAsset(asset) {
11
15
  return WALLET_PAYMENT_ASSET_TAGS.has(String(asset?.tag || '').toLowerCase());
12
16
  }
@@ -174,6 +178,32 @@ class WalletPassPaymentImpl {
174
178
  });
175
179
  return state;
176
180
  }
181
+ get hasEmptyWalletCart() {
182
+ return this.walletParams !== null && this.walletAssetsCalculationContext.products.length === 0;
183
+ }
184
+ walletAssetForEmptyCart(asset) {
185
+ const unavailableAsset = {
186
+ ...asset,
187
+ actualDeduction: 0,
188
+ deductionDetails: [],
189
+ _available_max_amount: 0,
190
+ _unified_available_status: 0,
191
+ _wallet_asset_recommended: false
192
+ };
193
+ const errorCode = asset.unified_error_code;
194
+ const reportedReason = asset.unified_messages?.title || asset.error_msg || asset.disabledReason;
195
+ const reportedUnavailable = Number(asset.unified_available_status) === 0 || asset.available === false || asset.isDisabled === true;
196
+ const hasAssetRestriction = errorCode ? !(0, _utils.isWalletOrderAvailabilityError)(errorCode) : reportedUnavailable && reportedReason && !LEGACY_CART_MESSAGES.has(reportedReason);
197
+ if (hasAssetRestriction) {
198
+ return unavailableAsset;
199
+ }
200
+ const evaluator = this.paymentModule.window?.getWalletPassEvaluator?.();
201
+ return {
202
+ ...unavailableAsset,
203
+ reasonCode: 'empty_cart',
204
+ reason: evaluator?.getText?.('empty_cart') || _locales.locales.en.empty_cart
205
+ };
206
+ }
177
207
  recalculateWalletAssets(items, requestedIds, selectionSources) {
178
208
  const committedKeys = new Set(this.walletAssetsState.committedIds.map(id => String(id)));
179
209
  const itemsByKey = new Map(items.map(item => [getWalletAssetKey(item), item]));
@@ -181,7 +211,10 @@ class WalletPassPaymentImpl {
181
211
  let nextItems = items;
182
212
  let selectedItems = requested;
183
213
  const evaluator = this.paymentModule.window?.getWalletPassEvaluator?.();
184
- if (evaluator?.recalculateVouchers) {
214
+ if (this.hasEmptyWalletCart) {
215
+ nextItems = items.map(asset => committedKeys.has(getWalletAssetKey(asset)) ? asset : this.walletAssetForEmptyCart(asset));
216
+ selectedItems = [];
217
+ } else if (evaluator?.recalculateVouchers) {
185
218
  try {
186
219
  const result = evaluator.recalculateVouchers(items, requested, this.walletAssetsCalculationContext.orderTotalAmount, this.walletAssetsCalculationContext.products);
187
220
  nextItems = mergeWalletAssets(items, result?.allWithUpdatedStatus || []);
@@ -868,14 +901,7 @@ class WalletPassPaymentImpl {
868
901
  if (!businessData.products?.length) {
869
902
  this.queuePendingAutoSelectForAssets(scanSelectedAssets);
870
903
  this.generateWalletParams(businessData);
871
- const restoredSearchedAssets = this.searchResults.filter(isWalletPaymentAsset).map(item => ({
872
- ...item,
873
- actualDeduction: 0,
874
- deductionDetails: [],
875
- _available_max_amount: 0,
876
- _unified_available_status: 0,
877
- _wallet_asset_recommended: false
878
- }));
904
+ const restoredSearchedAssets = this.searchResults.filter(isWalletPaymentAsset).map(item => this.walletAssetForEmptyCart(item));
879
905
  this.walletRecommendList = [];
880
906
  this.userIdentificationCodes = [];
881
907
  this.walletInitData = {
@@ -1170,10 +1196,15 @@ class WalletPassPaymentImpl {
1170
1196
  selectionSources[String(id)] = 'scan';
1171
1197
  });
1172
1198
  const selected = this.walletAssetsBehavior.autoSelectAfterSearch ? this.recalculateWalletAssets(items, Array.from(new Set([...this.walletAssetsState.selectedIds, ...assetIds])), selectionSources) : this.recalculateWalletAssets(items, this.walletAssetsState.selectedIds, this.walletAssetsState.selectionSources);
1199
+ const anySelected = assetIds.some(id => selected.selectedIds.includes(id));
1200
+ if (this.hasEmptyWalletCart) {
1201
+ this.queuePendingAutoSelectForAssets(assetsToApply);
1202
+ }
1203
+ const firstAssetKey = getWalletAssetKey(asset);
1173
1204
  return {
1174
1205
  type: result.type,
1175
- asset,
1176
- selected: assetIds.some(id => selected.selectedIds.includes(id)),
1206
+ asset: selected.items.find(item => getWalletAssetKey(item) === firstAssetKey) || asset,
1207
+ selected: anySelected,
1177
1208
  state: selected
1178
1209
  };
1179
1210
  }
@@ -546,8 +546,11 @@ declare class Server {
546
546
  private shouldLookupLocalPrintOrder;
547
547
  private getLocalPrintOrderLookup;
548
548
  private mergeLocalPrintOrderInput;
549
+ private loadCloudInvoiceOrder;
550
+ private handleCloudOrderInvoice;
549
551
  private handleLocalPrintOrder;
550
552
  private normalizeRequestedReceiptLocales;
553
+ private rebuildOrderReceipt;
551
554
  private handleLocalOrderReceiptSnapshot;
552
555
  private handleMachinecodeBatchMeta;
553
556
  private resolveMachinecodeBatchMetadataLookup;
@@ -1387,6 +1387,18 @@ class Server {
1387
1387
  method: 'post',
1388
1388
  path: '/shop/local/print-order',
1389
1389
  handler: this.handleLocalPrintOrder.bind(this)
1390
+ }, {
1391
+ method: 'post',
1392
+ path: '/shop/local/cloud-order-invoice/lookup',
1393
+ handler: ({
1394
+ data
1395
+ }) => this.handleCloudOrderInvoice(data, false)
1396
+ }, {
1397
+ method: 'post',
1398
+ path: '/shop/local/cloud-order-invoice/submit',
1399
+ handler: ({
1400
+ data
1401
+ }) => this.handleCloudOrderInvoice(data, true)
1390
1402
  }, {
1391
1403
  method: 'post',
1392
1404
  path: '/shop/local/order-receipt-snapshot',
@@ -3897,10 +3909,15 @@ class Server {
3897
3909
  biz: next.business_code || 'ticket'
3898
3910
  });
3899
3911
  }
3900
- if (needsShopFullOrderNumber && idGenerator.generateReceiptId) {
3901
- next.shop_full_order_number = await idGenerator.generateReceiptId({
3902
- biz: next.business_code || 'ticket'
3903
- });
3912
+ if (needsShopFullOrderNumber) {
3913
+ const biz = next.business_code || 'ticket';
3914
+ if (idGenerator.getConfig?.(biz)?.enableShortNumber === false) {
3915
+ next.shop_full_order_number = next.shop_order_number;
3916
+ } else if (idGenerator.generateReceiptId) {
3917
+ next.shop_full_order_number = await idGenerator.generateReceiptId({
3918
+ biz
3919
+ });
3920
+ }
3904
3921
  }
3905
3922
  this.logInfo(`${title}: checkout 订单号已准备`, {
3906
3923
  shop_order_number: next.shop_order_number,
@@ -4095,6 +4112,125 @@ class Server {
4095
4112
  external_sale_number: localOrder.external_sale_number ?? definedInput.external_sale_number ?? definedInput.externalSaleNumber
4096
4113
  };
4097
4114
  }
4115
+ async loadCloudInvoiceOrder(orderId, shopId, assertCurrentShop) {
4116
+ if (!this.order) throw new Error('Cloud invoice order service is unavailable');
4117
+ const hasReceiptDetail = order => {
4118
+ // Use the same amount fields as the receipt builder, including historical
4119
+ // top-level amounts. Zero is a valid total; a missing total in a list row is not.
4120
+ const total = [order.summary?.expect_amount, order.expect_amount, order.summary?.total_amount, order.total_amount].find(value => value != null && value !== '');
4121
+ 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));
4122
+ };
4123
+ const local = await this.order.getLocalOrderByLookup(orderId, {
4124
+ exactOrderId: true
4125
+ });
4126
+ assertCurrentShop();
4127
+ if (local && String(local.order_id) === orderId) {
4128
+ if (local.shop_id != null && String(local.shop_id) !== shopId) {
4129
+ throw new Error('Cloud invoice order belongs to another shop');
4130
+ }
4131
+ if (String(local.shop_id) === shopId && hasReceiptDetail(local)) return local;
4132
+ }
4133
+
4134
+ // The generic detail route also matches short receipt numbers. Validate the
4135
+ // backend identity and live shop BEFORE its result enters the shared store.
4136
+ const result = await this.fetchAndPersistSalesOrderByLookup(orderId, {
4137
+ with: ['all']
4138
+ }, 'cloudOrderInvoice', undefined, fresh => {
4139
+ assertCurrentShop();
4140
+ if (String(fresh.order_id) !== orderId || fresh.shop_id != null && String(fresh.shop_id) !== shopId || !hasReceiptDetail(fresh)) {
4141
+ throw new Error('Cloud invoice order identity or detail is invalid');
4142
+ }
4143
+ // Some older shop-authenticated detail responses omit shop_id.
4144
+ return fresh.shop_id == null ? {
4145
+ ...fresh,
4146
+ shop_id: Number(shopId)
4147
+ } : fresh;
4148
+ });
4149
+ assertCurrentShop();
4150
+ const saved = result.order;
4151
+ if (!saved || String(saved.order_id) !== orderId || String(saved.shop_id) !== shopId || !hasReceiptDetail(saved)) {
4152
+ throw new Error(result.message || 'Cloud invoice order detail is unavailable');
4153
+ }
4154
+ return saved;
4155
+ }
4156
+ async handleCloudOrderInvoice(input, submit) {
4157
+ const orderId = typeof input?.order_id === 'string' ? input.order_id.trim() : Number.isSafeInteger(input?.order_id) ? String(input.order_id) : '';
4158
+ if (!/^[1-9]\d*$/.test(orderId)) {
4159
+ return {
4160
+ code: 400,
4161
+ status: false,
4162
+ message: 'Invalid cloud invoice order ID',
4163
+ data: null
4164
+ };
4165
+ }
4166
+ try {
4167
+ const shopId = String(this.getAppData('shop_id') ?? '');
4168
+ const tenantId = String(this.getAppData('tenant_id') ?? '');
4169
+ if (!/^[1-9]\d*$/.test(shopId) || !Number.isSafeInteger(Number(shopId))) {
4170
+ throw new Error('Cloud invoice shop is unavailable');
4171
+ }
4172
+ const assertCurrentShop = () => {
4173
+ if (String(this.getAppData('shop_id') ?? '') !== shopId || String(this.getAppData('tenant_id') ?? '') !== tenantId) {
4174
+ throw new Error('Cloud invoice shop context changed');
4175
+ }
4176
+ };
4177
+ const order = await this.loadCloudInvoiceOrder(orderId, shopId, assertCurrentShop);
4178
+ const businessCode = order.business_code.trim();
4179
+ if (!submit) return {
4180
+ code: 200,
4181
+ status: true,
4182
+ message: '',
4183
+ data: {
4184
+ business_code: businessCode
4185
+ }
4186
+ };
4187
+ if (input.business_code !== businessCode || typeof input.template_settings?.template !== 'string' || !input.template_settings.template.trim() || !Array.isArray(input.template_settings.modules)) {
4188
+ throw new Error('Cloud invoice template is missing or belongs to another business');
4189
+ }
4190
+ const settings = this.normalizePrintInvoiceTemplateSettings(input.template_settings);
4191
+ const receipt = await this.rebuildOrderReceipt(order, settings);
4192
+ const smallTicketData = receipt.payment_info?.small_ticket_data;
4193
+ if (!(0, _smallTicket.hasSmallTicketData)(smallTicketData)) throw new Error('Cloud invoice snapshot is unavailable');
4194
+ const deviceTask = this.getDeviceTaskPlugin();
4195
+ if (!deviceTask?.dispatch) throw new Error('Print task service is unavailable');
4196
+ const deviceId = await this.getShortNumberOrDeviceId();
4197
+ assertCurrentShop();
4198
+ await deviceTask.dispatch({
4199
+ action: 'print_all',
4200
+ device_id: deviceId,
4201
+ name: 'PRINT_V1',
4202
+ source: 'server',
4203
+ source_type: 'order',
4204
+ source_id: order.order_id,
4205
+ payload: {
4206
+ type: '0',
4207
+ template_settings: settings,
4208
+ data: {
4209
+ order_id: order.order_id,
4210
+ small_ticket_data: smallTicketData
4211
+ }
4212
+ }
4213
+ });
4214
+ return {
4215
+ code: 200,
4216
+ status: true,
4217
+ message: '',
4218
+ data: null
4219
+ };
4220
+ } catch (error) {
4221
+ const message = this.getUnknownErrorMessage(error);
4222
+ this.logWarning('Cloud invoice request failed', {
4223
+ orderId,
4224
+ message
4225
+ });
4226
+ return {
4227
+ code: 500,
4228
+ status: false,
4229
+ message,
4230
+ data: null
4231
+ };
4232
+ }
4233
+ }
4098
4234
  handleLocalPrintOrder = async ({
4099
4235
  data
4100
4236
  }) => {
@@ -4227,6 +4363,23 @@ class Server {
4227
4363
  if (!Array.isArray(value)) return [];
4228
4364
  return Array.from(new Set(value.filter(locale => typeof locale === 'string').map(locale => locale.trim()).filter(Boolean)));
4229
4365
  }
4366
+ rebuildOrderReceipt(order, templateSettings, locales) {
4367
+ const paymentInfo = {
4368
+ ...order.payment_info
4369
+ };
4370
+ delete paymentInfo.small_ticket_data;
4371
+ return this.withLocalSmallTicketData({
4372
+ ...order,
4373
+ small_ticket_data_flag: 1,
4374
+ payment_info: paymentInfo
4375
+ }, {
4376
+ locales,
4377
+ invoiceTemplateSettings: templateSettings,
4378
+ applyTemplateVisibility: true,
4379
+ includeReceiptKeys: templateSettings !== undefined,
4380
+ refreshResourceReference: true
4381
+ });
4382
+ }
4230
4383
  handleLocalOrderReceiptSnapshot = async ({
4231
4384
  data
4232
4385
  }) => {
@@ -4270,21 +4423,7 @@ class Server {
4270
4423
  }
4271
4424
  sourceOrder = remoteResult.order;
4272
4425
  }
4273
- const paymentInfo = {
4274
- ...(sourceOrder.payment_info || {})
4275
- };
4276
- delete paymentInfo.small_ticket_data;
4277
- const rebuiltOrder = await this.withLocalSmallTicketData({
4278
- ...sourceOrder,
4279
- small_ticket_data_flag: 1,
4280
- payment_info: paymentInfo
4281
- }, {
4282
- locales: this.normalizeRequestedReceiptLocales(input.locales),
4283
- invoiceTemplateSettings: input.template_settings === undefined ? undefined : this.normalizePrintInvoiceTemplateSettings(input.template_settings),
4284
- applyTemplateVisibility: true,
4285
- includeReceiptKeys: input.template_settings !== undefined,
4286
- refreshResourceReference: true
4287
- });
4426
+ const rebuiltOrder = await this.rebuildOrderReceipt(sourceOrder, input.template_settings === undefined ? undefined : this.normalizePrintInvoiceTemplateSettings(input.template_settings), this.normalizeRequestedReceiptLocales(input.locales));
4288
4427
  const smallTicketData = rebuiltOrder.payment_info?.small_ticket_data;
4289
4428
  if (!(0, _smallTicket.hasSmallTicketData)(smallTicketData)) {
4290
4429
  return {
@@ -5236,7 +5375,7 @@ class Server {
5236
5375
  const code = typeof value === 'number' ? value : Number(value);
5237
5376
  return Number.isFinite(code) ? code : 500;
5238
5377
  }
5239
- async fetchAndPersistSalesOrderByLookup(lookup, data, title, paymentIdentityOrder) {
5378
+ async fetchAndPersistSalesOrderByLookup(lookup, data, title, paymentIdentityOrder, prepareExactOrderForPersist) {
5240
5379
  if (!this.order?.getLocalOrderByLookup || !this.order?.upsertOrdersFromRemote) {
5241
5380
  this.logError(`${title}: Order 模块未注册`);
5242
5381
  return {
@@ -5289,7 +5428,7 @@ class Server {
5289
5428
  order: null
5290
5429
  };
5291
5430
  }
5292
- const localBeforeRefresh = this.order.getLocalOrderFromMemoryByLookup?.(lookup) || (this.shouldForceRemoteSalesDetail(data) ? await this.order.getLocalOrderByLookup(lookup) : null);
5431
+ const localBeforeRefresh = prepareExactOrderForPersist ? this.order.getOrderByOrderId?.(lookup) : this.order.getLocalOrderFromMemoryByLookup?.(lookup) || (this.shouldForceRemoteSalesDetail(data) ? await this.order.getLocalOrderByLookup(lookup) : null);
5293
5432
  let orderToPersist = fresh;
5294
5433
  if (paymentIdentityOrder) {
5295
5434
  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)) {
@@ -5321,6 +5460,7 @@ class Server {
5321
5460
  })
5322
5461
  };
5323
5462
  }
5463
+ if (prepareExactOrderForPersist) orderToPersist = prepareExactOrderForPersist(orderToPersist);
5324
5464
  if ((0, _localEftposState.requiresLocalPaymentRefresh)(localBeforeRefresh)) {
5325
5465
  if (String(fresh.order_id) !== String(localBeforeRefresh.order_id)) {
5326
5466
  throw new Error('远端订单身份不匹配,请重新刷新');
@@ -5329,7 +5469,9 @@ class Server {
5329
5469
  } else {
5330
5470
  await this.order.upsertOrdersFromRemote([orderToPersist]);
5331
5471
  }
5332
- let savedOrder = await this.order.getLocalOrderByLookup(lookup);
5472
+ let savedOrder = prepareExactOrderForPersist ? await this.order.getLocalOrderByLookup(lookup, {
5473
+ exactOrderId: true
5474
+ }) : await this.order.getLocalOrderByLookup(lookup);
5333
5475
  if (!savedOrder && fresh.order_id !== undefined && fresh.order_id !== null && String(fresh.order_id) !== String(lookup)) {
5334
5476
  savedOrder = await this.order.getLocalOrderByLookup(fresh.order_id);
5335
5477
  }