SubscriptionController.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /* eslint-disable
  2. camelcase,
  3. node/handle-callback-err,
  4. max-len,
  5. no-return-assign,
  6. no-unused-vars,
  7. */
  8. // TODO: This file was created by bulk-decaffeinate.
  9. // Fix any style issues and re-enable lint.
  10. /*
  11. * decaffeinate suggestions:
  12. * DS102: Remove unnecessary code created because of implicit returns
  13. * DS103: Rewrite code to no longer use __guard__
  14. * DS207: Consider shorter variations of null checks
  15. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  16. */
  17. let SubscriptionController
  18. const AuthenticationController = require('../Authentication/AuthenticationController')
  19. const SubscriptionHandler = require('./SubscriptionHandler')
  20. const PlansLocator = require('./PlansLocator')
  21. const SubscriptionViewModelBuilder = require('./SubscriptionViewModelBuilder')
  22. const LimitationsManager = require('./LimitationsManager')
  23. const RecurlyWrapper = require('./RecurlyWrapper')
  24. const Settings = require('settings-sharelatex')
  25. const logger = require('logger-sharelatex')
  26. const GeoIpLookup = require('../../infrastructure/GeoIpLookup')
  27. const UserGetter = require('../User/UserGetter')
  28. const FeaturesUpdater = require('./FeaturesUpdater')
  29. const planFeatures = require('./planFeatures')
  30. const GroupPlansData = require('./GroupPlansData')
  31. const V1SubscriptionManager = require('./V1SubscriptionManager')
  32. const Errors = require('../Errors/Errors')
  33. const HttpErrorHandler = require('../Errors/HttpErrorHandler')
  34. const SubscriptionErrors = require('./Errors')
  35. const OError = require('@overleaf/o-error')
  36. module.exports = SubscriptionController = {
  37. plansPage(req, res, next) {
  38. const plans = SubscriptionViewModelBuilder.buildPlansList()
  39. let currentUser = null
  40. return GeoIpLookup.getCurrencyCode(
  41. (req.query != null ? req.query.ip : undefined) || req.ip,
  42. function (err, recomendedCurrency) {
  43. if (err != null) {
  44. return next(err)
  45. }
  46. const render = () =>
  47. res.render('subscriptions/plans', {
  48. title: 'plans_and_pricing',
  49. plans,
  50. gaExperiments: Settings.gaExperiments.plansPage,
  51. gaOptimize: true,
  52. recomendedCurrency,
  53. planFeatures,
  54. groupPlans: GroupPlansData
  55. })
  56. const user_id = AuthenticationController.getLoggedInUserId(req)
  57. if (user_id != null) {
  58. return UserGetter.getUser(
  59. user_id,
  60. { signUpDate: 1 },
  61. function (err, user) {
  62. if (err != null) {
  63. return next(err)
  64. }
  65. currentUser = user
  66. return render()
  67. }
  68. )
  69. } else {
  70. return render()
  71. }
  72. }
  73. )
  74. },
  75. // get to show the recurly.js page
  76. paymentPage(req, res, next) {
  77. const user = AuthenticationController.getSessionUser(req)
  78. const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode)
  79. if (!plan) {
  80. return HttpErrorHandler.unprocessableEntity(req, res, 'Plan not found')
  81. }
  82. return LimitationsManager.userHasV1OrV2Subscription(
  83. user,
  84. function (err, hasSubscription) {
  85. if (err != null) {
  86. return next(err)
  87. }
  88. if (hasSubscription) {
  89. return res.redirect('/user/subscription?hasSubscription=true')
  90. } else {
  91. // LimitationsManager.userHasV2Subscription only checks Mongo. Double check with
  92. // Recurly as well at this point (we don't do this most places for speed).
  93. return SubscriptionHandler.validateNoSubscriptionInRecurly(
  94. user._id,
  95. function (error, valid) {
  96. if (error != null) {
  97. return next(error)
  98. }
  99. if (!valid) {
  100. res.redirect('/user/subscription?hasSubscription=true')
  101. } else {
  102. let currency =
  103. req.query.currency != null
  104. ? req.query.currency.toUpperCase()
  105. : undefined
  106. return GeoIpLookup.getCurrencyCode(
  107. (req.query != null ? req.query.ip : undefined) || req.ip,
  108. function (err, recomendedCurrency, countryCode) {
  109. if (err != null) {
  110. return next(err)
  111. }
  112. if (recomendedCurrency != null && currency == null) {
  113. currency = recomendedCurrency
  114. }
  115. return res.render('subscriptions/new', {
  116. title: 'subscribe',
  117. currency,
  118. countryCode,
  119. plan,
  120. showStudentPlan: req.query.ssp === 'true',
  121. recurlyConfig: JSON.stringify({
  122. currency,
  123. subdomain: Settings.apis.recurly.subdomain
  124. }),
  125. showCouponField: !!req.query.scf,
  126. showVatField: !!req.query.svf,
  127. gaOptimize: true
  128. })
  129. }
  130. )
  131. }
  132. }
  133. )
  134. }
  135. }
  136. )
  137. },
  138. userSubscriptionPage(req, res, next) {
  139. const user = AuthenticationController.getSessionUser(req)
  140. return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
  141. user,
  142. function (error, results) {
  143. if (error != null) {
  144. return next(error)
  145. }
  146. const {
  147. personalSubscription,
  148. memberGroupSubscriptions,
  149. managedGroupSubscriptions,
  150. confirmedMemberAffiliations,
  151. managedInstitutions,
  152. managedPublishers,
  153. v1SubscriptionStatus
  154. } = results
  155. return LimitationsManager.userHasV1OrV2Subscription(
  156. user,
  157. function (err, hasSubscription) {
  158. if (error != null) {
  159. return next(error)
  160. }
  161. const fromPlansPage = req.query.hasSubscription
  162. const plans = SubscriptionViewModelBuilder.buildPlansList()
  163. const data = {
  164. title: 'your_subscription',
  165. plans,
  166. user,
  167. hasSubscription,
  168. fromPlansPage,
  169. personalSubscription,
  170. memberGroupSubscriptions,
  171. managedGroupSubscriptions,
  172. confirmedMemberAffiliations,
  173. managedInstitutions,
  174. managedPublishers,
  175. v1SubscriptionStatus
  176. }
  177. return res.render('subscriptions/dashboard', data)
  178. }
  179. )
  180. }
  181. )
  182. },
  183. createSubscription(req, res, next) {
  184. const user = AuthenticationController.getSessionUser(req)
  185. const recurlyTokenIds = {
  186. billing: req.body.recurly_token_id,
  187. threeDSecureActionResult:
  188. req.body.recurly_three_d_secure_action_result_token_id
  189. }
  190. const { subscriptionDetails } = req.body
  191. return LimitationsManager.userHasV1OrV2Subscription(
  192. user,
  193. function (err, hasSubscription) {
  194. if (err != null) {
  195. return next(err)
  196. }
  197. if (hasSubscription) {
  198. logger.warn({ user_id: user._id }, 'user already has subscription')
  199. return res.sendStatus(409) // conflict
  200. }
  201. return SubscriptionHandler.createSubscription(
  202. user,
  203. subscriptionDetails,
  204. recurlyTokenIds,
  205. function (err) {
  206. if (!err) {
  207. return res.sendStatus(201)
  208. }
  209. if (
  210. err instanceof SubscriptionErrors.RecurlyTransactionError ||
  211. err instanceof Errors.InvalidError
  212. ) {
  213. logger.error({ err }, 'recurly transaction error, potential 422')
  214. return HttpErrorHandler.unprocessableEntity(
  215. req,
  216. res,
  217. err.message,
  218. OError.getFullInfo(err).public
  219. )
  220. }
  221. logger.warn(
  222. { err, user_id: user._id },
  223. 'something went wrong creating subscription'
  224. )
  225. next(err)
  226. }
  227. )
  228. }
  229. )
  230. },
  231. successful_subscription(req, res, next) {
  232. const user = AuthenticationController.getSessionUser(req)
  233. return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
  234. user,
  235. function (error, { personalSubscription }) {
  236. if (error != null) {
  237. return next(error)
  238. }
  239. if (personalSubscription == null) {
  240. return res.redirect('/user/subscription/plans')
  241. }
  242. return res.render('subscriptions/successful_subscription', {
  243. title: 'thank_you',
  244. personalSubscription
  245. })
  246. }
  247. )
  248. },
  249. cancelSubscription(req, res, next) {
  250. const user = AuthenticationController.getSessionUser(req)
  251. logger.log({ user_id: user._id }, 'canceling subscription')
  252. return SubscriptionHandler.cancelSubscription(user, function (err) {
  253. if (err != null) {
  254. OError.tag(err, 'something went wrong canceling subscription', {
  255. user_id: user._id
  256. })
  257. return next(err)
  258. }
  259. // Note: this redirect isn't used in the main flow as the redirection is
  260. // handled by Angular
  261. return res.redirect('/user/subscription/canceled')
  262. })
  263. },
  264. canceledSubscription(req, res, next) {
  265. const user = AuthenticationController.getSessionUser(req)
  266. return res.render('subscriptions/canceled_subscription', {
  267. title: 'subscription_canceled'
  268. })
  269. },
  270. cancelV1Subscription(req, res, next) {
  271. const user_id = AuthenticationController.getLoggedInUserId(req)
  272. logger.log({ user_id }, 'canceling v1 subscription')
  273. return V1SubscriptionManager.cancelV1Subscription(user_id, function (err) {
  274. if (err != null) {
  275. OError.tag(err, 'something went wrong canceling v1 subscription', {
  276. user_id
  277. })
  278. return next(err)
  279. }
  280. return res.redirect('/user/subscription')
  281. })
  282. },
  283. updateSubscription(req, res, next) {
  284. const _origin =
  285. __guard__(req != null ? req.query : undefined, x => x.origin) || null
  286. const user = AuthenticationController.getSessionUser(req)
  287. const planCode = req.body.plan_code
  288. if (planCode == null) {
  289. const err = new Error('plan_code is not defined')
  290. logger.warn(
  291. { user_id: user._id, err, planCode, origin: _origin, body: req.body },
  292. '[Subscription] error in updateSubscription form'
  293. )
  294. return next(err)
  295. }
  296. logger.log({ planCode, user_id: user._id }, 'updating subscription')
  297. return SubscriptionHandler.updateSubscription(
  298. user,
  299. planCode,
  300. null,
  301. function (err) {
  302. if (err != null) {
  303. OError.tag(err, 'something went wrong updating subscription', {
  304. user_id: user._id
  305. })
  306. return next(err)
  307. }
  308. return res.redirect('/user/subscription')
  309. }
  310. )
  311. },
  312. updateAccountEmailAddress(req, res, next) {
  313. const user = AuthenticationController.getSessionUser(req)
  314. RecurlyWrapper.updateAccountEmailAddress(
  315. user._id,
  316. user.email,
  317. function (error) {
  318. if (error) {
  319. return next(error)
  320. }
  321. res.sendStatus(200)
  322. }
  323. )
  324. },
  325. reactivateSubscription(req, res, next) {
  326. const user = AuthenticationController.getSessionUser(req)
  327. logger.log({ user_id: user._id }, 'reactivating subscription')
  328. return SubscriptionHandler.reactivateSubscription(user, function (err) {
  329. if (err != null) {
  330. OError.tag(err, 'something went wrong reactivating subscription', {
  331. user_id: user._id
  332. })
  333. return next(err)
  334. }
  335. return res.redirect('/user/subscription')
  336. })
  337. },
  338. recurlyCallback(req, res, next) {
  339. logger.log({ data: req.body }, 'received recurly callback')
  340. const event = Object.keys(req.body)[0]
  341. const eventData = req.body[event]
  342. if (
  343. [
  344. 'new_subscription_notification',
  345. 'updated_subscription_notification',
  346. 'expired_subscription_notification'
  347. ].includes(event)
  348. ) {
  349. const recurlySubscription = eventData.subscription
  350. return SubscriptionHandler.syncSubscription(
  351. recurlySubscription,
  352. { ip: req.ip },
  353. function (err) {
  354. if (err != null) {
  355. return next(err)
  356. }
  357. return res.sendStatus(200)
  358. }
  359. )
  360. } else if (event === 'billing_info_updated_notification') {
  361. const recurlyAccountCode = eventData.account.account_code
  362. return SubscriptionHandler.attemptPaypalInvoiceCollection(
  363. recurlyAccountCode,
  364. function (err) {
  365. if (err) {
  366. return next(err)
  367. }
  368. return res.sendStatus(200)
  369. }
  370. )
  371. } else {
  372. return res.sendStatus(200)
  373. }
  374. },
  375. renderUpgradeToAnnualPlanPage(req, res, next) {
  376. const user = AuthenticationController.getSessionUser(req)
  377. return LimitationsManager.userHasV2Subscription(
  378. user,
  379. function (err, hasSubscription, subscription) {
  380. let planName
  381. if (err != null) {
  382. return next(err)
  383. }
  384. const planCode =
  385. subscription != null ? subscription.planCode.toLowerCase() : undefined
  386. if (
  387. (planCode != null ? planCode.indexOf('annual') : undefined) !== -1
  388. ) {
  389. planName = 'annual'
  390. } else if (
  391. (planCode != null ? planCode.indexOf('student') : undefined) !== -1
  392. ) {
  393. planName = 'student'
  394. } else if (
  395. (planCode != null ? planCode.indexOf('collaborator') : undefined) !==
  396. -1
  397. ) {
  398. planName = 'collaborator'
  399. }
  400. if (!hasSubscription) {
  401. return res.redirect('/user/subscription/plans')
  402. }
  403. return res.render('subscriptions/upgradeToAnnual', {
  404. title: 'Upgrade to annual',
  405. planName
  406. })
  407. }
  408. )
  409. },
  410. processUpgradeToAnnualPlan(req, res, next) {
  411. const user = AuthenticationController.getSessionUser(req)
  412. const { planName } = req.body
  413. const coupon_code = Settings.coupon_codes.upgradeToAnnualPromo[planName]
  414. const annualPlanName = `${planName}-annual`
  415. logger.log(
  416. { user_id: user._id, planName: annualPlanName },
  417. 'user is upgrading to annual billing with discount'
  418. )
  419. return SubscriptionHandler.updateSubscription(
  420. user,
  421. annualPlanName,
  422. coupon_code,
  423. function (err) {
  424. if (err != null) {
  425. OError.tag(err, 'error updating subscription', {
  426. user_id: user._id
  427. })
  428. return next(err)
  429. }
  430. return res.sendStatus(200)
  431. }
  432. )
  433. },
  434. extendTrial(req, res, next) {
  435. const user = AuthenticationController.getSessionUser(req)
  436. return LimitationsManager.userHasV2Subscription(
  437. user,
  438. function (err, hasSubscription, subscription) {
  439. if (err != null) {
  440. return next(err)
  441. }
  442. return SubscriptionHandler.extendTrial(
  443. subscription,
  444. 14,
  445. function (err) {
  446. if (err != null) {
  447. return res.sendStatus(500)
  448. } else {
  449. return res.sendStatus(200)
  450. }
  451. }
  452. )
  453. }
  454. )
  455. },
  456. recurlyNotificationParser(req, res, next) {
  457. let xml = ''
  458. req.on('data', chunk => (xml += chunk))
  459. return req.on('end', () =>
  460. RecurlyWrapper._parseXml(xml, function (error, body) {
  461. if (error != null) {
  462. return next(error)
  463. }
  464. req.body = body
  465. return next()
  466. })
  467. )
  468. },
  469. refreshUserFeatures(req, res, next) {
  470. const { user_id } = req.params
  471. return FeaturesUpdater.refreshFeatures(user_id, function (error) {
  472. if (error != null) {
  473. return next(error)
  474. }
  475. return res.sendStatus(200)
  476. })
  477. }
  478. }
  479. function __guard__(value, transform) {
  480. return typeof value !== 'undefined' && value !== null
  481. ? transform(value)
  482. : undefined
  483. }