@solvimon/solvimon-web 0.1.0-alpha.16 → 0.1.0-alpha.18

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 (175) hide show
  1. package/README.md +33 -31
  2. package/dist/AddPaymentMethodPane.vue_vue_type_script_setup_true_lang-C2IRj-FB.mjs +238 -0
  3. package/dist/AddPaymentMethodPane.vue_vue_type_script_setup_true_lang-Rub9ifBk.js +1 -0
  4. package/dist/{BillingInformation.vue_vue_type_script_setup_true_lang-BYBAO4Au.mjs → BillingInformation.vue_vue_type_script_setup_true_lang-BWnZ98RQ.mjs} +2 -2
  5. package/dist/{BillingInformation.vue_vue_type_script_setup_true_lang-BI3Lg7nO.js → BillingInformation.vue_vue_type_script_setup_true_lang-DurgWlLC.js} +1 -1
  6. package/dist/{CustomerPaymentMethods.vue_vue_type_script_setup_true_lang-CTnn1gkW.mjs → CustomerPaymentMethods.vue_vue_type_script_setup_true_lang-D7gL7dZX.mjs} +3 -3
  7. package/dist/CustomerPaymentMethods.vue_vue_type_script_setup_true_lang-Df7CsbiW.js +1 -0
  8. package/dist/CustomerWalletBalances.vue_vue_type_script_setup_true_lang-OUg4yv7r.mjs +2654 -0
  9. package/dist/CustomerWalletBalances.vue_vue_type_script_setup_true_lang-mM5udvi8.js +1 -0
  10. package/dist/EmptyStatePlaceholder.vue_vue_type_script_setup_true_lang-BIpg-MSJ.mjs +53 -0
  11. package/dist/EmptyStatePlaceholder.vue_vue_type_script_setup_true_lang-BM3p8Pk8.js +1 -0
  12. package/dist/InvoiceDetailsBlock.vue_vue_type_script_setup_true_lang-D5eSNYH2.js +1 -0
  13. package/dist/{InvoiceDetailsBlock.vue_vue_type_script_setup_true_lang-ryvFEQMV.mjs → InvoiceDetailsBlock.vue_vue_type_script_setup_true_lang-DbY35gE_.mjs} +1 -1
  14. package/dist/{InvoiceHeader.vue_vue_type_script_setup_true_lang-DdpPrYxi.js → InvoiceHeader.vue_vue_type_script_setup_true_lang-Ci8r6tuC.js} +1 -1
  15. package/dist/{InvoiceHeader.vue_vue_type_script_setup_true_lang-bAiAbtMi.mjs → InvoiceHeader.vue_vue_type_script_setup_true_lang-jshby9pF.mjs} +1 -1
  16. package/dist/PaymentErrorCard.vue_vue_type_script_setup_true_lang-CNKxTtO7.js +1 -0
  17. package/dist/PaymentErrorCard.vue_vue_type_script_setup_true_lang-DBMgilG2.mjs +153 -0
  18. package/dist/PaymentFeedbackCard.vue_vue_type_script_setup_true_lang-CupZFJSF.mjs +52 -0
  19. package/dist/PaymentFeedbackCard.vue_vue_type_script_setup_true_lang-D6lpD1zo.js +1 -0
  20. package/dist/{PaymentHistoryBlock-BKMttUyk.mjs → PaymentHistoryBlock-Bxr8lUGs.mjs} +1 -1
  21. package/dist/{PaymentHistoryBlock-BGbTy4Se.js → PaymentHistoryBlock-COjIVYX4.js} +1 -1
  22. package/dist/PaymentHistoryBlock.vue_vue_type_script_setup_true_lang-Bmgx7PSt.js +1 -0
  23. package/dist/{PaymentHistoryBlock.vue_vue_type_script_setup_true_lang-tM7f_fQS.mjs → PaymentHistoryBlock.vue_vue_type_script_setup_true_lang-CDjGab5p.mjs} +1 -1
  24. package/dist/{PaymentIntegrationForm-D4QupHWl.js → PaymentIntegrationForm-BSauhuKv.js} +1 -1
  25. package/dist/{PaymentIntegrationForm-CypW6fZY.mjs → PaymentIntegrationForm-PIT8gHYN.mjs} +1 -1
  26. package/dist/PaymentIntegrationForm.vue_vue_type_script_setup_true_lang-5XKz3kop.js +1 -0
  27. package/dist/PaymentIntegrationForm.vue_vue_type_script_setup_true_lang-COO2ZUhN.mjs +148 -0
  28. package/dist/PaymentIntegrationFormAdyen-B-Jbu2hU.js +1 -0
  29. package/dist/PaymentIntegrationFormAdyen-Cjj9aK0E.mjs +729 -0
  30. package/dist/PaymentIntegrationFormStripe-Bnn8S1o5.js +1 -0
  31. package/dist/PaymentIntegrationFormStripe-arpua_ZT.mjs +545 -0
  32. package/dist/PaymentMethodForm-B7T5rrNz.mjs +4 -0
  33. package/dist/PaymentMethodForm-CLz3ZS-b.js +1 -0
  34. package/dist/{PaymentMethodForm.vue_vue_type_script_setup_true_lang-B8eNptZp.mjs → PaymentMethodForm.vue_vue_type_script_setup_true_lang-C4Zf92QP.mjs} +25 -14
  35. package/dist/PaymentMethodForm.vue_vue_type_script_setup_true_lang-UH9AVXnG.js +1 -0
  36. package/dist/{PaymentMethodsList.vue_vue_type_script_setup_true_lang-BUTqn4Ey.mjs → PaymentMethodsList.vue_vue_type_script_setup_true_lang-CIIt6fGp.mjs} +77 -31
  37. package/dist/PaymentMethodsList.vue_vue_type_script_setup_true_lang-ifai5HVr.js +1 -0
  38. package/dist/{SecurePaymentsKPI.vue_vue_type_script_setup_true_lang-Cqk-vonA.mjs → SecurePaymentsKPI.vue_vue_type_script_setup_true_lang-DaWlLor0.mjs} +115 -68
  39. package/dist/SecurePaymentsKPI.vue_vue_type_script_setup_true_lang-DdUoeTUL.js +1 -0
  40. package/dist/SubscriptionSchedules.vue_vue_type_script_setup_true_lang-CyYhYYRp.mjs +37 -0
  41. package/dist/SubscriptionSchedules.vue_vue_type_script_setup_true_lang-DdjYVNku.js +1 -0
  42. package/dist/SubscriptionSummary.vue_vue_type_script_setup_true_lang-Cu55ZvCH.js +1 -0
  43. package/dist/SubscriptionSummary.vue_vue_type_script_setup_true_lang-z8P1u1Gi.mjs +100 -0
  44. package/dist/SubscriptionsList.vue_vue_type_script_setup_true_lang-BKDMwuyh.js +1 -0
  45. package/dist/{SubscriptionsList.vue_vue_type_script_setup_true_lang-DB1p61kZ.mjs → SubscriptionsList.vue_vue_type_script_setup_true_lang-BOUSk2ZB.mjs} +22 -119
  46. package/dist/adyen-BMDZQBUG.js +1 -0
  47. package/dist/{url-1Lbg5Yni.mjs → adyen-Ba-mF3Jy.mjs} +31 -73
  48. package/dist/component--Y7Igv5i.mjs +1022 -0
  49. package/dist/component-DIy1hvJM.js +1 -0
  50. package/dist/components/BillingInformation/BillingInformation.cjs.js +1 -1
  51. package/dist/components/BillingInformation/BillingInformation.es.js +4 -4
  52. package/dist/components/BillingInformationForm/BillingInformationForm.cjs.js +1 -1
  53. package/dist/components/BillingInformationForm/BillingInformationForm.es.js +4 -4
  54. package/dist/components/CustomerPaymentMethods/CustomerPaymentMethods.cjs.js +1 -1
  55. package/dist/components/CustomerPaymentMethods/CustomerPaymentMethods.es.js +4 -4
  56. package/dist/components/Invoice/Invoice.cjs.js +1 -1
  57. package/dist/components/Invoice/Invoice.es.js +7 -7
  58. package/dist/components/InvoiceDetails/InvoiceDetails.cjs.js +1 -1
  59. package/dist/components/InvoiceDetails/InvoiceDetails.es.js +3 -3
  60. package/dist/components/InvoiceHeader/InvoiceHeader.cjs.js +1 -1
  61. package/dist/components/InvoiceHeader/InvoiceHeader.es.js +4 -4
  62. package/dist/components/InvoicesList/InvoicesList.cjs.js +1 -1
  63. package/dist/components/InvoicesList/InvoicesList.es.js +3 -3
  64. package/dist/components/PaymentHistory/PaymentHistory.cjs.js +1 -1
  65. package/dist/components/PaymentHistory/PaymentHistory.es.js +3 -3
  66. package/dist/components/PaymentMethodForm/PaymentMethodForm.cjs.js +1 -1
  67. package/dist/components/PaymentMethodForm/PaymentMethodForm.es.js +6 -6
  68. package/dist/components/SubscriptionSchedules/SubscriptionSchedules.cjs.js +1 -1
  69. package/dist/components/SubscriptionSchedules/SubscriptionSchedules.es.js +7 -58
  70. package/dist/components/SubscriptionsList/SubscriptionsList.cjs.js +1 -1
  71. package/dist/components/SubscriptionsList/SubscriptionsList.es.js +5 -5
  72. package/dist/components/WalletBalances/WalletBalances.cjs.js +1 -1
  73. package/dist/components/WalletBalances/WalletBalances.es.js +25 -9
  74. package/dist/core/action-request.types.d.ts +3 -15
  75. package/dist/core/index.cjs.js +1 -1
  76. package/dist/core/index.es.js +1 -1
  77. package/dist/core/types.d.ts +4 -2
  78. package/dist/{customer-Bv_fqXzO.mjs → customer-DovIxTG1.mjs} +1 -1
  79. package/dist/{customer-_W8gIX5m.js → customer-brfznoHY.js} +1 -1
  80. package/dist/en-US-BvOHPudj.js +1 -0
  81. package/dist/{en-US-DAgOSlgv.mjs → en-US-CXDO3qhq.mjs} +121 -36
  82. package/dist/index-BMWWP8xj.js +1 -0
  83. package/dist/index-Do7kzLpg.mjs +265 -0
  84. package/dist/index.cjs.js +1 -1
  85. package/dist/index.d.ts +2 -1
  86. package/dist/index.es.js +7 -4
  87. package/dist/invoices-Cf3dSYSj.js +1 -0
  88. package/dist/{invoices-BGb0AwVF.mjs → invoices-Dk-z04lg.mjs} +32 -16
  89. package/dist/{nl-NL-DCsmrA8A.mjs → nl-NL-BgL_PuBn.mjs} +126 -40
  90. package/dist/nl-NL-COGUFg60.js +1 -0
  91. package/dist/{paymentMethods-DvqlWe96.mjs → paymentMethods-BnF1XYS1.mjs} +21 -5
  92. package/dist/paymentMethods-DVDC_WfL.js +1 -0
  93. package/dist/{payments-DMDDI3MK.js → payments-DVZFO5yb.js} +1 -1
  94. package/dist/{payments-CpzTVrQM.mjs → payments-TnRjtlOw.mjs} +1 -1
  95. package/dist/pricing-CuYndX6t.js +1 -0
  96. package/dist/pricing-GwLCiSzs.mjs +19 -0
  97. package/dist/pricingPlanSchedule-B9HFiXy-.js +1 -0
  98. package/dist/pricingPlanSchedule-CXG3CQ61.mjs +146 -0
  99. package/dist/{registry-B-If1W_u.mjs → registry-Ck0Gb6rj.mjs} +7 -4
  100. package/dist/registry-Cra6yoB4.js +1 -0
  101. package/dist/screens/Checkout/Checkout.cjs.js +1 -1
  102. package/dist/screens/Checkout/Checkout.es.js +429 -689
  103. package/dist/screens/CustomerOverview/CustomerOverview.cjs.js +1 -1
  104. package/dist/screens/CustomerOverview/CustomerOverview.es.js +61 -39
  105. package/dist/screens/PayInvoice/PayInvoice.cjs.js +1 -1
  106. package/dist/screens/PayInvoice/PayInvoice.es.js +30 -13
  107. package/dist/screens/PaymentMethodsManagement/PaymentMethodsManagement.cjs.js +1 -1
  108. package/dist/screens/PaymentMethodsManagement/PaymentMethodsManagement.es.js +28 -18
  109. package/dist/screens/SubscriptionDetails/SubscriptionDetails.ce.d.ts +3 -0
  110. package/dist/screens/SubscriptionDetails/SubscriptionDetails.cjs.js +1 -0
  111. package/dist/screens/SubscriptionDetails/SubscriptionDetails.es.js +889 -0
  112. package/dist/screens/SubscriptionManagement/SubscriptionManagement.ce.d.ts +3 -0
  113. package/dist/screens/SubscriptionManagement/SubscriptionManagement.cjs.js +1 -0
  114. package/dist/screens/SubscriptionManagement/SubscriptionManagement.es.js +716 -0
  115. package/dist/solvimon-web.css +1 -1
  116. package/dist/subscription-C41lG-rH.mjs +89 -0
  117. package/dist/subscription-b0OPx8Du.js +1 -0
  118. package/dist/subscriptions-BFCKVHnP.js +1 -0
  119. package/dist/subscriptions-vEE4Y7qm.mjs +58 -0
  120. package/dist/{useActionDispatchProvider-Dz8-e4gZ.mjs → useActionDispatchProvider-BlEf-RZ5.mjs} +1 -1
  121. package/dist/{useActionDispatchProvider-BHTknMoH.js → useActionDispatchProvider-aJOy3kr1.js} +1 -1
  122. package/dist/{useCustomer-Z24KchWC.js → useCustomer-C1XTqmrQ.js} +1 -1
  123. package/dist/{useCustomer-VVJi8z2w.mjs → useCustomer-Cw8LXT6S.mjs} +2 -2
  124. package/dist/{useIncrementalLoading-DmOT2MXH.mjs → useIncrementalLoading-8WtKZ-mP.mjs} +2 -2
  125. package/dist/useIncrementalLoading-CkY2klIW.js +1 -0
  126. package/dist/{useInvoiceData-Bl87gzIS.js → useInvoiceData-BrxMo4Zt.js} +1 -1
  127. package/dist/{useInvoiceData-Di5pLPM0.mjs → useInvoiceData-Cy_ysMsq.mjs} +2 -2
  128. package/dist/{useInvoicesList-z19cteaD.mjs → useInvoicesList-DMsZn1tE.mjs} +4 -4
  129. package/dist/useInvoicesList-DmisMQzy.js +1 -0
  130. package/dist/{useLoadInitialData-CkpryfjF.mjs → useLoadInitialData-BP1v7qhd.mjs} +1 -1
  131. package/dist/{useLoadInitialData-CTqfiMTN.js → useLoadInitialData-_BjCD0Jc.js} +1 -1
  132. package/dist/{usePaymentMethodOptions-BoGHJjng.mjs → usePaymentMethodOptions-CWfGvW0U.mjs} +9 -3
  133. package/dist/{usePaymentMethodOptions-BsCZnCQW.js → usePaymentMethodOptions-xeSTmaVo.js} +1 -1
  134. package/dist/{usePaymentMethods-AC-4rrR9.js → usePaymentMethods-CAFMvSOr.js} +1 -1
  135. package/dist/{usePaymentMethods-ocHmNoP7.mjs → usePaymentMethods-Cyk4cjoE.mjs} +2 -2
  136. package/dist/{usePayments-CgXZeWrU.js → usePayments-BieVBaz-.js} +1 -1
  137. package/dist/{usePayments-D85eB5l4.mjs → usePayments-D88XSZfS.mjs} +10 -4
  138. package/dist/{usePortal-B1O1zgdV.mjs → usePortal-0NDlbFr9.mjs} +1 -1
  139. package/dist/{usePortal-DVD7PcWI.js → usePortal-B954nyEB.js} +1 -1
  140. package/dist/{useService-CHrkefKd.js → useService-BiljI7XA.js} +1 -1
  141. package/dist/{useService-DF57xuDd.mjs → useService-CqfJi5ST.mjs} +1 -1
  142. package/dist/useSubscription-9rJpFNUF.mjs +29 -0
  143. package/dist/useSubscription-k3limdu_.js +1 -0
  144. package/dist/vendor-ui-Dfh3_g4q.js +1 -0
  145. package/dist/{vendor-ui-B8IlviSs.mjs → vendor-ui-ItGf7wJV.mjs} +8006 -6329
  146. package/package.json +23 -9
  147. package/dist/CustomerPaymentMethods.vue_vue_type_script_setup_true_lang-C_uHr21N.js +0 -1
  148. package/dist/InvoiceDetailsBlock.vue_vue_type_script_setup_true_lang-DU6X3zxr.js +0 -1
  149. package/dist/PaymentHistoryBlock.vue_vue_type_script_setup_true_lang-CixdxEGm.js +0 -1
  150. package/dist/PaymentIntegrationForm.vue_vue_type_script_setup_true_lang-BBEM-YPz.js +0 -1
  151. package/dist/PaymentIntegrationForm.vue_vue_type_script_setup_true_lang-CrGSfZZs.mjs +0 -1537
  152. package/dist/PaymentMethodForm.vue_vue_type_script_setup_true_lang-eWmC5GOT.js +0 -1
  153. package/dist/PaymentMethodsList.vue_vue_type_script_setup_true_lang-Be_fF-R_.js +0 -1
  154. package/dist/SecurePaymentsKPI.vue_vue_type_script_setup_true_lang-BVoS3ZXS.js +0 -1
  155. package/dist/SubscriptionsList.vue_vue_type_script_setup_true_lang-56vu59V4.js +0 -1
  156. package/dist/component-Bg2JVC_O.mjs +0 -933
  157. package/dist/component-Bs8oszfD.js +0 -1
  158. package/dist/en-US-C0gIE4Q1.js +0 -1
  159. package/dist/index-CzL1ZcGi.mjs +0 -85
  160. package/dist/index-DRdBmZ2-.js +0 -1
  161. package/dist/invoices-D-OKipCg.js +0 -1
  162. package/dist/nl-NL-Br7muSHK.js +0 -1
  163. package/dist/paymentMethods-DIbB759g.js +0 -1
  164. package/dist/registry-uG2isab0.js +0 -1
  165. package/dist/screens/UpgradeSubscription/UpgradeSubscription.ce.d.ts +0 -3
  166. package/dist/screens/UpgradeSubscription/UpgradeSubscription.cjs.js +0 -1
  167. package/dist/screens/UpgradeSubscription/UpgradeSubscription.es.js +0 -1102
  168. package/dist/subscriptions-BPYyv09M.mjs +0 -75
  169. package/dist/subscriptions-CC61I6Nj.js +0 -1
  170. package/dist/url-B6-3PkW2.js +0 -1
  171. package/dist/useIncrementalLoading-CuSndpP2.js +0 -1
  172. package/dist/useInvoicesList-CFk-_oVK.js +0 -1
  173. package/dist/useWalletBalanceItems-BL-R5foK.js +0 -1
  174. package/dist/useWalletBalanceItems-COQDLfoZ.mjs +0 -109
  175. package/dist/vendor-ui-C3Tq-qY_.js +0 -1
@@ -0,0 +1,2654 @@
1
+ import { computed, ref, defineComponent, openBlock, createBlock, withCtx, unref, createElementBlock, createVNode, createTextVNode, toDisplayString, createCommentVNode, useModel, watch, createSlots, createElementVNode, mergeModels, mergeProps, renderSlot, reactive, normalizeClass, Fragment, renderList, withModifiers, onBeforeUnmount, normalizeStyle } from "vue";
2
+ import { w as withExpand, s as serializeQueryParams, a4 as isFlexiblePricing, a5 as hasOneOfPricingTypes, u as useIntl, a6 as _sfc_main$c, b as _sfc_main$d, a1 as _sfc_main$e, W as _sfc_main$f, a as _sfc_main$g, E as formatAmount, R as useValidation, Y as _sfc_main$h, a7 as _sfc_main$i, a8 as formatWalletBalanceValue, t as _sfc_main$j, $ as _sfc_main$k, o as getCustomerCountry, M as Modal, k as _sfc_main$o, D as _sfc_main$p, a9 as _sfc_main$q } from "./vendor-ui-ItGf7wJV.mjs";
3
+ import { c as createRequestService, u as useConfig, E as EXPAND_ALL, a as useLogger } from "./component--Y7Igv5i.mjs";
4
+ import { u as useService } from "./useService-CqfJi5ST.mjs";
5
+ import { _ as _sfc_main$b } from "./Skeleton.vue_vue_type_script_setup_true_lang-DGMxHc20.mjs";
6
+ import { c as common, a as requiredIf, r as required } from "./index-Do7kzLpg.mjs";
7
+ import { c as createInvoicesService } from "./invoices-Dk-z04lg.mjs";
8
+ import { u as useWatchDebounced } from "./useWatchDebounced-Zmxd6InB.mjs";
9
+ import { _ as _sfc_main$l, a as _sfc_main$m } from "./AddPaymentMethodPane.vue_vue_type_script_setup_true_lang-C2IRj-FB.mjs";
10
+ import { _ as _sfc_main$n } from "./SubscriptionSummary.vue_vue_type_script_setup_true_lang-z8P1u1Gi.mjs";
11
+ import { u as usePaymentMethodOptions } from "./usePaymentMethodOptions-CWfGvW0U.mjs";
12
+ function createWalletsService() {
13
+ const request = createRequestService();
14
+ const config = useConfig();
15
+ function getCustomerWalletBalances(customerId) {
16
+ const queryParams = withExpand({ expandParams: EXPAND_ALL });
17
+ return request({
18
+ url: `${config.apiUrls.config}/portal/customers/${customerId}/wallets/balance${serializeQueryParams(queryParams)}`,
19
+ options: { method: "POST" },
20
+ data: {}
21
+ });
22
+ }
23
+ return {
24
+ getCustomerWalletBalances
25
+ };
26
+ }
27
+ function useCustomerWalletBalances({ customerId }) {
28
+ const { getCustomerWalletBalances } = createWalletsService();
29
+ const { data, execute, apiStatus, error, isPending } = useService({
30
+ service: () => getCustomerWalletBalances(customerId)
31
+ });
32
+ const walletBalances = computed(
33
+ () => data.value ?? null
34
+ );
35
+ return { walletBalances, apiStatus, error, fetch: execute, isPending };
36
+ }
37
+ const getWalletBalanceForTopUpItem = (walletBalances = [], topUpItem) => {
38
+ if (!(topUpItem == null ? void 0 : topUpItem.pricing_item_id)) {
39
+ return void 0;
40
+ }
41
+ return walletBalances.find(
42
+ (balance) => (balance.charge_on_demand_pricing_items ?? []).some(
43
+ ({ pricing_item_id }) => pricing_item_id === topUpItem.pricing_item_id
44
+ )
45
+ );
46
+ };
47
+ const TOP_UP_MODAL_STEPS = ["TOP_UP", "ADD_PAYMENT_METHOD", "SUCCESS"];
48
+ const isChargeOnDemandPricingItem = (entry) => typeof entry === "object" && entry !== null && "pricing_item" in entry;
49
+ const getTopUpScheduleIds = (walletBalanceItem) => [
50
+ ...new Set(
51
+ ((walletBalanceItem == null ? void 0 : walletBalanceItem.charge_on_demand_pricing_items) ?? []).flatMap(
52
+ (entry) => isChargeOnDemandPricingItem(entry) && entry.pricing_plan_schedule_id ? [entry.pricing_plan_schedule_id] : []
53
+ )
54
+ )
55
+ ];
56
+ const getTopUpSubscriptions = (walletBalanceItem, subscriptions) => {
57
+ const toppedUpOn = new Set(getTopUpScheduleIds(walletBalanceItem));
58
+ return subscriptions.flatMap((subscription) => {
59
+ const scheduleInfos = (subscription.pricing_plan_schedule_infos ?? []).filter(
60
+ ({ id }) => toppedUpOn.has(id)
61
+ );
62
+ if (scheduleInfos.length === 0) {
63
+ return [];
64
+ }
65
+ return [
66
+ {
67
+ id: subscription.id,
68
+ name: subscription.name || subscription.reference || subscription.id,
69
+ scheduleIds: scheduleInfos.map(({ id }) => id),
70
+ enabledPricingIds: scheduleInfos.flatMap(
71
+ (info) => {
72
+ var _a;
73
+ return (((_a = info.pricing_plan_schedule) == null ? void 0 : _a.enabled_pricings) ?? []).flatMap(
74
+ ({ pricing_id }) => pricing_id ? [pricing_id] : []
75
+ );
76
+ }
77
+ )
78
+ }
79
+ ];
80
+ });
81
+ };
82
+ const withTopUpPricingItemsForSchedules = (walletBalanceItem, scheduleIds) => {
83
+ if (!walletBalanceItem || scheduleIds.length === 0) {
84
+ return walletBalanceItem;
85
+ }
86
+ const allowed = new Set(scheduleIds);
87
+ return {
88
+ ...walletBalanceItem,
89
+ charge_on_demand_pricing_items: (walletBalanceItem.charge_on_demand_pricing_items ?? []).filter(
90
+ (entry) => isChargeOnDemandPricingItem(entry) && !!entry.pricing_plan_schedule_id && allowed.has(entry.pricing_plan_schedule_id)
91
+ )
92
+ };
93
+ };
94
+ const getTopUpPricingItems = (walletBalanceItem) => ((walletBalanceItem == null ? void 0 : walletBalanceItem.charge_on_demand_pricing_items) ?? []).flatMap((entry) => {
95
+ var _a, _b;
96
+ if (!isChargeOnDemandPricingItem(entry)) {
97
+ return [];
98
+ }
99
+ const pricingItemId = entry.pricing_item_id ?? ((_a = entry.pricing_item) == null ? void 0 : _a.id);
100
+ if (!pricingItemId) {
101
+ return [];
102
+ }
103
+ return (((_b = entry.pricing_item) == null ? void 0 : _b.configs) ?? []).map((config) => {
104
+ const flexiblePricing = getFlexiblePricing(config, walletBalanceItem);
105
+ const fixedPricing = getFixedPricing(config, walletBalanceItem);
106
+ return {
107
+ pricingItemId,
108
+ ...entry.pricing_plan_schedule_id && {
109
+ pricingPlanScheduleId: entry.pricing_plan_schedule_id
110
+ },
111
+ config,
112
+ ...flexiblePricing && { flexiblePricing },
113
+ ...fixedPricing && { fixedPricing }
114
+ };
115
+ });
116
+ });
117
+ function getFixedPricing(config, walletBalanceItem) {
118
+ var _a, _b, _c;
119
+ if (!config.on_demand || !hasOneOfPricingTypes(config, ["FIXED"])) {
120
+ return void 0;
121
+ }
122
+ const amount = (_c = (_b = (_a = config.details) == null ? void 0 : _a.bands) == null ? void 0 : _b[0]) == null ? void 0 : _c.fixed_amount;
123
+ if (!amount) {
124
+ return void 0;
125
+ }
126
+ const walletCredits = getWalletCredits(walletBalanceItem);
127
+ const grantedCredits = walletCredits ? getGrantedCredits(config, walletBalanceItem) : void 0;
128
+ return {
129
+ amount,
130
+ value: grantedCredits && walletCredits ? toCreditsValue(grantedCredits.quantity, walletCredits) : { amount }
131
+ };
132
+ }
133
+ const getWalletCredits = (walletBalanceItem) => {
134
+ var _a;
135
+ return (_a = walletBalanceItem == null ? void 0 : walletBalanceItem.wallet_balance.balance) == null ? void 0 : _a.credits;
136
+ };
137
+ const getWalletGrants = (config, walletBalanceItem) => {
138
+ var _a;
139
+ const walletTypeId = (_a = walletBalanceItem == null ? void 0 : walletBalanceItem.wallet) == null ? void 0 : _a.wallet_type_id;
140
+ return (config.wallet_grants ?? []).filter(
141
+ ({ wallet_type_id }) => !walletTypeId || wallet_type_id === walletTypeId
142
+ );
143
+ };
144
+ const getCreditsConversion = (config, walletBalanceItem) => {
145
+ var _a, _b;
146
+ return (_b = (_a = getWalletGrants(config, walletBalanceItem).find(
147
+ ({ credits_grant }) => credits_grant == null ? void 0 : credits_grant.conversion
148
+ )) == null ? void 0 : _a.credits_grant) == null ? void 0 : _b.conversion;
149
+ };
150
+ const getGrantedCredits = (config, walletBalanceItem) => {
151
+ var _a, _b;
152
+ return (_b = (_a = getWalletGrants(config, walletBalanceItem).find(({ credits_grant }) => credits_grant == null ? void 0 : credits_grant.credits)) == null ? void 0 : _a.credits_grant) == null ? void 0 : _b.credits;
153
+ };
154
+ const toCreditsValue = (quantity, walletCredits) => ({ credits: { ...walletCredits, quantity } });
155
+ const toCreditsQuantity = (quantity, rate) => {
156
+ const parsedQuantity = Number(quantity);
157
+ const parsedRate = Number(rate);
158
+ return Number.isFinite(parsedQuantity) && Number.isFinite(parsedRate) ? String(parsedQuantity * parsedRate) : void 0;
159
+ };
160
+ function getFlexiblePricing(config, walletBalanceItem) {
161
+ var _a, _b, _c, _d, _e, _f, _g;
162
+ if (!config.on_demand || !isFlexiblePricing(config)) {
163
+ return void 0;
164
+ }
165
+ const band = (_b = (_a = config.details) == null ? void 0 : _a.bands) == null ? void 0 : _b[0];
166
+ const currency = ((_c = band == null ? void 0 : band.minimum_amount) == null ? void 0 : _c.currency) ?? ((_d = band == null ? void 0 : band.maximum_amount) == null ? void 0 : _d.currency) ?? ((_f = (_e = walletBalanceItem == null ? void 0 : walletBalanceItem.wallet_balance.balance) == null ? void 0 : _e.amount) == null ? void 0 : _f.currency);
167
+ if (!currency) {
168
+ return void 0;
169
+ }
170
+ const credits = getWalletCredits(walletBalanceItem);
171
+ const conversion = credits ? getCreditsConversion(config, walletBalanceItem) : void 0;
172
+ const unitName = (_g = credits == null ? void 0 : credits.credit_type) == null ? void 0 : _g.unit_name;
173
+ const toBound = (amount) => {
174
+ if (!amount) {
175
+ return void 0;
176
+ }
177
+ const quantity = credits && conversion ? toCreditsQuantity(amount.quantity, conversion.rate) : void 0;
178
+ return quantity !== void 0 && credits ? toCreditsValue(quantity, credits) : { amount };
179
+ };
180
+ return {
181
+ config: {
182
+ ...(band == null ? void 0 : band.minimum_amount) && { minimum_amount: band.minimum_amount },
183
+ ...(band == null ? void 0 : band.maximum_amount) && { maximum_amount: band.maximum_amount }
184
+ },
185
+ currency,
186
+ ...conversion && {
187
+ creditsConfiguration: {
188
+ conversionRate: conversion.rate,
189
+ ...(unitName == null ? void 0 : unitName.singular) && { unitNameSingle: unitName.singular },
190
+ ...(unitName == null ? void 0 : unitName.plural) && { unitNamePlural: unitName.plural }
191
+ }
192
+ },
193
+ bounds: {
194
+ ...toBound(band == null ? void 0 : band.minimum_amount) && { minimum: toBound(band == null ? void 0 : band.minimum_amount) },
195
+ ...toBound(band == null ? void 0 : band.maximum_amount) && { maximum: toBound(band == null ? void 0 : band.maximum_amount) }
196
+ }
197
+ };
198
+ }
199
+ const isCreditBasedTopUp = (item) => {
200
+ var _a, _b, _c, _d, _e;
201
+ return !!((_a = item.fixedPricing) == null ? void 0 : _a.value.credits) || !!((_b = item.flexiblePricing) == null ? void 0 : _b.creditsConfiguration) || !!((_e = ((_c = item.flexiblePricing) == null ? void 0 : _c.bounds.minimum) ?? ((_d = item.flexiblePricing) == null ? void 0 : _d.bounds.maximum)) == null ? void 0 : _e.credits);
202
+ };
203
+ const getCreditTypeId = (items) => {
204
+ var _a;
205
+ for (const { fixedPricing, flexiblePricing } of items) {
206
+ const credits = (fixedPricing == null ? void 0 : fixedPricing.value.credits) ?? ((_a = (flexiblePricing == null ? void 0 : flexiblePricing.bounds.minimum) ?? (flexiblePricing == null ? void 0 : flexiblePricing.bounds.maximum)) == null ? void 0 : _a.credits);
207
+ if (credits == null ? void 0 : credits.credit_type_id) {
208
+ return credits.credit_type_id;
209
+ }
210
+ }
211
+ return void 0;
212
+ };
213
+ const getAutoTopUpChargeCurrency = (items = []) => {
214
+ for (const { flexiblePricing, fixedPricing } of items) {
215
+ const currency = (flexiblePricing == null ? void 0 : flexiblePricing.currency) ?? (fixedPricing == null ? void 0 : fixedPricing.amount.currency);
216
+ if (currency) {
217
+ return currency;
218
+ }
219
+ }
220
+ return void 0;
221
+ };
222
+ const getAutoTopUpCreditUnitName = (items = []) => {
223
+ var _a, _b, _c;
224
+ for (const { fixedPricing, flexiblePricing } of items) {
225
+ const credits = (fixedPricing == null ? void 0 : fixedPricing.value.credits) ?? ((_a = (flexiblePricing == null ? void 0 : flexiblePricing.bounds.minimum) ?? (flexiblePricing == null ? void 0 : flexiblePricing.bounds.maximum)) == null ? void 0 : _a.credits);
226
+ if ((_c = (_b = credits == null ? void 0 : credits.credit_type) == null ? void 0 : _b.unit_name) == null ? void 0 : _c.plural) {
227
+ return credits.credit_type.unit_name.plural;
228
+ }
229
+ }
230
+ return void 0;
231
+ };
232
+ const getAutoTopUpConversionRate = (items = []) => {
233
+ var _a;
234
+ for (const { flexiblePricing } of items) {
235
+ const rate = (_a = flexiblePricing == null ? void 0 : flexiblePricing.creditsConfiguration) == null ? void 0 : _a.conversionRate;
236
+ if (rate) {
237
+ return rate;
238
+ }
239
+ }
240
+ return void 0;
241
+ };
242
+ const getAutoTopUpBounds = (items = []) => {
243
+ for (const { flexiblePricing } of items) {
244
+ const { minimum_amount: minimum, maximum_amount: maximum } = (flexiblePricing == null ? void 0 : flexiblePricing.config) ?? {};
245
+ if (minimum || maximum) {
246
+ return { ...minimum && { minimum }, ...maximum && { maximum } };
247
+ }
248
+ }
249
+ return {};
250
+ };
251
+ const getAutoTopUpDenomination = (items = []) => {
252
+ if (items.some(isCreditBasedTopUp)) {
253
+ const creditTypeId = getCreditTypeId(items);
254
+ return creditTypeId ? { creditTypeId } : void 0;
255
+ }
256
+ for (const { flexiblePricing, fixedPricing } of items) {
257
+ const currency = (flexiblePricing == null ? void 0 : flexiblePricing.currency) ?? (fixedPricing == null ? void 0 : fixedPricing.amount.currency);
258
+ if (currency) {
259
+ return { currency };
260
+ }
261
+ }
262
+ return void 0;
263
+ };
264
+ const getTopUpValue = (item, amount) => {
265
+ var _a;
266
+ if (item.fixedPricing) {
267
+ return item.fixedPricing.value;
268
+ }
269
+ if (!item.flexiblePricing || !amount) {
270
+ return void 0;
271
+ }
272
+ const { bounds, creditsConfiguration } = item.flexiblePricing;
273
+ const credits = (_a = bounds.minimum ?? bounds.maximum) == null ? void 0 : _a.credits;
274
+ const quantity = creditsConfiguration ? toCreditsQuantity(amount.quantity, creditsConfiguration.conversionRate) : void 0;
275
+ return credits && quantity !== void 0 ? toCreditsValue(quantity, credits) : { amount };
276
+ };
277
+ const getAutoTopUpEditorConfig = (items = []) => {
278
+ const denomination = getAutoTopUpDenomination(items);
279
+ if (!denomination) {
280
+ return void 0;
281
+ }
282
+ return {
283
+ denomination,
284
+ chargeCurrency: getAutoTopUpChargeCurrency(items) ?? "",
285
+ creditUnitName: getAutoTopUpCreditUnitName(items),
286
+ conversionRate: getAutoTopUpConversionRate(items),
287
+ topUpBounds: getAutoTopUpBounds(items)
288
+ };
289
+ };
290
+ const PREVIEW_DEBOUNCE_MS = 400;
291
+ function useTopUpInvoicePreview({
292
+ pricingPlanScheduleId,
293
+ pricingItems
294
+ }) {
295
+ const { previewChargeOnDemandPricingItems } = createInvoicesService();
296
+ const logger = useLogger();
297
+ const invoicePreview = ref();
298
+ const isPreviewPending = ref(false);
299
+ let latestRequestId = 0;
300
+ const loadPreview = async () => {
301
+ const scheduleId = pricingPlanScheduleId.value;
302
+ const requestId = ++latestRequestId;
303
+ if (!scheduleId || !pricingItems.value) {
304
+ if (pricingItems.value && !scheduleId) {
305
+ logger.warn(
306
+ "INVOICE_PREVIEW_SKIPPED",
307
+ "Skipped the top-up invoice preview: no schedule to charge it on",
308
+ { missing: ["pricingPlanScheduleId"] }
309
+ );
310
+ }
311
+ invoicePreview.value = void 0;
312
+ isPreviewPending.value = false;
313
+ return;
314
+ }
315
+ isPreviewPending.value = true;
316
+ try {
317
+ const invoice = await previewChargeOnDemandPricingItems({
318
+ pricingPlanScheduleId: scheduleId,
319
+ pricingItems: pricingItems.value
320
+ });
321
+ if (requestId === latestRequestId) {
322
+ invoicePreview.value = invoice;
323
+ }
324
+ } catch (error) {
325
+ if (requestId === latestRequestId) {
326
+ invoicePreview.value = void 0;
327
+ }
328
+ logger.error(
329
+ "INVOICE_PREVIEW_FAILED",
330
+ "Failed to load top-up invoice preview",
331
+ {},
332
+ error
333
+ );
334
+ } finally {
335
+ if (requestId === latestRequestId) {
336
+ isPreviewPending.value = false;
337
+ }
338
+ }
339
+ };
340
+ useWatchDebounced(pricingItems, () => void loadPreview(), {
341
+ debounce: PREVIEW_DEBOUNCE_MS,
342
+ deep: true
343
+ });
344
+ void loadPreview();
345
+ return { invoicePreview, isPreviewPending, loadPreview };
346
+ }
347
+ const _hoisted_1$8 = { key: 0 };
348
+ const _sfc_main$a = /* @__PURE__ */ defineComponent({
349
+ __name: "TopUpInvoicePreview",
350
+ props: {
351
+ pricingPlanScheduleId: { type: String },
352
+ pricingItems: { type: Array }
353
+ },
354
+ setup(__props) {
355
+ const props = __props;
356
+ const { $t } = useIntl();
357
+ const pricingPlanScheduleId = computed(() => props.pricingPlanScheduleId);
358
+ const pricingItems = computed(() => props.pricingItems);
359
+ const { invoicePreview } = useTopUpInvoicePreview({ pricingPlanScheduleId, pricingItems });
360
+ return (_ctx, _cache) => {
361
+ return openBlock(), createBlock(_sfc_main$b, {
362
+ class: "sv-top-up-invoice-preview h-[152px]",
363
+ "data-testid": "top-up-invoice-preview-skeleton"
364
+ }, {
365
+ default: withCtx(() => [
366
+ unref(invoicePreview) ? (openBlock(), createElementBlock("div", _hoisted_1$8, [
367
+ createVNode(unref(_sfc_main$c), { required: "" }, {
368
+ default: withCtx(() => [
369
+ createTextVNode(toDisplayString(unref($t)({
370
+ defaultMessage: "You will pay",
371
+ description: "Label above the preview of what topping up will be invoiced for",
372
+ id: "topup_modal.invoice_preview.label"
373
+ })), 1)
374
+ ]),
375
+ _: 1
376
+ }),
377
+ createVNode(unref(_sfc_main$d), { "content-background": "none" }, {
378
+ default: withCtx(() => [
379
+ createVNode(unref(_sfc_main$e), {
380
+ invoice: unref(invoicePreview),
381
+ "is-customer-facing": ""
382
+ }, null, 8, ["invoice"])
383
+ ]),
384
+ _: 1
385
+ })
386
+ ])) : createCommentVNode("", true)
387
+ ]),
388
+ _: 1
389
+ });
390
+ };
391
+ }
392
+ });
393
+ const getThresholdUnit = (denomination, creditUnitName) => denomination.currency ?? creditUnitName ?? denomination.creditTypeId ?? "";
394
+ const toInputValue = (quantity, unit) => ({
395
+ quantity: quantity ?? null,
396
+ currency: unit
397
+ });
398
+ const toFormState = (rule, { denomination, chargeCurrency, creditUnitName, minimumTopUp }) => {
399
+ var _a, _b, _c, _d, _e;
400
+ return {
401
+ enabled: (rule == null ? void 0 : rule.status) === "ACTIVE",
402
+ threshold: toInputValue(
403
+ ((_b = (_a = rule == null ? void 0 : rule.threshold) == null ? void 0 : _a.amount) == null ? void 0 : _b.quantity) ?? ((_d = (_c = rule == null ? void 0 : rule.threshold) == null ? void 0 : _c.credits) == null ? void 0 : _d.quantity),
404
+ getThresholdUnit(denomination, creditUnitName)
405
+ ),
406
+ topUpAmount: toInputValue(((_e = rule == null ? void 0 : rule.topup_amount) == null ? void 0 : _e.quantity) ?? minimumTopUp, chargeCurrency)
407
+ };
408
+ };
409
+ const toThreshold = (state, denomination) => {
410
+ var _a;
411
+ const quantity = (_a = state.threshold) == null ? void 0 : _a.quantity;
412
+ if (!quantity) {
413
+ return {};
414
+ }
415
+ return denomination.creditTypeId ? { credits: { quantity, credit_type_id: denomination.creditTypeId } } : { amount: { quantity, currency: denomination.currency ?? "" } };
416
+ };
417
+ const toTopUpAmount = (state, chargeCurrency) => {
418
+ var _a;
419
+ return ((_a = state.topUpAmount) == null ? void 0 : _a.quantity) ? {
420
+ quantity: state.topUpAmount.quantity,
421
+ currency: state.topUpAmount.currency ?? chargeCurrency
422
+ } : void 0;
423
+ };
424
+ const toAutoTopUpRule$1 = (state, { denomination, chargeCurrency }) => ({
425
+ status: state.enabled ? "ACTIVE" : "INACTIVE",
426
+ threshold: toThreshold(state, denomination),
427
+ ...toTopUpAmount(state, chargeCurrency) && {
428
+ topup_amount: toTopUpAmount(state, chargeCurrency)
429
+ }
430
+ });
431
+ const normalizeAutoTopUpRule = (rule, context) => toAutoTopUpRule$1(toFormState(rule, context), context);
432
+ const isSameAutoTopUpRule = (a, b) => JSON.stringify(a) === JSON.stringify(b);
433
+ const toQuantity = (value) => {
434
+ const quantity = Number(value == null ? void 0 : value.quantity);
435
+ return (value == null ? void 0 : value.quantity) && Number.isFinite(quantity) ? quantity : void 0;
436
+ };
437
+ const isAtLeastMinimum = (value, minimum) => {
438
+ const bound = Number(minimum == null ? void 0 : minimum.quantity);
439
+ return value === null || !(minimum == null ? void 0 : minimum.quantity) || !Number.isFinite(bound) || value >= bound;
440
+ };
441
+ const isWithinMaximum = (value, maximum) => {
442
+ const bound = Number(maximum == null ? void 0 : maximum.quantity);
443
+ return value === null || !(maximum == null ? void 0 : maximum.quantity) || !Number.isFinite(bound) || value <= bound;
444
+ };
445
+ const toNumber = (quantity) => {
446
+ const parsed = Number(quantity);
447
+ return quantity !== null && quantity !== void 0 && quantity !== "" && Number.isFinite(parsed) ? parsed : void 0;
448
+ };
449
+ const toConvertedQuantity = (quantity, base, conversionRate) => {
450
+ const value = toNumber(quantity);
451
+ const rate = toNumber(conversionRate);
452
+ if (value === void 0 || rate === void 0 || rate <= 0) {
453
+ return void 0;
454
+ }
455
+ return base === "CREDITS" ? value / rate : value * rate;
456
+ };
457
+ const toOtherBase = (quantity, from, to, conversionRate) => from === to ? toNumber(quantity) : toConvertedQuantity(quantity, from, conversionRate);
458
+ const toBaseQuantity = (quantity, base, conversionRate) => base === "CREDITS" ? toConvertedQuantity(quantity, "AMOUNT", conversionRate) : toNumber(quantity);
459
+ const toMoneyQuantity = (value) => value.toFixed(2);
460
+ const toFieldQuantity = (value, base) => base === "AMOUNT" ? toMoneyQuantity(value) : String(Number(value.toFixed(6)));
461
+ const toBoundQuantity = (bound, base, conversionRate, formatNumber) => {
462
+ const quantity = toBaseQuantity(bound == null ? void 0 : bound.quantity, base, conversionRate);
463
+ if (quantity === void 0) {
464
+ return void 0;
465
+ }
466
+ return base === "CREDITS" ? formatNumber(quantity) : toMoneyQuantity(quantity);
467
+ };
468
+ const _hoisted_1$7 = ["data-testid"];
469
+ const _sfc_main$9 = /* @__PURE__ */ defineComponent({
470
+ __name: "ConvertedAmountInput",
471
+ props: /* @__PURE__ */ mergeModels({
472
+ unit: { type: String },
473
+ modelBase: { type: String },
474
+ entryBase: { type: String },
475
+ conversionRate: { type: String },
476
+ showConversionHint: { type: Boolean },
477
+ currency: { type: String },
478
+ creditUnitName: { type: String },
479
+ bounds: { type: Object },
480
+ label: { type: String },
481
+ name: { type: String },
482
+ required: { type: Boolean },
483
+ disabled: { type: Boolean },
484
+ error: { type: [String, Object, Array] }
485
+ }, {
486
+ "modelValue": { default: "" },
487
+ "modelModifiers": {}
488
+ }),
489
+ emits: ["update:modelValue"],
490
+ setup(__props) {
491
+ const props = __props;
492
+ const model = useModel(__props, "modelValue");
493
+ const { $t, formatNumber } = useIntl();
494
+ const entryBase = computed(() => props.entryBase ?? props.modelBase);
495
+ const isConverted = computed(
496
+ () => entryBase.value !== props.modelBase && toNumber(props.conversionRate) !== void 0
497
+ );
498
+ const entered = ref("");
499
+ watch(
500
+ () => [model.value, entryBase.value, props.modelBase, props.conversionRate],
501
+ ([quantity]) => {
502
+ if (!isConverted.value) {
503
+ entered.value = quantity ?? "";
504
+ return;
505
+ }
506
+ if (quantity === toEnteredAsModel(entered.value)) {
507
+ return;
508
+ }
509
+ const converted = toOtherBase(
510
+ quantity,
511
+ props.modelBase,
512
+ entryBase.value,
513
+ props.conversionRate
514
+ );
515
+ entered.value = converted === void 0 ? "" : toFieldQuantity(converted, entryBase.value);
516
+ },
517
+ { immediate: true }
518
+ );
519
+ function toEnteredText(quantity) {
520
+ if (typeof quantity === "string") {
521
+ return quantity;
522
+ }
523
+ return typeof quantity === "number" ? String(quantity) : "";
524
+ }
525
+ function toEnteredAsModel(quantity) {
526
+ const converted = toOtherBase(quantity, entryBase.value, props.modelBase, props.conversionRate);
527
+ return converted === void 0 ? "" : toFieldQuantity(converted, props.modelBase);
528
+ }
529
+ const enteredQuantity = computed({
530
+ get: () => entered.value,
531
+ set: (quantity) => {
532
+ entered.value = toEnteredText(quantity);
533
+ model.value = isConverted.value ? toEnteredAsModel(entered.value) : entered.value;
534
+ }
535
+ });
536
+ const convertedQuantity = computed(
537
+ () => toConvertedQuantity(entered.value, entryBase.value, props.conversionRate)
538
+ );
539
+ const creditUnitName = computed(() => {
540
+ if (props.creditUnitName) {
541
+ return props.creditUnitName;
542
+ }
543
+ return entryBase.value === "CREDITS" ? props.unit : $t({
544
+ defaultMessage: "credits",
545
+ description: "Generic name for a wallet credit, where its credit type does not name one",
546
+ id: "converted_amount_input.credits"
547
+ });
548
+ });
549
+ const formatMoney = (quantity, currency) => formatAmount({ quantity: toMoneyQuantity(quantity), currency });
550
+ const formatCredits = (quantity) => `${formatNumber(quantity)} ${creditUnitName.value}`;
551
+ const helperText = computed(() => {
552
+ const converted = convertedQuantity.value;
553
+ if (!props.showConversionHint || converted === void 0) {
554
+ return void 0;
555
+ }
556
+ if (entryBase.value === "CREDITS") {
557
+ return props.currency ? $t(
558
+ {
559
+ defaultMessage: "Will cost {amount} excluding taxes",
560
+ description: "Helper text under a credits field, naming what those credits cost in money",
561
+ id: "converted_amount_input.cost"
562
+ },
563
+ { amount: formatMoney(converted, props.currency) }
564
+ ) : void 0;
565
+ }
566
+ return $t(
567
+ {
568
+ defaultMessage: "Buys about {credits}",
569
+ description: "Helper text under a money field, naming the credits that amount converts into",
570
+ id: "converted_amount_input.buys"
571
+ },
572
+ { credits: formatCredits(converted) }
573
+ );
574
+ });
575
+ const toBound = (bound) => toBoundQuantity(bound, entryBase.value, props.conversionRate, formatNumber);
576
+ const boundsUnit = computed(
577
+ () => {
578
+ var _a, _b, _c, _d;
579
+ return entryBase.value === "CREDITS" ? creditUnitName.value : ((_b = (_a = props.bounds) == null ? void 0 : _a.minimum) == null ? void 0 : _b.currency) ?? ((_d = (_c = props.bounds) == null ? void 0 : _c.maximum) == null ? void 0 : _d.currency) ?? props.unit;
580
+ }
581
+ );
582
+ const boundsText = computed(() => {
583
+ var _a, _b;
584
+ const minimum = toBound((_a = props.bounds) == null ? void 0 : _a.minimum);
585
+ const maximum = toBound((_b = props.bounds) == null ? void 0 : _b.maximum);
586
+ const unit = boundsUnit.value;
587
+ if (minimum && maximum) {
588
+ return $t(
589
+ {
590
+ defaultMessage: "Between {minimum} and {maximum} {unit}",
591
+ description: "Range of what a flexible top-up may be charged for, beside its label",
592
+ id: "converted_amount_input.bounds.range"
593
+ },
594
+ { minimum, maximum, unit }
595
+ );
596
+ }
597
+ if (minimum) {
598
+ return $t(
599
+ {
600
+ defaultMessage: "At least {minimum} {unit}",
601
+ description: "Smallest amount a flexible top-up may be charged for, beside its label",
602
+ id: "converted_amount_input.bounds.minimum"
603
+ },
604
+ { minimum, unit }
605
+ );
606
+ }
607
+ if (maximum) {
608
+ return $t(
609
+ {
610
+ defaultMessage: "Up to {maximum} {unit}",
611
+ description: "Largest amount a flexible top-up may be charged for, beside its label",
612
+ id: "converted_amount_input.bounds.maximum"
613
+ },
614
+ { maximum, unit }
615
+ );
616
+ }
617
+ return void 0;
618
+ });
619
+ return (_ctx, _cache) => {
620
+ return openBlock(), createBlock(unref(_sfc_main$f), {
621
+ modelValue: enteredQuantity.value,
622
+ "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => enteredQuantity.value = $event),
623
+ class: "sv-converted-amount-input",
624
+ type: "number",
625
+ "as-text-type": "",
626
+ name: __props.name,
627
+ label: __props.label,
628
+ required: __props.required,
629
+ disabled: __props.disabled,
630
+ error: __props.error
631
+ }, createSlots({
632
+ suffix: withCtx(() => [
633
+ createElementVNode("span", {
634
+ "data-testid": `${__props.name}-unit`
635
+ }, toDisplayString(__props.unit), 9, _hoisted_1$7)
636
+ ]),
637
+ _: 2
638
+ }, [
639
+ boundsText.value ? {
640
+ name: "label-suffix",
641
+ fn: withCtx(() => [
642
+ createVNode(unref(_sfc_main$g), {
643
+ tag: "span",
644
+ variant: "body-xs",
645
+ shade: "lighter",
646
+ "no-spacing": "",
647
+ "data-testid": `${__props.name}-bounds`
648
+ }, {
649
+ default: withCtx(() => [
650
+ createTextVNode(toDisplayString(boundsText.value), 1)
651
+ ]),
652
+ _: 1
653
+ }, 8, ["data-testid"])
654
+ ]),
655
+ key: "0"
656
+ } : void 0,
657
+ helperText.value ? {
658
+ name: "helper",
659
+ fn: withCtx(() => [
660
+ createVNode(unref(_sfc_main$g), {
661
+ tag: "span",
662
+ variant: "body-xs",
663
+ shade: "lighter",
664
+ "no-spacing": "",
665
+ "data-testid": `${__props.name}-conversion`
666
+ }, {
667
+ default: withCtx(() => [
668
+ createTextVNode(toDisplayString(helperText.value), 1)
669
+ ]),
670
+ _: 1
671
+ }, 8, ["data-testid"])
672
+ ]),
673
+ key: "1"
674
+ } : void 0
675
+ ]), 1032, ["modelValue", "name", "label", "required", "disabled", "error"]);
676
+ };
677
+ }
678
+ });
679
+ const _sfc_main$8 = /* @__PURE__ */ defineComponent({
680
+ __name: "Section",
681
+ props: {
682
+ emphasized: { type: Boolean, default: false },
683
+ contentClasses: { type: String },
684
+ contentBackground: { type: String },
685
+ title: { type: String },
686
+ noSpacing: { type: Boolean },
687
+ hasError: { type: Boolean },
688
+ noBorder: { type: Boolean }
689
+ },
690
+ setup(__props) {
691
+ const props = __props;
692
+ const ACCENT = [
693
+ "sv-section__accent relative",
694
+ "before:absolute before:inset-y-0.5 before:left-0.5 before:w-0.5",
695
+ "before:rounded-full before:bg-primary-600"
696
+ ].join(" ");
697
+ const contentClasses = computed(
698
+ () => [props.emphasized ? ACCENT : void 0, props.contentClasses].filter(Boolean).join(" ")
699
+ );
700
+ const sectionProps = computed(() => {
701
+ const { emphasized: _emphasized, ...rest } = props;
702
+ return rest;
703
+ });
704
+ return (_ctx, _cache) => {
705
+ return openBlock(), createBlock(unref(_sfc_main$d), mergeProps(sectionProps.value, {
706
+ class: "sv-section",
707
+ "content-classes": contentClasses.value
708
+ }), createSlots({
709
+ default: withCtx(() => [
710
+ renderSlot(_ctx.$slots, "default")
711
+ ]),
712
+ _: 2
713
+ }, [
714
+ _ctx.$slots.right ? {
715
+ name: "right",
716
+ fn: withCtx(() => [
717
+ renderSlot(_ctx.$slots, "right")
718
+ ]),
719
+ key: "0"
720
+ } : void 0
721
+ ]), 1040, ["content-classes"]);
722
+ };
723
+ }
724
+ });
725
+ const _hoisted_1$6 = { class: "flex grow flex-col" };
726
+ const _sfc_main$7 = /* @__PURE__ */ defineComponent({
727
+ __name: "AutoTopUpConfig",
728
+ props: {
729
+ config: { type: Object },
730
+ denomination: { type: Object },
731
+ creditUnitName: { type: String },
732
+ chargeCurrency: { type: String },
733
+ conversionRate: { type: String },
734
+ topUpBounds: { type: Object },
735
+ showThresholdConversion: { type: Boolean, default: true },
736
+ contained: { type: Boolean },
737
+ alwaysEnabled: { type: Boolean },
738
+ disabled: { type: Boolean }
739
+ },
740
+ emits: ["save"],
741
+ setup(__props, { expose: __expose, emit: __emit }) {
742
+ const props = __props;
743
+ const emit = __emit;
744
+ const { $t, formatNumber } = useIntl();
745
+ const formContext = computed(() => {
746
+ var _a, _b;
747
+ return {
748
+ denomination: props.denomination,
749
+ chargeCurrency: props.chargeCurrency,
750
+ creditUnitName: props.creditUnitName,
751
+ minimumTopUp: (_b = (_a = props.topUpBounds) == null ? void 0 : _a.minimum) == null ? void 0 : _b.quantity
752
+ };
753
+ });
754
+ const model = ref(toFormState(props.config, formContext.value));
755
+ const entryUnit = computed(() => getThresholdUnit(props.denomination, props.creditUnitName));
756
+ const entryBase = computed(
757
+ () => props.denomination.creditTypeId ? "CREDITS" : "AMOUNT"
758
+ );
759
+ const topUpUnit = computed(
760
+ () => entryBase.value === "CREDITS" ? entryUnit.value : props.chargeCurrency
761
+ );
762
+ const thresholdQuantity = computed({
763
+ get: () => {
764
+ var _a;
765
+ return ((_a = model.value.threshold) == null ? void 0 : _a.quantity) ?? "";
766
+ },
767
+ set: (quantity) => {
768
+ model.value.threshold = { quantity: quantity || null, currency: entryUnit.value };
769
+ }
770
+ });
771
+ const topUpQuantity = computed({
772
+ get: () => {
773
+ var _a;
774
+ return ((_a = model.value.topUpAmount) == null ? void 0 : _a.quantity) ?? "";
775
+ },
776
+ set: (quantity) => {
777
+ model.value.topUpAmount = { quantity: quantity || null, currency: props.chargeCurrency };
778
+ }
779
+ });
780
+ watch(
781
+ () => [props.config, formContext.value],
782
+ ([config, context]) => {
783
+ if (isSameAutoTopUpRule(normalizeAutoTopUpRule(config, context), currentRule())) {
784
+ return;
785
+ }
786
+ model.value = toFormState(config, context);
787
+ }
788
+ );
789
+ const isEnabled = computed({
790
+ get: () => props.alwaysEnabled || model.value.enabled,
791
+ set: (enabled) => {
792
+ model.value.enabled = enabled;
793
+ }
794
+ });
795
+ const rule = computed(
796
+ () => toAutoTopUpRule$1({ ...model.value, enabled: isEnabled.value }, formContext.value)
797
+ );
798
+ const currentRule = () => rule.value;
799
+ const validationState = reactive({
800
+ threshold: computed(() => toQuantity(model.value.threshold) ?? null),
801
+ topUpAmount: computed(() => toQuantity(model.value.topUpAmount) ?? null)
802
+ });
803
+ const formatBound = (bound) => {
804
+ if (!bound) {
805
+ return "";
806
+ }
807
+ const quantity = toBoundQuantity(bound, entryBase.value, props.conversionRate, formatNumber);
808
+ return quantity === void 0 ? formatAmount(bound) : `${quantity} ${topUpUnit.value}`;
809
+ };
810
+ const isRequired = requiredIf(() => isEnabled.value);
811
+ const validation = useValidation(
812
+ {
813
+ threshold: {
814
+ required: common.withMessage(
815
+ () => $t({
816
+ defaultMessage: "Enter the balance to top up at.",
817
+ description: "Error shown under the auto top-up threshold when it is left empty",
818
+ id: "auto_topup_config.threshold.required"
819
+ }),
820
+ isRequired
821
+ ),
822
+ notNegative: common.withMessage(
823
+ () => $t({
824
+ defaultMessage: "The balance to top up at cannot be negative.",
825
+ description: "Error shown under the auto top-up threshold when it is below zero",
826
+ id: "auto_topup_config.threshold.not_negative"
827
+ }),
828
+ (value) => value === null || value >= 0
829
+ )
830
+ },
831
+ topUpAmount: {
832
+ required: common.withMessage(
833
+ () => $t({
834
+ defaultMessage: "Enter the amount to top up with.",
835
+ description: "Error shown under the auto top-up amount when it is left empty",
836
+ id: "auto_topup_config.amount.required"
837
+ }),
838
+ isRequired
839
+ ),
840
+ positive: common.withMessage(
841
+ () => $t({
842
+ defaultMessage: "Top up with more than zero.",
843
+ description: "Error shown under the auto top-up amount when it is zero or negative",
844
+ id: "auto_topup_config.amount.positive"
845
+ }),
846
+ (value) => value === null || value > 0
847
+ ),
848
+ atLeastMinimum: common.withMessage(
849
+ () => {
850
+ var _a;
851
+ return $t(
852
+ {
853
+ defaultMessage: "Top up with at least {minimum}.",
854
+ description: "Error shown under the auto top-up amount when it is below what the pricing allows",
855
+ id: "auto_topup_config.amount.at_least_minimum"
856
+ },
857
+ { minimum: formatBound((_a = props.topUpBounds) == null ? void 0 : _a.minimum) }
858
+ );
859
+ },
860
+ (value) => {
861
+ var _a;
862
+ return isAtLeastMinimum(value, (_a = props.topUpBounds) == null ? void 0 : _a.minimum);
863
+ }
864
+ ),
865
+ withinMaximum: common.withMessage(
866
+ () => {
867
+ var _a;
868
+ return $t(
869
+ {
870
+ defaultMessage: "Top up with at most {maximum}.",
871
+ description: "Error shown under the auto top-up amount when it is above what the pricing allows",
872
+ id: "auto_topup_config.amount.within_maximum"
873
+ },
874
+ { maximum: formatBound((_a = props.topUpBounds) == null ? void 0 : _a.maximum) }
875
+ );
876
+ },
877
+ (value) => {
878
+ var _a;
879
+ return isWithinMaximum(value, (_a = props.topUpBounds) == null ? void 0 : _a.maximum);
880
+ }
881
+ )
882
+ }
883
+ },
884
+ validationState
885
+ );
886
+ const hasChanges = computed(
887
+ () => !isSameAutoTopUpRule(
888
+ currentRule(),
889
+ normalizeAutoTopUpRule(props.config, formContext.value)
890
+ )
891
+ );
892
+ function validate() {
893
+ validation.value.$touch();
894
+ return validation.value.$invalid ? void 0 : currentRule();
895
+ }
896
+ function submit() {
897
+ const rule2 = validate();
898
+ if (rule2) {
899
+ emit("save", rule2);
900
+ }
901
+ }
902
+ __expose({
903
+ submit,
904
+ validate,
905
+ rule,
906
+ hasChanges,
907
+ isInvalid: computed(() => validation.value.$invalid)
908
+ });
909
+ return (_ctx, _cache) => {
910
+ return openBlock(), createBlock(_sfc_main$8, {
911
+ class: "sv-auto-topup-config",
912
+ "content-background": __props.contained ? "gray" : "none",
913
+ "no-spacing": !__props.contained,
914
+ "no-border": !__props.contained
915
+ }, {
916
+ default: withCtx(() => [
917
+ !__props.alwaysEnabled ? (openBlock(), createBlock(unref(_sfc_main$h), {
918
+ key: 0,
919
+ modelValue: isEnabled.value,
920
+ "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => isEnabled.value = $event),
921
+ "no-spacing": "",
922
+ "label-position": "before",
923
+ class: "!flex",
924
+ disabled: __props.disabled
925
+ }, {
926
+ "inline-label": withCtx(() => [
927
+ createElementVNode("div", _hoisted_1$6, [
928
+ createVNode(unref(_sfc_main$g), {
929
+ tag: "span",
930
+ variant: "body-sm"
931
+ }, {
932
+ default: withCtx(() => [
933
+ createTextVNode(toDisplayString(unref($t)({
934
+ defaultMessage: "Auto top-up",
935
+ description: "Title of the automatic wallet top-up settings",
936
+ id: "auto_topup_config.title"
937
+ })), 1)
938
+ ]),
939
+ _: 1
940
+ }),
941
+ createVNode(unref(_sfc_main$g), {
942
+ tag: "span",
943
+ variant: "body-xs",
944
+ shade: "lighter"
945
+ }, {
946
+ default: withCtx(() => [
947
+ createTextVNode(toDisplayString(unref($t)({
948
+ defaultMessage: "Automatically top up your balance when it runs low.",
949
+ description: "Subtitle of the automatic wallet top-up settings",
950
+ id: "auto_topup_config.subtitle"
951
+ })), 1)
952
+ ]),
953
+ _: 1
954
+ })
955
+ ])
956
+ ]),
957
+ _: 1
958
+ }, 8, ["modelValue", "disabled"])) : createCommentVNode("", true),
959
+ createVNode(unref(_sfc_main$i), { "is-open": isEnabled.value }, {
960
+ default: withCtx(() => [
961
+ isEnabled.value ? (openBlock(), createElementBlock("div", {
962
+ key: 0,
963
+ class: normalizeClass(["grid grid-cols-1 gap-3", { "mt-4": !__props.alwaysEnabled }])
964
+ }, [
965
+ createVNode(_sfc_main$9, {
966
+ modelValue: thresholdQuantity.value,
967
+ "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => thresholdQuantity.value = $event),
968
+ name: "auto-top-up-threshold",
969
+ unit: entryUnit.value,
970
+ "model-base": entryBase.value,
971
+ "entry-base": entryBase.value,
972
+ currency: __props.chargeCurrency,
973
+ "conversion-rate": __props.conversionRate,
974
+ "show-conversion-hint": __props.showThresholdConversion,
975
+ required: "",
976
+ disabled: __props.disabled,
977
+ error: unref(validation).threshold.$errors,
978
+ label: unref($t)({
979
+ defaultMessage: "When your balance falls below",
980
+ description: "Label of the balance at which an automatic top-up is charged",
981
+ id: "auto_topup_config.threshold.label"
982
+ })
983
+ }, null, 8, ["modelValue", "unit", "model-base", "entry-base", "currency", "conversion-rate", "show-conversion-hint", "disabled", "error", "label"]),
984
+ createVNode(_sfc_main$9, {
985
+ modelValue: topUpQuantity.value,
986
+ "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => topUpQuantity.value = $event),
987
+ name: "auto-top-up-amount",
988
+ unit: topUpUnit.value,
989
+ "model-base": "AMOUNT",
990
+ "entry-base": entryBase.value,
991
+ currency: __props.chargeCurrency,
992
+ "credit-unit-name": __props.creditUnitName,
993
+ "conversion-rate": __props.conversionRate,
994
+ bounds: __props.topUpBounds,
995
+ "show-conversion-hint": "",
996
+ required: "",
997
+ disabled: __props.disabled,
998
+ error: unref(validation).topUpAmount.$errors,
999
+ label: unref($t)({
1000
+ defaultMessage: "Top-up with",
1001
+ description: "Label of the amount every automatic top-up adds",
1002
+ id: "auto_topup_config.amount.label"
1003
+ })
1004
+ }, null, 8, ["modelValue", "unit", "entry-base", "currency", "credit-unit-name", "conversion-rate", "bounds", "disabled", "error", "label"])
1005
+ ], 2)) : createCommentVNode("", true)
1006
+ ]),
1007
+ _: 1
1008
+ }, 8, ["is-open"])
1009
+ ]),
1010
+ _: 1
1011
+ }, 8, ["content-background", "no-spacing", "no-border"]);
1012
+ };
1013
+ }
1014
+ });
1015
+ const toTime = (createdAt) => {
1016
+ const parsed = Date.parse(createdAt ?? "");
1017
+ return Number.isFinite(parsed) ? parsed : 0;
1018
+ };
1019
+ function useDefaultPaymentMethod({
1020
+ paymentMethods,
1021
+ selectedPaymentMethodId,
1022
+ preferredPaymentMethodId
1023
+ }) {
1024
+ const sortedPaymentMethods = computed(
1025
+ () => [...paymentMethods.value ?? []].sort(
1026
+ (a, b) => toTime(b.created_at) - toTime(a.created_at)
1027
+ )
1028
+ );
1029
+ watch(
1030
+ () => [
1031
+ paymentMethods.value,
1032
+ preferredPaymentMethodId == null ? void 0 : preferredPaymentMethodId.value,
1033
+ selectedPaymentMethodId.value
1034
+ ],
1035
+ ([methods, preferredId, chosenId], previous) => {
1036
+ var _a;
1037
+ const previousMethods = previous == null ? void 0 : previous[0];
1038
+ const addedPaymentMethod = methods == null ? void 0 : methods.find(
1039
+ ({ id }) => !(previousMethods == null ? void 0 : previousMethods.some((previousMethod) => previousMethod.id === id))
1040
+ );
1041
+ if (addedPaymentMethod && (previousMethods == null ? void 0 : previousMethods.length)) {
1042
+ selectedPaymentMethodId.value = addedPaymentMethod.id;
1043
+ return;
1044
+ }
1045
+ const isStillOffered = (id) => !!id && !!(methods == null ? void 0 : methods.some((method) => method.id === id));
1046
+ if (isStillOffered(chosenId)) {
1047
+ return;
1048
+ }
1049
+ selectedPaymentMethodId.value = isStillOffered(preferredId) ? preferredId : (_a = (methods == null ? void 0 : methods.find(({ is_default }) => is_default)) ?? sortedPaymentMethods.value[0]) == null ? void 0 : _a.id;
1050
+ },
1051
+ { immediate: true }
1052
+ );
1053
+ return { sortedPaymentMethods };
1054
+ }
1055
+ function useWalletBalanceFormat() {
1056
+ const { $t, formatNumber } = useIntl();
1057
+ const formatValue = (value) => formatWalletBalanceValue($t, formatNumber, value);
1058
+ const formatOpenBalance = (balanceItem) => formatValue(balanceItem == null ? void 0 : balanceItem.wallet_balance.open_balance);
1059
+ return { formatValue, formatOpenBalance };
1060
+ }
1061
+ const _hoisted_1$5 = { class: "sv-top-up-form" };
1062
+ const _hoisted_2$2 = { class: "grid grid-cols-1 gap-4" };
1063
+ const _hoisted_3$1 = { class: "grid grid-cols-1 gap-1" };
1064
+ const _hoisted_4$1 = { class: "sv-top-up-form__option-details" };
1065
+ const _hoisted_5 = { key: 0 };
1066
+ const _sfc_main$6 = /* @__PURE__ */ defineComponent({
1067
+ __name: "TopUpModalForm",
1068
+ props: {
1069
+ topUpPricingItems: { type: null },
1070
+ paymentMethods: { type: Array },
1071
+ paymentMethodOptions: { type: Array },
1072
+ autoTopUpConfig: { type: Object }
1073
+ },
1074
+ emits: ["add-payment-method", "success", "save-auto-top-up", "failure"],
1075
+ setup(__props, { expose: __expose, emit: __emit }) {
1076
+ const props = __props;
1077
+ const emit = __emit;
1078
+ const { $t } = useIntl();
1079
+ const { formatValue } = useWalletBalanceFormat();
1080
+ const model = ref({
1081
+ pricing_plan_schedule_id: "",
1082
+ pricing_items: [],
1083
+ start_at: "",
1084
+ finalize_immediately: false,
1085
+ payment_method_id: void 0,
1086
+ preview: true
1087
+ });
1088
+ const chargeableItems = computed(() => {
1089
+ const chargeable = (props.topUpPricingItems ?? []).filter(
1090
+ (item) => item.flexiblePricing || item.fixedPricing
1091
+ );
1092
+ return [
1093
+ ...chargeable.filter(({ flexiblePricing }) => flexiblePricing),
1094
+ ...chargeable.filter(({ flexiblePricing }) => !flexiblePricing)
1095
+ ];
1096
+ });
1097
+ const findItem = (pricingItemId) => chargeableItems.value.find((item) => item.pricingItemId === pricingItemId);
1098
+ const pricingPlanScheduleId = computed(
1099
+ () => {
1100
+ var _a, _b;
1101
+ return (_b = (_a = props.topUpPricingItems) == null ? void 0 : _a.find((item) => item.pricingPlanScheduleId)) == null ? void 0 : _b.pricingPlanScheduleId;
1102
+ }
1103
+ );
1104
+ watch(
1105
+ pricingPlanScheduleId,
1106
+ (scheduleId) => {
1107
+ model.value.pricing_plan_schedule_id = scheduleId ?? "";
1108
+ },
1109
+ { immediate: true }
1110
+ );
1111
+ const getInitialAmount = (item) => {
1112
+ const { config, currency } = item.flexiblePricing ?? {};
1113
+ const minimum = config == null ? void 0 : config.minimum_amount;
1114
+ return minimum && currency ? { quantity: minimum.quantity, currency } : void 0;
1115
+ };
1116
+ const selectedPricingItemId = computed({
1117
+ get: () => {
1118
+ var _a;
1119
+ return (_a = model.value.pricing_items[0]) == null ? void 0 : _a.pricing_item_id;
1120
+ },
1121
+ set: (value) => {
1122
+ const item = findItem(typeof value === "string" ? value : void 0);
1123
+ if (!item) {
1124
+ model.value.pricing_items = [];
1125
+ return;
1126
+ }
1127
+ const initialAmount = getInitialAmount(item);
1128
+ model.value.pricing_items = [
1129
+ {
1130
+ pricing_item_id: item.pricingItemId,
1131
+ ...initialAmount && { flexible_amount: initialAmount }
1132
+ }
1133
+ ];
1134
+ }
1135
+ });
1136
+ watch(
1137
+ chargeableItems,
1138
+ (items) => {
1139
+ const chosenIsStillOffered = items.some(
1140
+ ({ pricingItemId }) => {
1141
+ var _a;
1142
+ return pricingItemId === ((_a = model.value.pricing_items[0]) == null ? void 0 : _a.pricing_item_id);
1143
+ }
1144
+ );
1145
+ if (chosenIsStillOffered) {
1146
+ return;
1147
+ }
1148
+ const preferred = items.find(({ flexiblePricing }) => flexiblePricing) ?? items[0];
1149
+ selectedPricingItemId.value = preferred == null ? void 0 : preferred.pricingItemId;
1150
+ },
1151
+ { immediate: true }
1152
+ );
1153
+ const flexibleAmount = computed({
1154
+ get: () => {
1155
+ var _a;
1156
+ return (_a = model.value.pricing_items[0]) == null ? void 0 : _a.flexible_amount;
1157
+ },
1158
+ set: (amount) => {
1159
+ var _a;
1160
+ const pricingItemId = (_a = model.value.pricing_items[0]) == null ? void 0 : _a.pricing_item_id;
1161
+ if (!pricingItemId) {
1162
+ return;
1163
+ }
1164
+ model.value.pricing_items = [
1165
+ { pricing_item_id: pricingItemId, ...amount && { flexible_amount: amount } }
1166
+ ];
1167
+ }
1168
+ });
1169
+ const getCostLabel = (optionValue) => {
1170
+ var _a;
1171
+ const fixedPricing = (_a = findItem(String(optionValue))) == null ? void 0 : _a.fixedPricing;
1172
+ return (fixedPricing == null ? void 0 : fixedPricing.value.credits) ? formatAmount(fixedPricing.amount) : void 0;
1173
+ };
1174
+ const selectedFlexiblePricing = computed(
1175
+ () => {
1176
+ var _a;
1177
+ return (_a = findItem(String(selectedPricingItemId.value))) == null ? void 0 : _a.flexiblePricing;
1178
+ }
1179
+ );
1180
+ const flexibleAmountQuantity = computed({
1181
+ get: () => {
1182
+ var _a;
1183
+ return ((_a = flexibleAmount.value) == null ? void 0 : _a.quantity) ?? "";
1184
+ },
1185
+ set: (quantity) => {
1186
+ var _a;
1187
+ const currency = (_a = selectedFlexiblePricing.value) == null ? void 0 : _a.currency;
1188
+ flexibleAmount.value = quantity && currency ? { quantity, currency } : void 0;
1189
+ }
1190
+ });
1191
+ const entryBaseFor = (pricing) => pricing.creditsConfiguration ? "CREDITS" : "AMOUNT";
1192
+ const creditUnitName = computed(() => getAutoTopUpCreditUnitName(props.topUpPricingItems));
1193
+ const entryUnitFor = (pricing) => pricing.creditsConfiguration ? creditUnitName.value ?? pricing.creditsConfiguration.unitNamePlural ?? pricing.creditsConfiguration.unitNameSingle ?? "" : pricing.currency;
1194
+ const flexiblePricingFor = (optionValue) => {
1195
+ var _a;
1196
+ const flexiblePricing = (_a = findItem(String(optionValue))) == null ? void 0 : _a.flexiblePricing;
1197
+ return flexiblePricing ? [flexiblePricing] : [];
1198
+ };
1199
+ const isFlexibleOption = (optionValue) => {
1200
+ var _a;
1201
+ return !!((_a = findItem(String(optionValue))) == null ? void 0 : _a.flexiblePricing);
1202
+ };
1203
+ const options = computed(
1204
+ () => chargeableItems.value.map((item) => {
1205
+ var _a;
1206
+ return {
1207
+ value: item.pricingItemId,
1208
+ label: item.fixedPricing ? formatValue(item.fixedPricing.value) : $t({
1209
+ defaultMessage: "Choose your own amount",
1210
+ description: "Label of the choose-your-amount option in the top-up modal",
1211
+ id: "topup_modal.flexible_option.label"
1212
+ }),
1213
+ ...((_a = item.flexiblePricing) == null ? void 0 : _a.bounds.minimum) && item.flexiblePricing.bounds.maximum && {
1214
+ description: $t(
1215
+ {
1216
+ defaultMessage: "Between {minimum} and {maximum}",
1217
+ description: "Bounds of the choose-your-amount option in the top-up modal",
1218
+ id: "topup_modal.flexible_option.bounds"
1219
+ },
1220
+ {
1221
+ minimum: formatValue(item.flexiblePricing.bounds.minimum),
1222
+ maximum: formatValue(item.flexiblePricing.bounds.maximum)
1223
+ }
1224
+ )
1225
+ }
1226
+ };
1227
+ })
1228
+ );
1229
+ const pricingItems = computed(() => {
1230
+ const chargeable = model.value.pricing_items.filter(
1231
+ (item) => {
1232
+ var _a;
1233
+ return !((_a = findItem(item.pricing_item_id)) == null ? void 0 : _a.flexiblePricing) || !!item.flexible_amount;
1234
+ }
1235
+ );
1236
+ return chargeable.length > 0 ? chargeable : void 0;
1237
+ });
1238
+ const autoTopUpEditor = computed(() => {
1239
+ const canSetUpAutoTopUp = !props.autoTopUpConfig && chargeableItems.value.some(({ flexiblePricing }) => flexiblePricing);
1240
+ return canSetUpAutoTopUp ? getAutoTopUpEditorConfig(props.topUpPricingItems) : void 0;
1241
+ });
1242
+ const autoTopUpFormRef = ref();
1243
+ const { chargeOnDemandPricingItems } = createInvoicesService();
1244
+ const logger = useLogger();
1245
+ const isCharging = ref(false);
1246
+ const canSubmit = computed(
1247
+ () => !!model.value.pricing_plan_schedule_id && !!pricingItems.value && !!model.value.payment_method_id
1248
+ );
1249
+ const validationState = reactive({
1250
+ paymentMethodId: computed(() => model.value.payment_method_id ?? null)
1251
+ });
1252
+ const validation = useValidation(
1253
+ {
1254
+ paymentMethodId: {
1255
+ required: common.withMessage(
1256
+ () => $t({
1257
+ defaultMessage: "Select a payment method to pay for this top-up.",
1258
+ description: "Error shown under the payment methods in the top-up modal when none is selected on submit",
1259
+ id: "topup_modal.payment_method_required"
1260
+ }),
1261
+ required
1262
+ )
1263
+ }
1264
+ },
1265
+ validationState
1266
+ );
1267
+ const chargedValue = computed(() => {
1268
+ const [chargedItem] = model.value.pricing_items;
1269
+ const item = findItem(chargedItem == null ? void 0 : chargedItem.pricing_item_id);
1270
+ return item ? getTopUpValue(item, chargedItem == null ? void 0 : chargedItem.flexible_amount) : void 0;
1271
+ });
1272
+ async function submit() {
1273
+ var _a, _b, _c;
1274
+ validation.value.$touch();
1275
+ const editedAutoTopUp = (_a = autoTopUpFormRef.value) == null ? void 0 : _a.validate();
1276
+ if (validation.value.$invalid || ((_b = autoTopUpFormRef.value) == null ? void 0 : _b.isInvalid) || !canSubmit.value || isCharging.value) {
1277
+ return;
1278
+ }
1279
+ isCharging.value = true;
1280
+ try {
1281
+ const invoice = await chargeOnDemandPricingItems({
1282
+ pricing_plan_schedule_id: model.value.pricing_plan_schedule_id,
1283
+ pricing_items: pricingItems.value ?? [],
1284
+ payment_method_id: model.value.payment_method_id,
1285
+ preview: false
1286
+ });
1287
+ if (editedAutoTopUp && ((_c = autoTopUpFormRef.value) == null ? void 0 : _c.hasChanges) && model.value.payment_method_id) {
1288
+ emit("save-auto-top-up", {
1289
+ rule: editedAutoTopUp,
1290
+ paymentMethodId: model.value.payment_method_id
1291
+ });
1292
+ }
1293
+ emit("success", invoice);
1294
+ } catch (error) {
1295
+ logger.error("TOP_UP_FAILED", "Failed to charge the wallet top-up", {}, error);
1296
+ emit("failure", error);
1297
+ } finally {
1298
+ isCharging.value = false;
1299
+ }
1300
+ }
1301
+ __expose({ submit, isCharging, canSubmit, chargedValue });
1302
+ const selectedPaymentMethodId = computed({
1303
+ get: () => model.value.payment_method_id ?? void 0,
1304
+ set: (paymentMethodId) => {
1305
+ model.value.payment_method_id = paymentMethodId;
1306
+ }
1307
+ });
1308
+ const { sortedPaymentMethods } = useDefaultPaymentMethod({
1309
+ paymentMethods: computed(() => props.paymentMethods),
1310
+ selectedPaymentMethodId
1311
+ });
1312
+ return (_ctx, _cache) => {
1313
+ return openBlock(), createElementBlock("form", _hoisted_1$5, [
1314
+ createElementVNode("div", _hoisted_2$2, [
1315
+ createElementVNode("div", _hoisted_3$1, [
1316
+ options.value.length > 0 ? (openBlock(), createBlock(unref(_sfc_main$j), {
1317
+ key: 0,
1318
+ modelValue: selectedPricingItemId.value,
1319
+ "onUpdate:modelValue": _cache[3] || (_cache[3] = ($event) => selectedPricingItemId.value = $event),
1320
+ class: "sv-top-up-form__options",
1321
+ name: "top-up-pricing-item",
1322
+ direction: "column",
1323
+ required: "",
1324
+ disabled: isCharging.value,
1325
+ options: options.value,
1326
+ "show-radio": false,
1327
+ label: unref($t)({
1328
+ defaultMessage: "Top up amount",
1329
+ description: "Label above the list of ways to top up the wallet in the top-up modal",
1330
+ id: "topup_modal.pricing_items.label"
1331
+ })
1332
+ }, {
1333
+ label: withCtx(({ option, optionValue }) => [
1334
+ createElementVNode("span", null, toDisplayString(option.label), 1),
1335
+ getCostLabel(optionValue) ? (openBlock(), createBlock(unref(_sfc_main$g), {
1336
+ key: 0,
1337
+ tag: "span",
1338
+ variant: "body-sm",
1339
+ shade: "lighter",
1340
+ weight: "normal",
1341
+ "no-spacing": "",
1342
+ class: "sv-top-up-form__option-cost"
1343
+ }, {
1344
+ default: withCtx(() => [
1345
+ createTextVNode(toDisplayString(getCostLabel(optionValue)), 1)
1346
+ ]),
1347
+ _: 2
1348
+ }, 1024)) : createCommentVNode("", true)
1349
+ ]),
1350
+ description: withCtx(({ option, optionValue }) => [
1351
+ createElementVNode("div", _hoisted_4$1, [
1352
+ option.description && !isFlexibleOption(optionValue) ? (openBlock(), createBlock(unref(_sfc_main$g), {
1353
+ key: 0,
1354
+ tag: "span",
1355
+ variant: "body-xs",
1356
+ shade: "lighter",
1357
+ "no-spacing": ""
1358
+ }, {
1359
+ default: withCtx(() => [
1360
+ createTextVNode(toDisplayString(option.description), 1)
1361
+ ]),
1362
+ _: 2
1363
+ }, 1024)) : createCommentVNode("", true),
1364
+ flexiblePricingFor(optionValue).length > 0 ? (openBlock(), createBlock(unref(_sfc_main$i), {
1365
+ key: 1,
1366
+ "is-open": String(optionValue) === selectedPricingItemId.value,
1367
+ lazy: ""
1368
+ }, {
1369
+ default: withCtx(() => [
1370
+ (openBlock(true), createElementBlock(Fragment, null, renderList(flexiblePricingFor(optionValue), (flexiblePricing) => {
1371
+ var _a;
1372
+ return openBlock(), createElementBlock("div", {
1373
+ key: flexiblePricing.currency,
1374
+ class: "sv-top-up-form__amount grid grid-cols-1 gap-3",
1375
+ onClick: _cache[1] || (_cache[1] = withModifiers(() => {
1376
+ }, ["stop"])),
1377
+ onKeydown: _cache[2] || (_cache[2] = withModifiers(() => {
1378
+ }, ["stop"]))
1379
+ }, [
1380
+ option.description ? (openBlock(), createBlock(unref(_sfc_main$g), {
1381
+ key: 0,
1382
+ tag: "span",
1383
+ variant: "body-xs",
1384
+ shade: "lighter",
1385
+ "no-spacing": ""
1386
+ }, {
1387
+ default: withCtx(() => [
1388
+ createTextVNode(toDisplayString(option.description), 1)
1389
+ ]),
1390
+ _: 2
1391
+ }, 1024)) : createCommentVNode("", true),
1392
+ createVNode(_sfc_main$9, {
1393
+ modelValue: flexibleAmountQuantity.value,
1394
+ "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => flexibleAmountQuantity.value = $event),
1395
+ name: "top-up-amount",
1396
+ "model-base": "AMOUNT",
1397
+ unit: entryUnitFor(flexiblePricing),
1398
+ "entry-base": entryBaseFor(flexiblePricing),
1399
+ currency: flexiblePricing.currency,
1400
+ "conversion-rate": (_a = flexiblePricing.creditsConfiguration) == null ? void 0 : _a.conversionRate,
1401
+ required: "",
1402
+ disabled: isCharging.value
1403
+ }, null, 8, ["modelValue", "unit", "entry-base", "currency", "conversion-rate", "disabled"])
1404
+ ], 32);
1405
+ }), 128))
1406
+ ]),
1407
+ _: 2
1408
+ }, 1032, ["is-open"])) : createCommentVNode("", true)
1409
+ ])
1410
+ ]),
1411
+ _: 1
1412
+ }, 8, ["modelValue", "disabled", "options", "label"])) : createCommentVNode("", true)
1413
+ ]),
1414
+ createElementVNode("div", null, [
1415
+ createVNode(_sfc_main$a, {
1416
+ "pricing-plan-schedule-id": pricingPlanScheduleId.value,
1417
+ "pricing-items": pricingItems.value
1418
+ }, null, 8, ["pricing-plan-schedule-id", "pricing-items"])
1419
+ ]),
1420
+ autoTopUpEditor.value ? (openBlock(), createElementBlock("div", _hoisted_5, [
1421
+ createVNode(_sfc_main$7, mergeProps({
1422
+ ref_key: "autoTopUpFormRef",
1423
+ ref: autoTopUpFormRef,
1424
+ class: "sv-top-up-form__auto-top-up"
1425
+ }, autoTopUpEditor.value, {
1426
+ contained: "",
1427
+ "show-threshold-conversion": false,
1428
+ disabled: isCharging.value
1429
+ }), null, 16, ["disabled"])
1430
+ ])) : createCommentVNode("", true),
1431
+ createElementVNode("div", null, [
1432
+ createVNode(unref(_sfc_main$k), { spacing: "xs" })
1433
+ ]),
1434
+ createElementVNode("div", null, [
1435
+ renderSlot(_ctx.$slots, "payment-method", {}, () => [
1436
+ createVNode(_sfc_main$l, {
1437
+ modelValue: selectedPaymentMethodId.value,
1438
+ "onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => selectedPaymentMethodId.value = $event),
1439
+ class: "sv-top-up-form__payment-methods",
1440
+ "payment-methods": unref(sortedPaymentMethods),
1441
+ required: "",
1442
+ error: unref(validation).paymentMethodId.$errors,
1443
+ "payment-method-options": __props.paymentMethodOptions,
1444
+ disabled: isCharging.value,
1445
+ label: unref($t)({
1446
+ defaultMessage: "Payment method",
1447
+ description: "Label above the payment method that pays for the top-up, in the top-up modal",
1448
+ id: "topup_modal.payment_method_selector.label"
1449
+ }),
1450
+ onAddPaymentMethod: _cache[5] || (_cache[5] = ($event) => emit("add-payment-method"))
1451
+ }, null, 8, ["modelValue", "payment-methods", "error", "payment-method-options", "disabled", "label"])
1452
+ ])
1453
+ ])
1454
+ ])
1455
+ ]);
1456
+ };
1457
+ }
1458
+ });
1459
+ const _hoisted_1$4 = { class: "sv-top-up-success grid grid-cols-1 gap-4" };
1460
+ const _sfc_main$5 = /* @__PURE__ */ defineComponent({
1461
+ __name: "TopUpModalSuccess",
1462
+ props: {
1463
+ addedValue: { type: Object },
1464
+ invoice: { type: Object }
1465
+ },
1466
+ setup(__props) {
1467
+ const { $t } = useIntl();
1468
+ return (_ctx, _cache) => {
1469
+ return openBlock(), createElementBlock("div", _hoisted_1$4, [
1470
+ __props.invoice ? (openBlock(), createBlock(unref(_sfc_main$d), {
1471
+ key: 0,
1472
+ "content-background": "none"
1473
+ }, {
1474
+ default: withCtx(() => [
1475
+ createVNode(unref(_sfc_main$g), {
1476
+ tag: "span",
1477
+ variant: "body-sm",
1478
+ weight: "semibold",
1479
+ class: "mb-2 block"
1480
+ }, {
1481
+ default: withCtx(() => [
1482
+ createTextVNode(toDisplayString(unref($t)({
1483
+ defaultMessage: "Receipt",
1484
+ description: "Heading above the invoice a completed top-up produced",
1485
+ id: "topup_modal.success.receipt.heading"
1486
+ })), 1)
1487
+ ]),
1488
+ _: 1
1489
+ }),
1490
+ createVNode(unref(_sfc_main$e), {
1491
+ invoice: __props.invoice,
1492
+ "is-customer-facing": ""
1493
+ }, null, 8, ["invoice"])
1494
+ ]),
1495
+ _: 1
1496
+ })) : createCommentVNode("", true)
1497
+ ]);
1498
+ };
1499
+ }
1500
+ });
1501
+ function useTopUpModalLabels({
1502
+ step,
1503
+ currentBalance,
1504
+ topUpValue
1505
+ }) {
1506
+ const { $t, formatNumber } = useIntl();
1507
+ const title = computed(() => {
1508
+ if (step.value === "ADD_PAYMENT_METHOD") {
1509
+ return $t({
1510
+ defaultMessage: "Add payment method",
1511
+ description: "Title of the top-up modal while the customer is adding a payment method",
1512
+ id: "topup_modal.add_payment_method.title"
1513
+ });
1514
+ }
1515
+ if (step.value === "SUCCESS") {
1516
+ return $t({
1517
+ defaultMessage: "Top-up complete",
1518
+ description: "Title of the top-up modal once the top-up has been charged",
1519
+ id: "topup_modal.success.modal_title"
1520
+ });
1521
+ }
1522
+ return $t({
1523
+ defaultMessage: "Top up balance",
1524
+ description: "Title of the wallet top-up modal",
1525
+ id: "topup_modal.title"
1526
+ });
1527
+ });
1528
+ const subTitle = computed(() => {
1529
+ if (step.value === "ADD_PAYMENT_METHOD") {
1530
+ return $t({
1531
+ defaultMessage: "Add a new payment method for topping up your balance.",
1532
+ description: "Subtitle of the top-up modal while the customer is adding a payment method",
1533
+ id: "topup_modal.add_payment_method.subtitle"
1534
+ });
1535
+ }
1536
+ if (step.value === "SUCCESS") {
1537
+ return $t({
1538
+ defaultMessage: "Your payment went through.",
1539
+ description: "Subtitle of the top-up modal once the top-up has been charged",
1540
+ id: "topup_modal.success.modal_subtitle"
1541
+ });
1542
+ }
1543
+ return $t(
1544
+ {
1545
+ defaultMessage: "Your current balance is {balance}.",
1546
+ description: "Subtitle of the top-up modal showing the current wallet balance",
1547
+ id: "topup_modal.subtitle"
1548
+ },
1549
+ { balance: currentBalance.value }
1550
+ );
1551
+ });
1552
+ const cancelButtonText = computed(
1553
+ () => step.value === "ADD_PAYMENT_METHOD" ? $t({
1554
+ defaultMessage: "Back",
1555
+ description: "Label of the button that leaves the add payment method step in the top-up modal",
1556
+ id: "topup_modal.back_button.label"
1557
+ }) : $t({
1558
+ defaultMessage: "Cancel",
1559
+ description: "Label of the button that closes the top-up modal",
1560
+ id: "topup_modal.cancel_button.label"
1561
+ })
1562
+ );
1563
+ const confirmButtonText = computed(() => {
1564
+ if (step.value === "ADD_PAYMENT_METHOD") {
1565
+ return $t({
1566
+ defaultMessage: "Save payment method",
1567
+ description: "Label of the confirm button in the top-up modal while adding a payment method",
1568
+ id: "topup_modal.save_payment_method.label"
1569
+ });
1570
+ }
1571
+ if (step.value === "SUCCESS") {
1572
+ return $t({
1573
+ defaultMessage: "Done",
1574
+ description: "Label of the button that dismisses the top-up modal once the top-up has been charged",
1575
+ id: "topup_modal.done_button.label"
1576
+ });
1577
+ }
1578
+ if (!topUpValue.value) {
1579
+ return $t({
1580
+ defaultMessage: "Top up balance",
1581
+ description: "Label of the confirm button in the top-up modal while no amount is entered",
1582
+ id: "topup_modal.confirm_button.empty.label"
1583
+ });
1584
+ }
1585
+ return $t(
1586
+ {
1587
+ defaultMessage: "Top up balance with {value}",
1588
+ description: "Label of the confirm button in the top-up modal once an amount is entered",
1589
+ id: "topup_modal.confirm_button.label"
1590
+ },
1591
+ { value: formatWalletBalanceValue($t, formatNumber, topUpValue.value) }
1592
+ );
1593
+ });
1594
+ return { title, subTitle, cancelButtonText, confirmButtonText };
1595
+ }
1596
+ function useCustomerPaymentMethodOptions({
1597
+ isOpen,
1598
+ customer
1599
+ }) {
1600
+ const { paymentMethodOptions, get, isPending } = usePaymentMethodOptions();
1601
+ watch(
1602
+ () => [isOpen.value, customer.value],
1603
+ ([open, currentCustomer]) => {
1604
+ if (!open || !currentCustomer) {
1605
+ return;
1606
+ }
1607
+ void get({
1608
+ customerId: currentCustomer.id,
1609
+ country: getCustomerCountry(currentCustomer)
1610
+ });
1611
+ },
1612
+ { immediate: true }
1613
+ );
1614
+ const settledOptions = computed(
1615
+ () => isPending.value ? void 0 : paymentMethodOptions.value
1616
+ );
1617
+ return { paymentMethodOptions, settledOptions, isPending };
1618
+ }
1619
+ function useElementHeight(target) {
1620
+ const height = ref(0);
1621
+ const measure = (element) => {
1622
+ height.value = (element == null ? void 0 : element.offsetHeight) ?? 0;
1623
+ };
1624
+ const observer = typeof ResizeObserver === "undefined" ? void 0 : new ResizeObserver((entries) => {
1625
+ var _a;
1626
+ const element = (_a = entries[0]) == null ? void 0 : _a.target;
1627
+ measure(element instanceof HTMLElement ? element : void 0);
1628
+ });
1629
+ watch(
1630
+ target,
1631
+ (element, previousElement) => {
1632
+ if (previousElement) {
1633
+ observer == null ? void 0 : observer.unobserve(previousElement);
1634
+ }
1635
+ measure(element);
1636
+ if (element) {
1637
+ observer == null ? void 0 : observer.observe(element);
1638
+ }
1639
+ },
1640
+ // `post` so the callback runs after the render that assigns the template ref, not before.
1641
+ { immediate: true, flush: "post" }
1642
+ );
1643
+ onBeforeUnmount(() => {
1644
+ observer == null ? void 0 : observer.disconnect();
1645
+ });
1646
+ return height;
1647
+ }
1648
+ const _hoisted_1$3 = ["inert"];
1649
+ const PANE_TRANSITION_MS = 300;
1650
+ const PANE_GAP = "1rem";
1651
+ const _sfc_main$4 = /* @__PURE__ */ defineComponent({
1652
+ __name: "SlidingPanes",
1653
+ props: {
1654
+ panes: { type: Array },
1655
+ current: { type: String }
1656
+ },
1657
+ setup(__props) {
1658
+ const props = __props;
1659
+ const isSwitchingPanes = ref(false);
1660
+ let switchTimeout;
1661
+ watch(
1662
+ () => props.current,
1663
+ () => {
1664
+ isSwitchingPanes.value = true;
1665
+ clearTimeout(switchTimeout);
1666
+ switchTimeout = setTimeout(() => {
1667
+ isSwitchingPanes.value = false;
1668
+ }, PANE_TRANSITION_MS);
1669
+ }
1670
+ );
1671
+ onBeforeUnmount(() => {
1672
+ clearTimeout(switchTimeout);
1673
+ });
1674
+ const paneElements = ref({});
1675
+ const paneRefSetters = {};
1676
+ const setPaneElement = (pane) => paneRefSetters[pane] ?? (paneRefSetters[pane] = (element) => {
1677
+ paneElements.value[pane] = element instanceof HTMLElement ? element : void 0;
1678
+ });
1679
+ const currentPaneElement = computed(() => paneElements.value[props.current]);
1680
+ const paneHeight = useElementHeight(currentPaneElement);
1681
+ const trackOffset = computed(() => {
1682
+ const index = props.panes.indexOf(props.current);
1683
+ return index > 0 ? `translateX(calc(${-index} * (100% + ${PANE_GAP})))` : "translateX(0px)";
1684
+ });
1685
+ return (_ctx, _cache) => {
1686
+ return openBlock(), createElementBlock("div", {
1687
+ class: normalizeClass([
1688
+ "sv-sliding-panes__viewport relative -mx-2 overflow-hidden px-2",
1689
+ isSwitchingPanes.value ? "transition-[height] duration-300 ease-in-out motion-reduce:transition-none" : ""
1690
+ ]),
1691
+ style: normalizeStyle(unref(paneHeight) ? { height: `${unref(paneHeight)}px` } : void 0)
1692
+ }, [
1693
+ createElementVNode("div", {
1694
+ class: "sv-sliding-panes__track flex items-start gap-4 transition-transform duration-300 ease-in-out motion-reduce:transition-none",
1695
+ style: normalizeStyle({ transform: trackOffset.value })
1696
+ }, [
1697
+ (openBlock(true), createElementBlock(Fragment, null, renderList(__props.panes, (pane) => {
1698
+ return openBlock(), createElementBlock("div", {
1699
+ key: pane,
1700
+ class: "sv-sliding-panes__pane w-full shrink-0",
1701
+ inert: pane !== __props.current || void 0
1702
+ }, [
1703
+ createElementVNode("div", {
1704
+ ref_for: true,
1705
+ ref: setPaneElement(pane)
1706
+ }, [
1707
+ renderSlot(_ctx.$slots, pane)
1708
+ ], 512)
1709
+ ], 8, _hoisted_1$3);
1710
+ }), 128))
1711
+ ], 4)
1712
+ ], 6);
1713
+ };
1714
+ }
1715
+ });
1716
+ const getActiveAutoTopUpConfig = (walletBalanceItem) => {
1717
+ var _a;
1718
+ return (((_a = walletBalanceItem == null ? void 0 : walletBalanceItem.wallet) == null ? void 0 : _a.auto_top_up_configs) ?? []).find(
1719
+ ({ status }) => status === "ACTIVE"
1720
+ );
1721
+ };
1722
+ const toAutoTopUpRule = (config) => config ? {
1723
+ status: config.status,
1724
+ threshold: config.threshold,
1725
+ ...config.topup_amount && { topup_amount: config.topup_amount }
1726
+ } : void 0;
1727
+ const getAutoTopUpChargeTarget = (topUpItem, topUpPricingItems = []) => {
1728
+ if ((topUpItem == null ? void 0 : topUpItem.pricing_item_id) && topUpItem.pricing_plan_schedule_id) {
1729
+ return {
1730
+ pricingItemId: topUpItem.pricing_item_id,
1731
+ pricingPlanScheduleId: topUpItem.pricing_plan_schedule_id
1732
+ };
1733
+ }
1734
+ const flexible = topUpPricingItems.find(
1735
+ ({ flexiblePricing, pricingPlanScheduleId }) => flexiblePricing && pricingPlanScheduleId
1736
+ );
1737
+ return (flexible == null ? void 0 : flexible.pricingPlanScheduleId) ? {
1738
+ pricingItemId: flexible.pricingItemId,
1739
+ pricingPlanScheduleId: flexible.pricingPlanScheduleId
1740
+ } : void 0;
1741
+ };
1742
+ const toCreateAutoTopUpConfigPayload = ({
1743
+ rule,
1744
+ walletBalanceItem,
1745
+ chargeTarget,
1746
+ paymentMethodId
1747
+ }) => {
1748
+ var _a, _b;
1749
+ const hasThreshold = !!(((_a = rule == null ? void 0 : rule.threshold) == null ? void 0 : _a.amount) ?? ((_b = rule == null ? void 0 : rule.threshold) == null ? void 0 : _b.credits));
1750
+ if (!rule || !hasThreshold || !(walletBalanceItem == null ? void 0 : walletBalanceItem.wallet_id) || !chargeTarget || !paymentMethodId) {
1751
+ return void 0;
1752
+ }
1753
+ return {
1754
+ wallet_id: walletBalanceItem.wallet_id,
1755
+ status: rule.status,
1756
+ threshold: rule.threshold,
1757
+ pricing_plan_schedule_id: chargeTarget.pricingPlanScheduleId,
1758
+ pricing_item_id: chargeTarget.pricingItemId,
1759
+ payment_method_id: paymentMethodId,
1760
+ ...rule.topup_amount && { topup_amount: rule.topup_amount }
1761
+ };
1762
+ };
1763
+ function useAddPaymentMethodStep({
1764
+ step,
1765
+ name,
1766
+ returnTo
1767
+ }) {
1768
+ const paneRef = ref();
1769
+ return {
1770
+ paneRef,
1771
+ isActive: computed(() => step.value === name),
1772
+ isSaving: computed(() => {
1773
+ var _a;
1774
+ return !!((_a = paneRef.value) == null ? void 0 : _a.isSaving);
1775
+ }),
1776
+ open: () => {
1777
+ step.value = name;
1778
+ },
1779
+ leave: () => {
1780
+ step.value = returnTo;
1781
+ },
1782
+ submit: () => {
1783
+ var _a;
1784
+ return (_a = paneRef.value) == null ? void 0 : _a.submit();
1785
+ }
1786
+ };
1787
+ }
1788
+ function createAutoTopUpConfigsService() {
1789
+ const request = createRequestService();
1790
+ const config = useConfig();
1791
+ const BASE_URL = "/portal/auto-top-up-configs";
1792
+ function getAutoTopUpConfigs(filters) {
1793
+ return request({
1794
+ url: `${config.apiUrls.config}${BASE_URL}`,
1795
+ query: { ...filters },
1796
+ isCollection: true
1797
+ });
1798
+ }
1799
+ function getAutoTopUpConfig(configId) {
1800
+ return request({
1801
+ url: `${config.apiUrls.config}${BASE_URL}/${configId}`
1802
+ });
1803
+ }
1804
+ function createAutoTopUpConfig(payload) {
1805
+ return request({
1806
+ url: `${config.apiUrls.config}${BASE_URL}`,
1807
+ options: { method: "POST" },
1808
+ data: payload
1809
+ });
1810
+ }
1811
+ function deactivateAutoTopUpConfig(configId) {
1812
+ return request({
1813
+ url: `${config.apiUrls.config}${BASE_URL}/${configId}/deactivate`,
1814
+ options: { method: "POST" }
1815
+ });
1816
+ }
1817
+ return {
1818
+ getAutoTopUpConfigs,
1819
+ getAutoTopUpConfig,
1820
+ createAutoTopUpConfig,
1821
+ deactivateAutoTopUpConfig
1822
+ };
1823
+ }
1824
+ function useSaveAutoTopUpConfig() {
1825
+ const { createAutoTopUpConfig } = createAutoTopUpConfigsService();
1826
+ const logger = useLogger();
1827
+ const isSaving = ref(false);
1828
+ const save = async (payload) => {
1829
+ if (!payload || isSaving.value) {
1830
+ return { saved: false };
1831
+ }
1832
+ isSaving.value = true;
1833
+ try {
1834
+ await createAutoTopUpConfig(payload);
1835
+ return { saved: true };
1836
+ } catch (error) {
1837
+ logger.error(
1838
+ "AUTO_TOP_UP_SAVE_FAILED",
1839
+ "Failed to save the automatic top-up rule",
1840
+ {},
1841
+ error
1842
+ );
1843
+ return { saved: false, error };
1844
+ } finally {
1845
+ isSaving.value = false;
1846
+ }
1847
+ };
1848
+ return { save, isSaving };
1849
+ }
1850
+ const _hoisted_1$2 = { class: "grid grid-cols-1 gap-4 pb-4" };
1851
+ const _hoisted_2$1 = {
1852
+ key: 0,
1853
+ class: "mb-4"
1854
+ };
1855
+ const _hoisted_3 = { class: "sr-only" };
1856
+ const _hoisted_4 = { class: "flex flex-col gap-2" };
1857
+ const _sfc_main$3 = /* @__PURE__ */ defineComponent({
1858
+ __name: "TopUpModal",
1859
+ props: {
1860
+ showModal: { type: Boolean },
1861
+ selectedBalanceItem: { type: Object },
1862
+ paymentMethods: { type: Array },
1863
+ customer: { type: Object },
1864
+ subscriptions: { type: Array }
1865
+ },
1866
+ emits: ["confirm", "close", "auto-top-up-saved", "payment-success", "payment-failed"],
1867
+ setup(__props, { emit: __emit }) {
1868
+ const props = __props;
1869
+ const emit = __emit;
1870
+ const { $t } = useIntl();
1871
+ const { formatOpenBalance } = useWalletBalanceFormat();
1872
+ const savedAutoTopUpRule = computed(
1873
+ () => toAutoTopUpRule(getActiveAutoTopUpConfig(props.selectedBalanceItem))
1874
+ );
1875
+ const currentBalance = computed(() => formatOpenBalance(props.selectedBalanceItem));
1876
+ const topUpSubscriptions = computed(
1877
+ () => getTopUpSubscriptions(props.selectedBalanceItem, props.subscriptions ?? [])
1878
+ );
1879
+ const selectedSubscriptionId = ref();
1880
+ watch(
1881
+ topUpSubscriptions,
1882
+ (available) => {
1883
+ var _a;
1884
+ const chosenIsStillOffered = available.some(
1885
+ ({ id }) => id === selectedSubscriptionId.value
1886
+ );
1887
+ if (!chosenIsStillOffered) {
1888
+ selectedSubscriptionId.value = (_a = available[0]) == null ? void 0 : _a.id;
1889
+ }
1890
+ },
1891
+ { immediate: true }
1892
+ );
1893
+ const hasSubscriptionChoice = computed(() => topUpSubscriptions.value.length > 1);
1894
+ const subscriptionOptions = computed(
1895
+ () => topUpSubscriptions.value.map(({ id, name }) => ({ value: id, label: name }))
1896
+ );
1897
+ const summaryById = computed(
1898
+ () => Object.fromEntries(
1899
+ topUpSubscriptions.value.flatMap(({ id, enabledPricingIds }) => {
1900
+ const subscription = (props.subscriptions ?? []).find(({ id: it }) => it === id);
1901
+ return subscription ? [[id, { subscription, enabledPricingIds }]] : [];
1902
+ })
1903
+ )
1904
+ );
1905
+ const balanceItemForSubscription = computed(() => {
1906
+ var _a;
1907
+ if (!props.selectedBalanceItem || !((_a = props.subscriptions) == null ? void 0 : _a.length)) {
1908
+ return props.selectedBalanceItem;
1909
+ }
1910
+ const selected = topUpSubscriptions.value.find(({ id }) => id === selectedSubscriptionId.value);
1911
+ if (!selected) {
1912
+ return { ...props.selectedBalanceItem, charge_on_demand_pricing_items: [] };
1913
+ }
1914
+ return withTopUpPricingItemsForSchedules(props.selectedBalanceItem, selected.scheduleIds);
1915
+ });
1916
+ const topUpPricingItems = computed(() => getTopUpPricingItems(balanceItemForSubscription.value));
1917
+ const {
1918
+ paymentMethodOptions,
1919
+ settledOptions,
1920
+ isPending: isPaymentMethodOptionsPending
1921
+ } = useCustomerPaymentMethodOptions({
1922
+ isOpen: computed(() => props.showModal),
1923
+ customer: computed(() => props.customer)
1924
+ });
1925
+ const step = ref("TOP_UP");
1926
+ const hasStoredPaymentMethods = computed(() => (props.paymentMethods ?? []).length > 0);
1927
+ const hasNoPaymentMethodOptions = computed(
1928
+ () => !isPaymentMethodOptionsPending.value && (paymentMethodOptions.value ?? []).length === 0
1929
+ );
1930
+ const isTopUpUnavailable = computed(
1931
+ () => step.value === "TOP_UP" && !hasStoredPaymentMethods.value && hasNoPaymentMethodOptions.value
1932
+ );
1933
+ const chargedInvoice = ref();
1934
+ const chargedValue = ref();
1935
+ const handlePaymentSuccess = () => {
1936
+ leaveAddPaymentMethod();
1937
+ emit("payment-success");
1938
+ };
1939
+ const {
1940
+ paneRef: addPaymentMethodRef,
1941
+ isActive: isAddingPaymentMethod,
1942
+ isSaving: isSavingPaymentMethod,
1943
+ open: openAddPaymentMethod,
1944
+ leave: leaveAddPaymentMethod,
1945
+ submit: submitPaymentMethod
1946
+ } = useAddPaymentMethodStep({ step, name: "ADD_PAYMENT_METHOD", returnTo: "TOP_UP" });
1947
+ const { save: saveRule } = useSaveAutoTopUpConfig();
1948
+ const topUpFormRef = ref();
1949
+ const topUpValue = computed(() => {
1950
+ var _a;
1951
+ return (_a = topUpFormRef.value) == null ? void 0 : _a.chargedValue;
1952
+ });
1953
+ const isPending = computed(() => {
1954
+ var _a;
1955
+ return isSavingPaymentMethod.value || !!((_a = topUpFormRef.value) == null ? void 0 : _a.isCharging);
1956
+ });
1957
+ const { title, subTitle, cancelButtonText, confirmButtonText } = useTopUpModalLabels({
1958
+ step,
1959
+ currentBalance,
1960
+ topUpValue
1961
+ });
1962
+ const handleConfirm = () => {
1963
+ var _a;
1964
+ if (isAddingPaymentMethod.value) {
1965
+ submitPaymentMethod();
1966
+ return;
1967
+ }
1968
+ void ((_a = topUpFormRef.value) == null ? void 0 : _a.submit());
1969
+ };
1970
+ const handleSaveAutoTopUp = async ({
1971
+ rule,
1972
+ paymentMethodId
1973
+ }) => {
1974
+ const { saved } = await saveRule(
1975
+ toCreateAutoTopUpConfigPayload({
1976
+ rule,
1977
+ walletBalanceItem: props.selectedBalanceItem,
1978
+ chargeTarget: getAutoTopUpChargeTarget(void 0, topUpPricingItems.value),
1979
+ paymentMethodId
1980
+ })
1981
+ );
1982
+ if (saved) {
1983
+ emit("auto-top-up-saved");
1984
+ }
1985
+ };
1986
+ const handleTopUpSuccess = (invoice) => {
1987
+ var _a;
1988
+ chargedInvoice.value = invoice;
1989
+ chargedValue.value = (_a = topUpFormRef.value) == null ? void 0 : _a.chargedValue;
1990
+ step.value = "SUCCESS";
1991
+ };
1992
+ const handleDone = () => {
1993
+ emit("confirm");
1994
+ emit("close");
1995
+ };
1996
+ const handleCancel = () => {
1997
+ if (isPending.value) {
1998
+ return;
1999
+ }
2000
+ if (isAddingPaymentMethod.value) {
2001
+ leaveAddPaymentMethod();
2002
+ return;
2003
+ }
2004
+ if (step.value === "SUCCESS") {
2005
+ handleDone();
2006
+ return;
2007
+ }
2008
+ emit("close");
2009
+ };
2010
+ const topUpFormKey = ref(0);
2011
+ watch(
2012
+ () => props.showModal,
2013
+ (showModal) => {
2014
+ if (!showModal) {
2015
+ return;
2016
+ }
2017
+ step.value = "TOP_UP";
2018
+ chargedInvoice.value = void 0;
2019
+ chargedValue.value = void 0;
2020
+ topUpFormKey.value += 1;
2021
+ }
2022
+ );
2023
+ return (_ctx, _cache) => {
2024
+ return openBlock(), createBlock(unref(Modal), {
2025
+ "no-click-away": "",
2026
+ "show-modal": __props.showModal,
2027
+ size: "lg",
2028
+ title: unref(title),
2029
+ "sub-title": unref(subTitle),
2030
+ "cancel-button-text": unref(cancelButtonText),
2031
+ "confirm-button-text": unref(confirmButtonText),
2032
+ "is-loading": isPending.value,
2033
+ onConfirm: handleConfirm,
2034
+ onClose: handleCancel
2035
+ }, createSlots({
2036
+ body: withCtx(() => [
2037
+ createElementVNode("div", _hoisted_1$2, [
2038
+ createVNode(_sfc_main$4, {
2039
+ panes: unref(TOP_UP_MODAL_STEPS),
2040
+ current: step.value
2041
+ }, {
2042
+ TOP_UP: withCtx(() => [
2043
+ hasSubscriptionChoice.value ? (openBlock(), createElementBlock("div", _hoisted_2$1, [
2044
+ createVNode(unref(_sfc_main$j), {
2045
+ modelValue: selectedSubscriptionId.value,
2046
+ "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedSubscriptionId.value = $event),
2047
+ class: "sv-topup-modal__subscription",
2048
+ name: "top-up-subscription",
2049
+ direction: "column",
2050
+ required: "",
2051
+ options: subscriptionOptions.value,
2052
+ "show-radio": false,
2053
+ label: unref($t)({
2054
+ defaultMessage: "Subscription to top up",
2055
+ description: "Label above the list of subscriptions a top-up can be charged against, in the top-up modal",
2056
+ id: "topup_modal.subscriptions.label"
2057
+ })
2058
+ }, {
2059
+ prefix: withCtx(({ optionValue }) => [
2060
+ summaryById.value[String(optionValue)] ? (openBlock(), createBlock(_sfc_main$n, {
2061
+ key: 0,
2062
+ class: "sv-topup-modal__subscription-option grow",
2063
+ "no-spacing": "",
2064
+ subscription: summaryById.value[String(optionValue)].subscription,
2065
+ "enabled-pricing-ids": summaryById.value[String(optionValue)].enabledPricingIds
2066
+ }, null, 8, ["subscription", "enabled-pricing-ids"])) : createCommentVNode("", true)
2067
+ ]),
2068
+ label: withCtx(({ option }) => [
2069
+ createElementVNode("span", _hoisted_3, toDisplayString(option.label), 1)
2070
+ ]),
2071
+ _: 1
2072
+ }, 8, ["modelValue", "options", "label"])
2073
+ ])) : createCommentVNode("", true),
2074
+ (openBlock(), createBlock(_sfc_main$6, {
2075
+ key: topUpFormKey.value,
2076
+ ref_key: "topUpFormRef",
2077
+ ref: topUpFormRef,
2078
+ "top-up-pricing-items": topUpPricingItems.value,
2079
+ "payment-methods": __props.paymentMethods,
2080
+ "auto-top-up-config": savedAutoTopUpRule.value,
2081
+ "payment-method-options": unref(settledOptions),
2082
+ onAddPaymentMethod: unref(openAddPaymentMethod),
2083
+ onSuccess: handleTopUpSuccess,
2084
+ onSaveAutoTopUp: handleSaveAutoTopUp
2085
+ }, null, 8, ["top-up-pricing-items", "payment-methods", "auto-top-up-config", "payment-method-options", "onAddPaymentMethod"]))
2086
+ ]),
2087
+ ADD_PAYMENT_METHOD: withCtx(() => [
2088
+ createVNode(_sfc_main$m, {
2089
+ ref_key: "addPaymentMethodRef",
2090
+ ref: addPaymentMethodRef,
2091
+ customer: __props.customer,
2092
+ "payment-method-options": unref(paymentMethodOptions),
2093
+ "is-loading": unref(isPaymentMethodOptionsPending),
2094
+ "is-active": unref(isAddingPaymentMethod),
2095
+ onSuccess: handlePaymentSuccess,
2096
+ onFailure: _cache[1] || (_cache[1] = (error) => _ctx.$emit("payment-failed", error))
2097
+ }, null, 8, ["customer", "payment-method-options", "is-loading", "is-active"])
2098
+ ]),
2099
+ SUCCESS: withCtx(() => [
2100
+ chargedInvoice.value ? (openBlock(), createBlock(_sfc_main$5, {
2101
+ key: 0,
2102
+ "added-value": chargedValue.value,
2103
+ invoice: chargedInvoice.value
2104
+ }, null, 8, ["added-value", "invoice"])) : createCommentVNode("", true)
2105
+ ]),
2106
+ _: 1
2107
+ }, 8, ["panes", "current"])
2108
+ ])
2109
+ ]),
2110
+ _: 2
2111
+ }, [
2112
+ step.value === "SUCCESS" || isTopUpUnavailable.value ? {
2113
+ name: "footer",
2114
+ fn: withCtx(() => [
2115
+ createElementVNode("div", _hoisted_4, [
2116
+ step.value === "SUCCESS" ? (openBlock(), createBlock(unref(_sfc_main$o), {
2117
+ key: 0,
2118
+ size: "lg",
2119
+ "data-testid": "done",
2120
+ onClick: handleDone
2121
+ }, {
2122
+ default: withCtx(() => [
2123
+ createTextVNode(toDisplayString(unref(confirmButtonText)), 1)
2124
+ ]),
2125
+ _: 1
2126
+ })) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
2127
+ createVNode(unref(_sfc_main$o), {
2128
+ size: "lg",
2129
+ disabled: "",
2130
+ "data-testid": "confirm"
2131
+ }, {
2132
+ default: withCtx(() => [
2133
+ createTextVNode(toDisplayString(unref(confirmButtonText)), 1)
2134
+ ]),
2135
+ _: 1
2136
+ }),
2137
+ createVNode(unref(_sfc_main$o), {
2138
+ size: "lg",
2139
+ color: "gray",
2140
+ variant: "ghost",
2141
+ "data-testid": "cancel",
2142
+ onClick: handleCancel
2143
+ }, {
2144
+ default: withCtx(() => [
2145
+ createTextVNode(toDisplayString(unref(cancelButtonText)), 1)
2146
+ ]),
2147
+ _: 1
2148
+ })
2149
+ ], 64))
2150
+ ])
2151
+ ]),
2152
+ key: "0"
2153
+ } : void 0
2154
+ ]), 1032, ["show-modal", "title", "sub-title", "cancel-button-text", "confirm-button-text", "is-loading"]);
2155
+ };
2156
+ }
2157
+ });
2158
+ const AUTO_TOP_UP_MODAL_STEPS = ["AUTO_TOP_UP", "ADD_PAYMENT_METHOD"];
2159
+ const _hoisted_1$1 = { class: "grid grid-cols-1 gap-4 pb-4" };
2160
+ const _hoisted_2 = { class: "grid grid-cols-1 gap-4" };
2161
+ const _sfc_main$2 = /* @__PURE__ */ defineComponent({
2162
+ __name: "AutoTopUpModal",
2163
+ props: {
2164
+ showModal: { type: Boolean },
2165
+ walletBalanceItem: { type: Object },
2166
+ topUpItem: { type: Object },
2167
+ paymentMethods: { type: Array },
2168
+ customer: { type: Object }
2169
+ },
2170
+ emits: ["saved", "close", "payment-success", "payment-failed"],
2171
+ setup(__props, { emit: __emit }) {
2172
+ const props = __props;
2173
+ const emit = __emit;
2174
+ const { $t } = useIntl();
2175
+ const { formatOpenBalance } = useWalletBalanceFormat();
2176
+ const step = ref("AUTO_TOP_UP");
2177
+ const currentBalance = computed(() => formatOpenBalance(props.walletBalanceItem));
2178
+ const topUpPricingItems = computed(() => getTopUpPricingItems(props.walletBalanceItem));
2179
+ const autoTopUpEditor = computed(() => getAutoTopUpEditorConfig(topUpPricingItems.value));
2180
+ const savedConfig = computed(() => getActiveAutoTopUpConfig(props.walletBalanceItem));
2181
+ const savedRule = computed(() => toAutoTopUpRule(savedConfig.value));
2182
+ const chargeTarget = computed(
2183
+ () => getAutoTopUpChargeTarget(props.topUpItem, topUpPricingItems.value)
2184
+ );
2185
+ const autoTopUpFormRef = ref();
2186
+ const previewPricingItems = computed(() => {
2187
+ var _a, _b;
2188
+ const amount = (_b = (_a = autoTopUpFormRef.value) == null ? void 0 : _a.rule) == null ? void 0 : _b.topup_amount;
2189
+ return (amount == null ? void 0 : amount.quantity) && chargeTarget.value ? [{ pricing_item_id: chargeTarget.value.pricingItemId, flexible_amount: amount }] : void 0;
2190
+ });
2191
+ const previewScheduleId = computed(() => {
2192
+ var _a;
2193
+ return (_a = chargeTarget.value) == null ? void 0 : _a.pricingPlanScheduleId;
2194
+ });
2195
+ const selectedPaymentMethodId = ref();
2196
+ const { sortedPaymentMethods } = useDefaultPaymentMethod({
2197
+ paymentMethods: computed(() => props.paymentMethods),
2198
+ selectedPaymentMethodId,
2199
+ preferredPaymentMethodId: computed(() => {
2200
+ var _a;
2201
+ return (_a = savedConfig.value) == null ? void 0 : _a.payment_method_id;
2202
+ })
2203
+ });
2204
+ const {
2205
+ paymentMethodOptions,
2206
+ settledOptions,
2207
+ isPending: isPaymentMethodOptionsPending
2208
+ } = useCustomerPaymentMethodOptions({
2209
+ isOpen: computed(() => props.showModal),
2210
+ customer: computed(() => props.customer)
2211
+ });
2212
+ const {
2213
+ paneRef: addPaymentMethodRef,
2214
+ isActive: isAddingPaymentMethod,
2215
+ isSaving: isSavingPaymentMethod,
2216
+ open: openAddPaymentMethod,
2217
+ leave: leaveAddPaymentMethod,
2218
+ submit: submitPaymentMethod
2219
+ } = useAddPaymentMethodStep({ step, name: "ADD_PAYMENT_METHOD", returnTo: "AUTO_TOP_UP" });
2220
+ const { save: saveRule, isSaving: isSavingRule } = useSaveAutoTopUpConfig();
2221
+ const isPending = computed(() => isSavingPaymentMethod.value || isSavingRule.value);
2222
+ const validationState = reactive({
2223
+ paymentMethodId: computed(() => selectedPaymentMethodId.value ?? null)
2224
+ });
2225
+ const validation = useValidation(
2226
+ {
2227
+ paymentMethodId: {
2228
+ required: common.withMessage(
2229
+ () => $t({
2230
+ defaultMessage: "Select a payment method to pay for automatic top-ups.",
2231
+ description: "Error shown in the auto top-up modal when no payment method is selected",
2232
+ id: "auto_topup_modal.payment_method.required"
2233
+ }),
2234
+ required
2235
+ )
2236
+ }
2237
+ },
2238
+ validationState
2239
+ );
2240
+ const title = computed(
2241
+ () => step.value === "ADD_PAYMENT_METHOD" ? $t({
2242
+ defaultMessage: "Add payment method",
2243
+ description: "Title of the auto top-up modal while the customer is adding a payment method",
2244
+ id: "auto_topup_modal.add_payment_method.title"
2245
+ }) : $t({
2246
+ defaultMessage: "Automatic top-up",
2247
+ description: "Title of the automatic wallet top-up modal",
2248
+ id: "auto_topup_modal.title"
2249
+ })
2250
+ );
2251
+ const subTitle = computed(
2252
+ () => step.value === "ADD_PAYMENT_METHOD" ? $t({
2253
+ defaultMessage: "This method pays for every automatic top-up.",
2254
+ description: "Subtitle of the auto top-up modal while the customer is adding a payment method",
2255
+ id: "auto_topup_modal.add_payment_method.subtitle"
2256
+ }) : $t(
2257
+ {
2258
+ defaultMessage: "Your current balance is {balance}. Enable auto top so you can stay productive",
2259
+ description: "Subtitle of the automatic wallet top-up modal, naming the balance",
2260
+ id: "auto_topup_modal.subtitle"
2261
+ },
2262
+ { balance: currentBalance.value }
2263
+ )
2264
+ );
2265
+ const cancelButtonText = computed(
2266
+ () => step.value === "ADD_PAYMENT_METHOD" ? $t({
2267
+ defaultMessage: "Back",
2268
+ description: "Button returning from adding a payment method to the auto top-up rule",
2269
+ id: "auto_topup_modal.add_payment_method.cancel"
2270
+ }) : $t({
2271
+ defaultMessage: "Cancel",
2272
+ description: "Button dismissing the auto top-up modal",
2273
+ id: "auto_topup_modal.cancel"
2274
+ })
2275
+ );
2276
+ const confirmButtonText = computed(
2277
+ () => step.value === "ADD_PAYMENT_METHOD" ? $t({
2278
+ defaultMessage: "Add payment method",
2279
+ description: "Button storing the payment method being added in the auto top-up modal",
2280
+ id: "auto_topup_modal.add_payment_method.confirm"
2281
+ }) : $t({
2282
+ defaultMessage: "Save",
2283
+ description: "Button saving the automatic top-up rule",
2284
+ id: "auto_topup_modal.confirm"
2285
+ })
2286
+ );
2287
+ async function save() {
2288
+ var _a;
2289
+ validation.value.$touch();
2290
+ if (isPending.value) {
2291
+ return;
2292
+ }
2293
+ const { saved, error } = await saveRule(
2294
+ toCreateAutoTopUpConfigPayload({
2295
+ rule: (_a = autoTopUpFormRef.value) == null ? void 0 : _a.validate(),
2296
+ walletBalanceItem: props.walletBalanceItem,
2297
+ chargeTarget: chargeTarget.value,
2298
+ paymentMethodId: selectedPaymentMethodId.value
2299
+ })
2300
+ );
2301
+ if (saved) {
2302
+ emit("saved");
2303
+ emit("close");
2304
+ return;
2305
+ }
2306
+ if (error) {
2307
+ emit("payment-failed", error);
2308
+ }
2309
+ }
2310
+ const handleConfirm = () => {
2311
+ if (isAddingPaymentMethod.value) {
2312
+ submitPaymentMethod();
2313
+ return;
2314
+ }
2315
+ void save();
2316
+ };
2317
+ const handlePaymentSuccess = () => {
2318
+ leaveAddPaymentMethod();
2319
+ emit("payment-success");
2320
+ };
2321
+ const handleCancel = () => {
2322
+ if (isPending.value) {
2323
+ return;
2324
+ }
2325
+ if (isAddingPaymentMethod.value) {
2326
+ leaveAddPaymentMethod();
2327
+ return;
2328
+ }
2329
+ emit("close");
2330
+ };
2331
+ const formKey = ref(0);
2332
+ watch(
2333
+ () => props.showModal,
2334
+ (showModal) => {
2335
+ if (!showModal) {
2336
+ return;
2337
+ }
2338
+ step.value = "AUTO_TOP_UP";
2339
+ selectedPaymentMethodId.value = void 0;
2340
+ formKey.value += 1;
2341
+ }
2342
+ );
2343
+ return (_ctx, _cache) => {
2344
+ return openBlock(), createBlock(unref(Modal), {
2345
+ "no-click-away": "",
2346
+ "show-modal": __props.showModal,
2347
+ size: "lg",
2348
+ title: title.value,
2349
+ "sub-title": subTitle.value,
2350
+ "cancel-button-text": cancelButtonText.value,
2351
+ "confirm-button-text": confirmButtonText.value,
2352
+ "is-loading": isPending.value,
2353
+ onConfirm: handleConfirm,
2354
+ onClose: handleCancel
2355
+ }, {
2356
+ body: withCtx(() => [
2357
+ createElementVNode("div", _hoisted_1$1, [
2358
+ createVNode(_sfc_main$4, {
2359
+ panes: unref(AUTO_TOP_UP_MODAL_STEPS),
2360
+ current: step.value
2361
+ }, {
2362
+ AUTO_TOP_UP: withCtx(() => [
2363
+ createElementVNode("div", _hoisted_2, [
2364
+ autoTopUpEditor.value ? (openBlock(), createBlock(_sfc_main$7, mergeProps({
2365
+ key: formKey.value,
2366
+ ref_key: "autoTopUpFormRef",
2367
+ ref: autoTopUpFormRef,
2368
+ class: "sv-auto-topup-modal__rule"
2369
+ }, autoTopUpEditor.value, {
2370
+ config: savedRule.value,
2371
+ "always-enabled": "",
2372
+ disabled: isPending.value
2373
+ }), null, 16, ["config", "disabled"])) : createCommentVNode("", true),
2374
+ createVNode(_sfc_main$a, {
2375
+ "pricing-plan-schedule-id": previewScheduleId.value,
2376
+ "pricing-items": previewPricingItems.value
2377
+ }, null, 8, ["pricing-plan-schedule-id", "pricing-items"]),
2378
+ createVNode(_sfc_main$l, {
2379
+ modelValue: selectedPaymentMethodId.value,
2380
+ "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedPaymentMethodId.value = $event),
2381
+ class: "sv-auto-topup-modal__payment-method",
2382
+ "payment-methods": unref(sortedPaymentMethods),
2383
+ "payment-method-options": unref(settledOptions),
2384
+ disabled: isPending.value,
2385
+ error: unref(validation).paymentMethodId.$errors,
2386
+ label: unref($t)({
2387
+ defaultMessage: "Pay automatic top-ups with",
2388
+ description: "Label above the payment method an automatic top-up is charged to",
2389
+ id: "auto_topup_modal.payment_method.label"
2390
+ }),
2391
+ onAddPaymentMethod: unref(openAddPaymentMethod)
2392
+ }, null, 8, ["modelValue", "payment-methods", "payment-method-options", "disabled", "error", "label", "onAddPaymentMethod"])
2393
+ ])
2394
+ ]),
2395
+ ADD_PAYMENT_METHOD: withCtx(() => [
2396
+ createVNode(_sfc_main$m, {
2397
+ ref_key: "addPaymentMethodRef",
2398
+ ref: addPaymentMethodRef,
2399
+ customer: __props.customer,
2400
+ "payment-method-options": unref(paymentMethodOptions),
2401
+ "is-loading": unref(isPaymentMethodOptionsPending),
2402
+ "is-active": unref(isAddingPaymentMethod),
2403
+ onSuccess: handlePaymentSuccess,
2404
+ onFailure: _cache[1] || (_cache[1] = (error) => _ctx.$emit("payment-failed", error))
2405
+ }, null, 8, ["customer", "payment-method-options", "is-loading", "is-active"])
2406
+ ]),
2407
+ _: 1
2408
+ }, 8, ["panes", "current"])
2409
+ ])
2410
+ ]),
2411
+ _: 1
2412
+ }, 8, ["show-modal", "title", "sub-title", "cancel-button-text", "confirm-button-text", "is-loading"]);
2413
+ };
2414
+ }
2415
+ });
2416
+ const _hoisted_1 = { class: "sv-auto-topup-cancellation-modal sv-auto-topup-cancellation-modal__body flex flex-col gap-3" };
2417
+ const _sfc_main$1 = /* @__PURE__ */ defineComponent({
2418
+ __name: "AutoTopUpCancellationModal",
2419
+ props: {
2420
+ showModal: { type: Boolean },
2421
+ config: { type: Object }
2422
+ },
2423
+ emits: ["confirmed", "close"],
2424
+ setup(__props, { emit: __emit }) {
2425
+ const props = __props;
2426
+ const emit = __emit;
2427
+ const { $t } = useIntl();
2428
+ const logger = useLogger();
2429
+ const { formatValue } = useWalletBalanceFormat();
2430
+ const { deactivateAutoTopUpConfig } = createAutoTopUpConfigsService();
2431
+ const isSubmitting = ref(false);
2432
+ const hasFailed = ref(false);
2433
+ watch(
2434
+ () => props.showModal,
2435
+ (showModal) => {
2436
+ if (showModal) {
2437
+ hasFailed.value = false;
2438
+ }
2439
+ }
2440
+ );
2441
+ const explanation = computed(() => {
2442
+ var _a, _b;
2443
+ const threshold = (_a = props.config) == null ? void 0 : _a.threshold;
2444
+ const topUpAmount = (_b = props.config) == null ? void 0 : _b.topup_amount;
2445
+ if (!(threshold == null ? void 0 : threshold.amount) && !(threshold == null ? void 0 : threshold.credits)) {
2446
+ return $t({
2447
+ defaultMessage: "Your balance will no longer be topped up automatically. You can still top up whenever you want to.",
2448
+ description: "Explanation in the modal that turns a wallet automatic top-up off",
2449
+ id: "auto_topup_cancellation_modal.explanation"
2450
+ });
2451
+ }
2452
+ if (!topUpAmount) {
2453
+ return $t(
2454
+ {
2455
+ defaultMessage: "Your balance will no longer be topped up automatically when it falls below {threshold}. You can still top up whenever you want to.",
2456
+ description: "Explanation in the modal that turns a wallet automatic top-up off, naming the threshold",
2457
+ id: "auto_topup_cancellation_modal.explanation_with_threshold"
2458
+ },
2459
+ { threshold: formatValue(threshold) }
2460
+ );
2461
+ }
2462
+ return $t(
2463
+ {
2464
+ defaultMessage: "Your balance will no longer be topped up with {amount} when it falls below {threshold}. You can still top up whenever you want to.",
2465
+ description: "Explanation in the modal that turns a wallet automatic top-up off, naming what it charged and when",
2466
+ id: "auto_topup_cancellation_modal.explanation_with_amount"
2467
+ },
2468
+ { amount: formatValue({ amount: topUpAmount }), threshold: formatValue(threshold) }
2469
+ );
2470
+ });
2471
+ const handleConfirm = async () => {
2472
+ var _a;
2473
+ const configId = (_a = props.config) == null ? void 0 : _a.id;
2474
+ if (!configId || isSubmitting.value) {
2475
+ return;
2476
+ }
2477
+ isSubmitting.value = true;
2478
+ hasFailed.value = false;
2479
+ try {
2480
+ await deactivateAutoTopUpConfig(configId);
2481
+ emit("confirmed");
2482
+ emit("close");
2483
+ } catch (error) {
2484
+ logger.error(
2485
+ "AUTO_TOP_UP_CANCELLATION_FAILED",
2486
+ "Failed to turn off a wallet's automatic top-up",
2487
+ {},
2488
+ error
2489
+ );
2490
+ hasFailed.value = true;
2491
+ } finally {
2492
+ isSubmitting.value = false;
2493
+ }
2494
+ };
2495
+ const handleClose = () => {
2496
+ if (isSubmitting.value) {
2497
+ return;
2498
+ }
2499
+ emit("close");
2500
+ };
2501
+ return (_ctx, _cache) => {
2502
+ return openBlock(), createBlock(unref(Modal), {
2503
+ size: "sm",
2504
+ "show-modal": __props.showModal,
2505
+ "is-loading": isSubmitting.value,
2506
+ "no-click-away": isSubmitting.value,
2507
+ "no-backdrop-close": isSubmitting.value,
2508
+ title: unref($t)({
2509
+ defaultMessage: "Turn off automatic top-up",
2510
+ description: "Title of the modal that turns a wallet automatic top-up off",
2511
+ id: "auto_topup_cancellation_modal.title"
2512
+ }),
2513
+ "confirm-button-text": unref($t)({
2514
+ defaultMessage: "Yes, turn it off",
2515
+ description: "Button confirming that a wallet automatic top-up is turned off",
2516
+ id: "auto_topup_cancellation_modal.confirm"
2517
+ }),
2518
+ "cancel-button-text": unref($t)({
2519
+ defaultMessage: "Cancel",
2520
+ description: "Button dismissing the modal that turns a wallet automatic top-up off",
2521
+ id: "auto_topup_cancellation_modal.cancel"
2522
+ }),
2523
+ onConfirm: handleConfirm,
2524
+ onClose: handleClose
2525
+ }, {
2526
+ body: withCtx(() => [
2527
+ createElementVNode("div", _hoisted_1, [
2528
+ createVNode(unref(_sfc_main$g), {
2529
+ variant: "body-sm",
2530
+ shade: "lighter",
2531
+ tag: "p",
2532
+ class: "sv-auto-topup-cancellation-modal__explanation"
2533
+ }, {
2534
+ default: withCtx(() => [
2535
+ createTextVNode(toDisplayString(explanation.value), 1)
2536
+ ]),
2537
+ _: 1
2538
+ }),
2539
+ hasFailed.value ? (openBlock(), createBlock(unref(_sfc_main$p), {
2540
+ key: 0,
2541
+ class: "sv-auto-topup-cancellation-modal__error sv-error",
2542
+ title: unref($t)({
2543
+ defaultMessage: "Could not turn off the automatic top-up. Please try again later.",
2544
+ description: "Error shown when turning a wallet automatic top-up off failed",
2545
+ id: "auto_topup_cancellation_modal.failed"
2546
+ })
2547
+ }, null, 8, ["title"])) : createCommentVNode("", true)
2548
+ ])
2549
+ ]),
2550
+ _: 1
2551
+ }, 8, ["show-modal", "is-loading", "no-click-away", "no-backdrop-close", "title", "confirm-button-text", "cancel-button-text"]);
2552
+ };
2553
+ }
2554
+ });
2555
+ const _sfc_main = /* @__PURE__ */ defineComponent({
2556
+ ...{ inheritAttrs: false },
2557
+ __name: "CustomerWalletBalances",
2558
+ props: {
2559
+ hasError: { type: Boolean },
2560
+ isLoading: { type: Boolean },
2561
+ walletBalances: { type: Array },
2562
+ showTopUpButton: { type: Boolean },
2563
+ customer: { type: Object },
2564
+ paymentMethods: { type: Array },
2565
+ subscriptions: { type: Array }
2566
+ },
2567
+ emits: ["top-up-charged", "auto-top-up-saved", "auto-top-up-cancelled", "payment-method-stored", "payment-failed"],
2568
+ setup(__props, { emit: __emit }) {
2569
+ const props = __props;
2570
+ const emit = __emit;
2571
+ const { $t } = useIntl();
2572
+ const selectedTopUpItem = ref();
2573
+ const selectedBalanceItem = computed(
2574
+ () => getWalletBalanceForTopUpItem(props.walletBalances, selectedTopUpItem.value)
2575
+ );
2576
+ const showTopUpModal = computed(() => !!selectedBalanceItem.value);
2577
+ const selectedAutoTopUpItem = ref();
2578
+ const showAutoTopUpModal = computed(() => !!selectedAutoTopUpItem.value);
2579
+ const autoTopUpWallet = computed(
2580
+ () => getWalletBalanceForTopUpItem(props.walletBalances, selectedAutoTopUpItem.value)
2581
+ );
2582
+ const cancellingAutoTopUpConfig = ref();
2583
+ const showAutoTopUpCancellation = computed(() => !!cancellingAutoTopUpConfig.value);
2584
+ return (_ctx, _cache) => {
2585
+ return openBlock(), createElementBlock(Fragment, null, [
2586
+ __props.isLoading ? (openBlock(), createBlock(_sfc_main$b, mergeProps({
2587
+ key: 0,
2588
+ variant: "section"
2589
+ }, _ctx.$attrs, {
2590
+ class: "sv-wallet-balances sv-root sv-component sv-loading min-h-48",
2591
+ "data-testid": "customer-wallet-balances-skeleton"
2592
+ }), null, 16)) : __props.hasError ? (openBlock(), createBlock(unref(_sfc_main$p), mergeProps({ key: 1 }, _ctx.$attrs, {
2593
+ class: "sv-wallet-balances sv-root sv-component sv-error",
2594
+ title: unref($t)({
2595
+ defaultMessage: "Could not load wallet balances",
2596
+ description: "Error shown when wallet balances fail to load",
2597
+ id: "wallet_balance.load_failed"
2598
+ })
2599
+ }), null, 16, ["title"])) : __props.walletBalances.length > 0 ? (openBlock(), createBlock(unref(_sfc_main$q), mergeProps({ key: 2 }, _ctx.$attrs, {
2600
+ class: "sv-wallet-balances sv-root sv-component",
2601
+ "customer-wallet-balances": __props.walletBalances,
2602
+ "show-auto-top-up": "",
2603
+ "show-manual-top-up": "",
2604
+ title: unref($t)(
2605
+ {
2606
+ defaultMessage: "{count, plural, one {Wallet} other {Wallets}}",
2607
+ description: "Title for the wallets block on the customer overview page",
2608
+ id: "customer_overview.wallet_balances_block.title"
2609
+ },
2610
+ { count: String(__props.walletBalances.length) }
2611
+ ),
2612
+ onTopUp: _cache[0] || (_cache[0] = ($event) => selectedTopUpItem.value = $event),
2613
+ onAutoTopUp: _cache[1] || (_cache[1] = ($event) => selectedAutoTopUpItem.value = $event),
2614
+ onCancelAutoTopUp: _cache[2] || (_cache[2] = ($event) => cancellingAutoTopUpConfig.value = $event)
2615
+ }), null, 16, ["customer-wallet-balances", "title"])) : createCommentVNode("", true),
2616
+ __props.showTopUpButton ? (openBlock(), createBlock(_sfc_main$3, {
2617
+ key: 3,
2618
+ "show-modal": showTopUpModal.value,
2619
+ "selected-balance-item": selectedBalanceItem.value,
2620
+ "payment-methods": __props.paymentMethods,
2621
+ customer: __props.customer,
2622
+ subscriptions: __props.subscriptions,
2623
+ onClose: _cache[3] || (_cache[3] = ($event) => selectedTopUpItem.value = void 0),
2624
+ onConfirm: _cache[4] || (_cache[4] = ($event) => emit("top-up-charged")),
2625
+ onPaymentSuccess: _cache[5] || (_cache[5] = ($event) => emit("payment-method-stored")),
2626
+ onPaymentFailed: _cache[6] || (_cache[6] = (error) => emit("payment-failed", error))
2627
+ }, null, 8, ["show-modal", "selected-balance-item", "payment-methods", "customer", "subscriptions"])) : createCommentVNode("", true),
2628
+ __props.showTopUpButton ? (openBlock(), createBlock(_sfc_main$2, {
2629
+ key: 4,
2630
+ "show-modal": showAutoTopUpModal.value,
2631
+ "wallet-balance-item": autoTopUpWallet.value,
2632
+ "top-up-item": selectedAutoTopUpItem.value,
2633
+ "payment-methods": __props.paymentMethods,
2634
+ customer: __props.customer,
2635
+ onClose: _cache[7] || (_cache[7] = ($event) => selectedAutoTopUpItem.value = void 0),
2636
+ onSaved: _cache[8] || (_cache[8] = ($event) => emit("auto-top-up-saved")),
2637
+ onPaymentSuccess: _cache[9] || (_cache[9] = ($event) => emit("payment-method-stored")),
2638
+ onPaymentFailed: _cache[10] || (_cache[10] = (error) => emit("payment-failed", error))
2639
+ }, null, 8, ["show-modal", "wallet-balance-item", "top-up-item", "payment-methods", "customer"])) : createCommentVNode("", true),
2640
+ __props.showTopUpButton ? (openBlock(), createBlock(_sfc_main$1, {
2641
+ key: 5,
2642
+ "show-modal": showAutoTopUpCancellation.value,
2643
+ config: cancellingAutoTopUpConfig.value,
2644
+ onClose: _cache[11] || (_cache[11] = ($event) => cancellingAutoTopUpConfig.value = void 0),
2645
+ onConfirmed: _cache[12] || (_cache[12] = ($event) => emit("auto-top-up-cancelled"))
2646
+ }, null, 8, ["show-modal", "config"])) : createCommentVNode("", true)
2647
+ ], 64);
2648
+ };
2649
+ }
2650
+ });
2651
+ export {
2652
+ _sfc_main as _,
2653
+ useCustomerWalletBalances as u
2654
+ };