root.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. 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. }
  65. eventTracking.sendMB('assistant-add-on-purchase')
  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. <OLCard className="p-3">
  94. {preview.change.type === 'add-on-purchase' ? (
  95. <h1>
  96. {t('add_add_on_to_your_plan', {
  97. addOnName: preview.change.addOn.name,
  98. })}
  99. </h1>
  100. ) : preview.change.type === 'premium-subscription' ? (
  101. <h1>
  102. {t('subscribe_to_plan', { planName: preview.change.plan.name })}
  103. </h1>
  104. ) : null}
  105. {payNowTask.isError && (
  106. <PaymentErrorNotification
  107. error={payNowTask.error as FetchError}
  108. />
  109. )}
  110. {aiAddOnChange && (
  111. <div>
  112. {aiAssistEnabled ? (
  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. ) : (
  128. <Trans
  129. i18nKey="add_error_assist_to_your_projects"
  130. components={{
  131. sparkle: (
  132. <img
  133. alt="sparkle"
  134. className="ai-error-assistant-sparkle"
  135. src={sparkleText}
  136. aria-hidden="true"
  137. key="sparkle"
  138. />
  139. ),
  140. }}
  141. />
  142. )}
  143. </div>
  144. )}
  145. <OLCard className="payment-summary-card mt-5">
  146. <h3>{t('due_today')}:</h3>
  147. {filteredLineItems.length > 1 ? (
  148. <>
  149. {filteredLineItems.map((item, index) => (
  150. <OLRow key={index}>
  151. <OLCol xs={9}>
  152. {item.subtotal < 0
  153. ? `Refund: ${item.description}`
  154. : item.description}
  155. </OLCol>
  156. <OLCol xs={3} className="text-end">
  157. <strong>
  158. {formatCurrency(item.subtotal, preview.currency)}
  159. </strong>
  160. </OLCol>
  161. </OLRow>
  162. ))}
  163. </>
  164. ) : (
  165. <>
  166. <OLRow>
  167. <OLCol xs={9}>{changeName}</OLCol>
  168. <OLCol xs={3} className="text-end">
  169. <strong>
  170. {formatCurrency(
  171. preview.immediateCharge.subtotal,
  172. preview.currency
  173. )}
  174. </strong>
  175. </OLCol>
  176. </OLRow>
  177. </>
  178. )}
  179. {preview.immediateCharge.tax > 0 && (
  180. <OLRow className="mt-1">
  181. <OLCol xs={9}>
  182. {t('vat')} {preview.nextInvoice.tax.rate * 100}%
  183. </OLCol>
  184. <OLCol xs={3} className="text-end">
  185. {formatCurrency(
  186. preview.immediateCharge.tax,
  187. preview.currency
  188. )}
  189. </OLCol>
  190. </OLRow>
  191. )}
  192. <OLRow className="mt-1">
  193. <OLCol xs={9}>{t('total_today')}</OLCol>
  194. <OLCol xs={3} className="text-end">
  195. <strong>
  196. {formatCurrency(
  197. preview.immediateCharge.total,
  198. preview.currency
  199. )}
  200. </strong>
  201. </OLCol>
  202. </OLRow>
  203. </OLCard>
  204. <div className="mt-5">
  205. <Trans
  206. i18nKey="this_total_reflects_the_amount_due_until"
  207. values={{ date: moment(preview.nextInvoice.date).format('LL') }}
  208. components={{ strong: <strong /> }}
  209. shouldUnescape
  210. tOptions={{ interpolation: { escapeValue: true } }}
  211. />{' '}
  212. <Trans
  213. i18nKey="we_will_use_your_existing_payment_method"
  214. values={{ paymentMethod: preview.paymentMethod }}
  215. components={{ strong: <strong /> }}
  216. shouldUnescape
  217. tOptions={{ interpolation: { escapeValue: true } }}
  218. />
  219. </div>
  220. {aiAddOnChange && (
  221. <div className="plan-terms mt-3">
  222. *{t('fair_usage_policy_applies')}
  223. </div>
  224. )}
  225. <div className="mt-5">
  226. <OLButton
  227. variant="primary"
  228. size="lg"
  229. onClick={handlePayNowClick}
  230. disabled={payNowTask.isLoading || payNowTask.isSuccess}
  231. >
  232. {t('pay_now')}
  233. </OLButton>
  234. </div>
  235. <OLCard className="payment-summary-card mt-5">
  236. <h3>{t('future_payments')}:</h3>
  237. <OLRow className="mt-1">
  238. <OLCol xs={9}>{preview.nextInvoice.plan.name}</OLCol>
  239. <OLCol xs={3} className="text-end">
  240. {formatCurrency(
  241. preview.nextInvoice.plan.amount,
  242. preview.currency
  243. )}
  244. </OLCol>
  245. </OLRow>
  246. {preview.nextInvoice.addOns.map(addOn => (
  247. <OLRow className="mt-1" key={addOn.code}>
  248. <OLCol xs={9}>
  249. {addOn.name}
  250. {addOn.quantity > 1 ? ` ×${addOn.quantity}` : ''}
  251. </OLCol>
  252. <OLCol xs={3} className="text-end">
  253. {formatCurrency(addOn.amount, preview.currency)}
  254. </OLCol>
  255. </OLRow>
  256. ))}
  257. {preview.nextInvoice.tax.rate > 0 && (
  258. <OLRow className="mt-1">
  259. <OLCol xs={9}>
  260. {t('vat')} {preview.nextInvoice.tax.rate * 100}%
  261. </OLCol>
  262. <OLCol xs={3} className="text-end">
  263. {formatCurrency(
  264. preview.nextInvoice.tax.amount,
  265. preview.currency
  266. )}
  267. </OLCol>
  268. </OLRow>
  269. )}
  270. <OLRow className="mt-1">
  271. <OLCol xs={9}>
  272. {preview.nextPlan.annual
  273. ? t('total_per_year')
  274. : t('total_per_month')}
  275. </OLCol>
  276. <OLCol xs={3} className="text-end">
  277. {formatCurrency(preview.nextInvoice.total, preview.currency)}
  278. </OLCol>
  279. </OLRow>
  280. </OLCard>
  281. <div className="mt-5">
  282. <Trans
  283. i18nKey="the_next_payment_will_be_collected_on"
  284. values={{ date: moment(preview.nextInvoice.date).format('LL') }}
  285. components={{ strong: <strong /> }}
  286. shouldUnescape
  287. tOptions={{ interpolation: { escapeValue: true } }}
  288. />
  289. </div>
  290. </OLCard>
  291. </OLCol>
  292. </OLRow>
  293. </div>
  294. )
  295. }
  296. async function payNow(preview: SubscriptionChangePreview) {
  297. try {
  298. if (preview.change.type === 'add-on-purchase') {
  299. await postJSON(
  300. `/user/subscription/addon/${preview.change.addOn.code}/add`
  301. )
  302. } else if (preview.change.type === 'premium-subscription') {
  303. await postJSON(subscriptionUpdateUrl, {
  304. body: { plan_code: preview.change.plan.code },
  305. })
  306. } else {
  307. throw new Error(
  308. `Unknown subscription change preview type: ${preview.change}`
  309. )
  310. }
  311. } catch (e) {
  312. const { handled } = await handleStripePaymentAction(e as FetchError)
  313. if (!handled) {
  314. throw e
  315. }
  316. }
  317. }
  318. export default PreviewSubscriptionChange