SubscriptionFormatters.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const dateformat = require('dateformat')
  2. const { formatCurrencyLocalized } = require('../../util/currency')
  3. /**
  4. * @import { CurrencyCode } from '../../../../types/currency-code'
  5. */
  6. const currencySymbols = {
  7. EUR: '€',
  8. USD: '$',
  9. GBP: '£',
  10. SEK: 'kr',
  11. CAD: '$',
  12. NOK: 'kr',
  13. DKK: 'kr',
  14. AUD: '$',
  15. NZD: '$',
  16. CHF: 'Fr',
  17. SGD: '$',
  18. INR: '₹',
  19. BRL: 'R$',
  20. MXN: '$',
  21. COP: '$',
  22. CLP: '$',
  23. PEN: 'S/',
  24. }
  25. function formatPriceDefault(priceInCents, currency) {
  26. if (!currency) {
  27. currency = 'USD'
  28. } else if (currency === 'CLP') {
  29. // CLP doesn't have minor units, recurly stores the whole major unit without cents
  30. return priceInCents.toLocaleString('es-CL', {
  31. style: 'currency',
  32. currency,
  33. minimumFractionDigits: 0,
  34. })
  35. }
  36. let string = String(Math.round(priceInCents))
  37. if (string.length === 2) {
  38. string = `0${string}`
  39. }
  40. if (string.length === 1) {
  41. string = `00${string}`
  42. }
  43. if (string.length === 0) {
  44. string = '000'
  45. }
  46. const cents = string.slice(-2)
  47. const dollars = string.slice(0, -2)
  48. const symbol = currencySymbols[currency]
  49. return `${symbol}${dollars}.${cents}`
  50. }
  51. /**
  52. * @param {number} priceInCents - price in the smallest currency unit (e.g. dollar cents, CLP units, ...)
  53. * @param {CurrencyCode?} currency - currency code (default to USD)
  54. * @param {string} [locale] - locale string
  55. * @returns {string} - formatted price
  56. */
  57. function formatPriceLocalized(priceInCents, currency = 'USD', locale) {
  58. const isNoCentsCurrency = ['CLP', 'JPY', 'KRW', 'VND'].includes(currency)
  59. const priceInCurrencyUnit = isNoCentsCurrency
  60. ? priceInCents
  61. : priceInCents / 100
  62. return formatCurrencyLocalized(priceInCurrencyUnit, currency, locale)
  63. }
  64. function formatDateTime(date) {
  65. if (!date) {
  66. return null
  67. }
  68. return dateformat(date, 'mmmm dS, yyyy h:MM TT Z', true)
  69. }
  70. function formatDate(date) {
  71. if (!date) {
  72. return null
  73. }
  74. return dateformat(date, 'mmmm dS, yyyy', true)
  75. }
  76. module.exports = {
  77. formatPriceDefault,
  78. formatPriceLocalized,
  79. formatDateTime,
  80. formatDate,
  81. }