format.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { DEFAULT_DISCOUNT_RATE } from '../constants'
  2. // ============================================================================
  3. // Wallet-specific Formatting Functions
  4. // ============================================================================
  5. /**
  6. * Format Creem price with currency symbol (USD/EUR)
  7. */
  8. export function formatCreemPrice(
  9. price: number,
  10. currency: 'USD' | 'EUR'
  11. ): string {
  12. const symbol = currency === 'EUR' ? '€' : '$'
  13. return `${symbol}${price.toFixed(2)}`
  14. }
  15. /**
  16. * Format large quota numbers with K/M suffix
  17. */
  18. export function formatQuotaShort(quota: number): string {
  19. if (quota >= 1000000) {
  20. return `${(quota / 1000000).toFixed(1)}M`
  21. }
  22. if (quota >= 1000) {
  23. return `${(quota / 1000).toFixed(1)}K`
  24. }
  25. return quota.toString()
  26. }
  27. /**
  28. * Format currency amount that is already in local currency.
  29. * This is used for payment amounts that have been calculated via priceRatio.
  30. */
  31. export function formatCurrency(amount: number | string): string {
  32. const numeric =
  33. typeof amount === 'number' ? amount : Number.parseFloat(String(amount))
  34. if (!Number.isFinite(numeric)) return '-'
  35. return new Intl.NumberFormat(undefined, {
  36. minimumFractionDigits: 0,
  37. maximumFractionDigits: Math.abs(numeric) >= 1 ? 2 : 4,
  38. }).format(numeric)
  39. }
  40. /**
  41. * Get discount label for display (e.g., "20% OFF")
  42. */
  43. export function getDiscountLabel(discount: number): string {
  44. if (discount >= DEFAULT_DISCOUNT_RATE) {
  45. return ''
  46. }
  47. const off = Math.round((1 - discount) * 100)
  48. return `${off}% OFF`
  49. }
  50. /**
  51. * Calculate pricing details for a preset amount
  52. */
  53. export function calculatePresetPricing(
  54. presetValue: number,
  55. priceRatio: number,
  56. discount: number,
  57. usdExchangeRate: number = 1
  58. ) {
  59. const originalPrice = presetValue * priceRatio
  60. const actualPrice = originalPrice * discount
  61. const savedAmount = originalPrice - actualPrice
  62. const hasDiscount = discount < 1.0
  63. const displayValue = presetValue * usdExchangeRate
  64. return {
  65. displayValue,
  66. originalPrice,
  67. actualPrice,
  68. savedAmount,
  69. hasDiscount,
  70. }
  71. }