SubscriptionController.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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 SubscriptionErrors = require('./Errors')
  33. const HttpErrors = require('@overleaf/o-error/http')
  34. module.exports = SubscriptionController = {
  35. plansPage(req, res, next) {
  36. const plans = SubscriptionViewModelBuilder.buildViewModel()
  37. let viewName = 'subscriptions/plans'
  38. if (req.query.v != null) {
  39. viewName = `${viewName}_${req.query.v}`
  40. }
  41. logger.log({ viewName }, 'showing plans page')
  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. recomendedCurrency,
  55. planFeatures,
  56. groupPlans: GroupPlansData
  57. })
  58. const user_id = AuthenticationController.getLoggedInUserId(req)
  59. if (user_id != null) {
  60. return UserGetter.getUser(user_id, { signUpDate: 1 }, function(
  61. err,
  62. user
  63. ) {
  64. if (err != null) {
  65. return next(err)
  66. }
  67. currentUser = user
  68. return render()
  69. })
  70. } else {
  71. return render()
  72. }
  73. }
  74. )
  75. },
  76. // get to show the recurly.js page
  77. paymentPage(req, res, next) {
  78. const user = AuthenticationController.getSessionUser(req)
  79. const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode)
  80. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  81. err,
  82. hasSubscription
  83. ) {
  84. if (err != null) {
  85. return next(err)
  86. }
  87. if (hasSubscription || plan == null) {
  88. return res.redirect('/user/subscription?hasSubscription=true')
  89. } else {
  90. // LimitationsManager.userHasV2Subscription only checks Mongo. Double check with
  91. // Recurly as well at this point (we don't do this most places for speed).
  92. return SubscriptionHandler.validateNoSubscriptionInRecurly(
  93. user._id,
  94. function(error, valid) {
  95. if (error != null) {
  96. return next(error)
  97. }
  98. if (!valid) {
  99. res.redirect('/user/subscription?hasSubscription=true')
  100. } else {
  101. let currency =
  102. req.query.currency != null
  103. ? req.query.currency.toUpperCase()
  104. : undefined
  105. return GeoIpLookup.getCurrencyCode(
  106. (req.query != null ? req.query.ip : undefined) || req.ip,
  107. function(err, recomendedCurrency, countryCode) {
  108. if (err != null) {
  109. return next(err)
  110. }
  111. if (recomendedCurrency != null && currency == null) {
  112. currency = recomendedCurrency
  113. }
  114. return res.render('subscriptions/new', {
  115. title: 'subscribe',
  116. plan_code: req.query.planCode,
  117. currency,
  118. countryCode,
  119. plan,
  120. showStudentPlan: req.query.ssp,
  121. recurlyConfig: JSON.stringify({
  122. currency,
  123. subdomain: Settings.apis.recurly.subdomain
  124. }),
  125. showCouponField: req.query.scf,
  126. showVatField: req.query.svf,
  127. couponCode: req.query.cc || ''
  128. })
  129. }
  130. )
  131. }
  132. }
  133. )
  134. }
  135. })
  136. },
  137. userSubscriptionPage(req, res, next) {
  138. const user = AuthenticationController.getSessionUser(req)
  139. return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
  140. user,
  141. function(error, results) {
  142. if (error != null) {
  143. return next(error)
  144. }
  145. const {
  146. personalSubscription,
  147. memberGroupSubscriptions,
  148. managedGroupSubscriptions,
  149. confirmedMemberInstitutions,
  150. managedInstitutions,
  151. managedPublishers,
  152. v1SubscriptionStatus
  153. } = results
  154. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  155. err,
  156. hasSubscription
  157. ) {
  158. if (error != null) {
  159. return next(error)
  160. }
  161. const fromPlansPage = req.query.hasSubscription
  162. logger.log(
  163. {
  164. user,
  165. hasSubscription,
  166. fromPlansPage,
  167. personalSubscription,
  168. memberGroupSubscriptions,
  169. managedGroupSubscriptions,
  170. confirmedMemberInstitutions,
  171. managedInstitutions,
  172. managedPublishers,
  173. v1SubscriptionStatus
  174. },
  175. 'showing subscription dashboard'
  176. )
  177. const plans = SubscriptionViewModelBuilder.buildViewModel()
  178. const data = {
  179. title: 'your_subscription',
  180. plans,
  181. user,
  182. hasSubscription,
  183. fromPlansPage,
  184. personalSubscription,
  185. memberGroupSubscriptions,
  186. managedGroupSubscriptions,
  187. confirmedMemberInstitutions,
  188. managedInstitutions,
  189. managedPublishers,
  190. v1SubscriptionStatus
  191. }
  192. return res.render('subscriptions/dashboard', data)
  193. })
  194. }
  195. )
  196. },
  197. createSubscription(req, res, next) {
  198. const user = AuthenticationController.getSessionUser(req)
  199. const recurlyTokenIds = {
  200. billing: req.body.recurly_token_id,
  201. threeDSecureActionResult:
  202. req.body.recurly_three_d_secure_action_result_token_id
  203. }
  204. const { subscriptionDetails } = req.body
  205. logger.log(
  206. { user_id: user._id, subscriptionDetails },
  207. 'creating subscription'
  208. )
  209. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  210. err,
  211. hasSubscription
  212. ) {
  213. if (err != null) {
  214. return next(err)
  215. }
  216. if (hasSubscription) {
  217. logger.warn({ user_id: user._id }, 'user already has subscription')
  218. res.sendStatus(409) // conflict
  219. }
  220. return SubscriptionHandler.createSubscription(
  221. user,
  222. subscriptionDetails,
  223. recurlyTokenIds,
  224. function(err) {
  225. if (!err) {
  226. return res.sendStatus(201)
  227. }
  228. if (err instanceof SubscriptionErrors.RecurlyTransactionError) {
  229. return next(
  230. new HttpErrors.UnprocessableEntityError({}).withCause(err)
  231. )
  232. }
  233. logger.warn(
  234. { err, user_id: user._id },
  235. 'something went wrong creating subscription'
  236. )
  237. next(err)
  238. }
  239. )
  240. })
  241. },
  242. successful_subscription(req, res, next) {
  243. const user = AuthenticationController.getSessionUser(req)
  244. return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
  245. user,
  246. function(error, { personalSubscription }) {
  247. if (error != null) {
  248. return next(error)
  249. }
  250. if (personalSubscription == null) {
  251. return res.redirect('/user/subscription/plans')
  252. }
  253. return res.render('subscriptions/successful_subscription', {
  254. title: 'thank_you',
  255. personalSubscription
  256. })
  257. }
  258. )
  259. },
  260. cancelSubscription(req, res, next) {
  261. const user = AuthenticationController.getSessionUser(req)
  262. logger.log({ user_id: user._id }, 'canceling subscription')
  263. return SubscriptionHandler.cancelSubscription(user, function(err) {
  264. if (err != null) {
  265. logger.warn(
  266. { err, user_id: user._id },
  267. 'something went wrong canceling subscription'
  268. )
  269. return next(err)
  270. }
  271. // Note: this redirect isn't used in the main flow as the redirection is
  272. // handled by Angular
  273. return res.redirect('/user/subscription/canceled')
  274. })
  275. },
  276. canceledSubscription(req, res, next) {
  277. const user = AuthenticationController.getSessionUser(req)
  278. return res.render('subscriptions/canceled_subscription', {
  279. title: 'subscription_canceled'
  280. })
  281. },
  282. cancelV1Subscription(req, res, next) {
  283. const user_id = AuthenticationController.getLoggedInUserId(req)
  284. logger.log({ user_id }, 'canceling v1 subscription')
  285. return V1SubscriptionManager.cancelV1Subscription(user_id, function(err) {
  286. if (err != null) {
  287. logger.warn(
  288. { err, user_id },
  289. 'something went wrong canceling v1 subscription'
  290. )
  291. return next(err)
  292. }
  293. return res.redirect('/user/subscription')
  294. })
  295. },
  296. updateSubscription(req, res, next) {
  297. const _origin =
  298. __guard__(req != null ? req.query : undefined, x => x.origin) || null
  299. const user = AuthenticationController.getSessionUser(req)
  300. const planCode = req.body.plan_code
  301. if (planCode == null) {
  302. const err = new Error('plan_code is not defined')
  303. logger.warn(
  304. { user_id: user._id, err, planCode, origin: _origin, body: req.body },
  305. '[Subscription] error in updateSubscription form'
  306. )
  307. return next(err)
  308. }
  309. logger.log({ planCode, user_id: user._id }, 'updating subscription')
  310. return SubscriptionHandler.updateSubscription(
  311. user,
  312. planCode,
  313. null,
  314. function(err) {
  315. if (err != null) {
  316. logger.warn(
  317. { err, user_id: user._id },
  318. 'something went wrong updating subscription'
  319. )
  320. return next(err)
  321. }
  322. return res.redirect('/user/subscription')
  323. }
  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. // we only care if a subscription has exipired
  343. if (
  344. req.body != null &&
  345. req.body['expired_subscription_notification'] != null
  346. ) {
  347. const recurlySubscription =
  348. req.body['expired_subscription_notification'].subscription
  349. return SubscriptionHandler.recurlyCallback(
  350. recurlySubscription,
  351. { ip: req.ip },
  352. function(err) {
  353. if (err != null) {
  354. return next(err)
  355. }
  356. return res.sendStatus(200)
  357. }
  358. )
  359. } else {
  360. return res.sendStatus(200)
  361. }
  362. },
  363. renderUpgradeToAnnualPlanPage(req, res, next) {
  364. const user = AuthenticationController.getSessionUser(req)
  365. return LimitationsManager.userHasV2Subscription(user, function(
  366. err,
  367. hasSubscription,
  368. subscription
  369. ) {
  370. let planName
  371. if (err != null) {
  372. return next(err)
  373. }
  374. const planCode =
  375. subscription != null ? subscription.planCode.toLowerCase() : undefined
  376. if ((planCode != null ? planCode.indexOf('annual') : undefined) !== -1) {
  377. planName = 'annual'
  378. } else if (
  379. (planCode != null ? planCode.indexOf('student') : undefined) !== -1
  380. ) {
  381. planName = 'student'
  382. } else if (
  383. (planCode != null ? planCode.indexOf('collaborator') : undefined) !== -1
  384. ) {
  385. planName = 'collaborator'
  386. }
  387. if (!hasSubscription) {
  388. return res.redirect('/user/subscription/plans')
  389. }
  390. logger.log(
  391. { planName, user_id: user._id },
  392. 'rendering upgrade to annual page'
  393. )
  394. return res.render('subscriptions/upgradeToAnnual', {
  395. title: 'Upgrade to annual',
  396. planName
  397. })
  398. })
  399. },
  400. processUpgradeToAnnualPlan(req, res, next) {
  401. const user = AuthenticationController.getSessionUser(req)
  402. const { planName } = req.body
  403. const coupon_code = Settings.coupon_codes.upgradeToAnnualPromo[planName]
  404. const annualPlanName = `${planName}-annual`
  405. logger.log(
  406. { user_id: user._id, planName: annualPlanName },
  407. 'user is upgrading to annual billing with discount'
  408. )
  409. return SubscriptionHandler.updateSubscription(
  410. user,
  411. annualPlanName,
  412. coupon_code,
  413. function(err) {
  414. if (err != null) {
  415. logger.warn({ err, user_id: user._id }, 'error updating subscription')
  416. return next(err)
  417. }
  418. return res.sendStatus(200)
  419. }
  420. )
  421. },
  422. extendTrial(req, res, next) {
  423. const user = AuthenticationController.getSessionUser(req)
  424. return LimitationsManager.userHasV2Subscription(user, function(
  425. err,
  426. hasSubscription,
  427. subscription
  428. ) {
  429. if (err != null) {
  430. return next(err)
  431. }
  432. return SubscriptionHandler.extendTrial(subscription, 14, function(err) {
  433. if (err != null) {
  434. return res.send(500)
  435. } else {
  436. return res.send(200)
  437. }
  438. })
  439. })
  440. },
  441. recurlyNotificationParser(req, res, next) {
  442. let xml = ''
  443. req.on('data', chunk => (xml += chunk))
  444. return req.on('end', () =>
  445. RecurlyWrapper._parseXml(xml, function(error, body) {
  446. if (error != null) {
  447. return next(error)
  448. }
  449. req.body = body
  450. return next()
  451. })
  452. )
  453. },
  454. refreshUserFeatures(req, res, next) {
  455. const { user_id } = req.params
  456. return FeaturesUpdater.refreshFeatures(user_id, function(error) {
  457. if (error != null) {
  458. return next(error)
  459. }
  460. return res.sendStatus(200)
  461. })
  462. }
  463. }
  464. function __guard__(value, transform) {
  465. return typeof value !== 'undefined' && value !== null
  466. ? transform(value)
  467. : undefined
  468. }