SubscriptionController.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /* eslint-disable
  2. camelcase,
  3. 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 SubscriptionErrors = require('./Errors')
  34. const HttpErrors = require('@overleaf/o-error/http')
  35. module.exports = SubscriptionController = {
  36. plansPage(req, res, next) {
  37. const plans = SubscriptionViewModelBuilder.buildPlansList()
  38. let viewName = 'subscriptions/plans'
  39. if (req.query.v != null) {
  40. viewName = `${viewName}_${req.query.v}`
  41. }
  42. let currentUser = null
  43. return GeoIpLookup.getCurrencyCode(
  44. (req.query != null ? req.query.ip : undefined) || req.ip,
  45. function(err, recomendedCurrency) {
  46. if (err != null) {
  47. return next(err)
  48. }
  49. const render = () =>
  50. res.render(viewName, {
  51. title: 'plans_and_pricing',
  52. plans,
  53. gaExperiments: Settings.gaExperiments.plansPage,
  54. gaOptimize: true,
  55. recomendedCurrency,
  56. planFeatures,
  57. groupPlans: GroupPlansData
  58. })
  59. const user_id = AuthenticationController.getLoggedInUserId(req)
  60. if (user_id != null) {
  61. return UserGetter.getUser(user_id, { signUpDate: 1 }, function(
  62. err,
  63. user
  64. ) {
  65. if (err != null) {
  66. return next(err)
  67. }
  68. currentUser = user
  69. return render()
  70. })
  71. } else {
  72. return render()
  73. }
  74. }
  75. )
  76. },
  77. // get to show the recurly.js page
  78. paymentPage(req, res, next) {
  79. const user = AuthenticationController.getSessionUser(req)
  80. const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode)
  81. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  82. err,
  83. hasSubscription
  84. ) {
  85. if (err != null) {
  86. return next(err)
  87. }
  88. if (hasSubscription || plan == null) {
  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. plan_code: req.query.planCode,
  118. currency,
  119. countryCode,
  120. plan,
  121. showStudentPlan: req.query.ssp,
  122. recurlyConfig: JSON.stringify({
  123. currency,
  124. subdomain: Settings.apis.recurly.subdomain
  125. }),
  126. showCouponField: req.query.scf,
  127. showVatField: req.query.svf,
  128. couponCode: req.query.cc || '',
  129. gaOptimize: true,
  130. ITMCampaign: req.query.itm_campaign,
  131. ITMContent: req.query.itm_content
  132. })
  133. }
  134. )
  135. }
  136. }
  137. )
  138. }
  139. })
  140. },
  141. userSubscriptionPage(req, res, next) {
  142. const user = AuthenticationController.getSessionUser(req)
  143. return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
  144. user,
  145. function(error, results) {
  146. if (error != null) {
  147. return next(error)
  148. }
  149. const {
  150. personalSubscription,
  151. memberGroupSubscriptions,
  152. managedGroupSubscriptions,
  153. confirmedMemberAffiliations,
  154. managedInstitutions,
  155. managedPublishers,
  156. v1SubscriptionStatus
  157. } = results
  158. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  159. err,
  160. hasSubscription
  161. ) {
  162. if (error != null) {
  163. return next(error)
  164. }
  165. const fromPlansPage = req.query.hasSubscription
  166. const plans = SubscriptionViewModelBuilder.buildPlansList()
  167. const data = {
  168. title: 'your_subscription',
  169. plans,
  170. user,
  171. hasSubscription,
  172. fromPlansPage,
  173. personalSubscription,
  174. memberGroupSubscriptions,
  175. managedGroupSubscriptions,
  176. confirmedMemberAffiliations,
  177. managedInstitutions,
  178. managedPublishers,
  179. v1SubscriptionStatus
  180. }
  181. return res.render('subscriptions/dashboard', data)
  182. })
  183. }
  184. )
  185. },
  186. createSubscription(req, res, next) {
  187. const user = AuthenticationController.getSessionUser(req)
  188. const recurlyTokenIds = {
  189. billing: req.body.recurly_token_id,
  190. threeDSecureActionResult:
  191. req.body.recurly_three_d_secure_action_result_token_id
  192. }
  193. const { subscriptionDetails } = req.body
  194. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  195. err,
  196. hasSubscription
  197. ) {
  198. if (err != null) {
  199. return next(err)
  200. }
  201. if (hasSubscription) {
  202. logger.warn({ user_id: user._id }, 'user already has subscription')
  203. res.sendStatus(409) // conflict
  204. }
  205. return SubscriptionHandler.createSubscription(
  206. user,
  207. subscriptionDetails,
  208. recurlyTokenIds,
  209. function(err) {
  210. if (!err) {
  211. return res.sendStatus(201)
  212. }
  213. if (err instanceof SubscriptionErrors.RecurlyTransactionError) {
  214. return next(
  215. new HttpErrors.UnprocessableEntityError({}).withCause(err)
  216. )
  217. } else if (err instanceof Errors.InvalidError) {
  218. return next(
  219. new HttpErrors.UnprocessableEntityError({}).withCause(err)
  220. )
  221. }
  222. logger.warn(
  223. { err, user_id: user._id },
  224. 'something went wrong creating subscription'
  225. )
  226. next(err)
  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. logger.warn(
  255. { err, user_id: user._id },
  256. 'something went wrong canceling subscription'
  257. )
  258. return next(err)
  259. }
  260. // Note: this redirect isn't used in the main flow as the redirection is
  261. // handled by Angular
  262. return res.redirect('/user/subscription/canceled')
  263. })
  264. },
  265. canceledSubscription(req, res, next) {
  266. const user = AuthenticationController.getSessionUser(req)
  267. return res.render('subscriptions/canceled_subscription', {
  268. title: 'subscription_canceled'
  269. })
  270. },
  271. cancelV1Subscription(req, res, next) {
  272. const user_id = AuthenticationController.getLoggedInUserId(req)
  273. logger.log({ user_id }, 'canceling v1 subscription')
  274. return V1SubscriptionManager.cancelV1Subscription(user_id, function(err) {
  275. if (err != null) {
  276. logger.warn(
  277. { err, user_id },
  278. 'something went wrong canceling v1 subscription'
  279. )
  280. return next(err)
  281. }
  282. return res.redirect('/user/subscription')
  283. })
  284. },
  285. updateSubscription(req, res, next) {
  286. const _origin =
  287. __guard__(req != null ? req.query : undefined, x => x.origin) || null
  288. const user = AuthenticationController.getSessionUser(req)
  289. const planCode = req.body.plan_code
  290. if (planCode == null) {
  291. const err = new Error('plan_code is not defined')
  292. logger.warn(
  293. { user_id: user._id, err, planCode, origin: _origin, body: req.body },
  294. '[Subscription] error in updateSubscription form'
  295. )
  296. return next(err)
  297. }
  298. logger.log({ planCode, user_id: user._id }, 'updating subscription')
  299. return SubscriptionHandler.updateSubscription(
  300. user,
  301. planCode,
  302. null,
  303. function(err) {
  304. if (err != null) {
  305. logger.warn(
  306. { err, user_id: user._id },
  307. 'something went wrong updating subscription'
  308. )
  309. return next(err)
  310. }
  311. return res.redirect('/user/subscription')
  312. }
  313. )
  314. },
  315. updateAccountEmailAddress(req, res, next) {
  316. const user = AuthenticationController.getSessionUser(req)
  317. RecurlyWrapper.updateAccountEmailAddress(user._id, user.email, function(
  318. error
  319. ) {
  320. if (error) {
  321. return next(new HttpErrors.InternalServerError({}).withCause(error))
  322. }
  323. res.sendStatus(200)
  324. })
  325. },
  326. reactivateSubscription(req, res, next) {
  327. const user = AuthenticationController.getSessionUser(req)
  328. logger.log({ user_id: user._id }, 'reactivating subscription')
  329. return SubscriptionHandler.reactivateSubscription(user, function(err) {
  330. if (err != null) {
  331. logger.warn(
  332. { err, user_id: user._id },
  333. 'something went wrong reactivating subscription'
  334. )
  335. return next(err)
  336. }
  337. return res.redirect('/user/subscription')
  338. })
  339. },
  340. recurlyCallback(req, res, next) {
  341. logger.log({ data: req.body }, 'received recurly callback')
  342. const event = Object.keys(req.body)[0]
  343. const eventData = req.body[event]
  344. if (
  345. [
  346. 'new_subscription_notification',
  347. 'updated_subscription_notification',
  348. 'expired_subscription_notification'
  349. ].includes(event)
  350. ) {
  351. const recurlySubscription = eventData.subscription
  352. return SubscriptionHandler.syncSubscription(
  353. recurlySubscription,
  354. { ip: req.ip },
  355. function(err) {
  356. if (err != null) {
  357. return next(err)
  358. }
  359. return res.sendStatus(200)
  360. }
  361. )
  362. } else if (event === 'billing_info_updated_notification') {
  363. const recurlyAccountCode = eventData.account.account_code
  364. return SubscriptionHandler.attemptPaypalInvoiceCollection(
  365. recurlyAccountCode,
  366. function(err) {
  367. if (err) {
  368. return next(err)
  369. }
  370. return res.sendStatus(200)
  371. }
  372. )
  373. } else {
  374. return res.sendStatus(200)
  375. }
  376. },
  377. renderUpgradeToAnnualPlanPage(req, res, next) {
  378. const user = AuthenticationController.getSessionUser(req)
  379. return LimitationsManager.userHasV2Subscription(user, function(
  380. err,
  381. hasSubscription,
  382. subscription
  383. ) {
  384. let planName
  385. if (err != null) {
  386. return next(err)
  387. }
  388. const planCode =
  389. subscription != null ? subscription.planCode.toLowerCase() : undefined
  390. if ((planCode != null ? planCode.indexOf('annual') : undefined) !== -1) {
  391. planName = 'annual'
  392. } else if (
  393. (planCode != null ? planCode.indexOf('student') : undefined) !== -1
  394. ) {
  395. planName = 'student'
  396. } else if (
  397. (planCode != null ? planCode.indexOf('collaborator') : undefined) !== -1
  398. ) {
  399. planName = 'collaborator'
  400. }
  401. if (!hasSubscription) {
  402. return res.redirect('/user/subscription/plans')
  403. }
  404. return res.render('subscriptions/upgradeToAnnual', {
  405. title: 'Upgrade to annual',
  406. planName
  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. logger.warn({ err, user_id: user._id }, 'error updating subscription')
  426. return next(err)
  427. }
  428. return res.sendStatus(200)
  429. }
  430. )
  431. },
  432. extendTrial(req, res, next) {
  433. const user = AuthenticationController.getSessionUser(req)
  434. return LimitationsManager.userHasV2Subscription(user, function(
  435. err,
  436. hasSubscription,
  437. subscription
  438. ) {
  439. if (err != null) {
  440. return next(err)
  441. }
  442. return SubscriptionHandler.extendTrial(subscription, 14, function(err) {
  443. if (err != null) {
  444. return res.send(500)
  445. } else {
  446. return res.send(200)
  447. }
  448. })
  449. })
  450. },
  451. recurlyNotificationParser(req, res, next) {
  452. let xml = ''
  453. req.on('data', chunk => (xml += chunk))
  454. return req.on('end', () =>
  455. RecurlyWrapper._parseXml(xml, function(error, body) {
  456. if (error != null) {
  457. return next(error)
  458. }
  459. req.body = body
  460. return next()
  461. })
  462. )
  463. },
  464. refreshUserFeatures(req, res, next) {
  465. const { user_id } = req.params
  466. return FeaturesUpdater.refreshFeatures(user_id, function(error) {
  467. if (error != null) {
  468. return next(error)
  469. }
  470. return res.sendStatus(200)
  471. })
  472. }
  473. }
  474. function __guard__(value, transform) {
  475. return typeof value !== 'undefined' && value !== null
  476. ? transform(value)
  477. : undefined
  478. }