@pisell/pisellos 2.2.326 → 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.
@@ -29,12 +29,9 @@ import dayjs from 'dayjs';
29
29
  import { cloneDeep } from 'lodash-es';
30
30
  import { BaseModule } from "../../modules/BaseModule";
31
31
  import { SalesHooks } from "./types";
32
- import { getDefaultInvoiceLayoutConfig, getDefaultInvoiceTemplateSettings, OpenDataModule } from "../../modules/OpenData";
32
+ import { getDefaultInvoiceLayoutConfig, getDefaultInvoiceTemplateSettings, OpenDataModule, normalizeInvoiceLayoutFromTemplateSettings } from "../../modules/OpenData";
33
33
  export * from "./types";
34
34
  var UNPAID_PAYMENT_STATUSES = new Set(['unpaid', 'partially_paid', 'payment_processing']);
35
- var INVOICE_OPEN_DATA_SECTION_CODES = ['documents'];
36
- var INVOICE_OPEN_DATA_CACHE_TTL = 5 * 60 * 1000;
37
-
38
35
  /**
39
36
  * Sales 解决方案基础骨架
40
37
  *
@@ -64,9 +61,6 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
64
61
  _defineProperty(_assertThisInitialized(_this), "logger", void 0);
65
62
  // LoggerManager 实例
66
63
  _defineProperty(_assertThisInitialized(_this), "invoiceOpenDataModule", null);
67
- _defineProperty(_assertThisInitialized(_this), "invoiceOpenDataTarget", null);
68
- _defineProperty(_assertThisInitialized(_this), "invoiceOpenDataInFlight", null);
69
- _defineProperty(_assertThisInitialized(_this), "invoiceOpenDataInFlightTarget", null);
70
64
  return _this;
71
65
  }
72
66
  _createClass(SalesImpl, [{
@@ -110,9 +104,6 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
110
104
  // 在这里补充从 Server/Order 读取 currentDay 原始数据并转换为预约列表。
111
105
 
112
106
  this.logger = appPlugin === null || appPlugin === void 0 ? void 0 : appPlugin.getApp().logger;
113
- this.invoiceOpenDataTarget = null;
114
- this.invoiceOpenDataInFlight = null;
115
- this.invoiceOpenDataInFlightTarget = null;
116
107
  this.invoiceOpenDataModule = new OpenDataModule("".concat(this.name, "_invoiceOpenData"));
117
108
  this.core.registerModule(this.invoiceOpenDataModule, {
118
109
  initialState: {},
@@ -122,9 +113,9 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
122
113
  platform: (_this$otherParams = this.otherParams) === null || _this$otherParams === void 0 ? void 0 : _this$otherParams.platform
123
114
  }
124
115
  });
125
- _context.next = 18;
116
+ _context.next = 15;
126
117
  return this.core.effects.emit("".concat(this.name, ":onInited"), {});
127
- case 18:
118
+ case 15:
128
119
  case "end":
129
120
  return _context.stop();
130
121
  }
@@ -259,93 +250,6 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
259
250
  var normalized = String((_ref = channel !== null && channel !== void 0 ? channel : contextChannel) !== null && _ref !== void 0 ? _ref : '').trim();
260
251
  return !normalized || normalized === 'system' ? 'pos' : normalized;
261
252
  }
262
- }, {
263
- key: "loadInvoiceOpenData",
264
- value: function () {
265
- var _loadInvoiceOpenData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(businessCode, channel) {
266
- var target, cachedData, lastFetchedAt, request, openData;
267
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
268
- while (1) switch (_context4.prev = _context4.next) {
269
- case 0:
270
- if (this.invoiceOpenDataModule) {
271
- _context4.next = 2;
272
- break;
273
- }
274
- throw new Error('Sales Invoice OpenData 模块未初始化');
275
- case 2:
276
- target = "".concat(businessCode, "+").concat(channel);
277
- cachedData = this.invoiceOpenDataModule.getOpenData();
278
- lastFetchedAt = this.invoiceOpenDataModule.getLastFetchedAt();
279
- if (!(cachedData && this.invoiceOpenDataTarget === target && typeof lastFetchedAt === 'number' && Date.now() - lastFetchedAt < INVOICE_OPEN_DATA_CACHE_TTL)) {
280
- _context4.next = 10;
281
- break;
282
- }
283
- if (!(typeof this.invoiceOpenDataModule.ensureInvoiceTemplateSettings === 'function')) {
284
- _context4.next = 9;
285
- break;
286
- }
287
- _context4.next = 9;
288
- return this.invoiceOpenDataModule.ensureInvoiceTemplateSettings(target);
289
- case 9:
290
- return _context4.abrupt("return", cachedData);
291
- case 10:
292
- if (!this.invoiceOpenDataInFlight) {
293
- _context4.next = 21;
294
- break;
295
- }
296
- if (!(this.invoiceOpenDataInFlightTarget === target)) {
297
- _context4.next = 13;
298
- break;
299
- }
300
- return _context4.abrupt("return", this.invoiceOpenDataInFlight);
301
- case 13:
302
- _context4.prev = 13;
303
- _context4.next = 16;
304
- return this.invoiceOpenDataInFlight;
305
- case 16:
306
- _context4.next = 20;
307
- break;
308
- case 18:
309
- _context4.prev = 18;
310
- _context4.t0 = _context4["catch"](13);
311
- case 20:
312
- return _context4.abrupt("return", this.loadInvoiceOpenData(businessCode, channel));
313
- case 21:
314
- request = this.invoiceOpenDataModule.fetchOpenData({
315
- scope: 'board',
316
- target: target,
317
- section_code: [].concat(INVOICE_OPEN_DATA_SECTION_CODES)
318
- });
319
- this.invoiceOpenDataInFlight = request;
320
- this.invoiceOpenDataInFlightTarget = target;
321
- _context4.prev = 24;
322
- _context4.next = 27;
323
- return request;
324
- case 27:
325
- openData = _context4.sent;
326
- // clearOpenDataCache() 或后续请求接管后,旧响应不得复活 target 归属。
327
- if (this.invoiceOpenDataInFlight === request) {
328
- this.invoiceOpenDataTarget = target;
329
- }
330
- return _context4.abrupt("return", openData);
331
- case 30:
332
- _context4.prev = 30;
333
- if (this.invoiceOpenDataInFlight === request) {
334
- this.invoiceOpenDataInFlight = null;
335
- this.invoiceOpenDataInFlightTarget = null;
336
- }
337
- return _context4.finish(30);
338
- case 33:
339
- case "end":
340
- return _context4.stop();
341
- }
342
- }, _callee4, this, [[13, 18], [24,, 30, 33]]);
343
- }));
344
- function loadInvoiceOpenData(_x4, _x5) {
345
- return _loadInvoiceOpenData.apply(this, arguments);
346
- }
347
- return loadInvoiceOpenData;
348
- }()
349
253
  }, {
350
254
  key: "logInvoiceOpenDataFallback",
351
255
  value: function logInvoiceOpenDataFallback(error) {
@@ -366,43 +270,41 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
366
270
  }, {
367
271
  key: "resolveInvoiceConfigs",
368
272
  value: function () {
369
- var _resolveInvoiceConfigs = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(businessCode, channel) {
370
- var _this$invoiceOpenData, _this$invoiceOpenData2, _this$invoiceOpenData3, _this$invoiceOpenData4;
371
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
372
- while (1) switch (_context5.prev = _context5.next) {
273
+ var _resolveInvoiceConfigs = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(businessCode, channel) {
274
+ var templateSettings;
275
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
276
+ while (1) switch (_context4.prev = _context4.next) {
373
277
  case 0:
374
- _context5.prev = 0;
375
- _context5.next = 3;
376
- return this.loadInvoiceOpenData(businessCode, channel);
377
- case 3:
378
- if (!(this.invoiceOpenDataTarget !== "".concat(businessCode, "+").concat(channel))) {
379
- _context5.next = 5;
278
+ _context4.prev = 0;
279
+ if (this.invoiceOpenDataModule) {
280
+ _context4.next = 3;
380
281
  break;
381
282
  }
382
- return _context5.abrupt("return", {
383
- invoice: getDefaultInvoiceLayoutConfig(),
384
- templateSettings: getDefaultInvoiceTemplateSettings()
385
- });
283
+ throw new Error('Sales Invoice OpenData 模块未初始化');
284
+ case 3:
285
+ _context4.next = 5;
286
+ return this.invoiceOpenDataModule.loadPrintInvoiceTemplate("".concat(businessCode, "+").concat(channel), 'manual');
386
287
  case 5:
387
- return _context5.abrupt("return", {
388
- invoice: (_this$invoiceOpenData = (_this$invoiceOpenData2 = this.invoiceOpenDataModule) === null || _this$invoiceOpenData2 === void 0 ? void 0 : _this$invoiceOpenData2.getInvoiceLayoutConfig()) !== null && _this$invoiceOpenData !== void 0 ? _this$invoiceOpenData : getDefaultInvoiceLayoutConfig(),
389
- templateSettings: (_this$invoiceOpenData3 = (_this$invoiceOpenData4 = this.invoiceOpenDataModule) === null || _this$invoiceOpenData4 === void 0 ? void 0 : _this$invoiceOpenData4.getInvoiceTemplateSettings()) !== null && _this$invoiceOpenData3 !== void 0 ? _this$invoiceOpenData3 : getDefaultInvoiceTemplateSettings()
288
+ templateSettings = _context4.sent;
289
+ return _context4.abrupt("return", {
290
+ invoice: normalizeInvoiceLayoutFromTemplateSettings(templateSettings),
291
+ templateSettings: templateSettings
390
292
  });
391
- case 8:
392
- _context5.prev = 8;
393
- _context5.t0 = _context5["catch"](0);
394
- this.logInvoiceOpenDataFallback(_context5.t0);
395
- return _context5.abrupt("return", {
293
+ case 9:
294
+ _context4.prev = 9;
295
+ _context4.t0 = _context4["catch"](0);
296
+ this.logInvoiceOpenDataFallback(_context4.t0);
297
+ return _context4.abrupt("return", {
396
298
  invoice: getDefaultInvoiceLayoutConfig(),
397
299
  templateSettings: getDefaultInvoiceTemplateSettings()
398
300
  });
399
- case 12:
301
+ case 13:
400
302
  case "end":
401
- return _context5.stop();
303
+ return _context4.stop();
402
304
  }
403
- }, _callee5, this, [[0, 8]]);
305
+ }, _callee4, this, [[0, 9]]);
404
306
  }));
405
- function resolveInvoiceConfigs(_x6, _x7) {
307
+ function resolveInvoiceConfigs(_x4, _x5) {
406
308
  return _resolveInvoiceConfigs.apply(this, arguments);
407
309
  }
408
310
  return resolveInvoiceConfigs;
@@ -410,31 +312,31 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
410
312
  }, {
411
313
  key: "printLocalOrderReceipt",
412
314
  value: function () {
413
- var _printLocalOrderReceipt = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(lookup, options) {
315
+ var _printLocalOrderReceipt = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(lookup, options) {
414
316
  var _options$businessCode;
415
317
  var normalizedLookup, businessCode, channel, _yield$this$resolveIn, invoice, templateSettings, lookupPayload;
416
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
417
- while (1) switch (_context6.prev = _context6.next) {
318
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
319
+ while (1) switch (_context5.prev = _context5.next) {
418
320
  case 0:
419
321
  normalizedLookup = typeof lookup === 'string' ? lookup.trim() : lookup;
420
322
  if (!(normalizedLookup === '' || normalizedLookup === null || normalizedLookup === undefined)) {
421
- _context6.next = 3;
323
+ _context5.next = 3;
422
324
  break;
423
325
  }
424
326
  throw new Error('Sales 本地小票打印需要订单标识');
425
327
  case 3:
426
328
  businessCode = String((_options$businessCode = options === null || options === void 0 ? void 0 : options.businessCode) !== null && _options$businessCode !== void 0 ? _options$businessCode : '').trim();
427
329
  if (businessCode) {
428
- _context6.next = 6;
330
+ _context5.next = 6;
429
331
  break;
430
332
  }
431
333
  throw new Error('Sales 本地小票打印需要 businessCode');
432
334
  case 6:
433
335
  channel = this.getInvoiceSalesChannel(options === null || options === void 0 ? void 0 : options.channel);
434
- _context6.next = 9;
336
+ _context5.next = 9;
435
337
  return this.resolveInvoiceConfigs(businessCode, channel);
436
338
  case 9:
437
- _yield$this$resolveIn = _context6.sent;
339
+ _yield$this$resolveIn = _context5.sent;
438
340
  invoice = _yield$this$resolveIn.invoice;
439
341
  templateSettings = _yield$this$resolveIn.templateSettings;
440
342
  lookupPayload = typeof normalizedLookup === 'number' ? {
@@ -442,7 +344,7 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
442
344
  } : {
443
345
  external_sale_number: normalizedLookup
444
346
  };
445
- return _context6.abrupt("return", this.request.post('/shop/local/print-order', _objectSpread(_objectSpread({}, lookupPayload), {}, {
347
+ return _context5.abrupt("return", this.request.post('/shop/local/print-order', _objectSpread(_objectSpread({}, lookupPayload), {}, {
446
348
  lookup_order_from_db: 1,
447
349
  small_ticket_data_flag: 1,
448
350
  business_code: businessCode,
@@ -455,23 +357,95 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
455
357
  }));
456
358
  case 14:
457
359
  case "end":
458
- return _context6.stop();
360
+ return _context5.stop();
459
361
  }
460
- }, _callee6, this);
362
+ }, _callee5, this);
461
363
  }));
462
- function printLocalOrderReceipt(_x8, _x9) {
364
+ function printLocalOrderReceipt(_x6, _x7) {
463
365
  return _printLocalOrderReceipt.apply(this, arguments);
464
366
  }
465
367
  return printLocalOrderReceipt;
368
+ }()
369
+ }, {
370
+ key: "printCloudOrderInvoice",
371
+ value: function () {
372
+ var _printCloudOrderInvoice = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(input) {
373
+ var _lookup$data;
374
+ var orderId, channel, openData, requestOptions, lookup, businessCode, settings, result;
375
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
376
+ while (1) switch (_context6.prev = _context6.next) {
377
+ case 0:
378
+ orderId = input === null || input === void 0 ? void 0 : input.order_id;
379
+ channel = typeof (input === null || input === void 0 ? void 0 : input.channel) === 'string' ? input.channel.trim() : '';
380
+ if (channel) {
381
+ _context6.next = 4;
382
+ break;
383
+ }
384
+ throw new Error('Cloud Invoice requires a channel');
385
+ case 4:
386
+ openData = this.invoiceOpenDataModule;
387
+ if (openData) {
388
+ _context6.next = 7;
389
+ break;
390
+ }
391
+ throw new Error('Cloud Invoice is not initialized');
392
+ case 7:
393
+ requestOptions = {
394
+ osServer: true,
395
+ customToast: function customToast() {}
396
+ };
397
+ _context6.next = 10;
398
+ return this.request.post('/shop/local/cloud-order-invoice/lookup', {
399
+ order_id: orderId
400
+ }, requestOptions);
401
+ case 10:
402
+ lookup = _context6.sent;
403
+ if (!((lookup === null || lookup === void 0 ? void 0 : lookup.status) !== true || lookup.code !== 200)) {
404
+ _context6.next = 13;
405
+ break;
406
+ }
407
+ throw new Error((lookup === null || lookup === void 0 ? void 0 : lookup.message) || 'Cloud Invoice order lookup failed');
408
+ case 13:
409
+ businessCode = (_lookup$data = lookup.data) === null || _lookup$data === void 0 || (_lookup$data = _lookup$data.business_code) === null || _lookup$data === void 0 ? void 0 : _lookup$data.trim();
410
+ if (businessCode) {
411
+ _context6.next = 16;
412
+ break;
413
+ }
414
+ throw new Error('Cloud Invoice order has no business_code');
415
+ case 16:
416
+ _context6.next = 18;
417
+ return openData.loadCloudInvoiceTemplate("".concat(businessCode, "+").concat(channel));
418
+ case 18:
419
+ settings = _context6.sent;
420
+ _context6.next = 21;
421
+ return this.request.post('/shop/local/cloud-order-invoice/submit', {
422
+ order_id: orderId,
423
+ business_code: businessCode,
424
+ template_settings: settings
425
+ }, requestOptions);
426
+ case 21:
427
+ result = _context6.sent;
428
+ if (!((result === null || result === void 0 ? void 0 : result.status) !== true || result.code !== 200)) {
429
+ _context6.next = 24;
430
+ break;
431
+ }
432
+ throw new Error((result === null || result === void 0 ? void 0 : result.message) || 'Cloud Invoice dispatch failed');
433
+ case 24:
434
+ case "end":
435
+ return _context6.stop();
436
+ }
437
+ }, _callee6, this);
438
+ }));
439
+ function printCloudOrderInvoice(_x8) {
440
+ return _printCloudOrderInvoice.apply(this, arguments);
441
+ }
442
+ return printCloudOrderInvoice;
466
443
  }() /** 清除独立 Documents 缓存;下一次打印会按当前 target 重新获取。 */
467
444
  }, {
468
445
  key: "clearOpenDataCache",
469
446
  value: function clearOpenDataCache() {
470
- var _this$invoiceOpenData5;
471
- this.invoiceOpenDataInFlight = null;
472
- this.invoiceOpenDataInFlightTarget = null;
473
- this.invoiceOpenDataTarget = null;
474
- (_this$invoiceOpenData5 = this.invoiceOpenDataModule) === null || _this$invoiceOpenData5 === void 0 || _this$invoiceOpenData5.clearCache();
447
+ var _this$invoiceOpenData;
448
+ (_this$invoiceOpenData = this.invoiceOpenDataModule) === null || _this$invoiceOpenData === void 0 || _this$invoiceOpenData.clearCache();
475
449
  }
476
450
 
477
451
  // -------------------------------------------------------------------------
@@ -1197,7 +1171,7 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
1197
1171
  }
1198
1172
  }, _callee8, this);
1199
1173
  }));
1200
- function getResourceBookingList(_x10) {
1174
+ function getResourceBookingList(_x9) {
1201
1175
  return _getResourceBookingList.apply(this, arguments);
1202
1176
  }
1203
1177
  return getResourceBookingList;
@@ -1320,7 +1294,7 @@ export var SalesImpl = /*#__PURE__*/function (_BaseModule) {
1320
1294
  }
1321
1295
  }, _callee9, this);
1322
1296
  }));
1323
- function getResourceBookingItem(_x11) {
1297
+ function getResourceBookingItem(_x10) {
1324
1298
  return _getResourceBookingItem.apply(this, arguments);
1325
1299
  }
1326
1300
  return getResourceBookingItem;
@@ -56,6 +56,11 @@ export interface SalesPrintLocalOrderReceiptOptions {
56
56
  /** 当前销售入口;缺失或为 system 时按 pos 处理。 */
57
57
  channel?: string;
58
58
  }
59
+ /** Native cloud-order notification. */
60
+ export interface CloudOrderInvoiceRequest {
61
+ order_id: string | number;
62
+ channel: string;
63
+ }
59
64
  /**
60
65
  * Sales 解决方案状态
61
66
  *
@@ -90,6 +95,7 @@ export interface SalesModuleAPI {
90
95
  changeBookingStatus: (params: ChangeBookingStatusParams) => Promise<any>;
91
96
  /** 按本地订单标识打印小票;本地未命中时由 OS Server 负责远端兜底。 */
92
97
  printLocalOrderReceipt: <T = any>(lookup: string | number, options: SalesPrintLocalOrderReceiptOptions) => Promise<T>;
98
+ printCloudOrderInvoice: (request: CloudOrderInvoiceRequest) => Promise<void>;
93
99
  /** 清除 Legacy Sales 独立维护的 Documents OpenData 缓存。 */
94
100
  clearOpenDataCache: () => void;
95
101
  /** 获取资源维度的预约占用列表 */
@@ -14,6 +14,8 @@ export var SalesHooks = /*#__PURE__*/function (SalesHooks) {
14
14
  * 当前不要直接把 OrderData 当作最终 UI 数据结构。
15
15
  */
16
16
 
17
+ /** Native cloud-order notification. */
18
+
17
19
  /**
18
20
  * Sales 解决方案状态
19
21
  *
@@ -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;