SubscriptionController.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. module.exports = SubscriptionController = {
  33. plansPage(req, res, next) {
  34. const plans = SubscriptionViewModelBuilder.buildViewModel()
  35. let viewName = 'subscriptions/plans'
  36. if (req.query.v != null) {
  37. viewName = `${viewName}_${req.query.v}`
  38. }
  39. logger.log({ viewName }, 'showing plans page')
  40. let currentUser = null
  41. return GeoIpLookup.getCurrencyCode(
  42. (req.query != null ? req.query.ip : undefined) || req.ip,
  43. function(err, recomendedCurrency) {
  44. if (err != null) {
  45. return next(err)
  46. }
  47. const render = () =>
  48. res.render(viewName, {
  49. title: 'plans_and_pricing',
  50. plans,
  51. gaExperiments: Settings.gaExperiments.plansPage,
  52. recomendedCurrency,
  53. planFeatures,
  54. groupPlans: GroupPlansData
  55. })
  56. const user_id = AuthenticationController.getLoggedInUserId(req)
  57. if (user_id != null) {
  58. return UserGetter.getUser(user_id, { signUpDate: 1 }, function(
  59. err,
  60. user
  61. ) {
  62. if (err != null) {
  63. return next(err)
  64. }
  65. currentUser = user
  66. return render()
  67. })
  68. } else {
  69. return render()
  70. }
  71. }
  72. )
  73. },
  74. // get to show the recurly.js page
  75. paymentPage(req, res, next) {
  76. const user = AuthenticationController.getSessionUser(req)
  77. const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode)
  78. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  79. err,
  80. hasSubscription
  81. ) {
  82. if (err != null) {
  83. return next(err)
  84. }
  85. if (hasSubscription || plan == null) {
  86. return res.redirect('/user/subscription?hasSubscription=true')
  87. } else {
  88. // LimitationsManager.userHasV2Subscription only checks Mongo. Double check with
  89. // Recurly as well at this point (we don't do this most places for speed).
  90. return SubscriptionHandler.validateNoSubscriptionInRecurly(
  91. user._id,
  92. function(error, valid) {
  93. if (error != null) {
  94. return next(error)
  95. }
  96. if (!valid) {
  97. res.redirect('/user/subscription?hasSubscription=true')
  98. } else {
  99. let currency =
  100. req.query.currency != null
  101. ? req.query.currency.toUpperCase()
  102. : undefined
  103. return GeoIpLookup.getCurrencyCode(
  104. (req.query != null ? req.query.ip : undefined) || req.ip,
  105. function(err, recomendedCurrency, countryCode) {
  106. if (err != null) {
  107. return next(err)
  108. }
  109. if (recomendedCurrency != null && currency == null) {
  110. currency = recomendedCurrency
  111. }
  112. return res.render('subscriptions/new', {
  113. title: 'subscribe',
  114. plan_code: req.query.planCode,
  115. currency,
  116. countryCode,
  117. plan,
  118. showStudentPlan: req.query.ssp,
  119. recurlyConfig: JSON.stringify({
  120. currency,
  121. subdomain: Settings.apis.recurly.subdomain
  122. }),
  123. showCouponField: req.query.scf,
  124. showVatField: req.query.svf,
  125. couponCode: req.query.cc || ''
  126. })
  127. }
  128. )
  129. }
  130. }
  131. )
  132. }
  133. })
  134. },
  135. userSubscriptionPage(req, res, next) {
  136. const user = AuthenticationController.getSessionUser(req)
  137. return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
  138. user,
  139. function(error, results) {
  140. if (error != null) {
  141. return next(error)
  142. }
  143. const {
  144. personalSubscription,
  145. memberGroupSubscriptions,
  146. managedGroupSubscriptions,
  147. confirmedMemberInstitutions,
  148. managedInstitutions,
  149. managedPublishers,
  150. v1SubscriptionStatus
  151. } = results
  152. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  153. err,
  154. hasSubscription
  155. ) {
  156. if (error != null) {
  157. return next(error)
  158. }
  159. const fromPlansPage = req.query.hasSubscription
  160. logger.log(
  161. {
  162. user,
  163. hasSubscription,
  164. fromPlansPage,
  165. personalSubscription,
  166. memberGroupSubscriptions,
  167. managedGroupSubscriptions,
  168. confirmedMemberInstitutions,
  169. managedInstitutions,
  170. managedPublishers,
  171. v1SubscriptionStatus
  172. },
  173. 'showing subscription dashboard'
  174. )
  175. const plans = SubscriptionViewModelBuilder.buildViewModel()
  176. const data = {
  177. title: 'your_subscription',
  178. plans,
  179. user,
  180. hasSubscription,
  181. fromPlansPage,
  182. personalSubscription,
  183. memberGroupSubscriptions,
  184. managedGroupSubscriptions,
  185. confirmedMemberInstitutions,
  186. managedInstitutions,
  187. managedPublishers,
  188. v1SubscriptionStatus
  189. }
  190. return res.render('subscriptions/dashboard', data)
  191. })
  192. }
  193. )
  194. },
  195. createSubscription(req, res, next) {
  196. const user = AuthenticationController.getSessionUser(req)
  197. const { recurly_token_id } = req.body
  198. const { subscriptionDetails } = req.body
  199. logger.log(
  200. { recurly_token_id, user_id: user._id, subscriptionDetails },
  201. 'creating subscription'
  202. )
  203. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  204. err,
  205. hasSubscription
  206. ) {
  207. if (err != null) {
  208. return next(err)
  209. }
  210. if (hasSubscription) {
  211. logger.warn({ user_id: user._id }, 'user already has subscription')
  212. res.sendStatus(409) // conflict
  213. }
  214. return SubscriptionHandler.createSubscription(
  215. user,
  216. subscriptionDetails,
  217. recurly_token_id,
  218. function(err) {
  219. if (err != null) {
  220. logger.warn(
  221. { err, user_id: user._id },
  222. 'something went wrong creating subscription'
  223. )
  224. return next(err)
  225. }
  226. return res.sendStatus(201)
  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. reactivateSubscription(req, res, next) {
  316. const user = AuthenticationController.getSessionUser(req)
  317. logger.log({ user_id: user._id }, 'reactivating subscription')
  318. return SubscriptionHandler.reactivateSubscription(user, function(err) {
  319. if (err != null) {
  320. logger.warn(
  321. { err, user_id: user._id },
  322. 'something went wrong reactivating subscription'
  323. )
  324. return next(err)
  325. }
  326. return res.redirect('/user/subscription')
  327. })
  328. },
  329. recurlyCallback(req, res, next) {
  330. logger.log({ data: req.body }, 'received recurly callback')
  331. // we only care if a subscription has exipired
  332. if (
  333. req.body != null &&
  334. req.body['expired_subscription_notification'] != null
  335. ) {
  336. const recurlySubscription =
  337. req.body['expired_subscription_notification'].subscription
  338. return SubscriptionHandler.recurlyCallback(recurlySubscription, function(
  339. err
  340. ) {
  341. if (err != null) {
  342. return next(err)
  343. }
  344. return res.sendStatus(200)
  345. })
  346. } else {
  347. return res.sendStatus(200)
  348. }
  349. },
  350. renderUpgradeToAnnualPlanPage(req, res, next) {
  351. const user = AuthenticationController.getSessionUser(req)
  352. return LimitationsManager.userHasV2Subscription(user, function(
  353. err,
  354. hasSubscription,
  355. subscription
  356. ) {
  357. let planName
  358. if (err != null) {
  359. return next(err)
  360. }
  361. const planCode =
  362. subscription != null ? subscription.planCode.toLowerCase() : undefined
  363. if ((planCode != null ? planCode.indexOf('annual') : undefined) !== -1) {
  364. planName = 'annual'
  365. } else if (
  366. (planCode != null ? planCode.indexOf('student') : undefined) !== -1
  367. ) {
  368. planName = 'student'
  369. } else if (
  370. (planCode != null ? planCode.indexOf('collaborator') : undefined) !== -1
  371. ) {
  372. planName = 'collaborator'
  373. }
  374. if (!hasSubscription) {
  375. return res.redirect('/user/subscription/plans')
  376. }
  377. logger.log(
  378. { planName, user_id: user._id },
  379. 'rendering upgrade to annual page'
  380. )
  381. return res.render('subscriptions/upgradeToAnnual', {
  382. title: 'Upgrade to annual',
  383. planName
  384. })
  385. })
  386. },
  387. processUpgradeToAnnualPlan(req, res, next) {
  388. const user = AuthenticationController.getSessionUser(req)
  389. const { planName } = req.body
  390. const coupon_code = Settings.coupon_codes.upgradeToAnnualPromo[planName]
  391. const annualPlanName = `${planName}-annual`
  392. logger.log(
  393. { user_id: user._id, planName: annualPlanName },
  394. 'user is upgrading to annual billing with discount'
  395. )
  396. return SubscriptionHandler.updateSubscription(
  397. user,
  398. annualPlanName,
  399. coupon_code,
  400. function(err) {
  401. if (err != null) {
  402. logger.warn({ err, user_id: user._id }, 'error updating subscription')
  403. return next(err)
  404. }
  405. return res.sendStatus(200)
  406. }
  407. )
  408. },
  409. extendTrial(req, res, next) {
  410. const user = AuthenticationController.getSessionUser(req)
  411. return LimitationsManager.userHasV2Subscription(user, function(
  412. err,
  413. hasSubscription,
  414. subscription
  415. ) {
  416. if (err != null) {
  417. return next(err)
  418. }
  419. return SubscriptionHandler.extendTrial(subscription, 14, function(err) {
  420. if (err != null) {
  421. return res.send(500)
  422. } else {
  423. return res.send(200)
  424. }
  425. })
  426. })
  427. },
  428. recurlyNotificationParser(req, res, next) {
  429. let xml = ''
  430. req.on('data', chunk => (xml += chunk))
  431. return req.on('end', () =>
  432. RecurlyWrapper._parseXml(xml, function(error, body) {
  433. if (error != null) {
  434. return next(error)
  435. }
  436. req.body = body
  437. return next()
  438. })
  439. )
  440. },
  441. refreshUserFeatures(req, res, next) {
  442. const { user_id } = req.params
  443. return FeaturesUpdater.refreshFeatures(user_id, function(error) {
  444. if (error != null) {
  445. return next(error)
  446. }
  447. return res.sendStatus(200)
  448. })
  449. }
  450. }
  451. function __guard__(value, transform) {
  452. return typeof value !== 'undefined' && value !== null
  453. ? transform(value)
  454. : undefined
  455. }