root.tsx 12 KB

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