payment-context.tsx 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import {
  2. useState,
  3. useEffect,
  4. useLayoutEffect,
  5. useMemo,
  6. useCallback,
  7. useRef,
  8. useContext,
  9. createContext,
  10. } from 'react'
  11. import { useTranslation } from 'react-i18next'
  12. import getMeta from '../../../utils/meta'
  13. import * as eventTracking from '../../../infrastructure/event-tracking'
  14. import {
  15. PaymentContextValue,
  16. PricingFormState,
  17. } from './types/payment-context-value'
  18. import { Plan } from '../../../../../types/subscription/plan'
  19. import {
  20. RecurlyOptions,
  21. SubscriptionPricingStateTax,
  22. } from 'recurly__recurly-js'
  23. import { SubscriptionPricingInstanceCustom } from '../../../../../types/recurly/pricing/subscription'
  24. function usePayment({ publicKey }: RecurlyOptions) {
  25. const { t } = useTranslation()
  26. const plan: Plan = getMeta('ol-plan')
  27. const initialCountry: PricingFormState['country'] = getMeta(
  28. 'ol-countryCode',
  29. ''
  30. )
  31. const initialCouponCode: PricingFormState['coupon'] = getMeta(
  32. 'ol-couponCode',
  33. ''
  34. )
  35. const currencySymbols: Record<
  36. PaymentContextValue['currencyCode'],
  37. PaymentContextValue['currencySymbol']
  38. > = getMeta('ol-currencySymbols')
  39. const initiallySelectedCurrencyCode: string = getMeta(
  40. 'ol-recommendedCurrency'
  41. )
  42. const [recurlyLoading, setRecurlyLoading] = useState(true)
  43. const [recurlyLoadError, setRecurlyLoadError] = useState(false)
  44. const [recurlyPrice, setRecurlyPrice] = useState<{
  45. subtotal: string
  46. plan: string
  47. addons: string
  48. setup_fee: string
  49. discount: string
  50. tax: string
  51. total: string
  52. }>()
  53. const [monthlyBilling, setMonthlyBilling] = useState<boolean>()
  54. const [taxes, setTaxes] = useState<SubscriptionPricingStateTax[]>([])
  55. const [coupon, setCoupon] = useState<{
  56. discountMonths?: number
  57. discountRate?: number
  58. singleUse: boolean
  59. normalPrice: number
  60. name: string
  61. normalPriceWithoutTax: number
  62. }>()
  63. const [couponError, setCouponError] = useState('')
  64. const [trialLength, setTrialLength] = useState<number>()
  65. const [currencyCode, setCurrencyCode] = useState(
  66. initiallySelectedCurrencyCode
  67. )
  68. const [pricingFormState, setPricingFormState] = useState<PricingFormState>({
  69. first_name: '',
  70. last_name: '',
  71. postal_code: '',
  72. address1: '',
  73. address2: '',
  74. state: '',
  75. city: '',
  76. company: '',
  77. vat_number: '',
  78. country: initialCountry,
  79. coupon: initialCouponCode,
  80. })
  81. const pricing = useRef<SubscriptionPricingInstanceCustom>()
  82. const limitedCurrencyCodes = Array.from(
  83. new Set([initiallySelectedCurrencyCode, 'USD', 'EUR', 'GBP'])
  84. )
  85. const limitedCurrencies = limitedCurrencyCodes.reduce((prev, cur) => {
  86. return { ...prev, [cur]: currencySymbols[cur] }
  87. }, {} as Record<string, string>)
  88. const currencySymbol = limitedCurrencies[currencyCode]
  89. useLayoutEffect(() => {
  90. if (typeof recurly === 'undefined' || !recurly) {
  91. setRecurlyLoadError(true)
  92. return
  93. }
  94. eventTracking.sendMB('payment-page-view', { plan: plan.planCode })
  95. eventTracking.send(
  96. 'subscription-funnel',
  97. 'subscription-form-viewed',
  98. plan.planCode
  99. )
  100. recurly.configure({ publicKey })
  101. pricing.current =
  102. recurly.Pricing.Subscription() as SubscriptionPricingInstanceCustom
  103. const setupPricing = () => {
  104. setRecurlyLoading(true)
  105. pricing.current
  106. ?.plan(plan.planCode, { quantity: 1 })
  107. .address({
  108. first_name: '',
  109. last_name: '',
  110. country: initialCountry,
  111. })
  112. .tax({ tax_code: 'digital', vat_number: '' })
  113. .currency(initiallySelectedCurrencyCode)
  114. .coupon(initialCouponCode)
  115. .catch(function (err) {
  116. if (
  117. initiallySelectedCurrencyCode !== 'USD' &&
  118. err.name === 'invalid-currency'
  119. ) {
  120. setCurrencyCode('USD')
  121. setupPricing()
  122. } else if (err.name === 'api-error' && err.code === 'not-found') {
  123. // not-found here should refer to the coupon code, plan_code should be valid
  124. setCouponError(t('coupon_code_is_not_valid_for_selected_plan'))
  125. } else {
  126. // Bail out on other errors, form state will not be correct
  127. setRecurlyLoadError(true)
  128. throw err
  129. }
  130. })
  131. .done(() => {
  132. setRecurlyLoading(false)
  133. })
  134. }
  135. setupPricing()
  136. }, [
  137. initialCountry,
  138. initialCouponCode,
  139. initiallySelectedCurrencyCode,
  140. plan.planCode,
  141. publicKey,
  142. t,
  143. ])
  144. useEffect(() => {
  145. pricing.current?.on('change', function () {
  146. if (!pricing.current) return
  147. const trialLength = pricing.current.items.plan?.trial?.length
  148. setTrialLength(trialLength)
  149. const recurlyPrice = trialLength
  150. ? pricing.current.price.next
  151. : pricing.current.price.now
  152. setRecurlyPrice(recurlyPrice)
  153. const monthlyBilling = pricing.current.items.plan?.period.length === 1
  154. setMonthlyBilling(monthlyBilling)
  155. setTaxes(pricing.current.price.taxes)
  156. // TODO availableCurrencies for preview section (limitedCurrencies is implemented)
  157. // for (const currencyCode in pricing.items.plan.price) {
  158. // if (MultiCurrencyPricing.plans[currencyCode]) {
  159. // $scope.availableCurrencies[currencyCode] =
  160. // MultiCurrencyPricing.plans[currencyCode]
  161. // }
  162. // }
  163. const couponData = (() => {
  164. if (pricing.current.items.coupon?.discount.type === 'percent') {
  165. const coupon = pricing.current.items.coupon
  166. const basePrice = parseInt(pricing.current.price.base.plan.unit, 10)
  167. const discountData =
  168. coupon.applies_for_months > 0 && coupon.discount.rate
  169. ? {
  170. discountMonths: coupon.applies_for_months,
  171. discountRate: coupon.discount.rate * 100,
  172. }
  173. : {}
  174. const couponData = {
  175. singleUse: coupon.single_use,
  176. normalPrice: basePrice,
  177. name: coupon.name,
  178. normalPriceWithoutTax: basePrice,
  179. ...discountData,
  180. }
  181. if (pricing.current.price.taxes[0]?.rate) {
  182. couponData.normalPrice +=
  183. basePrice * parseFloat(pricing.current.price.taxes[0].rate)
  184. }
  185. return couponData
  186. }
  187. })()
  188. setCoupon(couponData)
  189. })
  190. }, [])
  191. const addCoupon = useCallback(
  192. (coupon: PricingFormState['coupon']) => {
  193. setRecurlyLoading(true)
  194. setCouponError('')
  195. pricing.current
  196. ?.coupon(coupon)
  197. .catch(function (err) {
  198. if (err.name === 'api-error' && err.code === 'not-found') {
  199. setCouponError(t('coupon_code_is_not_valid_for_selected_plan'))
  200. } else {
  201. setCouponError(
  202. t('an_error_occurred_when_verifying_the_coupon_code')
  203. )
  204. throw err
  205. }
  206. })
  207. .done(() => {
  208. setRecurlyLoading(false)
  209. })
  210. },
  211. [t]
  212. )
  213. const updateCountry = useCallback(
  214. (country: PricingFormState['country']) => {
  215. setRecurlyLoading(true)
  216. pricing.current
  217. ?.address({
  218. country,
  219. first_name: pricingFormState.first_name,
  220. last_name: pricingFormState.last_name,
  221. })
  222. .done(() => {
  223. setRecurlyLoading(false)
  224. })
  225. },
  226. [pricingFormState.first_name, pricingFormState.last_name]
  227. )
  228. const applyVatNumber = useCallback(
  229. (vatNumber: PricingFormState['vat_number']) => {
  230. setRecurlyLoading(true)
  231. pricing.current
  232. ?.tax({ tax_code: 'digital', vat_number: vatNumber })
  233. .done(() => {
  234. setRecurlyLoading(false)
  235. })
  236. },
  237. []
  238. )
  239. // TODO - for preview panel
  240. const changeCurrency = useCallback(
  241. (newCurrency: string) => {
  242. setRecurlyLoading(true)
  243. setCurrencyCode(newCurrency)
  244. pricing.current
  245. ?.currency(newCurrency)
  246. .catch(function (err) {
  247. if (currencyCode !== 'USD' && err.name === 'invalid-currency') {
  248. setCurrencyCode('USD')
  249. } else {
  250. throw err
  251. }
  252. })
  253. .done(() => {
  254. setRecurlyLoading(false)
  255. })
  256. },
  257. [currencyCode]
  258. )
  259. const value = useMemo<PaymentContextValue>(
  260. () => ({
  261. currencyCode,
  262. setCurrencyCode,
  263. currencySymbol,
  264. limitedCurrencies,
  265. pricingFormState,
  266. setPricingFormState,
  267. plan,
  268. pricing,
  269. recurlyLoading,
  270. recurlyLoadError,
  271. recurlyPrice,
  272. monthlyBilling,
  273. taxes,
  274. coupon,
  275. couponError,
  276. trialLength,
  277. addCoupon,
  278. applyVatNumber,
  279. changeCurrency,
  280. updateCountry,
  281. }),
  282. [
  283. currencyCode,
  284. setCurrencyCode,
  285. currencySymbol,
  286. limitedCurrencies,
  287. pricingFormState,
  288. setPricingFormState,
  289. plan,
  290. pricing,
  291. recurlyLoading,
  292. recurlyLoadError,
  293. recurlyPrice,
  294. monthlyBilling,
  295. taxes,
  296. coupon,
  297. couponError,
  298. trialLength,
  299. addCoupon,
  300. applyVatNumber,
  301. changeCurrency,
  302. updateCountry,
  303. ]
  304. )
  305. return { value }
  306. }
  307. const PaymentContext = createContext<PaymentContextValue | undefined>(undefined)
  308. type PaymentProviderProps = {
  309. publicKey: string
  310. children: React.ReactNode
  311. }
  312. export function PaymentProvider({ publicKey, ...props }: PaymentProviderProps) {
  313. const { value } = usePayment({ publicKey })
  314. return <PaymentContext.Provider value={value} {...props} />
  315. }
  316. export function usePaymentContext() {
  317. const context = useContext(PaymentContext)
  318. if (!context) {
  319. throw new Error('PaymentContext is only available inside PaymentProvider')
  320. }
  321. return context
  322. }