@pisell/pisellos 2.3.221 → 2.3.223

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.
@@ -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) {
@@ -219,22 +223,85 @@ class OpenDataModule extends _BaseModule.BaseModule {
219
223
  } : {})
220
224
  });
221
225
  }
226
+ loadCloudInvoiceTemplate(target) {
227
+ return this.loadPrintInvoiceTemplate(target, 'cloud');
228
+ }
222
229
 
223
- /** Cloud orders must resolve their own channel's template before printing. */
224
- async loadCloudInvoiceTemplate(target) {
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;
267
+ }
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) {
225
274
  const response = await this.requestOpenData({
226
275
  scope: 'board',
227
276
  target,
228
277
  section_code: ['documents']
229
278
  }, true);
279
+ assertCurrent();
230
280
  if (response?.status !== true || response.code !== 200 || !isRecord(response.data)) {
231
281
  throw new Error(response?.message || 'Cloud Invoice settings unavailable');
232
282
  }
283
+ if (skipDocument) return {
284
+ settings: (0, _utils.getDefaultInvoiceTemplateSettings)()
285
+ };
233
286
  const raw = response.data['documents.invoice_template'];
234
287
  const documentId = resolveInvoiceDocumentId(raw);
235
- if (documentId) return this.fetchInvoiceTemplateDocument(documentId, true);
236
- if (raw == null || typeof raw === 'string' && !raw.trim()) return (0, _utils.getDefaultInvoiceTemplateSettings)();
237
- if (isLegacyInvoiceTemplate(raw)) return (0, _utils.normalizeInvoiceTemplateSettings)(response.data);
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
+ };
238
305
  throw new Error('Cloud Invoice template identifier is invalid');
239
306
  }
240
307
  getOpenData() {
@@ -251,7 +318,7 @@ class OpenDataModule extends _BaseModule.BaseModule {
251
318
  const documentId = resolveInvoiceDocumentId(this.store.data?.['documents.invoice_template']);
252
319
  if (documentId) {
253
320
  const target = this.store.invoiceTemplateTarget;
254
- if (!target || this.store.invoiceTemplateCacheKey !== this.buildInvoiceTemplateCacheKey(target, documentId)) {
321
+ if (!target || this.store.invoiceTemplateCacheKey !== this.buildInvoiceCacheKey(target, documentId)) {
255
322
  return (0, _utils.getDefaultInvoiceTemplateSettings)();
256
323
  }
257
324
  }
@@ -307,7 +374,7 @@ class OpenDataModule extends _BaseModule.BaseModule {
307
374
  cacheKey: null
308
375
  };
309
376
  }
310
- const cacheKey = this.buildInvoiceTemplateCacheKey(target, documentId);
377
+ const cacheKey = this.buildInvoiceCacheKey(target, documentId);
311
378
  if (this.store.invoiceTemplateTarget === target && this.store.invoiceTemplateDocumentId === documentId && this.store.invoiceTemplateCacheKey === cacheKey && isRecord(this.store.invoiceTemplateSettings)) {
312
379
  return {
313
380
  settings: (0, _utils.normalizeRawInvoiceTemplateSettings)(this.store.invoiceTemplateSettings),
@@ -348,9 +415,9 @@ class OpenDataModule extends _BaseModule.BaseModule {
348
415
  cacheKey
349
416
  };
350
417
  }
351
- buildInvoiceTemplateCacheKey(target, documentId) {
418
+ buildInvoiceCacheKey(target, variant) {
352
419
  const getData = this.appPlugin?.getData?.();
353
- 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]);
354
421
  }
355
422
  async fetchInvoiceTemplateDocument(documentId, strict = false) {
356
423
  const response = await this.request.get(`/document:get?filterByTk=${encodeURIComponent(documentId)}`, {}, {
@@ -395,6 +462,8 @@ class OpenDataModule extends _BaseModule.BaseModule {
395
462
  clearCache() {
396
463
  this.fetchRevision += 1;
397
464
  this.invoiceTemplateCacheRevision += 1;
465
+ this.printInvoiceTemplates.clear();
466
+ this.lastManualPrintKey = undefined;
398
467
  this.invoiceTemplateDocumentCache.clear();
399
468
  this.invoiceTemplateDocumentInFlight.clear();
400
469
  this.store.data = null;
@@ -642,7 +642,7 @@ export declare class OrderModule extends BaseModule implements Module, OrderModu
642
642
  generateIdempotencyToken(): string;
643
643
  syncPaymentsToOrder<T = any>(params: SyncPaymentsToOrderParams): Promise<SyncPaymentsToOrderResult<T>>;
644
644
  createOrder(params: CommitOrderParams['query']): {
645
- type: "appointment_booking" | "virtual";
645
+ type: "virtual" | "appointment_booking";
646
646
  platform: string;
647
647
  sales_channel: string;
648
648
  order_sales_channel: string;
@@ -15,6 +15,23 @@ const DEFAULT_BUSINESS_HOURS = {
15
15
  startTime: '00:00',
16
16
  endTime: '00:00'
17
17
  };
18
+ // Only factory-owned snapshots are immutable. A caller may provide a mutable
19
+ // projection, or freeze its outer object without freezing its products/cells.
20
+ const immutableProjections = new WeakSet();
21
+ const projectionStaticIndices = new WeakMap();
22
+ function getProjectionStaticIndex(projection, key, build) {
23
+ if (!immutableProjections.has(projection)) return build(projection);
24
+ let indices = projectionStaticIndices.get(projection);
25
+ if (!indices) {
26
+ indices = {};
27
+ projectionStaticIndices.set(projection, indices);
28
+ }
29
+ const existing = indices[key];
30
+ if (existing) return existing;
31
+ const index = build(projection);
32
+ indices[key] = index;
33
+ return index;
34
+ }
18
35
  function availabilityError(code, message, details) {
19
36
  return new _types.AvailabilityError(code, message, details);
20
37
  }
@@ -796,10 +813,12 @@ function createAvailabilityProjection(input) {
796
813
  resources,
797
814
  resourceOccupancies
798
815
  };
799
- return deepFreeze({
816
+ const projection = deepFreeze({
800
817
  ...projectionBase,
801
818
  cells: buildCells(projectionBase)
802
819
  });
820
+ immutableProjections.add(projection);
821
+ return projection;
803
822
  }
804
823
  function uniqByOccupancy(occupancies) {
805
824
  const map = new Map();
@@ -1916,8 +1935,8 @@ function queryAvailabilityProjection(projection, request, runtimeOptions = {}) {
1916
1935
  assertRangesWithinProjection(projection, request.selectedRanges);
1917
1936
  }
1918
1937
  const productIdSet = request.productIds?.length ? new Set(request.productIds.map(String)) : null;
1919
- const productIndex = buildProductIndex(projection);
1920
- const cellIndex = buildAvailabilityCellIndex(projection);
1938
+ const productIndex = getProjectionStaticIndex(projection, 'productIndex', buildProductIndex);
1939
+ const cellIndex = getProjectionStaticIndex(projection, 'cellIndex', buildAvailabilityCellIndex);
1921
1940
  const groupResourceIndex = buildGroupResourceIndex({
1922
1941
  projection,
1923
1942
  resourceIds: request.resourceIds,
@@ -2192,14 +2211,14 @@ function validateAvailabilitySelection(projection, params, runtimeOptions = {})
2192
2211
  const normalizedPartySize = normalizePartySize(params.partySize);
2193
2212
  const normalizedBookingCount = normalizeBookingCount(params.bookingCount);
2194
2213
  assertRangesWithinProjection(projection, [params.candidate]);
2195
- const productIndex = buildProductIndex(projection);
2214
+ const productIndex = getProjectionStaticIndex(projection, 'productIndex', buildProductIndex);
2196
2215
  const evaluatedAt = formatDateTime((0, _localClock.localDateToScalar)(new Date()), projection.meta.timezone, (0, _localClock.extractFixedOffsetMinutes)(projection.meta.now) ?? (0, _localClock.captureRuntimeOffsetMinutes)());
2197
2216
  const evaluated = evaluateCandidate(projection, params.candidate, {
2198
2217
  partySize: normalizedPartySize,
2199
2218
  evaluatedAt,
2200
2219
  requirementSelections: params.requirementSelections,
2201
2220
  allowImplicitSelection: false,
2202
- cellIndex: buildAvailabilityCellIndex(projection),
2221
+ cellIndex: getProjectionStaticIndex(projection, 'cellIndex', buildAvailabilityCellIndex),
2203
2222
  productIndex,
2204
2223
  groupResourceIndex: buildGroupResourceIndex({
2205
2224
  projection,
@@ -342,7 +342,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
342
342
  date: string;
343
343
  status: string;
344
344
  week: string;
345
- weekNum: 0 | 2 | 1 | 5 | 3 | 4 | 6;
345
+ weekNum: 0 | 2 | 1 | 3 | 4 | 5 | 6;
346
346
  }[]>;
347
347
  submitTimeSlot(timeSlots: TimeSliceItem): void;
348
348
  private getScheduleDataByIds;
@@ -27,9 +27,6 @@ export declare class SalesImpl extends BaseModule implements Module, SalesModule
27
27
  protected request: RequestPlugin;
28
28
  private logger;
29
29
  private invoiceOpenDataModule;
30
- private invoiceOpenDataTarget;
31
- private invoiceOpenDataInFlight;
32
- private invoiceOpenDataInFlightTarget;
33
30
  constructor(name?: string, version?: string);
34
31
  initialize(core: PisellCore, options?: ModuleOptions): Promise<void>;
35
32
  /** 获取当前 store 快照 */
@@ -51,7 +48,6 @@ export declare class SalesImpl extends BaseModule implements Module, SalesModule
51
48
  * Legacy Sales 的系统上下文没有可打印的 system target,因此统一回退 pos。
52
49
  */
53
50
  private getInvoiceSalesChannel;
54
- private loadInvoiceOpenData;
55
51
  private logInvoiceOpenDataFallback;
56
52
  private resolveInvoiceConfigs;
57
53
  printLocalOrderReceipt<T = any>(lookup: string | number, options: SalesPrintLocalOrderReceiptOptions): Promise<T>;
@@ -26,8 +26,6 @@ Object.keys(_types).forEach(function (key) {
26
26
  var _OpenData = require("../../modules/OpenData");
27
27
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28
28
  const UNPAID_PAYMENT_STATUSES = new Set(['unpaid', 'partially_paid', 'payment_processing']);
29
- const INVOICE_OPEN_DATA_SECTION_CODES = ['documents'];
30
- const INVOICE_OPEN_DATA_CACHE_TTL = 5 * 60 * 1000;
31
29
  /**
32
30
  * Sales 解决方案基础骨架
33
31
  *
@@ -50,9 +48,6 @@ class SalesImpl extends _BaseModule.BaseModule {
50
48
  request;
51
49
  logger; // LoggerManager 实例
52
50
  invoiceOpenDataModule = null;
53
- invoiceOpenDataTarget = null;
54
- invoiceOpenDataInFlight = null;
55
- invoiceOpenDataInFlightTarget = null;
56
51
  constructor(name, version) {
57
52
  super(name, version);
58
53
  }
@@ -85,9 +80,6 @@ class SalesImpl extends _BaseModule.BaseModule {
85
80
  // 在这里补充从 Server/Order 读取 currentDay 原始数据并转换为预约列表。
86
81
 
87
82
  this.logger = appPlugin?.getApp().logger;
88
- this.invoiceOpenDataTarget = null;
89
- this.invoiceOpenDataInFlight = null;
90
- this.invoiceOpenDataInFlightTarget = null;
91
83
  this.invoiceOpenDataModule = new _OpenData.OpenDataModule(`${this.name}_invoiceOpenData`);
92
84
  this.core.registerModule(this.invoiceOpenDataModule, {
93
85
  initialState: {},
@@ -174,51 +166,6 @@ class SalesImpl extends _BaseModule.BaseModule {
174
166
  const normalized = String(channel ?? contextChannel ?? '').trim();
175
167
  return !normalized || normalized === 'system' ? 'pos' : normalized;
176
168
  }
177
- async loadInvoiceOpenData(businessCode, channel) {
178
- if (!this.invoiceOpenDataModule) {
179
- throw new Error('Sales Invoice OpenData 模块未初始化');
180
- }
181
- const target = `${businessCode}+${channel}`;
182
- const cachedData = this.invoiceOpenDataModule.getOpenData();
183
- const lastFetchedAt = this.invoiceOpenDataModule.getLastFetchedAt();
184
- if (cachedData && this.invoiceOpenDataTarget === target && typeof lastFetchedAt === 'number' && Date.now() - lastFetchedAt < INVOICE_OPEN_DATA_CACHE_TTL) {
185
- if (typeof this.invoiceOpenDataModule.ensureInvoiceTemplateSettings === 'function') {
186
- await this.invoiceOpenDataModule.ensureInvoiceTemplateSettings(target);
187
- }
188
- return cachedData;
189
- }
190
- if (this.invoiceOpenDataInFlight) {
191
- if (this.invoiceOpenDataInFlightTarget === target) {
192
- return this.invoiceOpenDataInFlight;
193
- }
194
- try {
195
- await this.invoiceOpenDataInFlight;
196
- } catch {
197
- // 另一 target 的失败不应阻断当前 target 获取自己的 Documents 配置。
198
- }
199
- return this.loadInvoiceOpenData(businessCode, channel);
200
- }
201
- const request = this.invoiceOpenDataModule.fetchOpenData({
202
- scope: 'board',
203
- target,
204
- section_code: [...INVOICE_OPEN_DATA_SECTION_CODES]
205
- });
206
- this.invoiceOpenDataInFlight = request;
207
- this.invoiceOpenDataInFlightTarget = target;
208
- try {
209
- const openData = await request;
210
- // clearOpenDataCache() 或后续请求接管后,旧响应不得复活 target 归属。
211
- if (this.invoiceOpenDataInFlight === request) {
212
- this.invoiceOpenDataTarget = target;
213
- }
214
- return openData;
215
- } finally {
216
- if (this.invoiceOpenDataInFlight === request) {
217
- this.invoiceOpenDataInFlight = null;
218
- this.invoiceOpenDataInFlightTarget = null;
219
- }
220
- }
221
- }
222
169
  logInvoiceOpenDataFallback(error) {
223
170
  const message = error instanceof Error ? error.message : String(error);
224
171
  if (this.logger?.addLog) {
@@ -235,16 +182,11 @@ class SalesImpl extends _BaseModule.BaseModule {
235
182
  }
236
183
  async resolveInvoiceConfigs(businessCode, channel) {
237
184
  try {
238
- await this.loadInvoiceOpenData(businessCode, channel);
239
- if (this.invoiceOpenDataTarget !== `${businessCode}+${channel}`) {
240
- return {
241
- invoice: (0, _OpenData.getDefaultInvoiceLayoutConfig)(),
242
- templateSettings: (0, _OpenData.getDefaultInvoiceTemplateSettings)()
243
- };
244
- }
185
+ if (!this.invoiceOpenDataModule) throw new Error('Sales Invoice OpenData 模块未初始化');
186
+ const templateSettings = await this.invoiceOpenDataModule.loadPrintInvoiceTemplate(`${businessCode}+${channel}`, 'manual');
245
187
  return {
246
- invoice: this.invoiceOpenDataModule?.getInvoiceLayoutConfig() ?? (0, _OpenData.getDefaultInvoiceLayoutConfig)(),
247
- templateSettings: this.invoiceOpenDataModule?.getInvoiceTemplateSettings() ?? (0, _OpenData.getDefaultInvoiceTemplateSettings)()
188
+ invoice: (0, _OpenData.normalizeInvoiceLayoutFromTemplateSettings)(templateSettings),
189
+ templateSettings
248
190
  };
249
191
  } catch (error) {
250
192
  this.logInvoiceOpenDataFallback(error);
@@ -317,9 +259,6 @@ class SalesImpl extends _BaseModule.BaseModule {
317
259
 
318
260
  /** 清除独立 Documents 缓存;下一次打印会按当前 target 重新获取。 */
319
261
  clearOpenDataCache() {
320
- this.invoiceOpenDataInFlight = null;
321
- this.invoiceOpenDataInFlightTarget = null;
322
- this.invoiceOpenDataTarget = null;
323
262
  this.invoiceOpenDataModule?.clearCache();
324
263
  }
325
264
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "2.3.221",
4
+ "version": "2.3.223",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",