root.tsx 12 KB

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