diff --git a/src/services/stripe.ts b/src/services/stripe.ts index 73322a4..8c9d1af 100644 --- a/src/services/stripe.ts +++ b/src/services/stripe.ts @@ -1,6 +1,8 @@ import { loadStripe } from '@stripe/stripe-js'; import Stripe from 'stripe'; +import { calculateCurrencyAmount } from '@/utils/calculateCurrencyAmount'; + export default class StripeService { private stripe: Stripe; @@ -36,9 +38,9 @@ export default class StripeService { metadata: { userId, plan }, }; - if (currency && currency !== 'usd') { + if (currency) { const unitAmount = price.unit_amount; - const newUnitAmount = unitAmount ? unitAmount * 6 : 0; + const newUnitAmount = calculateCurrencyAmount(String(unitAmount), currency); sessionData.line_items = [{ price_data: { diff --git a/src/utils/calculateCurrencyAmount.ts b/src/utils/calculateCurrencyAmount.ts new file mode 100644 index 0000000..04f63db --- /dev/null +++ b/src/utils/calculateCurrencyAmount.ts @@ -0,0 +1,14 @@ +const currencyRates: { [key: string]: number } = { + usd: 1, + brl: 6, +}; + +export const calculateCurrencyAmount = (amount: string, currency: string = 'usd'): number => { + const rate = currencyRates[currency.toLowerCase()]; + + if (rate === undefined) { + throw new Error(`Currency not supported: ${currency}`); + } + + return Number(amount) * rate; +}; \ No newline at end of file diff --git a/src/utils/transformPurchasePlansDTO.ts b/src/utils/transformPurchasePlansDTO.ts index 6de4f96..5bdf1b9 100644 --- a/src/utils/transformPurchasePlansDTO.ts +++ b/src/utils/transformPurchasePlansDTO.ts @@ -1,3 +1,5 @@ +import { calculateCurrencyAmount } from "./calculateCurrencyAmount"; + export interface InputData { id: string; productName: string; @@ -21,7 +23,7 @@ interface Plan { type PlanDetails = Omit; -export function transformPurchasePlansDTO(data: InputData[], translate: (key: string) => string, currency?: string): Plan[] { +export function transformPurchasePlansDTO(data: InputData[], translate: (key: string) => string, currency: string): Plan[] { const planDetails: Record = { "Starter": { id: "starter", @@ -60,8 +62,8 @@ export function transformPurchasePlansDTO(data: InputData[], translate: (key: st const plansMap: Record = {}; - const setPlanPrice = (planName: string, interval: 'month' | 'year', amount: string, id: string, currency: string = 'usd'): void => { - const newUnitAmount = currency !== 'usd' ? Number(amount) * 6 : amount; + const setPlanPrice = (planName: string, interval: 'month' | 'year', amount: string, id: string, currency: string): void => { + const newUnitAmount = calculateCurrencyAmount(amount, currency); if (interval === 'month') {