SubscriptionGroupController.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 UserGetter from '../User/UserGetter.js'
  11. import { Subscription } from '../../models/Subscription.js'
  12. import { isProfessionalGroupPlan } from './PlansHelper.mjs'
  13. import {
  14. MissingBillingInfoError,
  15. ManuallyCollectedError,
  16. PendingChangeError,
  17. InactiveError,
  18. SubtotalLimitExceededError,
  19. HasPastDueInvoiceError,
  20. HasNoAdditionalLicenseWhenManuallyCollectedError,
  21. } from './Errors.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. const groupAuditLog = {
  101. initiatorId: loggedInUserId,
  102. ipAddress: req.ip,
  103. }
  104. try {
  105. await SubscriptionGroupHandler.promises.removeUserFromGroup(
  106. subscriptionId,
  107. userToRemoveId,
  108. groupAuditLog
  109. )
  110. } catch (error) {
  111. logger.err(
  112. { err: error, userToRemoveId, subscriptionId },
  113. 'error removing self from group'
  114. )
  115. return res.sendStatus(500)
  116. }
  117. res.sendStatus(200)
  118. }
  119. /**
  120. * @param {import("express").Request} req
  121. * @param {import("express").Response} res
  122. * @returns {Promise<void>}
  123. */
  124. async function addSeatsToGroupSubscription(req, res) {
  125. try {
  126. const userId = SessionManager.getLoggedInUserId(req.session)
  127. const { subscription, paymentProviderSubscription, plan } =
  128. await SubscriptionGroupHandler.promises.getUsersGroupSubscriptionDetails(
  129. userId
  130. )
  131. await SubscriptionGroupHandler.promises.ensureFlexibleLicensingEnabled(plan)
  132. await SubscriptionGroupHandler.promises.ensureSubscriptionHasNoPendingChanges(
  133. paymentProviderSubscription
  134. )
  135. await SubscriptionGroupHandler.promises.ensureSubscriptionIsActive(
  136. subscription
  137. )
  138. await SubscriptionGroupHandler.promises.ensureSubscriptionHasNoPastDueInvoice(
  139. subscription
  140. )
  141. await SubscriptionGroupHandler.promises.checkBillingInfoExistence(
  142. paymentProviderSubscription,
  143. userId
  144. )
  145. await SubscriptionGroupHandler.promises.ensureSubscriptionHasAdditionalLicenseAddOnWhenCollectionMethodIsManual(
  146. paymentProviderSubscription
  147. )
  148. res.render('subscriptions/add-seats', {
  149. subscriptionId: subscription._id,
  150. groupName: subscription.teamName,
  151. totalLicenses: subscription.membersLimit,
  152. isProfessional: isProfessionalGroupPlan(subscription),
  153. isCollectionMethodManual:
  154. paymentProviderSubscription.isCollectionMethodManual,
  155. })
  156. } catch (error) {
  157. if (error instanceof MissingBillingInfoError) {
  158. return res.redirect(
  159. '/user/subscription/group/missing-billing-information'
  160. )
  161. }
  162. if (error instanceof HasNoAdditionalLicenseWhenManuallyCollectedError) {
  163. return res.redirect(
  164. '/user/subscription/group/manually-collected-subscription'
  165. )
  166. }
  167. if (
  168. error instanceof PendingChangeError ||
  169. error instanceof InactiveError ||
  170. error instanceof HasPastDueInvoiceError
  171. ) {
  172. return res.redirect('/user/subscription')
  173. }
  174. logger.err(
  175. { error },
  176. 'error while getting users group subscription details'
  177. )
  178. return res.redirect('/user/subscription')
  179. }
  180. }
  181. /**
  182. * @param {import("express").Request} req
  183. * @param {import("express").Response} res
  184. * @returns {Promise<void>}
  185. */
  186. async function previewAddSeatsSubscriptionChange(req, res) {
  187. try {
  188. const userId = SessionManager.getLoggedInUserId(req.session)
  189. const preview =
  190. await SubscriptionGroupHandler.promises.previewAddSeatsSubscriptionChange(
  191. userId,
  192. req.body.adding
  193. )
  194. res.json(preview)
  195. } catch (error) {
  196. if (
  197. error instanceof MissingBillingInfoError ||
  198. error instanceof PendingChangeError ||
  199. error instanceof InactiveError ||
  200. error instanceof HasPastDueInvoiceError ||
  201. error instanceof HasNoAdditionalLicenseWhenManuallyCollectedError
  202. ) {
  203. return res.status(422).end()
  204. }
  205. if (error instanceof SubtotalLimitExceededError) {
  206. return res.status(422).json({
  207. code: 'subtotal_limit_exceeded',
  208. adding: req.body.adding,
  209. })
  210. }
  211. logger.err(
  212. { error },
  213. 'error trying to preview "add seats" subscription change'
  214. )
  215. return res.status(500).end()
  216. }
  217. }
  218. /**
  219. * @param {import("express").Request} req
  220. * @param {import("express").Response} res
  221. * @returns {Promise<void>}
  222. */
  223. async function createAddSeatsSubscriptionChange(req, res) {
  224. try {
  225. const userId = SessionManager.getLoggedInUserId(req.session)
  226. const create =
  227. await SubscriptionGroupHandler.promises.createAddSeatsSubscriptionChange(
  228. userId,
  229. req.body.adding,
  230. req.body.poNumber
  231. )
  232. res.json(create)
  233. } catch (error) {
  234. if (
  235. error instanceof MissingBillingInfoError ||
  236. error instanceof PendingChangeError ||
  237. error instanceof InactiveError ||
  238. error instanceof HasPastDueInvoiceError ||
  239. error instanceof HasNoAdditionalLicenseWhenManuallyCollectedError
  240. ) {
  241. return res.status(422).end()
  242. }
  243. if (error instanceof SubtotalLimitExceededError) {
  244. return res.status(422).json({
  245. code: 'subtotal_limit_exceeded',
  246. adding: req.body.adding,
  247. })
  248. }
  249. logger.err(
  250. { error },
  251. 'error trying to create "add seats" subscription change'
  252. )
  253. return res.status(500).end()
  254. }
  255. }
  256. async function submitForm(req, res) {
  257. const userId = SessionManager.getLoggedInUserId(req.session)
  258. const userEmail = await UserGetter.promises.getUserEmail(userId)
  259. const { adding, poNumber } = req.body
  260. const { paymentProviderSubscription } =
  261. await SubscriptionGroupHandler.promises.getUsersGroupSubscriptionDetails(
  262. userId
  263. )
  264. if (paymentProviderSubscription.isCollectionMethodManual) {
  265. await SubscriptionGroupHandler.promises.updateSubscriptionPaymentTerms(
  266. userId,
  267. paymentProviderSubscription,
  268. poNumber
  269. )
  270. }
  271. const messageLines = [`\n**Overleaf Sales Contact Form:**`]
  272. messageLines.push('**Subject:** Self-Serve Group User Increase Request')
  273. messageLines.push(`**Estimated Number of Users:** ${adding}`)
  274. if (poNumber) {
  275. messageLines.push(`**PO Number:** ${poNumber}`)
  276. }
  277. messageLines.push(
  278. `**Message:** This email has been generated on behalf of user with email **${userEmail}** ` +
  279. 'to request an increase in the total number of users for their subscription.'
  280. )
  281. const messageFormatted = messageLines.join('\n\n')
  282. const data = {
  283. email: userEmail,
  284. subject: 'Sales Contact Form',
  285. message: messageFormatted,
  286. inbox: 'sales',
  287. }
  288. await Modules.promises.hooks.fire('sendSupportRequest', data)
  289. res.sendStatus(204)
  290. }
  291. async function subscriptionUpgradePage(req, res) {
  292. try {
  293. const userId = SessionManager.getLoggedInUserId(req.session)
  294. const changePreview =
  295. await SubscriptionGroupHandler.promises.getGroupPlanUpgradePreview(userId)
  296. const olSubscription = await Subscription.findOne({
  297. admin_id: userId,
  298. }).exec()
  299. res.render('subscriptions/upgrade-group-subscription-react', {
  300. changePreview,
  301. totalLicenses: olSubscription.membersLimit,
  302. groupName: olSubscription.teamName,
  303. })
  304. } catch (error) {
  305. if (error instanceof MissingBillingInfoError) {
  306. return res.redirect(
  307. '/user/subscription/group/missing-billing-information'
  308. )
  309. }
  310. if (error instanceof ManuallyCollectedError) {
  311. return res.redirect(
  312. '/user/subscription/group/manually-collected-subscription'
  313. )
  314. }
  315. if (error instanceof SubtotalLimitExceededError) {
  316. return res.redirect('/user/subscription/group/subtotal-limit-exceeded')
  317. }
  318. if (error instanceof PendingChangeError || error instanceof InactiveError) {
  319. return res.redirect('/user/subscription')
  320. }
  321. logger.err({ error }, 'error loading upgrade subscription page')
  322. return res.redirect('/user/subscription')
  323. }
  324. }
  325. async function upgradeSubscription(req, res) {
  326. try {
  327. const userId = SessionManager.getLoggedInUserId(req.session)
  328. await SubscriptionGroupHandler.promises.upgradeGroupPlan(userId)
  329. return res.sendStatus(200)
  330. } catch (error) {
  331. logger.err({ error }, 'error trying to upgrade subscription')
  332. return res.sendStatus(500)
  333. }
  334. }
  335. async function missingBillingInformation(req, res) {
  336. try {
  337. const userId = SessionManager.getLoggedInUserId(req.session)
  338. const subscription =
  339. await SubscriptionLocator.promises.getUsersSubscription(userId)
  340. res.render('subscriptions/missing-billing-information', {
  341. groupName: subscription.teamName,
  342. })
  343. } catch (error) {
  344. logger.err(
  345. { error },
  346. 'error trying to render missing billing information page'
  347. )
  348. return res.render('/user/subscription')
  349. }
  350. }
  351. async function manuallyCollectedSubscription(req, res) {
  352. try {
  353. const userId = SessionManager.getLoggedInUserId(req.session)
  354. const subscription =
  355. await SubscriptionLocator.promises.getUsersSubscription(userId)
  356. res.render('subscriptions/manually-collected-subscription', {
  357. groupName: subscription.teamName,
  358. })
  359. } catch (error) {
  360. logger.err(
  361. { error },
  362. 'error trying to render manually collected subscription page'
  363. )
  364. return res.render('/user/subscription')
  365. }
  366. }
  367. async function subtotalLimitExceeded(req, res) {
  368. try {
  369. const userId = SessionManager.getLoggedInUserId(req.session)
  370. const subscription =
  371. await SubscriptionLocator.promises.getUsersSubscription(userId)
  372. res.render('subscriptions/subtotal-limit-exceeded', {
  373. groupName: subscription.teamName,
  374. })
  375. } catch (error) {
  376. logger.err({ error }, 'error trying to render subtotal limit exceeded page')
  377. return res.render('/user/subscription')
  378. }
  379. }
  380. export default {
  381. removeUserFromGroup: expressify(removeUserFromGroup),
  382. removeSelfFromGroup: expressify(removeSelfFromGroup),
  383. addSeatsToGroupSubscription: expressify(addSeatsToGroupSubscription),
  384. submitForm: expressify(submitForm),
  385. previewAddSeatsSubscriptionChange: expressify(
  386. previewAddSeatsSubscriptionChange
  387. ),
  388. createAddSeatsSubscriptionChange: expressify(
  389. createAddSeatsSubscriptionChange
  390. ),
  391. subscriptionUpgradePage: expressify(subscriptionUpgradePage),
  392. upgradeSubscription: expressify(upgradeSubscription),
  393. missingBillingInformation: expressify(missingBillingInformation),
  394. manuallyCollectedSubscription: expressify(manuallyCollectedSubscription),
  395. subtotalLimitExceeded: expressify(subtotalLimitExceeded),
  396. }