SubscriptionGroupController.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. // ts-check
  2. import SubscriptionGroupHandler from './SubscriptionGroupHandler.js'
  3. import OError from '@overleaf/o-error'
  4. import logger from '@overleaf/logger'
  5. import SubscriptionLocator from './SubscriptionLocator.js'
  6. import SessionManager from '../Authentication/SessionManager.js'
  7. import UserAuditLogHandler from '../User/UserAuditLogHandler.js'
  8. import { expressify } from '@overleaf/promise-utils'
  9. import Modules from '../../infrastructure/Modules.js'
  10. import SplitTestHandler from '../SplitTests/SplitTestHandler.js'
  11. import UserGetter from '../User/UserGetter.js'
  12. import { Subscription } from '../../models/Subscription.js'
  13. import { isProfessionalGroupPlan } from './PlansHelper.mjs'
  14. import {
  15. MissingBillingInfoError,
  16. ManuallyCollectedError,
  17. PendingChangeError,
  18. InactiveError,
  19. SubtotalLimitExceededError,
  20. } from './Errors.js'
  21. import RecurlyClient from './RecurlyClient.js'
  22. /**
  23. * @import { Subscription } from "../../../../types/subscription/dashboard/subscription.js"
  24. */
  25. /**
  26. * @param {import("express").Request} req
  27. * @param {import("express").Response} res
  28. * @returns {Promise<void>}
  29. */
  30. async function removeUserFromGroup(req, res) {
  31. const subscription = req.entity
  32. const userToRemoveId = req.params.user_id
  33. const loggedInUserId = SessionManager.getLoggedInUserId(req.session)
  34. const subscriptionId = subscription._id
  35. logger.debug(
  36. { subscriptionId, userToRemoveId },
  37. 'removing user from group subscription'
  38. )
  39. await _removeUserFromGroup(req, res, {
  40. userToRemoveId,
  41. loggedInUserId,
  42. subscription,
  43. })
  44. }
  45. /**
  46. * @param {import("express").Request} req
  47. * @param {import("express").Response} res
  48. * @returns {Promise<void>}
  49. */
  50. async function removeSelfFromGroup(req, res) {
  51. const userToRemoveId = SessionManager.getLoggedInUserId(req.session)
  52. const subscription = await SubscriptionLocator.promises.getSubscription(
  53. req.query.subscriptionId
  54. )
  55. await _removeUserFromGroup(req, res, {
  56. userToRemoveId,
  57. loggedInUserId: userToRemoveId,
  58. subscription,
  59. })
  60. }
  61. /**
  62. * @param {import("express").Request} req
  63. * @param {import("express").Response} res
  64. * @param {string} userToRemoveId
  65. * @param {string} loggedInUserId
  66. * @param {Subscription} subscription
  67. * @returns {Promise<void>}
  68. * @private
  69. */
  70. async function _removeUserFromGroup(
  71. req,
  72. res,
  73. { userToRemoveId, loggedInUserId, subscription }
  74. ) {
  75. const subscriptionId = subscription._id
  76. const groupSSOActive = (
  77. await Modules.promises.hooks.fire('hasGroupSSOEnabled', subscription)
  78. )?.[0]
  79. if (groupSSOActive) {
  80. await Modules.promises.hooks.fire(
  81. 'unlinkUserFromGroupSSO',
  82. userToRemoveId,
  83. subscriptionId
  84. )
  85. }
  86. try {
  87. await UserAuditLogHandler.promises.addEntry(
  88. userToRemoveId,
  89. 'remove-from-group-subscription',
  90. loggedInUserId,
  91. req.ip,
  92. { subscriptionId }
  93. )
  94. } catch (auditLogError) {
  95. throw OError.tag(auditLogError, 'error adding audit log entry', {
  96. userToRemoveId,
  97. subscriptionId,
  98. })
  99. }
  100. try {
  101. await SubscriptionGroupHandler.promises.removeUserFromGroup(
  102. subscriptionId,
  103. userToRemoveId
  104. )
  105. } catch (error) {
  106. logger.err(
  107. { err: error, userToRemoveId, subscriptionId },
  108. 'error removing self from group'
  109. )
  110. return res.sendStatus(500)
  111. }
  112. res.sendStatus(200)
  113. }
  114. /**
  115. * @param {import("express").Request} req
  116. * @param {import("express").Response} res
  117. * @returns {Promise<void>}
  118. */
  119. async function addSeatsToGroupSubscription(req, res) {
  120. try {
  121. const userId = SessionManager.getLoggedInUserId(req.session)
  122. const { subscription, recurlySubscription, plan } =
  123. await SubscriptionGroupHandler.promises.getUsersGroupSubscriptionDetails(
  124. userId
  125. )
  126. await SubscriptionGroupHandler.promises.ensureFlexibleLicensingEnabled(plan)
  127. await SubscriptionGroupHandler.promises.ensureSubscriptionHasNoPendingChanges(
  128. recurlySubscription
  129. )
  130. await SubscriptionGroupHandler.promises.ensureSubscriptionIsActive(
  131. subscription
  132. )
  133. const { variant: flexibleLicensingForManuallyBilledSubscriptionsVariant } =
  134. await SplitTestHandler.promises.getAssignment(
  135. req,
  136. res,
  137. 'flexible-group-licensing-for-manually-billed-subscriptions'
  138. )
  139. if (flexibleLicensingForManuallyBilledSubscriptionsVariant === 'enabled') {
  140. await SubscriptionGroupHandler.promises.checkBillingInfoExistence(
  141. recurlySubscription,
  142. userId
  143. )
  144. } else {
  145. await SubscriptionGroupHandler.promises.ensureSubscriptionCollectionMethodIsNotManual(
  146. recurlySubscription
  147. )
  148. // Check if the user has missing billing details
  149. await RecurlyClient.promises.getPaymentMethod(userId)
  150. }
  151. res.render('subscriptions/add-seats', {
  152. subscriptionId: subscription._id,
  153. groupName: subscription.teamName,
  154. totalLicenses: subscription.membersLimit,
  155. isProfessional: isProfessionalGroupPlan(subscription),
  156. isCollectionMethodManual: recurlySubscription.isCollectionMethodManual,
  157. })
  158. } catch (error) {
  159. if (error instanceof MissingBillingInfoError) {
  160. return res.redirect(
  161. '/user/subscription/group/missing-billing-information'
  162. )
  163. }
  164. if (error instanceof ManuallyCollectedError) {
  165. return res.redirect(
  166. '/user/subscription/group/manually-collected-subscription'
  167. )
  168. }
  169. if (error instanceof PendingChangeError || error instanceof InactiveError) {
  170. return res.redirect('/user/subscription')
  171. }
  172. logger.err(
  173. { error },
  174. 'error while getting users group subscription details'
  175. )
  176. return res.redirect('/user/subscription')
  177. }
  178. }
  179. /**
  180. * @param {import("express").Request} req
  181. * @param {import("express").Response} res
  182. * @returns {Promise<void>}
  183. */
  184. async function previewAddSeatsSubscriptionChange(req, res) {
  185. try {
  186. const userId = SessionManager.getLoggedInUserId(req.session)
  187. const preview =
  188. await SubscriptionGroupHandler.promises.previewAddSeatsSubscriptionChange(
  189. userId,
  190. req.body.adding
  191. )
  192. res.json(preview)
  193. } catch (error) {
  194. if (
  195. error instanceof MissingBillingInfoError ||
  196. error instanceof ManuallyCollectedError ||
  197. error instanceof PendingChangeError ||
  198. error instanceof InactiveError
  199. ) {
  200. return res.status(422).end()
  201. }
  202. if (error instanceof SubtotalLimitExceededError) {
  203. return res.status(422).json({
  204. code: 'subtotal_limit_exceeded',
  205. adding: req.body.adding,
  206. })
  207. }
  208. logger.err(
  209. { error },
  210. 'error trying to preview "add seats" subscription change'
  211. )
  212. return res.status(500).end()
  213. }
  214. }
  215. /**
  216. * @param {import("express").Request} req
  217. * @param {import("express").Response} res
  218. * @returns {Promise<void>}
  219. */
  220. async function createAddSeatsSubscriptionChange(req, res) {
  221. try {
  222. const userId = SessionManager.getLoggedInUserId(req.session)
  223. const create =
  224. await SubscriptionGroupHandler.promises.createAddSeatsSubscriptionChange(
  225. userId,
  226. req.body.adding,
  227. req.body.poNumber
  228. )
  229. res.json(create)
  230. } catch (error) {
  231. if (
  232. error instanceof MissingBillingInfoError ||
  233. error instanceof ManuallyCollectedError ||
  234. error instanceof PendingChangeError ||
  235. error instanceof InactiveError
  236. ) {
  237. return res.status(422).end()
  238. }
  239. if (error instanceof SubtotalLimitExceededError) {
  240. return res.status(422).json({
  241. code: 'subtotal_limit_exceeded',
  242. adding: req.body.adding,
  243. })
  244. }
  245. logger.err(
  246. { error },
  247. 'error trying to create "add seats" subscription change'
  248. )
  249. return res.status(500).end()
  250. }
  251. }
  252. async function submitForm(req, res) {
  253. const userId = SessionManager.getLoggedInUserId(req.session)
  254. const userEmail = await UserGetter.promises.getUserEmail(userId)
  255. const { adding, poNumber } = req.body
  256. const { recurlySubscription } =
  257. await SubscriptionGroupHandler.promises.getUsersGroupSubscriptionDetails(
  258. userId
  259. )
  260. if (recurlySubscription.isCollectionMethodManual) {
  261. await SubscriptionGroupHandler.promises.updateSubscriptionPaymentTerms(
  262. userId,
  263. recurlySubscription,
  264. poNumber
  265. )
  266. }
  267. const messageLines = [`\n**Overleaf Sales Contact Form:**`]
  268. messageLines.push('**Subject:** Self-Serve Group User Increase Request')
  269. messageLines.push(`**Estimated Number of Users:** ${adding}`)
  270. if (poNumber) {
  271. messageLines.push(`**PO Number:** ${poNumber}`)
  272. }
  273. messageLines.push(
  274. `**Message:** This email has been generated on behalf of user with email **${userEmail}** ` +
  275. 'to request an increase in the total number of users for their subscription.'
  276. )
  277. const messageFormatted = messageLines.join('\n\n')
  278. const data = {
  279. email: userEmail,
  280. subject: 'Sales Contact Form',
  281. message: messageFormatted,
  282. inbox: 'sales',
  283. }
  284. await Modules.promises.hooks.fire('sendSupportRequest', data)
  285. res.sendStatus(204)
  286. }
  287. async function subscriptionUpgradePage(req, res) {
  288. try {
  289. const userId = SessionManager.getLoggedInUserId(req.session)
  290. const changePreview =
  291. await SubscriptionGroupHandler.promises.getGroupPlanUpgradePreview(userId)
  292. const olSubscription = await Subscription.findOne({
  293. admin_id: userId,
  294. }).exec()
  295. res.render('subscriptions/upgrade-group-subscription-react', {
  296. changePreview,
  297. totalLicenses: olSubscription.membersLimit,
  298. groupName: olSubscription.teamName,
  299. })
  300. } catch (error) {
  301. if (error instanceof MissingBillingInfoError) {
  302. return res.redirect(
  303. '/user/subscription/group/missing-billing-information'
  304. )
  305. }
  306. if (error instanceof ManuallyCollectedError) {
  307. return res.redirect(
  308. '/user/subscription/group/manually-collected-subscription'
  309. )
  310. }
  311. if (error instanceof SubtotalLimitExceededError) {
  312. return res.redirect('/user/subscription/group/subtotal-limit-exceeded')
  313. }
  314. if (error instanceof PendingChangeError || error instanceof InactiveError) {
  315. return res.redirect('/user/subscription')
  316. }
  317. logger.err({ error }, 'error loading upgrade subscription page')
  318. return res.redirect('/user/subscription')
  319. }
  320. }
  321. async function upgradeSubscription(req, res) {
  322. try {
  323. const userId = SessionManager.getLoggedInUserId(req.session)
  324. await SubscriptionGroupHandler.promises.upgradeGroupPlan(userId)
  325. return res.sendStatus(200)
  326. } catch (error) {
  327. logger.err({ error }, 'error trying to upgrade subscription')
  328. return res.sendStatus(500)
  329. }
  330. }
  331. async function missingBillingInformation(req, res) {
  332. try {
  333. const userId = SessionManager.getLoggedInUserId(req.session)
  334. const subscription =
  335. await SubscriptionLocator.promises.getUsersSubscription(userId)
  336. res.render('subscriptions/missing-billing-information', {
  337. groupName: subscription.teamName,
  338. })
  339. } catch (error) {
  340. logger.err(
  341. { error },
  342. 'error trying to render missing billing information page'
  343. )
  344. return res.render('/user/subscription')
  345. }
  346. }
  347. async function manuallyCollectedSubscription(req, res) {
  348. try {
  349. const userId = SessionManager.getLoggedInUserId(req.session)
  350. const subscription =
  351. await SubscriptionLocator.promises.getUsersSubscription(userId)
  352. res.render('subscriptions/manually-collected-subscription', {
  353. groupName: subscription.teamName,
  354. })
  355. } catch (error) {
  356. logger.err(
  357. { error },
  358. 'error trying to render manually collected subscription page'
  359. )
  360. return res.render('/user/subscription')
  361. }
  362. }
  363. async function subtotalLimitExceeded(req, res) {
  364. try {
  365. const userId = SessionManager.getLoggedInUserId(req.session)
  366. const subscription =
  367. await SubscriptionLocator.promises.getUsersSubscription(userId)
  368. res.render('subscriptions/subtotal-limit-exceeded', {
  369. groupName: subscription.teamName,
  370. })
  371. } catch (error) {
  372. logger.err({ error }, 'error trying to render subtotal limit exceeded page')
  373. return res.render('/user/subscription')
  374. }
  375. }
  376. export default {
  377. removeUserFromGroup: expressify(removeUserFromGroup),
  378. removeSelfFromGroup: expressify(removeSelfFromGroup),
  379. addSeatsToGroupSubscription: expressify(addSeatsToGroupSubscription),
  380. submitForm: expressify(submitForm),
  381. previewAddSeatsSubscriptionChange: expressify(
  382. previewAddSeatsSubscriptionChange
  383. ),
  384. createAddSeatsSubscriptionChange: expressify(
  385. createAddSeatsSubscriptionChange
  386. ),
  387. subscriptionUpgradePage: expressify(subscriptionUpgradePage),
  388. upgradeSubscription: expressify(upgradeSubscription),
  389. missingBillingInformation: expressify(missingBillingInformation),
  390. manuallyCollectedSubscription: expressify(manuallyCollectedSubscription),
  391. subtotalLimitExceeded: expressify(subtotalLimitExceeded),
  392. }