@pisell/pisellos 2.3.109 → 2.3.110

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.
@@ -27,13 +27,20 @@ const LABELS = {
27
27
  eftpos: 'Eftpos',
28
28
  wallet: 'Wallet',
29
29
  giftCard: 'Gift card',
30
+ pointCard: 'Point card',
30
31
  balance: 'Balance',
32
+ validity: 'Validity',
31
33
  remainingAmount: 'Remaining amount',
32
34
  redeemPoints: 'Redeem points',
33
- remainingPoints: 'Remaining points',
35
+ remainingPoints: 'Points balance',
34
36
  table: 'Table',
37
+ bookingId: 'Booking ID',
38
+ bookingDateTime: 'Date & time',
39
+ bookingResource: 'Resource',
40
+ bookingHolder: 'Holder',
35
41
  orderDiscount: 'Order discount',
36
42
  manualDiscount: 'Manual discount',
43
+ manualMarkup: 'Manual markup',
37
44
  payProcessingFee: 'Pay processing fee',
38
45
  surchargeIncluded: 'Surcharge(Included)',
39
46
  rounding: 'Rounding',
@@ -59,13 +66,20 @@ const LABELS = {
59
66
  eftpos: '刷卡支付',
60
67
  wallet: '钱包支付',
61
68
  giftCard: '礼品卡',
69
+ pointCard: '积分卡',
62
70
  balance: '余额',
71
+ validity: '有效期',
63
72
  remainingAmount: '剩余金额',
64
73
  redeemPoints: '本次使用积分',
65
- remainingPoints: '剩余积分',
74
+ remainingPoints: '积分余额',
66
75
  table: '桌台',
76
+ bookingId: '预约编号',
77
+ bookingDateTime: '日期和时间',
78
+ bookingResource: '资源',
79
+ bookingHolder: '预约人',
67
80
  orderDiscount: '整单折扣',
68
81
  manualDiscount: '手动折扣',
82
+ manualMarkup: '手动加价',
69
83
  payProcessingFee: '支付手续费',
70
84
  surchargeIncluded: '手续费(已含)',
71
85
  rounding: '抹零',
@@ -91,13 +105,20 @@ const LABELS = {
91
105
  eftpos: '刷卡支付',
92
106
  wallet: '錢包支付',
93
107
  giftCard: '禮品卡',
108
+ pointCard: '積分卡',
94
109
  balance: '餘額',
110
+ validity: '有效期',
95
111
  remainingAmount: '剩餘金額',
96
112
  redeemPoints: '本次使用積分',
97
- remainingPoints: '剩餘積分',
113
+ remainingPoints: '積分餘額',
98
114
  table: '桌台',
115
+ bookingId: '預約編號',
116
+ bookingDateTime: '日期和時間',
117
+ bookingResource: '資源',
118
+ bookingHolder: '預約人',
99
119
  orderDiscount: '整單折扣',
100
120
  manualDiscount: '手動折扣',
121
+ manualMarkup: '手動加價',
101
122
  payProcessingFee: '支付手續費',
102
123
  surchargeIncluded: '手續費(已含)',
103
124
  rounding: '抹零',
@@ -121,13 +142,20 @@ const LABELS = {
121
142
  eftpos: 'カード',
122
143
  wallet: 'ウォレット',
123
144
  giftCard: 'ギフトカード',
145
+ pointCard: 'ポイントカード',
124
146
  balance: '残高',
147
+ validity: '有効期限',
125
148
  remainingAmount: '残高',
126
149
  redeemPoints: '利用ポイント',
127
- remainingPoints: '残りポイント',
150
+ remainingPoints: 'ポイント残高',
128
151
  table: 'テーブル',
152
+ bookingId: '予約ID',
153
+ bookingDateTime: '日時',
154
+ bookingResource: 'リソース',
155
+ bookingHolder: '予約者',
129
156
  orderDiscount: '注文割引',
130
157
  manualDiscount: '手動割引',
158
+ manualMarkup: '手動値上げ',
131
159
  payProcessingFee: '決済手数料',
132
160
  rounding: '端数調整',
133
161
  gross: '総重量',
@@ -152,13 +180,20 @@ const LABELS = {
152
180
  eftpos: 'Cartão',
153
181
  wallet: 'Carteira',
154
182
  giftCard: 'Cartão-presente',
183
+ pointCard: 'Cartão de pontos',
155
184
  balance: 'Saldo',
185
+ validity: 'Validade',
156
186
  remainingAmount: 'Saldo restante',
157
187
  redeemPoints: 'Pontos utilizados',
158
- remainingPoints: 'Pontos restantes',
188
+ remainingPoints: 'Saldo de pontos',
159
189
  table: 'Mesa',
190
+ bookingId: 'ID da reserva',
191
+ bookingDateTime: 'Data e hora',
192
+ bookingResource: 'Recurso',
193
+ bookingHolder: 'Titular',
160
194
  orderDiscount: 'Desconto do pedido',
161
195
  manualDiscount: 'Desconto manual',
196
+ manualMarkup: 'Acréscimo manual',
162
197
  payProcessingFee: 'Taxa de processamento',
163
198
  rounding: 'Arredondamento',
164
199
  gross: 'Peso bruto',
@@ -264,9 +299,7 @@ function buildBaseData(params) {
264
299
  payment_status: financials.paymentStatus,
265
300
  total_amount: formatMoney(financials.totalAmount, currencySymbol),
266
301
  has_pay: formatMoney(financials.netPaymentApplied, currencySymbol),
267
- ...(isPresentId(financials.amountGap) ? {
268
- amount_gap: formatMoney(financials.amountGap, currencySymbol)
269
- } : {}),
302
+ amount_gap: formatCalculatedMoney(financials.amountGap ?? 0, currencySymbol),
270
303
  is_repeat: 0,
271
304
  buzzer: stringify(order.buzzer || order.pickup_number || order.metadata?.buzzer),
272
305
  order_no: orderNumber,
@@ -278,7 +311,8 @@ function buildBaseData(params) {
278
311
  }
279
312
  function buildProducts(order, locale, productMap) {
280
313
  const products = Array.isArray(order.products) ? order.products : [];
281
- return products.map(product => {
314
+ return products.map(rawProduct => {
315
+ const product = restoreReceiptDiscountHierarchy(rawProduct);
282
316
  const quantity = toNumber(product.product_quantity ?? product.quantity ?? product.num ?? 1, 1);
283
317
  const originalPrice = product.original_price ?? product.selling_price ?? product.payment_price ?? product.price ?? 0;
284
318
  const sellingPrice = product.selling_price ?? product.payment_price ?? product.price ?? originalPrice;
@@ -318,15 +352,24 @@ function buildProducts(order, locale, productMap) {
318
352
  });
319
353
  const productNote = resolveProductNote(product, locale);
320
354
  const basePrice = resolveProductBasePrice(product);
355
+ const resolvedCombinations = Array.isArray(product.combinations) && product.combinations.length ? normalizeExistingCombinations(product.combinations, locale, currencySymbol) : combinations;
356
+ const shouldIncludeBasePrice = options.length > 0 || resolvedCombinations.length > 0 || hasProductDiscount(product, extensionList);
321
357
  return {
322
358
  product_title: productTitle,
323
359
  product_quantity: quantity,
324
360
  selling_price: formatMoney(sellingPrice, currencySymbol),
361
+ total_selling_price: formatCalculatedMoney(new _decimal.default(toMoneyNumber(sellingPrice)).mul(quantity), currencySymbol),
325
362
  original_price: formatMoney(originalPrice, currencySymbol),
326
- ...(isPresentId(basePrice) ? {
327
- base_price: formatMoney(basePrice, currencySymbol)
363
+ ...(shouldIncludeBasePrice ? {
364
+ base_price: formatCalculatedMoney(basePrice ?? 0, currencySymbol)
328
365
  } : {}),
329
366
  total_original_price: formatMoney(new _decimal.default(toMoneyNumber(originalPrice)).mul(quantity), currencySymbol),
367
+ ...(options.length ? {
368
+ options_total_price: sumNormalizedOptionTotals(options, currencySymbol)
369
+ } : {}),
370
+ ...(resolvedCombinations.length ? {
371
+ package_items_total_price: sumCombinationTotals(resolvedCombinations, currencySymbol)
372
+ } : {}),
330
373
  extension_list: extensionList,
331
374
  ...(isPresentId(productUid) ? {
332
375
  product_uid: productUid
@@ -343,14 +386,79 @@ function buildProducts(order, locale, productMap) {
343
386
  ...(resolvedVariant ? {
344
387
  variant: resolvedVariant
345
388
  } : {}),
346
- ...(Array.isArray(product.combinations) && product.combinations.length ? {
347
- combinations: normalizeExistingCombinations(product.combinations, locale)
348
- } : combinations.length ? {
349
- combinations
389
+ ...(resolvedCombinations.length ? {
390
+ combinations: resolvedCombinations
350
391
  } : {})
351
392
  };
352
393
  });
353
394
  }
395
+ const RECEIPT_BUNDLE_MAP_ID_KEY = 'custom_product_bundle_map_id';
396
+ function restoreReceiptDiscountHierarchy(source) {
397
+ if (!source || typeof source !== 'object' || Array.isArray(source)) {
398
+ return source;
399
+ }
400
+ const childKey = Array.isArray(source.combinations) && source.combinations.length ? 'combinations' : Array.isArray(source.product_bundle) && source.product_bundle.length ? 'product_bundle' : null;
401
+ if (!childKey) return {
402
+ ...source
403
+ };
404
+ const children = source[childKey].map(child => child && typeof child === 'object' && !Array.isArray(child) ? restoreReceiptDiscountHierarchy(child) : child);
405
+ const restored = {
406
+ ...source,
407
+ [childKey]: children
408
+ };
409
+ if (!Array.isArray(source.discount_list) || !source.discount_list.length) {
410
+ return restored;
411
+ }
412
+ const descendantsByMapId = new Map();
413
+ indexReceiptDiscountTargets(children, descendantsByMapId);
414
+ if (!descendantsByMapId.size) return restored;
415
+ const ownDiscounts = [];
416
+ for (const discount of source.discount_list) {
417
+ const mapId = getReceiptDiscountBundleMapId(discount);
418
+ const target = mapId ? descendantsByMapId.get(mapId) : undefined;
419
+ if (!target) {
420
+ ownDiscounts.push(discount);
421
+ continue;
422
+ }
423
+ const targetDiscounts = Array.isArray(target.discount_list) ? target.discount_list : [];
424
+ if (!targetDiscounts.some(item => isSameReceiptDiscount(item, discount))) {
425
+ target.discount_list = [...targetDiscounts, discount];
426
+ }
427
+ }
428
+ restored.discount_list = ownDiscounts;
429
+ return restored;
430
+ }
431
+ function indexReceiptDiscountTargets(nodes, targets) {
432
+ for (const node of nodes) {
433
+ if (!node || typeof node !== 'object' || Array.isArray(node)) continue;
434
+ const mapId = getReceiptBundleMapId(node);
435
+ if (mapId && !targets.has(mapId)) targets.set(mapId, node);
436
+ const children = Array.isArray(node.combinations) && node.combinations.length ? node.combinations : Array.isArray(node.product_bundle) ? node.product_bundle : [];
437
+ indexReceiptDiscountTargets(children, targets);
438
+ }
439
+ }
440
+ function normalizeReceiptId(value) {
441
+ if (value === undefined || value === null) return null;
442
+ const normalized = String(value).trim();
443
+ return normalized ? normalized : null;
444
+ }
445
+ function getReceiptBundleMapId(node) {
446
+ return normalizeReceiptId(node.metadata?.[RECEIPT_BUNDLE_MAP_ID_KEY] ?? node._id);
447
+ }
448
+ function getReceiptDiscountBundleMapId(discount) {
449
+ return normalizeReceiptId(discount?.metadata?.[RECEIPT_BUNDLE_MAP_ID_KEY]);
450
+ }
451
+ function isSameReceiptDiscount(left, right) {
452
+ const leftOrderDiscountId = normalizeReceiptId(left?.order_discount_id);
453
+ const rightOrderDiscountId = normalizeReceiptId(right?.order_discount_id);
454
+ if (leftOrderDiscountId && rightOrderDiscountId) {
455
+ return leftOrderDiscountId === rightOrderDiscountId;
456
+ }
457
+ const leftResourceId = normalizeReceiptId(left?.discount?.resource_id ?? left?.resource_id ?? left?.discount_id);
458
+ const rightResourceId = normalizeReceiptId(right?.discount?.resource_id ?? right?.resource_id ?? right?.discount_id);
459
+ if (!leftResourceId || !rightResourceId) return false;
460
+ return leftResourceId === rightResourceId && getReceiptDiscountBundleMapId(left) === getReceiptDiscountBundleMapId(right) && String(left?.amount ?? left?.value ?? left?.discount_amount ?? '') === String(right?.amount ?? right?.value ?? right?.discount_amount ?? '');
461
+ }
354
462
  function resolveProductBasePrice(product) {
355
463
  const metadata = product.metadata || {};
356
464
  const origin = product._origin || metadata.origin || {};
@@ -366,15 +474,35 @@ function normalizeProductDiscounts(params) {
366
474
  currencySymbol,
367
475
  quantity
368
476
  } = params;
369
- return normalizeArray(product.discount_list).map(discount => {
477
+ const rows = normalizeArray(product.discount_list).filter(discount => {
478
+ const amount = discount.amount ?? discount.value ?? discount.discount_amount;
479
+ return isNonZero(amount);
480
+ }).map(discount => {
370
481
  const title = resolveDiscountTitleWithPercent(discount, locale);
371
482
  const amount = discount.amount ?? discount.value ?? discount.discount_amount;
372
- const formattedAmount = formatNegativeMoney(new _decimal.default(toMoneyNumber(amount)).mul(quantity), currencySymbol);
483
+ const isMarkup = isManualMarkup(discount);
484
+ const totalAmount = new _decimal.default(toMoneyNumber(amount)).mul(quantity);
485
+ const formattedAmount = isMarkup ? formatMoney(totalAmount.abs(), currencySymbol) : formatNegativeMoney(totalAmount, currencySymbol);
373
486
  return {
374
487
  item: title,
375
- value: formattedAmount
488
+ value: formattedAmount,
489
+ isMarkup
376
490
  };
377
491
  });
492
+ return rows.sort((left, right) => Number(right.isMarkup) - Number(left.isMarkup)).map(({
493
+ isMarkup: _isMarkup,
494
+ ...row
495
+ }) => row);
496
+ }
497
+ function isManualMarkup(discount) {
498
+ if (discount.type !== 'product') return false;
499
+ if (discount.discount?.discount_type === 'change_price') return true;
500
+ const amount = discount.amount ?? discount.value ?? discount.discount_amount;
501
+ return new _decimal.default(toMoneyNumber(amount)).isNegative();
502
+ }
503
+ function hasProductDiscount(product, extensionList = []) {
504
+ const hasDiscountListAmount = normalizeArray(product.discount_list).some(discount => isNonZero(discount.amount ?? discount.value ?? discount.discount_amount));
505
+ return hasDiscountListAmount || extensionList.some(row => /^\s*-/.test(stringify(row?.value)));
378
506
  }
379
507
  function buildProductExtensionList(params) {
380
508
  const {
@@ -457,7 +585,9 @@ function resolveDiscountTitleWithPercent(discount, locale) {
457
585
  function resolveDiscountTitle(discount, locale) {
458
586
  const title = getLocalizedValue(discount.discount?.name ?? discount.discount?.title ?? discount.discount?.message ?? discount.name ?? discount.title ?? discount.message, locale);
459
587
  if (title) return title;
460
- if (discount.type === 'product') return label(locale, 'manualDiscount');
588
+ if (discount.type === 'product') {
589
+ return label(locale, isManualMarkup(discount) ? 'manualMarkup' : 'manualDiscount');
590
+ }
461
591
  return '';
462
592
  }
463
593
  function resolveProductTitle(params) {
@@ -483,6 +613,7 @@ function normalizeProductOptions(params) {
483
613
  const rawOptions = Array.isArray(params.options) ? params.options : Array.isArray(product.options) ? product.options : Array.isArray(product.product_sku?.option) ? product.product_sku.option : [];
484
614
  return rawOptions.map(option => {
485
615
  const price = option.original_price ?? option.add_price ?? option.price;
616
+ const quantity = toNumber(option.num ?? option.quantity ?? 1, 1);
486
617
  const value = option.value ?? option.option ?? option.item;
487
618
  const name = getProductTitleSource(option, locale) || resolveOptionTitleFromParentProduct({
488
619
  option,
@@ -492,11 +623,12 @@ function normalizeProductOptions(params) {
492
623
  return {
493
624
  name,
494
625
  ...(option.num !== undefined || option.quantity !== undefined ? {
495
- num: toNumber(option.num ?? option.quantity, 1)
626
+ num: quantity
496
627
  } : {}),
497
628
  ...(price !== undefined && price !== null && price !== '' ? {
498
629
  price: formatMoney(price, currencySymbol)
499
630
  } : {}),
631
+ total_price: formatCalculatedMoney(new _decimal.default(toMoneyNumber(price ?? 0)).mul(quantity), currencySymbol),
500
632
  ...(value !== undefined && value !== null && value !== '' ? {
501
633
  value: getLocalizedValue(value, locale)
502
634
  } : {})
@@ -527,44 +659,124 @@ function normalizeProductCombinations(params) {
527
659
  parentProduct
528
660
  });
529
661
  const productNote = resolveProductNote(bundle, locale);
530
- const nestedCombinations = Array.isArray(bundle.combinations) ? normalizeExistingCombinations(bundle.combinations, locale) : [];
662
+ const nestedCombinations = Array.isArray(bundle.combinations) ? normalizeExistingCombinations(bundle.combinations, locale, currencySymbol) : [];
663
+ const quantity = toNumber(bundle.num ?? bundle.quantity ?? 1, 1);
664
+ const formattedPrice = formatBundlePrice(bundle, currencySymbol);
665
+ const optionsTotal = sumNormalizedOptionTotals(combinationsOptions, currencySymbol);
666
+ const explicitBasePrice = resolveCombinationBasePrice(bundle);
667
+ const basePrice = isPresentId(explicitBasePrice) ? explicitBasePrice : 0;
668
+ const extensionList = buildProductExtensionList({
669
+ product: bundle,
670
+ locale,
671
+ currencySymbol,
672
+ quantity,
673
+ originalPrice: formattedPrice
674
+ });
675
+ const shouldIncludeBasePrice = combinationsOptions.length > 0 || nestedCombinations.length > 0 || hasProductDiscount(bundle, extensionList);
531
676
  return {
532
677
  product_title: baseTitle,
533
- product_quantity: toNumber(bundle.num ?? bundle.quantity ?? 1, 1),
534
- price: formatBundlePrice(bundle, currencySymbol),
678
+ product_quantity: quantity,
679
+ price: formattedPrice,
680
+ total_selling_price: formatCalculatedMoney(new _decimal.default(toMoneyNumber(formattedPrice)).mul(quantity), currencySymbol),
681
+ ...(shouldIncludeBasePrice ? {
682
+ base_price: formatCalculatedMoney(basePrice, currencySymbol)
683
+ } : {}),
535
684
  combinations_options: combinationsOptions,
685
+ ...(combinationsOptions.length ? {
686
+ options_total_price: optionsTotal
687
+ } : {}),
688
+ ...(nestedCombinations.length ? {
689
+ package_items_total_price: sumCombinationTotals(nestedCombinations, currencySymbol)
690
+ } : {}),
536
691
  ...(productNote ? {
537
692
  product_note: productNote
538
693
  } : {}),
694
+ ...(extensionList.length ? {
695
+ extension_list: extensionList
696
+ } : {}),
539
697
  ...(nestedCombinations.length ? {
540
698
  combinations: nestedCombinations
541
699
  } : {})
542
700
  };
543
701
  });
544
702
  }
545
- function normalizeExistingCombinations(combinations, locale) {
703
+ function normalizeExistingCombinations(combinations, locale, currencySymbol) {
546
704
  return combinations.map(combination => {
547
705
  if (!combination || typeof combination !== 'object' || Array.isArray(combination)) {
548
706
  return combination;
549
707
  }
550
708
  const productNote = resolveProductNote(combination, locale);
551
- const nestedCombinations = Array.isArray(combination.combinations) ? normalizeExistingCombinations(combination.combinations, locale) : undefined;
709
+ const rawOptions = Array.isArray(combination.combinations_options) ? combination.combinations_options : Array.isArray(combination.options) ? combination.options : [];
710
+ const normalizedOptions = normalizeProductOptions({
711
+ product: {},
712
+ locale,
713
+ currencySymbol,
714
+ options: rawOptions
715
+ });
716
+ const nestedCombinations = Array.isArray(combination.combinations) ? normalizeExistingCombinations(combination.combinations, locale, currencySymbol) : [];
552
717
  const snapshot = {
553
718
  ...combination
554
719
  };
555
720
  delete snapshot.product_note;
556
721
  delete snapshot.note;
722
+ delete snapshot.combinations;
723
+ delete snapshot.discount_list;
724
+ const quantity = toNumber(combination.product_quantity ?? combination.num ?? combination.quantity ?? 1, 1);
725
+ const unitPrice = firstPresentValue(combination.selling_price, combination.price, combination.original_price) ?? 0;
726
+ const optionsAmount = sumMoneyValues(normalizedOptions.map(option => option.total_price));
727
+ const explicitBasePrice = resolveCombinationBasePrice(combination, true);
728
+ const basePrice = isPresentId(explicitBasePrice) ? explicitBasePrice : 0;
729
+ const extensionList = buildProductExtensionList({
730
+ product: combination,
731
+ locale,
732
+ currencySymbol,
733
+ quantity,
734
+ originalPrice: unitPrice
735
+ });
736
+ const shouldIncludeBasePrice = normalizedOptions.length > 0 || nestedCombinations.length > 0 || hasProductDiscount(combination, extensionList);
557
737
  return {
558
738
  ...snapshot,
739
+ product_quantity: quantity,
740
+ total_selling_price: formatCalculatedMoney(new _decimal.default(toMoneyNumber(unitPrice)).mul(quantity), currencySymbol),
741
+ ...(shouldIncludeBasePrice ? {
742
+ base_price: formatCalculatedMoney(basePrice, currencySymbol)
743
+ } : {}),
744
+ ...(Array.isArray(combination.combinations_options) ? {
745
+ combinations_options: normalizedOptions
746
+ } : Array.isArray(combination.options) ? {
747
+ options: normalizedOptions
748
+ } : {}),
749
+ ...(normalizedOptions.length ? {
750
+ options_total_price: formatCalculatedMoney(optionsAmount, currencySymbol)
751
+ } : {}),
752
+ ...(nestedCombinations.length ? {
753
+ package_items_total_price: sumCombinationTotals(nestedCombinations, currencySymbol)
754
+ } : {}),
559
755
  ...(productNote ? {
560
756
  product_note: productNote
561
757
  } : {}),
562
- ...(nestedCombinations ? {
758
+ ...(extensionList.length ? {
759
+ extension_list: extensionList
760
+ } : {}),
761
+ ...(nestedCombinations.length ? {
563
762
  combinations: nestedCombinations
564
763
  } : {})
565
764
  };
566
765
  });
567
766
  }
767
+ function sumMoneyValues(values) {
768
+ return values.reduce((sum, value) => sum.plus(toMoneyNumber(value)), new _decimal.default(0));
769
+ }
770
+ function resolveCombinationBasePrice(combination, preferOriginalPrice = false) {
771
+ const fallbackPrices = preferOriginalPrice ? [combination.original_price, combination.product_price, combination.price] : [combination.price, combination.original_price, combination.product_price];
772
+ return firstPresentValue(combination.base_price, combination.metadata?.source_product_price, ...fallbackPrices);
773
+ }
774
+ function sumNormalizedOptionTotals(options, currencySymbol) {
775
+ return formatCalculatedMoney(sumMoneyValues(options.map(option => option.total_price)), currencySymbol);
776
+ }
777
+ function sumCombinationTotals(combinations, currencySymbol) {
778
+ return formatCalculatedMoney(sumMoneyValues(combinations.map(combination => combination.total_selling_price)), currencySymbol);
779
+ }
568
780
  function resolveProductNote(product, locale) {
569
781
  const productNote = getLocalizedValue(product.product_note, locale).trim();
570
782
  if (productNote) return productNote;
@@ -795,12 +1007,6 @@ function buildFees(params) {
795
1007
  });
796
1008
  const isPriceIncludeTax = firstPresentValue(summary.is_price_include_tax, order.is_price_include_tax, shopInfo.is_price_include_tax);
797
1009
  const roundingAmount = firstPresentValue(summary.rounding_amount, order.rounding_amount);
798
- if (isNonZero(roundingAmount)) {
799
- fees.push({
800
- item: label(locale, 'rounding'),
801
- value: formatMoney(roundingAmount, currencySymbol)
802
- });
803
- }
804
1010
  const payProcessingFee = financials.payProcessingFee;
805
1011
  if (isNonZero(payProcessingFee)) {
806
1012
  fees.push({
@@ -811,12 +1017,14 @@ function buildFees(params) {
811
1017
  const productExpectAmount = firstPresentValue(summary.product_expect_amount, summary.product_amount, order.product_expect_amount);
812
1018
  const productOriginalAmount = firstPresentValue(summary.product_original_amount, order.product_original_amount) ?? calculateProductOriginalAmount(order);
813
1019
  const totalSavingsAmount = new _decimal.default(toMoneyNumber(productOriginalAmount)).minus(toMoneyNumber(productExpectAmount)).plus(toMoneyNumber(discountAmount));
1020
+ const itemDiscountAmount = new _decimal.default(toMoneyNumber(productExpectAmount ?? 0)).minus(toMoneyNumber(productOriginalAmount));
814
1021
  return {
815
1022
  fees,
816
1023
  countFee: {
817
1024
  total_amount: formatMoney(firstPresentValue(summary.total_amount, order.total_amount) ?? 0, currencySymbol),
818
1025
  original_item_amount: formatMoney(productOriginalAmount, currencySymbol),
819
1026
  product_expect_amount: formatMoney(productExpectAmount ?? 0, currencySymbol),
1027
+ item_discount_amount: formatCalculatedMoney(itemDiscountAmount, currencySymbol),
820
1028
  expect_amount: formatMoney(financials.totalAmount, currencySymbol),
821
1029
  product_quantity: toNumber(firstPresentValue(summary.product_quantity, products.reduce((sum, product) => sum + product.product_quantity, 0)), 0),
822
1030
  has_pay: formatMoney(financials.orderPaidAmount, currencySymbol),
@@ -922,24 +1130,13 @@ function buildDelivery(order, locale) {
922
1130
  function buildAppointment(order, locale) {
923
1131
  const bookings = sortBookings(normalizeArray(order.bookings));
924
1132
  if (bookings.length) {
925
- return bookings.map(booking => {
926
- const snapshot = {
927
- ...booking
928
- };
929
- delete snapshot.product_uid;
930
- delete snapshot.booking_uid;
931
- const productUid = firstPresentValue(booking.product_uid, booking.metadata?.product_uid);
932
- const bookingUid = firstPresentValue(booking.metadata?.unique_identification_number, booking.booking_uid);
933
- return {
934
- ...snapshot,
935
- ...(isPresentId(productUid) ? {
936
- product_uid: productUid
937
- } : {}),
938
- ...(isPresentId(bookingUid) ? {
939
- booking_uid: bookingUid
940
- } : {})
941
- };
942
- });
1133
+ const allResources = normalizeArray(order.resources || order.resource_list);
1134
+ return bookings.flatMap(booking => buildAppointmentRows({
1135
+ booking,
1136
+ allResources,
1137
+ bookingCount: bookings.length,
1138
+ locale
1139
+ }));
943
1140
  }
944
1141
  const tableName = order.table_name || order.metadata?.table_name || order.metadata?.table?.name || order.form_data?.table_name;
945
1142
  if (!tableName) return [];
@@ -948,6 +1145,82 @@ function buildAppointment(order, locale) {
948
1145
  value: getLocalizedValue(tableName, locale)
949
1146
  }];
950
1147
  }
1148
+ function buildAppointmentRows(params) {
1149
+ const {
1150
+ booking,
1151
+ allResources,
1152
+ bookingCount,
1153
+ locale
1154
+ } = params;
1155
+ const productUid = stringify(firstPresentValue(booking.product_uid, booking.metadata?.product_uid)).trim();
1156
+ const bookingUid = stringify(firstPresentValue(booking.metadata?.unique_identification_number, booking.booking_uid)).trim();
1157
+ const association = {
1158
+ product_uid: productUid,
1159
+ booking_uid: bookingUid
1160
+ };
1161
+ const bookingId = stringify(firstPresentValue(booking.booking_id, booking.schedule_event_id, bookingUid)).trim();
1162
+ const bookingTime = formatBookingRange(booking, locale);
1163
+ const resourceText = formatBookingResources(resolveBookingResourcesForReceipt(booking, allResources, bookingCount), locale);
1164
+ const holder = getLocalizedValue(booking.holder?.name ?? booking.metadata?.holder?.name, locale).trim();
1165
+ return [{
1166
+ item: label(locale, 'bookingId'),
1167
+ value: bookingId,
1168
+ ...association
1169
+ }, {
1170
+ item: label(locale, 'bookingDateTime'),
1171
+ value: bookingTime,
1172
+ ...association
1173
+ }, {
1174
+ item: label(locale, 'bookingResource'),
1175
+ value: resourceText,
1176
+ ...association
1177
+ }, {
1178
+ item: label(locale, 'bookingHolder'),
1179
+ value: holder,
1180
+ ...association
1181
+ }].filter(row => Boolean(row.value));
1182
+ }
1183
+ function formatBookingRange(booking, locale) {
1184
+ const startDate = stringify(booking.start_date);
1185
+ const startTime = stringify(booking.start_time);
1186
+ const endDate = stringify(booking.end_date || startDate);
1187
+ const endTime = stringify(booking.end_time);
1188
+ const start = firstValidBookingDate(booking.start_at, booking.start_datetime, booking.start_date_time, `${startDate} ${startTime}`.trim());
1189
+ const end = firstValidBookingDate(booking.end_at, booking.end_datetime, booking.end_date_time, endTime ? `${endDate} ${endTime}`.trim() : '');
1190
+ if (!start) {
1191
+ return [startDate, startTime, endTime ? `- ${endDate} ${endTime}` : ''].filter(Boolean).join(' ');
1192
+ }
1193
+ const dateFormat = locale === 'en' ? 'DD/MM/YYYY' : 'YYYY/MM/DD';
1194
+ const startText = start.format(`${dateFormat} HH:mm`);
1195
+ if (!end) return startText;
1196
+ return `${startText} - ${end.isSame(start, 'day') ? end.format('HH:mm') : end.format(`${dateFormat} HH:mm`)}`;
1197
+ }
1198
+ function firstValidBookingDate(...values) {
1199
+ for (const value of values) {
1200
+ if (!isPresentId(value)) continue;
1201
+ const parsed = (0, _dayjs.default)(value);
1202
+ if (parsed.isValid()) return parsed;
1203
+ }
1204
+ return null;
1205
+ }
1206
+ function resolveBookingResourcesForReceipt(booking, allResources, bookingCount) {
1207
+ const embedded = normalizeArray(booking.resources).filter(resource => Boolean(resource) && typeof resource === 'object' && !Array.isArray(resource));
1208
+ const resourceIds = new Set([booking.resource_id, booking.relation_id, ...normalizeArray(booking.resource_ids), ...normalizeArray(booking.metadata?.resource_ids)].map(value => stringify(value).trim()).filter(Boolean));
1209
+ for (const resource of embedded) {
1210
+ const id = stringify(resource.id ?? resource.resource_id ?? resource.relation_id).trim();
1211
+ if (id) resourceIds.add(id);
1212
+ }
1213
+ if (resourceIds.size) {
1214
+ const matched = allResources.filter(resource => resourceIds.has(stringify(resource.id ?? resource.resource_id ?? resource.relation_id).trim()));
1215
+ if (matched.length) return matched;
1216
+ }
1217
+ if (embedded.length) return embedded;
1218
+ if (bookingCount === 1 && allResources.length) return allResources;
1219
+ return [];
1220
+ }
1221
+ function formatBookingResources(resources, locale) {
1222
+ return resources.map(resource => [getLocalizedValue(resource.form_title || resource.metadata?.form_name || resource.relation_form_name || resource.metadata?.relation_form_name, locale), getLocalizedValue(resource.title || resource.name || resource.main_field || resource.metadata?.main_field || resource.metadata?.resource_name, locale)].filter(Boolean).join(' ')).filter(Boolean).join(', ');
1223
+ }
951
1224
  function sortBookings(bookings) {
952
1225
  return bookings.map((booking, index) => ({
953
1226
  booking,
@@ -999,7 +1272,9 @@ function buildPaymentData(params) {
999
1272
  payment,
1000
1273
  locale: params.locale,
1001
1274
  currencySymbol: params.currencySymbol,
1002
- includeFundRecordBalance: false
1275
+ includeFundRecordBalance: false,
1276
+ includeFundRecordUsage: true,
1277
+ includePaymentAmount: true
1003
1278
  }));
1004
1279
  }
1005
1280
  function buildRefundData(params) {
@@ -1083,28 +1358,107 @@ function resolveRefundPayment(refund, payments) {
1083
1358
  return matchedPayment || refund;
1084
1359
  }
1085
1360
  function buildWallets(params) {
1086
- const paymentWallets = normalizeArray(params.order.payments).filter(payment => isPrintablePayment(payment) && !!getFundRecord(payment)).map(payment => buildPaymentItems({
1361
+ const displayedWalletPayments = normalizeArray(params.order.payments).filter(payment => isPrintablePayment(payment) && !!getFundRecord(payment));
1362
+ const paymentWallets = displayedWalletPayments.map(payment => buildPaymentItems({
1087
1363
  payment,
1088
1364
  locale: params.locale,
1089
1365
  currencySymbol: params.currencySymbol,
1090
- includeFundRecordBalance: true
1366
+ includeFundRecordBalance: true,
1367
+ includeFundRecordUsage: false,
1368
+ includePaymentAmount: false
1091
1369
  }));
1092
- return [...paymentWallets, ...buildVoucherAssets(params)];
1370
+ const displayedWalletPassIds = collectDisplayedWalletPassIds(displayedWalletPayments);
1371
+ return [...paymentWallets, ...buildVoucherAssets(params), ...buildPointCardSnapshotAssets({
1372
+ order: params.order,
1373
+ locale: params.locale,
1374
+ displayedWalletPassIds
1375
+ })];
1376
+ }
1377
+ function collectDisplayedWalletPassIds(payments) {
1378
+ const ids = new Set();
1379
+ payments.forEach(payment => {
1380
+ const fundRecord = getFundRecord(payment);
1381
+ [payment.voucher_id, fundRecord?.voucher_id].forEach(value => {
1382
+ const id = normalizeWalletPassId(value);
1383
+ if (id) ids.add(id);
1384
+ });
1385
+ });
1386
+ return ids;
1387
+ }
1388
+ function buildPointCardSnapshotAssets(params) {
1389
+ const snapshots = params.order.order_meta_list?.point_cards_snapshot;
1390
+ if (!Array.isArray(snapshots)) return [];
1391
+ const snapshotTime = firstPresentValue(params.order.updated_at, params.order.created_at);
1392
+ const seenSnapshotIds = new Set();
1393
+ return snapshots.flatMap(snapshot => {
1394
+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return [];
1395
+ const pointCard = snapshot;
1396
+ if (stringify(pointCard.tag).trim().toLowerCase() !== 'point_card') return [];
1397
+ const id = normalizeWalletPassId(pointCard.id);
1398
+ if (!id || seenSnapshotIds.has(id)) return [];
1399
+ seenSnapshotIds.add(id);
1400
+ if (params.displayedWalletPassIds.has(id)) return [];
1401
+ const rows = [{
1402
+ item: stringify(pointCard.product_name).trim() || label(params.locale, 'pointCard'),
1403
+ value: ''
1404
+ }];
1405
+ const remainingPoints = getPointCardSnapshotRemainingPoints(pointCard);
1406
+ if (remainingPoints) {
1407
+ rows.push({
1408
+ item: label(params.locale, 'remainingPoints'),
1409
+ value: trimDecimal(remainingPoints)
1410
+ });
1411
+ }
1412
+ if (isPresentId(snapshotTime)) {
1413
+ rows.push({
1414
+ item: formatDateTime(snapshotTime, params.locale),
1415
+ value: ''
1416
+ });
1417
+ }
1418
+ return [rows];
1419
+ });
1420
+ }
1421
+ function normalizeWalletPassId(value) {
1422
+ if (typeof value === 'number') return Number.isFinite(value) ? String(value) : null;
1423
+ if (typeof value !== 'string') return null;
1424
+ return value.trim() || null;
1425
+ }
1426
+ function getPointCardSnapshotRemainingPoints(snapshot) {
1427
+ if (!isNumericAmount(snapshot.par_value) || !isNumericAmount(snapshot.used_par_value)) {
1428
+ return null;
1429
+ }
1430
+ return _decimal.default.max(new _decimal.default(snapshot.par_value).minus(new _decimal.default(snapshot.used_par_value)), 0);
1093
1431
  }
1094
1432
  function buildVoucherAssets(params) {
1095
1433
  const seenVoucherKeys = new Set();
1434
+ const fallbackAssetTime = firstPresentValue(params.order.updated_at, params.order.created_at);
1096
1435
  return normalizeArray(params.order.vouchers).flatMap((voucher, index) => {
1097
1436
  if (!voucher || typeof voucher !== 'object' || Array.isArray(voucher)) return [];
1098
1437
  const voucherKey = getVoucherAssetKey(voucher, index);
1099
1438
  if (seenVoucherKeys.has(voucherKey)) return [];
1100
1439
  seenVoucherKeys.add(voucherKey);
1101
1440
  const name = getVoucherAssetName(voucher, params.locale);
1441
+ const assetTime = firstPresentValue(voucher.updated_at, voucher.created_at, voucher.collection_time, fallbackAssetTime);
1442
+ const timeRow = isPresentId(assetTime) ? {
1443
+ item: formatDateTime(assetTime, params.locale),
1444
+ value: ''
1445
+ } : null;
1446
+ if (isTicketVoucher(voucher)) {
1447
+ const validity = getVoucherValidity(voucher, params.locale);
1448
+ return [[{
1449
+ item: name,
1450
+ value: ''
1451
+ }, ...(validity ? [{
1452
+ item: label(params.locale, 'validity'),
1453
+ value: validity
1454
+ }] : [])]];
1455
+ }
1102
1456
  const percent = getVoucherDiscountPercent(voucher);
1103
1457
  if (percent) {
1104
1458
  return [[{
1105
1459
  item: appendPercentToVoucherName(name, percent),
1106
1460
  value: formatVoucherDiscount(percent, params.locale)
1107
- }]];
1461
+ }, ...(timeRow ? [timeRow] : [])]];
1108
1462
  }
1109
1463
  const balance = getVoucherBalance(voucher);
1110
1464
  return [[{
@@ -1113,9 +1467,83 @@ function buildVoucherAssets(params) {
1113
1467
  }, {
1114
1468
  item: label(params.locale, 'balance'),
1115
1469
  value: formatMoney(balance, params.currencySymbol)
1116
- }]];
1470
+ }, ...(timeRow ? [timeRow] : [])]];
1471
+ });
1472
+ }
1473
+ function isTicketVoucher(voucher) {
1474
+ return stringify(voucher.tag).trim().toLowerCase() === 'ticket';
1475
+ }
1476
+ function getVoucherValidity(voucher, locale) {
1477
+ const availableTime = firstPresentValue(voucher.available_time, voucher.avaliable_time, voucher.metadata?.available_time, voucher.metadata?.avaliable_time);
1478
+ const availableTimeText = formatVoucherAvailableTime(availableTime, locale);
1479
+ if (availableTimeText) return availableTimeText;
1480
+ const startDate = firstPresentValue(voucher.valid_from, voucher.start_at, voucher.start_date_time, voucher.start_date, voucher.metadata?.valid_from, voucher.metadata?.start_at, voucher.metadata?.start_date);
1481
+ const endDate = firstPresentValue(voucher.valid_to, voucher.end_at, voucher.end_date_time, voucher.expire_date, voucher.end_date, voucher.expire_time, voucher.metadata?.valid_to, voucher.metadata?.end_at, voucher.metadata?.expire_date, voucher.metadata?.end_date, voucher.metadata?.expire_time);
1482
+ return formatVoucherValidityRange(startDate, endDate, locale, {
1483
+ startTime: voucher.start_time ?? voucher.metadata?.start_time,
1484
+ endTime: voucher.end_time ?? voucher.metadata?.end_time
1117
1485
  });
1118
1486
  }
1487
+ function formatVoucherAvailableTime(value, locale) {
1488
+ if (!isPresentId(value)) return '';
1489
+ if (Array.isArray(value)) {
1490
+ return value.map(item => formatVoucherAvailableTime(item, locale)).filter(Boolean).join(', ');
1491
+ }
1492
+ if (typeof value !== 'object') return stringify(value).trim();
1493
+ const start = firstPresentValue(value.start, value.start_at, value.start_date_time, value.start_date);
1494
+ const end = firstPresentValue(value.end, value.end_at, value.end_date_time, value.expire_time, value.expire_date, value.end_date);
1495
+ if (isPresentId(start) || isPresentId(end)) {
1496
+ return formatVoucherValidityRange(start, end, locale, {
1497
+ startTime: value.start_time,
1498
+ endTime: value.end_time
1499
+ });
1500
+ }
1501
+ return getLocalizedValue(value, locale).trim();
1502
+ }
1503
+ function formatVoucherValidityRange(startValue, endValue, locale, times = {}) {
1504
+ const start = combineVoucherDateAndTime(startValue, times.startTime);
1505
+ const end = combineVoucherDateAndTime(endValue, times.endTime);
1506
+ const startPart = formatVoucherValidityDate(start, locale);
1507
+ const endPart = formatVoucherValidityDate(end, locale);
1508
+ if (startPart.text && endPart.text) {
1509
+ const parsedStart = (0, _dayjs.default)(start);
1510
+ const parsedEnd = (0, _dayjs.default)(end);
1511
+ const sameDay = parsedStart.isValid() && parsedEnd.isValid() && parsedStart.isSame(parsedEnd, 'day');
1512
+ if (sameDay && startPart.time && endPart.time) {
1513
+ return `${startPart.time} - ${endPart.time} ${startPart.date}`;
1514
+ }
1515
+ return `${startPart.text} - ${endPart.text}`;
1516
+ }
1517
+ return startPart.text || endPart.text;
1518
+ }
1519
+ function combineVoucherDateAndTime(dateValue, timeValue) {
1520
+ if (!isPresentId(dateValue) || !isPresentId(timeValue)) return dateValue;
1521
+ const dateText = stringify(dateValue).trim();
1522
+ if (/\d{1,2}:\d{2}/.test(dateText)) return dateValue;
1523
+ return `${dateText} ${stringify(timeValue).trim()}`;
1524
+ }
1525
+ function formatVoucherValidityDate(value, locale) {
1526
+ if (!isPresentId(value)) return {
1527
+ date: '',
1528
+ time: '',
1529
+ text: ''
1530
+ };
1531
+ const source = stringify(value).trim();
1532
+ const parsed = (0, _dayjs.default)(source);
1533
+ if (!parsed.isValid()) return {
1534
+ date: '',
1535
+ time: '',
1536
+ text: source
1537
+ };
1538
+ const hasTime = /\d{1,2}:\d{2}/.test(source);
1539
+ const date = parsed.format(locale === 'en' ? 'DD/MM/YYYY' : 'YYYY/MM/DD');
1540
+ const time = hasTime ? parsed.format(/\d{1,2}:\d{2}:\d{2}/.test(source) ? 'HH:mm:ss' : 'HH:mm') : '';
1541
+ return {
1542
+ date,
1543
+ time,
1544
+ text: time ? `${time} ${date}` : date
1545
+ };
1546
+ }
1119
1547
  function getVoucherAssetKey(voucher, index) {
1120
1548
  const identity = firstPresentValue(voucher.voucher_id, voucher.id, voucher.code, voucher.encoded);
1121
1549
  return identity === undefined ? `voucher-index:${index}` : `voucher:${String(identity)}`;
@@ -1153,12 +1581,14 @@ function buildPaymentItems(params) {
1153
1581
  payment,
1154
1582
  locale,
1155
1583
  currencySymbol,
1156
- includeFundRecordBalance
1584
+ includeFundRecordBalance,
1585
+ includeFundRecordUsage,
1586
+ includePaymentAmount
1157
1587
  } = params;
1158
1588
  const serviceFee = getPaymentServiceFee(payment);
1159
1589
  const items = [{
1160
1590
  item: paymentMethodName(payment, locale),
1161
- value: formatMoney(resolveReceiptPaymentAmount(payment, serviceFee), currencySymbol)
1591
+ value: includePaymentAmount ? formatMoney(resolveReceiptPaymentAmount(payment, serviceFee), currencySymbol) : ''
1162
1592
  }];
1163
1593
  items.push(...buildCashChangePaymentItems({
1164
1594
  payment,
@@ -1178,7 +1608,8 @@ function buildPaymentItems(params) {
1178
1608
  fundRecord,
1179
1609
  locale,
1180
1610
  currencySymbol,
1181
- includeBalance: includeFundRecordBalance
1611
+ includeBalance: includeFundRecordBalance,
1612
+ includeUsage: includeFundRecordUsage
1182
1613
  }));
1183
1614
  } else {
1184
1615
  const remainingAmount = payment.remaining_amount ?? payment.balance ?? payment.metadata?.remaining_amount;
@@ -1242,17 +1673,20 @@ function buildFundRecordPaymentItems(params) {
1242
1673
  fundRecord,
1243
1674
  locale,
1244
1675
  currencySymbol,
1245
- includeBalance
1676
+ includeBalance,
1677
+ includeUsage
1246
1678
  } = params;
1247
1679
  const items = [];
1248
1680
  const usingBeforeValue = fundRecord.using_before_value;
1249
1681
  const usingAfterValue = fundRecord.using_after_value;
1250
1682
  if (isPointCardPayment(payment) && usingBeforeValue !== undefined && usingAfterValue !== undefined) {
1251
1683
  const usedPoints = new _decimal.default(toMoneyNumber(usingBeforeValue)).minus(toMoneyNumber(usingAfterValue));
1252
- items.push({
1253
- item: label(locale, 'redeemPoints'),
1254
- value: trimDecimal(usedPoints)
1255
- });
1684
+ if (includeUsage) {
1685
+ items.push({
1686
+ item: label(locale, 'redeemPoints'),
1687
+ value: trimDecimal(usedPoints)
1688
+ });
1689
+ }
1256
1690
  if (includeBalance) {
1257
1691
  items.push({
1258
1692
  item: label(locale, 'remainingPoints'),
@@ -1263,7 +1697,7 @@ function buildFundRecordPaymentItems(params) {
1263
1697
  }
1264
1698
  if (includeBalance && usingAfterValue !== undefined && usingAfterValue !== null) {
1265
1699
  items.push({
1266
- item: label(locale, 'remainingAmount'),
1700
+ item: label(locale, 'balance'),
1267
1701
  value: formatMoney(usingAfterValue, currencySymbol)
1268
1702
  });
1269
1703
  }
@@ -1377,6 +1811,11 @@ function formatMoney(value, currencySymbol) {
1377
1811
  const amount = new _decimal.default(toMoneyNumber(value));
1378
1812
  return `${currencySymbol}${amount.toFixed(2)}`;
1379
1813
  }
1814
+ function formatCalculatedMoney(value, currencySymbol) {
1815
+ const amount = new _decimal.default(toMoneyNumber(value));
1816
+ const sign = amount.isNegative() ? '-' : '';
1817
+ return `${sign}${currencySymbol}${amount.abs().toFixed(2)}`;
1818
+ }
1380
1819
  function formatNegativeMoney(value, currencySymbol) {
1381
1820
  const amount = new _decimal.default(toMoneyNumber(value)).abs();
1382
1821
  return `-${currencySymbol}${amount.toFixed(2)}`;