root.tsx 12 KB

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