overleaf/services/web/frontend/js/features/subscription/util/recurly-pricing.tsx
Jessica Lawshe d4057a7bcc Merge pull request #11602 from overleaf/jel-react-personal-subscription-dash-pt-6
[web] Continue migration of change plan UI to React

GitOrigin-RevId: 4f6176ac101ba3c57134cf5c86329e205f17ab23
2023-02-08 09:06:37 +00:00

56 lines
1.7 KiB
TypeScript

import { SubscriptionPricingState } from '@recurly/recurly-js'
import getMeta from '../../../utils/meta'
import { currencies, CurrencyCode } from '../data/currency'
export function formatPriceForDisplayData(price: string, taxRate: number) {
const currencyCode: CurrencyCode = getMeta('ol-recommendedCurrency')
const currencySymbol = currencies[currencyCode]
const totalPriceExTax = parseFloat(price)
let taxAmount = totalPriceExTax * taxRate
if (isNaN(taxAmount)) {
taxAmount = 0
}
const totalWithTax = totalPriceExTax + taxAmount
return {
totalForDisplay: `${currencySymbol}${
totalWithTax % 1 !== 0 ? totalWithTax.toFixed(2) : totalWithTax
}`,
totalAsNumber: totalWithTax,
subtotal: `${currencySymbol}${totalPriceExTax.toFixed(2)}`,
tax: `${currencySymbol}${taxAmount.toFixed(2)}`,
includesTax: taxAmount !== 0,
}
}
export function loadDisplayPriceWithTaxPromise(
planCode: string,
currency: CurrencyCode,
taxRate: number
) {
if (!recurly) return
return new Promise<ReturnType<typeof formatPriceForDisplayData> | undefined>(
resolve => {
recurly.Pricing.Subscription()
.plan(planCode, { quantity: 1 })
.currency(currency)
.catch(function (error) {
console.error(error)
})
.done(response => {
if (response) {
const price =
response as unknown as SubscriptionPricingState['price']
// type expects response to be {price: {next: ...}}
// but the real response is {next: ...}
const data = formatPriceForDisplayData(price.next.total, taxRate)
resolve(data)
} else {
resolve(undefined)
}
})
}
)
}