SubscriptionHelper.mjs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // @ts-check
  2. import Settings from '@overleaf/settings'
  3. import { formatCurrency } from '../../util/currency.js'
  4. import GroupPlansData from './GroupPlansData.mjs'
  5. import { isStandaloneAiAddOnPlanCode } from './AiHelper.mjs'
  6. import { Subscription } from '../../models/Subscription.mjs'
  7. const MILLISECONDS = 1_000
  8. /**
  9. * Recompute the subscription state for Stripe subscriptions based on pause periods.
  10. * This function checks if a subscription should transition between 'active' and 'paused'
  11. * states based on the current time and pause period metadata.
  12. *
  13. * @param {Object} subscription - The MongoDB subscription document
  14. * @returns {Promise<Object>} - The updated subscription document with recomputed state
  15. */
  16. async function recomputeSubscriptionState(subscription) {
  17. if (
  18. !subscription?.paymentProvider?.subscriptionId ||
  19. !subscription.paymentProvider.pausePeriodStart ||
  20. !subscription.paymentProvider.pausePeriodEnd ||
  21. !subscription?.paymentProvider.service.includes('stripe')
  22. ) {
  23. return subscription
  24. }
  25. const now = Date.now() / MILLISECONDS
  26. const pauseStartTime =
  27. new Date(subscription.paymentProvider.pausePeriodStart).getTime() /
  28. MILLISECONDS
  29. const currentState = subscription.paymentProvider.state
  30. const pauseEndTime =
  31. new Date(subscription.paymentProvider.pausePeriodEnd).getTime() /
  32. MILLISECONDS
  33. const shouldBePaused =
  34. pauseEndTime && now >= pauseStartTime && now < pauseEndTime
  35. let newState
  36. if (shouldBePaused && currentState !== 'paused') {
  37. newState = 'paused'
  38. } else if (
  39. !shouldBePaused &&
  40. currentState === 'paused' &&
  41. pauseEndTime &&
  42. now >= pauseEndTime
  43. ) {
  44. newState = 'active'
  45. }
  46. if (newState) {
  47. await Subscription.updateOne(
  48. { _id: subscription._id },
  49. { 'paymentProvider.state': newState }
  50. ).exec()
  51. subscription.paymentProvider.state = newState
  52. }
  53. return subscription
  54. }
  55. /**
  56. * If the user changes to a less expensive plan, we shouldn't apply the change immediately.
  57. * This is to avoid unintended/artifical credits on users Recurly accounts.
  58. */
  59. function shouldPlanChangeAtTermEnd(oldPlan, newPlan, isInTrial) {
  60. if (isInTrial) {
  61. // we should always upgrade or downgrade immediately if actively in trial
  62. return false
  63. }
  64. if (
  65. oldPlan.annual === newPlan.annual &&
  66. isStandaloneAiAddOnPlanCode(oldPlan.planCode) &&
  67. !isStandaloneAiAddOnPlanCode(newPlan.planCode)
  68. ) {
  69. // changing from an standalone AI add-on plan to a non-AI plan should not be considered a downgrade
  70. return false
  71. }
  72. return oldPlan.price_in_cents > newPlan.price_in_cents
  73. }
  74. /**
  75. * @import { CurrencyCode } from '../../../../types/subscription/currency'
  76. */
  77. /**
  78. * @typedef {Object} PlanToPrice
  79. * @property {string} collaborator
  80. * @property {string} professional
  81. */
  82. /**
  83. * @typedef {Object} LocalizedGroupPrice
  84. * @property {PlanToPrice} price
  85. * @property {PlanToPrice} pricePerUser
  86. */
  87. /**
  88. * @param {CurrencyCode} recommendedCurrency
  89. * @param {string} locale
  90. * @returns {LocalizedGroupPrice}
  91. */
  92. function generateInitialLocalizedGroupPrice(recommendedCurrency, locale) {
  93. const INITIAL_LICENSE_SIZE = 2
  94. // the price is in cents, so divide by 100 to get the value
  95. const collaboratorPrice =
  96. GroupPlansData.enterprise.collaborator[recommendedCurrency][
  97. INITIAL_LICENSE_SIZE
  98. ].price_in_cents / 100
  99. const collaboratorPricePerUser = collaboratorPrice / INITIAL_LICENSE_SIZE
  100. const professionalPrice =
  101. GroupPlansData.enterprise.professional[recommendedCurrency][
  102. INITIAL_LICENSE_SIZE
  103. ].price_in_cents / 100
  104. const professionalPricePerUser = professionalPrice / INITIAL_LICENSE_SIZE
  105. /**
  106. * @param {number} price
  107. * @returns {string}
  108. */
  109. const formatPrice = price =>
  110. formatCurrency(price, recommendedCurrency, locale, true)
  111. return {
  112. price: {
  113. collaborator: formatPrice(collaboratorPrice),
  114. professional: formatPrice(professionalPrice),
  115. },
  116. pricePerUser: {
  117. collaborator: formatPrice(collaboratorPricePerUser),
  118. professional: formatPrice(professionalPricePerUser),
  119. },
  120. }
  121. }
  122. function isPaidSubscription(subscription) {
  123. const hasRecurlySubscription =
  124. subscription?.recurlySubscription_id &&
  125. subscription?.recurlySubscription_id !== ''
  126. const hasStripeSubscription =
  127. subscription?.paymentProvider?.subscriptionId &&
  128. subscription?.paymentProvider?.subscriptionId !== ''
  129. return !!(subscription && (hasRecurlySubscription || hasStripeSubscription))
  130. }
  131. function isIndividualActivePaidSubscription(subscription) {
  132. return (
  133. isPaidSubscription(subscription) &&
  134. subscription?.groupPlan === false &&
  135. subscription?.recurlyStatus?.state !== 'canceled' &&
  136. subscription?.paymentProvider?.state !== 'canceled'
  137. )
  138. }
  139. function getPaymentProviderSubscriptionId(subscription) {
  140. if (subscription?.recurlySubscription_id) {
  141. return subscription.recurlySubscription_id
  142. }
  143. if (subscription?.paymentProvider?.subscriptionId) {
  144. return subscription.paymentProvider.subscriptionId
  145. }
  146. return null
  147. }
  148. function getPaidSubscriptionState(subscription) {
  149. if (subscription?.recurlyStatus?.state) {
  150. return subscription.recurlyStatus.state
  151. }
  152. if (subscription?.paymentProvider?.state) {
  153. return subscription.paymentProvider.state
  154. }
  155. return null
  156. }
  157. function getSubscriptionTrialStartedAt(subscription) {
  158. if (subscription?.recurlyStatus?.trialStartedAt) {
  159. return subscription.recurlyStatus?.trialStartedAt
  160. }
  161. return subscription?.paymentProvider?.trialStartedAt
  162. }
  163. function getSubscriptionTrialEndsAt(subscription) {
  164. if (subscription?.recurlyStatus?.trialEndsAt) {
  165. return subscription.recurlyStatus?.trialEndsAt
  166. }
  167. return subscription?.paymentProvider?.trialEndsAt
  168. }
  169. function isInTrial(trialEndsAt) {
  170. if (!trialEndsAt) {
  171. return false
  172. }
  173. return trialEndsAt.getTime() > Date.now()
  174. }
  175. /**
  176. * Get the Recurly customer admin URL
  177. * @param {string | null} customerId - The customer ID in Recurly
  178. * @returns {string | null}
  179. */
  180. function getRecurlyCustomerAdminUrl(customerId) {
  181. if (customerId == null) {
  182. return null
  183. }
  184. const isStagOrDev =
  185. Settings.siteUrl.includes('dev-overleaf') ||
  186. Settings.siteUrl.includes('stag-overleaf')
  187. const baseUrl = isStagOrDev
  188. ? 'https://sharelatex-sandbox.recurly.com'
  189. : 'https://sharelatex.recurly.com'
  190. return `${baseUrl}/accounts/${customerId}`
  191. }
  192. /**
  193. * Get the Stripe customer admin URL
  194. * @param {string | null} customerId - The customer ID in Stripe
  195. * @param {string} service - The Stripe service ('stripe-us' or 'stripe-uk')
  196. * @returns {string | null}
  197. */
  198. function getStripeCustomerAdminUrl(customerId, service) {
  199. if (customerId == null || service == null) {
  200. return null
  201. }
  202. let accountId = null
  203. if (service === 'stripe-us') {
  204. accountId = Settings.apis.stripeUS?.accountId
  205. } else if (service === 'stripe-uk') {
  206. accountId = Settings.apis.stripeUK?.accountId
  207. }
  208. if (accountId == null) {
  209. return null
  210. }
  211. const isStagOrDev =
  212. Settings.siteUrl.includes('dev-overleaf') ||
  213. Settings.siteUrl.includes('stag-overleaf')
  214. const baseUrl = isStagOrDev
  215. ? `https://dashboard.stripe.com/${accountId}/test`
  216. : `https://dashboard.stripe.com/${accountId}`
  217. return `${baseUrl}/customers/${customerId}`
  218. }
  219. export default {
  220. shouldPlanChangeAtTermEnd,
  221. generateInitialLocalizedGroupPrice,
  222. isPaidSubscription,
  223. isIndividualActivePaidSubscription,
  224. getRecurlyCustomerAdminUrl,
  225. getStripeCustomerAdminUrl,
  226. getPaymentProviderSubscriptionId,
  227. getPaidSubscriptionState,
  228. getSubscriptionTrialStartedAt,
  229. getSubscriptionTrialEndsAt,
  230. isInTrial,
  231. recomputeSubscriptionState,
  232. }