@pisell/pisellos 2.3.113 → 2.3.115

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 (42) hide show
  1. package/dist/modules/Order/index.d.ts +14 -4
  2. package/dist/modules/Order/index.js +316 -248
  3. package/dist/modules/Order/types.d.ts +11 -0
  4. package/dist/modules/Order/utils.d.ts +3 -1
  5. package/dist/modules/Order/utils.js +171 -63
  6. package/dist/modules/Payment/index.d.ts +0 -5
  7. package/dist/modules/Payment/index.js +35 -85
  8. package/dist/modules/ResourcePlanner/planner.js +9 -5
  9. package/dist/modules/ResourcePlanner/types.d.ts +2 -1
  10. package/dist/server/index.js +4 -0
  11. package/dist/server/modules/order/index.js +6 -0
  12. package/dist/server/modules/order/types.d.ts +9 -0
  13. package/dist/server/modules/payment/index.d.ts +25 -6
  14. package/dist/server/modules/payment/index.js +660 -133
  15. package/dist/server/utils/small-ticket.js +108 -4
  16. package/dist/solution/BaseSales/index.d.ts +8 -0
  17. package/dist/solution/BaseSales/index.js +1381 -1141
  18. package/dist/solution/BookingByStep/index.d.ts +1 -1
  19. package/dist/solution/BookingTicket/index.d.ts +2 -1
  20. package/dist/solution/BookingTicket/index.js +37 -16
  21. package/lib/model/strategy/adapter/promotion/index.js +1 -46
  22. package/lib/modules/Order/index.d.ts +14 -4
  23. package/lib/modules/Order/index.js +50 -15
  24. package/lib/modules/Order/types.d.ts +11 -0
  25. package/lib/modules/Order/utils.d.ts +3 -1
  26. package/lib/modules/Order/utils.js +101 -0
  27. package/lib/modules/Payment/index.d.ts +0 -5
  28. package/lib/modules/Payment/index.js +3 -28
  29. package/lib/modules/ResourcePlanner/planner.js +9 -5
  30. package/lib/modules/ResourcePlanner/types.d.ts +2 -1
  31. package/lib/server/index.js +4 -0
  32. package/lib/server/modules/order/index.js +6 -0
  33. package/lib/server/modules/order/types.d.ts +9 -0
  34. package/lib/server/modules/payment/index.d.ts +25 -6
  35. package/lib/server/modules/payment/index.js +350 -78
  36. package/lib/server/utils/small-ticket.js +114 -11
  37. package/lib/solution/BaseSales/index.d.ts +8 -0
  38. package/lib/solution/BaseSales/index.js +134 -22
  39. package/lib/solution/BookingByStep/index.d.ts +1 -1
  40. package/lib/solution/BookingTicket/index.d.ts +2 -1
  41. package/lib/solution/BookingTicket/index.js +23 -5
  42. package/package.json +1 -1
@@ -5,18 +5,33 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.PaymentServerModule = void 0;
7
7
  var _BaseModule = require("../../../modules/BaseModule");
8
+ var _lodashEs = require("lodash-es");
8
9
  const WALLET_PASS_CODE = 'WALLET_PASS';
9
10
  const WALLET_DEPENDENT_CODES = new Set(['PRODUCTVOUCHER', 'GIFTCARD', 'POINTCARD']);
10
11
  const PAYMENT_METHODS_LOADED_EVENT = 'payment:onPaymentMethodsLoaded';
12
+ const PAYMENT_METHODS_CHANGED_EVENT = 'payment:onPaymentMethodsChanged';
13
+ const PAYMENT_METHOD_STORE_NAME = 'pay_method';
14
+ const CUSTOM_PAYMENT_MODULE = 'custom_payment';
15
+ const PAYMENT_METHOD_SYNC_DEBOUNCE_MS = 500;
16
+ const SNAPSHOT_ORDER_FIELD = '__payment_snapshot_order';
17
+ const SNAPSHOT_SHOP_ID_FIELD = '__payment_snapshot_shop_id';
11
18
  class PaymentServerModule extends _BaseModule.BaseModule {
12
19
  defaultName = 'payment';
13
20
  defaultVersion = '1.0.0';
14
21
  request;
15
22
  app;
16
23
  logger;
24
+ dbManager;
17
25
  store;
18
- payMethodMemoryCache = null;
19
- payMethodListInFlight = null;
26
+ paymentDataSource;
27
+ initialLoadInFlight = null;
28
+ refreshInFlight = null;
29
+ hasLoadedPayMethods = false;
30
+ hasEmittedLoaded = false;
31
+ syncTimer;
32
+ pendingMessageUuids = new Set();
33
+ queuedTrailingRefresh = false;
34
+ trailingMessageUuids = new Set();
20
35
  constructor(name, version) {
21
36
  super(name || 'payment', version);
22
37
  }
@@ -31,78 +46,327 @@ class PaymentServerModule extends _BaseModule.BaseModule {
31
46
  const appPlugin = core.getPlugin('app');
32
47
  this.app = appPlugin?.getApp();
33
48
  this.logger = this.app?.logger;
49
+ this.dbManager = this.app?.sqlite;
34
50
  if (!this.request && !this.app?.request) {
35
51
  throw new Error('PaymentServerModule 需要 request 插件或 app.request 支持');
36
52
  }
53
+ this.initPaymentDataSource();
54
+ this.setupPaymentMethodSync();
37
55
  this.logInfo('PaymentServerModule initialized successfully', {
38
- hasAppRequest: !!this.app?.request
56
+ hasAppRequest: !!this.app?.request,
57
+ hasSQLite: !!this.dbManager,
58
+ hasPaymentDataSource: !!this.paymentDataSource
39
59
  });
40
60
  }
41
-
42
- // getRoutes(): RouteDefinition[] {
43
- // return [
44
- // {
45
- // method: 'get',
46
- // path: '/pay/custom-payment/all',
47
- // handler: async ({ data, config }) => {
48
- // const payMethods = await this.getPayMethodListAsync({
49
- // shouldFilter: this.shouldFilterPayMethods(data, config),
50
- // });
51
- // return {
52
- // code: 200,
53
- // status: true,
54
- // data: payMethods,
55
- // };
56
- // },
57
- // },
58
- // ];
59
- // }
60
-
61
+ async preload() {
62
+ try {
63
+ await this.ensureInitialPayMethods('preload');
64
+ } catch (error) {
65
+ this.logError('preload 支付方式失败,保持空列表并允许后续读取重试', {
66
+ error: this.getErrorMessage(error)
67
+ });
68
+ }
69
+ }
61
70
  async getPayMethodListAsync(options = {}) {
62
- this.logInfo('Starting getPayMethodListAsync');
63
- if (this.payMethodMemoryCache?.length) {
64
- return this.resolvePayMethods(this.payMethodMemoryCache, options);
71
+ this.logInfo('Starting getPayMethodListAsync', {
72
+ hasLoadedPayMethods: this.hasLoadedPayMethods,
73
+ cachedCount: this.store.payMethods.length
74
+ });
75
+ if (!this.hasLoadedPayMethods) {
76
+ try {
77
+ await this.ensureInitialPayMethods('route');
78
+ } catch (error) {
79
+ this.logError('getPayMethodListAsync 初始化失败', {
80
+ error: this.getErrorMessage(error)
81
+ });
82
+ }
83
+ } else if (!this.paymentDataSource) {
84
+ try {
85
+ await this.refreshPayMethodsSingleFlight({
86
+ trigger: 'compat.route',
87
+ emitChanged: false
88
+ });
89
+ } catch (error) {
90
+ this.logWarning('兼容模式远端刷新失败,保留当前运行态快照', {
91
+ error: this.getErrorMessage(error)
92
+ });
93
+ }
65
94
  }
66
- if (this.payMethodListInFlight) {
67
- const payMethods = await this.payMethodListInFlight;
68
- return this.resolvePayMethods(payMethods, options);
95
+ return this.resolvePayMethods(this.store.payMethods, options);
96
+ }
97
+ async ensureInitialPayMethods(trigger) {
98
+ if (this.hasLoadedPayMethods) return this.store.payMethods;
99
+ if (this.initialLoadInFlight) return this.initialLoadInFlight;
100
+ this.initialLoadInFlight = (async () => {
101
+ const localSnapshot = await this.loadPayMethodsFromSQLite();
102
+ if (localSnapshot.available) {
103
+ this.setPayMethodMirror(localSnapshot.methods);
104
+ this.logInfo('从 SQLite 加载支付方式兜底快照', {
105
+ trigger,
106
+ count: localSnapshot.methods.length,
107
+ shopScope: this.resolveCurrentShopScope(localSnapshot.methods)
108
+ });
109
+ }
110
+ try {
111
+ await this.refreshPayMethodsSingleFlight({
112
+ trigger,
113
+ emitChanged: false
114
+ });
115
+ this.hasLoadedPayMethods = true;
116
+ } catch (error) {
117
+ if (!localSnapshot.available) throw error;
118
+ this.hasLoadedPayMethods = true;
119
+ this.logWarning('远端刷新失败,继续使用 SQLite 支付方式快照', {
120
+ trigger,
121
+ count: localSnapshot.methods.length,
122
+ error: this.getErrorMessage(error)
123
+ });
124
+ }
125
+ if (!this.hasEmittedLoaded) {
126
+ this.hasEmittedLoaded = true;
127
+ await this.core.effects.emit(PAYMENT_METHODS_LOADED_EVENT, this.store.payMethods);
128
+ }
129
+ return this.store.payMethods;
130
+ })().finally(() => {
131
+ this.initialLoadInFlight = null;
132
+ });
133
+ return this.initialLoadInFlight;
134
+ }
135
+ initPaymentDataSource() {
136
+ const PaymentDataSourceClass = this.core.serverOptions?.All_DATA_SOURCES?.PaymentDataSource;
137
+ if (!PaymentDataSourceClass) {
138
+ this.logWarning('PaymentDataSource 不可用,使用无本地持久化的兼容模式');
139
+ return;
69
140
  }
70
- this.payMethodListInFlight = this.loadPayMethodListAsync().finally(() => {
71
- this.payMethodListInFlight = null;
141
+ this.paymentDataSource = new PaymentDataSourceClass();
142
+ }
143
+ setupPaymentMethodSync() {
144
+ if (!this.paymentDataSource) return;
145
+ this.paymentDataSource.run({
146
+ pubsub: {
147
+ callback: res => {
148
+ const message = res?.data || res;
149
+ if (!message || message.module !== CUSTOM_PAYMENT_MODULE) return;
150
+ const messageUuid = String(message.message_uuid || '').trim();
151
+ if (messageUuid) this.pendingMessageUuids.add(messageUuid);
152
+ this.logInfo('收到 custom_payment Ably 消息,等待全量刷新', {
153
+ message_uuid: messageUuid || undefined,
154
+ action: message.action,
155
+ operation: message.operation
156
+ });
157
+ this.schedulePaymentMethodRefresh();
158
+ }
159
+ }
160
+ }).catch(error => {
161
+ this.logError('建立 custom_payment pubsub 订阅失败', {
162
+ error: this.getErrorMessage(error)
163
+ });
72
164
  });
73
- const payMethods = await this.payMethodListInFlight;
74
- return this.resolvePayMethods(payMethods, options);
75
165
  }
76
- clearPayMethodCache() {
77
- this.payMethodMemoryCache = null;
78
- this.store.payMethods = [];
166
+ schedulePaymentMethodRefresh() {
167
+ if (this.syncTimer) clearTimeout(this.syncTimer);
168
+ this.syncTimer = setTimeout(() => {
169
+ this.syncTimer = undefined;
170
+ const messageUuids = [...this.pendingMessageUuids];
171
+ this.pendingMessageUuids.clear();
172
+ void this.refreshPayMethodsSingleFlight({
173
+ trigger: 'ably',
174
+ emitChanged: true,
175
+ messageUuids
176
+ }).catch(error => {
177
+ this.logError('custom_payment Ably 全量刷新失败,保留旧快照', {
178
+ message_uuids: messageUuids,
179
+ error: this.getErrorMessage(error)
180
+ });
181
+ });
182
+ }, PAYMENT_METHOD_SYNC_DEBOUNCE_MS);
79
183
  }
80
- async loadPayMethodListAsync() {
184
+ async refreshPayMethodsSingleFlight(context) {
185
+ if (this.refreshInFlight) {
186
+ if (context.trigger.startsWith('ably')) {
187
+ this.queuedTrailingRefresh = true;
188
+ context.messageUuids?.forEach(uuid => this.trailingMessageUuids.add(uuid));
189
+ this.logInfo('支付方式刷新进行中,已排队一次尾随刷新', {
190
+ trigger: context.trigger,
191
+ message_uuids: context.messageUuids || []
192
+ });
193
+ }
194
+ return this.refreshInFlight;
195
+ }
196
+ const refreshTask = this.performRemoteRefresh(context);
197
+ this.refreshInFlight = refreshTask;
81
198
  try {
82
- const payMethods = await this.fetchRemotePayMethods();
83
- this.setPayMethodCache(payMethods);
84
- await this.core.effects.emit(PAYMENT_METHODS_LOADED_EVENT, payMethods);
85
- this.logInfo('getPayMethodListAsync completed successfully', {
86
- payMethods
199
+ return await refreshTask;
200
+ } finally {
201
+ if (this.refreshInFlight === refreshTask) this.refreshInFlight = null;
202
+ if (this.queuedTrailingRefresh) {
203
+ this.queuedTrailingRefresh = false;
204
+ const messageUuids = [...this.trailingMessageUuids];
205
+ this.trailingMessageUuids.clear();
206
+ void this.refreshPayMethodsSingleFlight({
207
+ trigger: 'ably.trailing',
208
+ emitChanged: true,
209
+ messageUuids
210
+ }).catch(error => {
211
+ this.logError('custom_payment 尾随刷新失败,保留当前快照', {
212
+ message_uuids: messageUuids,
213
+ error: this.getErrorMessage(error)
214
+ });
215
+ });
216
+ }
217
+ }
218
+ }
219
+ async performRemoteRefresh(context) {
220
+ const oldMethods = this.store.payMethods;
221
+ const payMethods = await this.fetchRemotePayMethods();
222
+ const persisted = await this.replacePayMethodsInSQLite(payMethods);
223
+ if (!persisted) {
224
+ this.logWarning('SQLite 不可用,支付方式仅用于当前运行时', {
225
+ trigger: context.trigger,
226
+ count: payMethods.length
87
227
  });
88
- return payMethods;
89
- } catch (error) {
90
- console.error('[PaymentServerModule] 获取支付方式列表失败', error);
91
- this.logError('getPayMethodListAsync failed', error);
92
- return [];
93
228
  }
229
+ this.setPayMethodMirror(payMethods);
230
+ this.hasLoadedPayMethods = true;
231
+ const changed = !this.arePayMethodsEqual(oldMethods, payMethods);
232
+ if (context.emitChanged && changed) {
233
+ await this.core.effects.emit(PAYMENT_METHODS_CHANGED_EVENT, {
234
+ oldMethods,
235
+ newMethods: this.store.payMethods
236
+ });
237
+ }
238
+ this.logInfo('远端支付方式全量刷新成功', {
239
+ trigger: context.trigger,
240
+ message_uuids: context.messageUuids || [],
241
+ count: payMethods.length,
242
+ persisted,
243
+ changed
244
+ });
245
+ return this.store.payMethods;
94
246
  }
95
247
  async fetchRemotePayMethods() {
96
- const requester = this.app?.request || this.request;
97
- const response = await requester.get('/shop/pay/custom-payment/all', undefined);
98
- const payMethods = response?.data || response || [];
99
- return Array.isArray(payMethods) ? payMethods : [];
248
+ const response = this.paymentDataSource ? await this.paymentDataSource.run({
249
+ http: {
250
+ url: '/shop/pay/custom-payment/all'
251
+ }
252
+ }) : await (this.app?.request || this.request).get('/shop/pay/custom-payment/all', undefined);
253
+ const payMethods = response?.data !== undefined ? response.data : response;
254
+ if (!Array.isArray(payMethods)) {
255
+ throw new Error('支付方式全量接口返回值不是数组');
256
+ }
257
+ if (payMethods.some(method => !method || method.id === undefined || method.id === null)) {
258
+ throw new Error('支付方式全量接口存在缺少 id 的记录');
259
+ }
260
+ return payMethods;
261
+ }
262
+ async loadPayMethodsFromSQLite() {
263
+ if (!this.dbManager) return {
264
+ available: false,
265
+ methods: []
266
+ };
267
+ try {
268
+ const rows = await this.dbManager.getAll(PAYMENT_METHOD_STORE_NAME);
269
+ if (!Array.isArray(rows) || rows.length === 0) {
270
+ return {
271
+ available: false,
272
+ methods: []
273
+ };
274
+ }
275
+ const currentShopScope = this.resolveCurrentShopScope();
276
+ if (!currentShopScope) {
277
+ this.logWarning('无法确认当前店铺,忽略 SQLite 支付方式快照');
278
+ return {
279
+ available: false,
280
+ methods: []
281
+ };
282
+ }
283
+ const scopedRows = rows.filter(row => String(row?.[SNAPSHOT_SHOP_ID_FIELD] || '') === currentShopScope);
284
+ if (scopedRows.length === 0) {
285
+ this.logWarning('忽略其他店铺的 SQLite 支付方式快照', {
286
+ currentShopScope,
287
+ storedShopScopes: [...new Set(rows.map(row => String(row?.[SNAPSHOT_SHOP_ID_FIELD] || '')).filter(Boolean))]
288
+ });
289
+ return {
290
+ available: false,
291
+ methods: []
292
+ };
293
+ }
294
+ const methods = scopedRows.slice().sort((left, right) => Number(left?.[SNAPSHOT_ORDER_FIELD] || 0) - Number(right?.[SNAPSHOT_ORDER_FIELD] || 0)).map(row => this.stripSnapshotFields(row));
295
+ return {
296
+ available: true,
297
+ methods
298
+ };
299
+ } catch (error) {
300
+ this.logWarning('从 SQLite 读取支付方式失败', {
301
+ error: this.getErrorMessage(error)
302
+ });
303
+ return {
304
+ available: false,
305
+ methods: []
306
+ };
307
+ }
308
+ }
309
+ async replacePayMethodsInSQLite(payMethods) {
310
+ if (!this.dbManager) return false;
311
+ const previousRows = await this.dbManager.getAll(PAYMENT_METHOD_STORE_NAME);
312
+ const shopScope = this.resolveCurrentShopScope(payMethods);
313
+ const snapshotRows = payMethods.map((method, index) => ({
314
+ ...method,
315
+ [SNAPSHOT_ORDER_FIELD]: index,
316
+ [SNAPSHOT_SHOP_ID_FIELD]: shopScope
317
+ }));
318
+ try {
319
+ await this.dbManager.clear(PAYMENT_METHOD_STORE_NAME);
320
+ if (snapshotRows.length > 0) {
321
+ await this.dbManager.bulkAdd(PAYMENT_METHOD_STORE_NAME, snapshotRows);
322
+ }
323
+ return true;
324
+ } catch (error) {
325
+ const writeError = this.getErrorMessage(error);
326
+ try {
327
+ await this.dbManager.clear(PAYMENT_METHOD_STORE_NAME);
328
+ if (Array.isArray(previousRows) && previousRows.length > 0) {
329
+ await this.dbManager.bulkAdd(PAYMENT_METHOD_STORE_NAME, previousRows);
330
+ }
331
+ } catch (rollbackError) {
332
+ this.logError('支付方式 SQLite 快照回滚失败', {
333
+ writeError,
334
+ rollbackError: this.getErrorMessage(rollbackError)
335
+ });
336
+ }
337
+ throw new Error(`支付方式 SQLite 全量替换失败: ${writeError}`);
338
+ }
339
+ }
340
+ resolveCurrentShopScope(payMethods = []) {
341
+ const readStorageObject = key => {
342
+ try {
343
+ const raw = this.app?.storage?.getStorage?.(key);
344
+ if (!raw) return {};
345
+ if (typeof raw === 'object') return raw;
346
+ const parsed = JSON.parse(raw);
347
+ return parsed && typeof parsed === 'object' ? parsed : {};
348
+ } catch {
349
+ return {};
350
+ }
351
+ };
352
+ const selectedStore = readStorageObject('selectedStore');
353
+ const core = readStorageObject('core');
354
+ const scope = selectedStore.id ?? selectedStore.shop_id ?? core.id ?? core.shop_id ?? payMethods.find(method => method?.shop_id != null)?.shop_id;
355
+ return scope === undefined || scope === null ? '' : String(scope);
356
+ }
357
+ stripSnapshotFields(row) {
358
+ const {
359
+ [SNAPSHOT_ORDER_FIELD]: _snapshotOrder,
360
+ [SNAPSHOT_SHOP_ID_FIELD]: _snapshotShopId,
361
+ ...method
362
+ } = row;
363
+ return method;
100
364
  }
101
- shouldFilterPayMethods(data, config) {
102
- return data?.filterPaymentMethods === true || config?.filterPaymentMethods === true;
365
+ arePayMethodsEqual(left, right) {
366
+ return (0, _lodashEs.isEqual)(left, right);
103
367
  }
104
368
  resolvePayMethods(payMethods, options) {
105
- if (!options.shouldFilter) return payMethods;
369
+ if (!options.shouldFilter) return [...payMethods];
106
370
  return this.filterPayMethods(payMethods);
107
371
  }
108
372
  filterPayMethods(payMethods) {
@@ -121,48 +385,56 @@ class PaymentServerModule extends _BaseModule.BaseModule {
121
385
  });
122
386
  return availableMethods;
123
387
  }
124
- setPayMethodCache(payMethods) {
125
- this.payMethodMemoryCache = payMethods;
126
- this.store.payMethods = payMethods;
388
+ setPayMethodMirror(payMethods) {
389
+ this.store.payMethods = payMethods.map(method => ({
390
+ ...method
391
+ }));
392
+ }
393
+ getErrorMessage(error) {
394
+ return error instanceof Error ? error.message : String(error);
127
395
  }
128
396
  logInfo(title, metadata) {
129
397
  try {
130
- if (this.logger) {
131
- this.logger.addLog({
132
- type: 'info',
133
- title: `[PaymentServerModule] ${title}`,
134
- metadata: metadata || {}
135
- });
136
- }
398
+ this.logger?.addLog({
399
+ type: 'info',
400
+ title: `[PaymentServerModule] ${title}`,
401
+ metadata: metadata || {}
402
+ });
137
403
  } catch {
138
404
  // 日志记录失败不影响主流程
139
405
  }
140
406
  }
141
407
  logWarning(title, metadata) {
142
408
  try {
143
- if (this.logger) {
144
- this.logger.addLog({
145
- type: 'warning',
146
- title: `[PaymentServerModule] ${title}`,
147
- metadata: metadata || {}
148
- });
149
- }
409
+ this.logger?.addLog({
410
+ type: 'warning',
411
+ title: `[PaymentServerModule] ${title}`,
412
+ metadata: metadata || {}
413
+ });
150
414
  } catch {
151
415
  // 日志记录失败不影响主流程
152
416
  }
153
417
  }
154
418
  logError(title, metadata) {
155
419
  try {
156
- if (this.logger) {
157
- this.logger.addLog({
158
- type: 'error',
159
- title: `[PaymentServerModule] ${title}`,
160
- metadata: metadata || {}
161
- });
162
- }
420
+ this.logger?.addLog({
421
+ type: 'error',
422
+ title: `[PaymentServerModule] ${title}`,
423
+ metadata: metadata || {}
424
+ });
163
425
  } catch {
164
426
  // 日志记录失败不影响主流程
165
427
  }
166
428
  }
429
+ destroy() {
430
+ if (this.syncTimer) clearTimeout(this.syncTimer);
431
+ this.syncTimer = undefined;
432
+ this.pendingMessageUuids.clear();
433
+ this.trailingMessageUuids.clear();
434
+ this.queuedTrailingRefresh = false;
435
+ this.paymentDataSource?.destroy?.();
436
+ this.paymentDataSource = undefined;
437
+ super.destroy();
438
+ }
167
439
  }
168
440
  exports.PaymentServerModule = PaymentServerModule;
@@ -1378,20 +1378,30 @@ function resolveRefundPayment(refund, payments) {
1378
1378
  return matchedPayment || refund;
1379
1379
  }
1380
1380
  function buildWallets(params) {
1381
+ const virtualCurrencySnapshots = collectVirtualCurrencySnapshots(params.order);
1381
1382
  const displayedWalletPayments = normalizeArray(params.order.payments).filter(payment => isPrintablePayment(payment) && !!getFundRecord(payment));
1382
- const paymentWallets = displayedWalletPayments.map(payment => buildPaymentItems({
1383
- payment,
1384
- locale: params.locale,
1385
- currencySymbol: params.currencySymbol,
1386
- includeFundRecordBalance: true,
1387
- includeFundRecordUsage: false,
1388
- includePaymentAmount: false
1389
- }));
1383
+ const paymentWallets = displayedWalletPayments.map(payment => {
1384
+ const virtualCurrencySnapshot = findVirtualCurrencySnapshotForPayment(payment, virtualCurrencySnapshots.byId);
1385
+ return buildPaymentItems({
1386
+ payment,
1387
+ locale: params.locale,
1388
+ currencySymbol: params.currencySymbol,
1389
+ includeFundRecordBalance: true,
1390
+ includeFundRecordUsage: false,
1391
+ includePaymentAmount: false,
1392
+ virtualCurrencyUnit: virtualCurrencySnapshot ? getVirtualCurrencySnapshotUnit(virtualCurrencySnapshot, params.locale) : undefined
1393
+ });
1394
+ });
1390
1395
  const displayedWalletPassIds = collectDisplayedWalletPassIds(displayedWalletPayments);
1391
1396
  return [...paymentWallets, ...buildVoucherAssets(params), ...buildPointCardSnapshotAssets({
1392
1397
  order: params.order,
1393
1398
  locale: params.locale,
1394
1399
  displayedWalletPassIds
1400
+ }), ...buildVirtualCurrencySnapshotAssets({
1401
+ snapshots: virtualCurrencySnapshots.items,
1402
+ order: params.order,
1403
+ locale: params.locale,
1404
+ displayedWalletPassIds
1395
1405
  })];
1396
1406
  }
1397
1407
  function collectDisplayedWalletPassIds(payments) {
@@ -1438,6 +1448,88 @@ function buildPointCardSnapshotAssets(params) {
1438
1448
  return [rows];
1439
1449
  });
1440
1450
  }
1451
+ function collectVirtualCurrencySnapshots(order) {
1452
+ const items = [];
1453
+ const byId = new Map();
1454
+ const snapshots = order.order_meta_list?.virtual_currency_snapshot;
1455
+ if (!Array.isArray(snapshots)) return {
1456
+ items,
1457
+ byId
1458
+ };
1459
+ snapshots.forEach(snapshot => {
1460
+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return;
1461
+ const virtualCurrency = snapshot;
1462
+ if (stringify(virtualCurrency.tag).trim().toLowerCase() !== 'virtual_currency') return;
1463
+ const id = normalizeWalletPassId(virtualCurrency.id);
1464
+ if (!id || byId.has(id)) return;
1465
+ byId.set(id, virtualCurrency);
1466
+ items.push(virtualCurrency);
1467
+ });
1468
+ return {
1469
+ items,
1470
+ byId
1471
+ };
1472
+ }
1473
+ function findVirtualCurrencySnapshotForPayment(payment, snapshotsById) {
1474
+ const fundRecord = getFundRecord(payment);
1475
+ for (const value of [fundRecord?.voucher_id, payment.voucher_id]) {
1476
+ const id = normalizeWalletPassId(value);
1477
+ if (!id) continue;
1478
+ const snapshot = snapshotsById.get(id);
1479
+ if (snapshot) return snapshot;
1480
+ }
1481
+ return undefined;
1482
+ }
1483
+ function buildVirtualCurrencySnapshotAssets(params) {
1484
+ const snapshotTime = firstPresentValue(params.order.updated_at, params.order.created_at);
1485
+ return params.snapshots.flatMap(virtualCurrency => {
1486
+ const id = normalizeWalletPassId(virtualCurrency.id);
1487
+ if (!id || params.displayedWalletPassIds.has(id)) return [];
1488
+ const rows = [{
1489
+ item: stringify(virtualCurrency.product_name).trim(),
1490
+ value: ''
1491
+ }];
1492
+ const balance = getVirtualCurrencySnapshotBalance(virtualCurrency);
1493
+ if (balance) {
1494
+ rows.push({
1495
+ item: label(params.locale, 'balance'),
1496
+ value: formatVirtualCurrencyBalance(balance, getVirtualCurrencySnapshotUnit(virtualCurrency, params.locale))
1497
+ });
1498
+ }
1499
+ if (isPresentId(snapshotTime)) {
1500
+ rows.push({
1501
+ item: formatDateTime(snapshotTime, params.locale),
1502
+ value: ''
1503
+ });
1504
+ }
1505
+ return [rows];
1506
+ });
1507
+ }
1508
+ function getVirtualCurrencySnapshotBalance(snapshot) {
1509
+ if (!isNumericAmount(snapshot.par_value) || !isNumericAmount(snapshot.used_par_value)) {
1510
+ return null;
1511
+ }
1512
+ return _decimal.default.max(new _decimal.default(snapshot.par_value).minus(new _decimal.default(snapshot.used_par_value)), 0);
1513
+ }
1514
+ function getVirtualCurrencySnapshotUnit(snapshot, locale) {
1515
+ return getNonEmptyLocalizedValue(snapshot.name, locale);
1516
+ }
1517
+ function getNonEmptyLocalizedValue(value, locale) {
1518
+ if (value === undefined || value === null) return '';
1519
+ if (typeof value !== 'object' || Array.isArray(value)) return stringify(value).trim();
1520
+ const dashedLocale = locale.replace('_', '-');
1521
+ const underscoredLocale = locale.replace('-', '_');
1522
+ for (const candidate of [value[locale], value[dashedLocale], value[underscoredLocale], value.original, value.auto, value.default, value.en]) {
1523
+ const text = stringify(candidate).trim();
1524
+ if (text) return text;
1525
+ }
1526
+ return '';
1527
+ }
1528
+ function formatVirtualCurrencyBalance(value, unit) {
1529
+ const amount = trimDecimal(value);
1530
+ const normalizedUnit = unit.trim();
1531
+ return normalizedUnit ? `${amount} ${normalizedUnit}` : amount;
1532
+ }
1441
1533
  function normalizeWalletPassId(value) {
1442
1534
  if (typeof value === 'number') return Number.isFinite(value) ? String(value) : null;
1443
1535
  if (typeof value !== 'string') return null;
@@ -1604,7 +1696,8 @@ function buildPaymentItems(params) {
1604
1696
  currencySymbol,
1605
1697
  includeFundRecordBalance,
1606
1698
  includeFundRecordUsage,
1607
- includePaymentAmount
1699
+ includePaymentAmount,
1700
+ virtualCurrencyUnit
1608
1701
  } = params;
1609
1702
  const serviceFee = getPaymentServiceFee(payment);
1610
1703
  const items = [{
@@ -1630,7 +1723,8 @@ function buildPaymentItems(params) {
1630
1723
  locale,
1631
1724
  currencySymbol,
1632
1725
  includeBalance: includeFundRecordBalance,
1633
- includeUsage: includeFundRecordUsage
1726
+ includeUsage: includeFundRecordUsage,
1727
+ virtualCurrencyUnit
1634
1728
  }));
1635
1729
  } else {
1636
1730
  const remainingAmount = payment.remaining_amount ?? payment.balance ?? payment.metadata?.remaining_amount;
@@ -1695,7 +1789,8 @@ function buildFundRecordPaymentItems(params) {
1695
1789
  locale,
1696
1790
  currencySymbol,
1697
1791
  includeBalance,
1698
- includeUsage
1792
+ includeUsage,
1793
+ virtualCurrencyUnit
1699
1794
  } = params;
1700
1795
  const items = [];
1701
1796
  const usingBeforeValue = fundRecord.using_before_value;
@@ -1717,6 +1812,14 @@ function buildFundRecordPaymentItems(params) {
1717
1812
  return items;
1718
1813
  }
1719
1814
  if (includeBalance && usingAfterValue !== undefined && usingAfterValue !== null) {
1815
+ if (virtualCurrencyUnit !== undefined) {
1816
+ if (!isNumericAmount(usingAfterValue)) return items;
1817
+ items.push({
1818
+ item: label(locale, 'balance'),
1819
+ value: formatVirtualCurrencyBalance(new _decimal.default(usingAfterValue), virtualCurrencyUnit)
1820
+ });
1821
+ return items;
1822
+ }
1720
1823
  items.push({
1721
1824
  item: label(locale, 'balance'),
1722
1825
  value: formatMoney(usingAfterValue, currencySymbol)