root.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import { useCallback, useEffect } from 'react'
  2. import moment from 'moment'
  3. import { useTranslation, Trans } from 'react-i18next'
  4. import {
  5. SubscriptionChangePreview,
  6. AddOnPurchase,
  7. PremiumSubscriptionChange,
  8. } from '../../../../../../types/subscription/subscription-change-preview'
  9. import getMeta from '@/utils/meta'
  10. import { formatCurrency } from '@/shared/utils/currency'
  11. import useAsync from '@/shared/hooks/use-async'
  12. import { useLocation } from '@/shared/hooks/use-location'
  13. import { debugConsole } from '@/utils/debugging'
  14. import { FetchError, postJSON } from '@/infrastructure/fetch-json'
  15. import OLCard from '@/shared/components/ol/ol-card'
  16. import OLRow from '@/shared/components/ol/ol-row'
  17. import OLCol from '@/shared/components/ol/ol-col'
  18. import OLButton from '@/shared/components/ol/ol-button'
  19. import { subscriptionUpdateUrl } from '@/features/subscription/data/subscription-url'
  20. import * as eventTracking from '@/infrastructure/event-tracking'
  21. import sparkleText from '@/shared/svgs/ai-sparkle-text.svg'
  22. import PaymentErrorNotification from '@/features/subscription/components/shared/payment-error-notification'
  23. import handleStripePaymentAction from '../../util/handle-stripe-payment-action'
  24. import RedirectedPaymentErrorNotification from '../shared/redirected-payment-error-notification'
  25. import TrialDisabledNotification from './trial-disabled-notification'
  26. function PreviewSubscriptionChange() {
  27. const preview = getMeta(
  28. 'ol-subscriptionChangePreview'
  29. ) as SubscriptionChangePreview
  30. const purchaseReferrer = getMeta('ol-purchaseReferrer')
  31. const { t } = useTranslation()
  32. const payNowTask = useAsync()
  33. const location = useLocation()
  34. // Filter out items that cancel each other out (AI assist items with subtotals that sum to 0)
  35. const filteredLineItems = preview.immediateCharge.lineItems.filter(
  36. (item, index, arr) => {
  37. if (!item.isAiAssist) return true
  38. // TODO: this can be removed when all subscriptions are using Stripe
  39. const isCanceledByAnotherItem = arr.some(
  40. (otherItem, otherIndex) =>
  41. otherIndex !== index &&
  42. otherItem.isAiAssist &&
  43. otherItem.subtotal + item.subtotal === 0
  44. )
  45. return !isCanceledByAnotherItem
  46. }
  47. )
  48. useEffect(() => {
  49. if (preview.change.type === 'add-on-purchase') {
  50. eventTracking.sendMB('preview-subscription-change-view', {
  51. plan: preview.change.addOn.code,
  52. upgradeType: 'add-on',
  53. referrer: purchaseReferrer,
  54. })
  55. }
  56. }, [preview.change, purchaseReferrer])
  57. const handlePayNowClick = useCallback(() => {
  58. if (preview.change.type === 'add-on-purchase') {
  59. eventTracking.sendMB('subscription-change-form-submit', {
  60. plan: preview.change.addOn.code,
  61. upgradeType: 'add-on',
  62. referrer: purchaseReferrer,
  63. })
  64. eventTracking.sendMB('assistant-add-on-purchase')
  65. }
  66. payNowTask
  67. .runAsync(payNow(preview))
  68. .then(() => {
  69. if (preview.change.type === 'add-on-purchase') {
  70. eventTracking.sendMB('subscription-change-form-success', {
  71. plan: preview.change.addOn.code,
  72. upgradeType: 'add-on',
  73. referrer: purchaseReferrer,
  74. })
  75. }
  76. location.replace('/user/subscription/thank-you')
  77. })
  78. .catch(debugConsole.error)
  79. }, [purchaseReferrer, location, payNowTask, preview])
  80. const aiAddOnChange =
  81. preview.change.type === 'add-on-purchase' &&
  82. preview.change.addOn.code === 'assistant'
  83. // the driver of the change, which we can display as the immediate charge
  84. const changeName =
  85. preview.change.type === 'add-on-purchase'
  86. ? (preview.change as AddOnPurchase).addOn.name
  87. : (preview.change as PremiumSubscriptionChange).plan.name
  88. return (
  89. <div className="container">
  90. <OLRow>
  91. <OLCol md={{ offset: 2, span: 8 }}>
  92. <RedirectedPaymentErrorNotification />
  93. <TrialDisabledNotification />
  94. <OLCard className="p-3">
  95. {preview.change.type === 'add-on-purchase' ? (
  96. <h1>
  97. {t('add_add_on_to_your_plan', {
  98. addOnName: preview.change.addOn.name,
  99. })}
  100. </h1>
  101. ) : preview.change.type === 'premium-subscription' ? (
  102. <h1>
  103. {t('subscribe_to_plan', { planName: preview.change.plan.name })}
  104. </h1>
  105. ) : null}
  106. {payNowTask.isError && (
  107. <PaymentErrorNotification
  108. error={payNowTask.error as FetchError}
  109. />
  110. )}
  111. {aiAddOnChange && (
  112. <div>
  113. <Trans
  114. i18nKey="add_ai_assist_to_your_plan"
  115. components={{
  116. sparkle: (
  117. <img
  118. alt="sparkle"
  119. className="ai-error-assistant-sparkle"
  120. src={sparkleText}
  121. aria-hidden="true"
  122. key="sparkle"
  123. />
  124. ),
  125. }}
  126. />
  127. </div>
  128. )}
  129. <OLCard className="payment-summary-card mt-5">
  130. <h3>{t('due_today')}:</h3>
  131. {filteredLineItems.length > 1 ? (
  132. <>
  133. {filteredLineItems.map((item, index) => (
  134. <OLRow key={index}>
  135. <OLCol xs={9}>
  136. {item.subtotal < 0
  137. ? `Refund: ${item.description}`
  138. : item.description}
  139. </OLCol>
  140. <OLCol xs={3} className="text-end">
  141. <strong>
  142. {formatCurrency(item.subtotal, preview.currency)}
  143. </strong>
  144. </OLCol>
  145. </OLRow>
  146. ))}
  147. </>
  148. ) : (
  149. <>
  150. <OLRow>
  151. <OLCol xs={9}>{changeName}</OLCol>
  152. <OLCol xs={3} className="text-end">
  153. <strong>
  154. {formatCurrency(
  155. preview.immediateCharge.subtotal,
  156. preview.currency
  157. )}
  158. </strong>
  159. </OLCol>
  160. </OLRow>
  161. </>
  162. )}
  163. {preview.immediateCharge.tax > 0 && (
  164. <OLRow className="mt-1">
  165. <OLCol xs={9}>
  166. {t('vat')} {preview.nextInvoice.tax.rate * 100}%
  167. </OLCol>
  168. <OLCol xs={3} className="text-end">
  169. {formatCurrency(
  170. preview.immediateCharge.tax,
  171. preview.currency
  172. )}
  173. </OLCol>
  174. </OLRow>
  175. )}
  176. <OLRow className="mt-1">
  177. <OLCol xs={9}>{t('total_today')}</OLCol>
  178. <OLCol xs={3} className="text-end">
  179. <strong>
  180. {formatCurrency(
  181. preview.immediateCharge.total,
  182. preview.currency
  183. )}
  184. </strong>
  185. </OLCol>
  186. </OLRow>
  187. </OLCard>
  188. <div className="mt-5">
  189. <Trans
  190. i18nKey="this_total_reflects_the_amount_due_until"
  191. values={{ date: moment(preview.nextInvoice.date).format('LL') }}
  192. components={{ strong: <strong /> }}
  193. shouldUnescape
  194. tOptions={{ interpolation: { escapeValue: true } }}
  195. />{' '}
  196. <Trans
  197. i18nKey="we_will_use_your_existing_payment_method"
  198. values={{ paymentMethod: preview.paymentMethod }}
  199. components={{ strong: <strong /> }}
  200. shouldUnescape
  201. tOptions={{ interpolation: { escapeValue: true } }}
  202. />
  203. </div>
  204. {aiAddOnChange && (
  205. <div className="plan-terms mt-3">
  206. *{t('fair_usage_policy_applies')}
  207. </div>
  208. )}
  209. <div className="mt-5">
  210. <OLButton
  211. variant="primary"
  212. size="lg"
  213. onClick={handlePayNowClick}
  214. disabled={payNowTask.isLoading || payNowTask.isSuccess}
  215. >
  216. {t('pay_now')}
  217. </OLButton>
  218. </div>
  219. <OLCard className="payment-summary-card mt-5">
  220. <h3>{t('future_payments')}:</h3>
  221. <OLRow className="mt-1">
  222. <OLCol xs={9}>{preview.nextInvoice.plan.name}</OLCol>
  223. <OLCol xs={3} className="text-end">
  224. {formatCurrency(
  225. preview.nextInvoice.plan.amount,
  226. preview.currency
  227. )}
  228. </OLCol>
  229. </OLRow>
  230. {preview.nextInvoice.addOns.map(addOn => (
  231. <OLRow className="mt-1" key={addOn.code}>
  232. <OLCol xs={9}>
  233. {addOn.name}
  234. {addOn.quantity > 1 ? ` ×${addOn.quantity}` : ''}
  235. </OLCol>
  236. <OLCol xs={3} className="text-end">
  237. {formatCurrency(addOn.amount, preview.currency)}
  238. </OLCol>
  239. </OLRow>
  240. ))}
  241. {preview.nextInvoice.tax.rate > 0 && (
  242. <OLRow className="mt-1">
  243. <OLCol xs={9}>
  244. {t('vat')} {preview.nextInvoice.tax.rate * 100}%
  245. </OLCol>
  246. <OLCol xs={3} className="text-end">
  247. {formatCurrency(
  248. preview.nextInvoice.tax.amount,
  249. preview.currency
  250. )}
  251. </OLCol>
  252. </OLRow>
  253. )}
  254. <OLRow className="mt-1">
  255. <OLCol xs={9}>
  256. {preview.nextPlan.annual
  257. ? t('total_per_year')
  258. : t('total_per_month')}
  259. </OLCol>
  260. <OLCol xs={3} className="text-end">
  261. {formatCurrency(preview.nextInvoice.total, preview.currency)}
  262. </OLCol>
  263. </OLRow>
  264. </OLCard>
  265. <div className="mt-5">
  266. <Trans
  267. i18nKey="the_next_payment_will_be_collected_on"
  268. values={{ date: moment(preview.nextInvoice.date).format('LL') }}
  269. components={{ strong: <strong /> }}
  270. shouldUnescape
  271. tOptions={{ interpolation: { escapeValue: true } }}
  272. />
  273. </div>
  274. </OLCard>
  275. </OLCol>
  276. </OLRow>
  277. </div>
  278. )
  279. }
  280. async function payNow(preview: SubscriptionChangePreview) {
  281. try {
  282. if (preview.change.type === 'add-on-purchase') {
  283. await postJSON(
  284. `/user/subscription/addon/${preview.change.addOn.code}/add`
  285. )
  286. } else if (preview.change.type === 'premium-subscription') {
  287. await postJSON(subscriptionUpdateUrl, {
  288. body: { plan_code: preview.change.plan.code },
  289. })
  290. } else {
  291. throw new Error(
  292. `Unknown subscription change preview type: ${preview.change}`
  293. )
  294. }
  295. } catch (e) {
  296. const { handled } = await handleStripePaymentAction(e as FetchError)
  297. if (!handled) {
  298. throw e
  299. }
  300. }
  301. }
  302. export default PreviewSubscriptionChange