root.tsx 12 KB

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