usePaymentPlatformFees.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { getPaymentPlatformFees } from 'src/api/payment'
  2. import { ref } from 'vue'
  3. const platformFees = ref({
  4. pix: null,
  5. credit_card: null,
  6. service_package_min_3_schedules_credit_card: null,
  7. service_package_min_3_schedules_pix: null,
  8. })
  9. let loadingPromise = null
  10. const normalizeFee = (value) => {
  11. if (value === null || value === undefined || value === '') return null
  12. const fee = Number(value)
  13. if (!Number.isFinite(fee)) return null
  14. return fee > 1 ? fee / 100 : fee
  15. }
  16. const firstDefined = (...values) => values.find((value) => value !== null && value !== undefined && value !== '')
  17. const normalizePlatformFees = (fees) => {
  18. const normalized = {
  19. pix: normalizeFee(firstDefined(
  20. fees?.pix,
  21. fees?.PIX,
  22. fees?.pix_fee,
  23. fees?.pix_fee_rate,
  24. fees?.platform_pix_fee_rate,
  25. )),
  26. credit_card: normalizeFee(firstDefined(
  27. fees?.credit_card,
  28. fees?.creditCard,
  29. fees?.credit_card_fee,
  30. fees?.credit_card_fee_rate,
  31. fees?.platform_credit_card_fee_rate,
  32. )),
  33. service_package_min_3_schedules_credit_card: normalizeFee(firstDefined(
  34. fees?.service_package_min_3_schedules_credit_card,
  35. fees?.servicePackageMin3SchedulesCreditCard,
  36. )),
  37. service_package_min_3_schedules_pix: normalizeFee(firstDefined(
  38. fees?.service_package_min_3_schedules_pix,
  39. fees?.servicePackageMin3SchedulesPix,
  40. )),
  41. }
  42. if (normalized.pix === null || normalized.credit_card === null) {
  43. console.warn('Invalid payment platform fees payload', fees)
  44. }
  45. return normalized
  46. }
  47. export function usePaymentPlatformFees() {
  48. const loadPlatformFees = async () => {
  49. if (!loadingPromise) {
  50. loadingPromise = getPaymentPlatformFees()
  51. .then((fees) => {
  52. platformFees.value = normalizePlatformFees(fees)
  53. })
  54. .finally(() => {
  55. loadingPromise = null
  56. })
  57. }
  58. await loadingPromise
  59. }
  60. return {
  61. platformFees,
  62. loadPlatformFees,
  63. }
  64. }