SubscriptionController.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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.buildViewModel()
  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. ITMCampaign: req.query.itm_campaign,
  130. ITMContent: req.query.itm_content
  131. })
  132. }
  133. )
  134. }
  135. }
  136. )
  137. }
  138. })
  139. },
  140. userSubscriptionPage(req, res, next) {
  141. const user = AuthenticationController.getSessionUser(req)
  142. return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
  143. user,
  144. function(error, results) {
  145. if (error != null) {
  146. return next(error)
  147. }
  148. const {
  149. personalSubscription,
  150. memberGroupSubscriptions,
  151. managedGroupSubscriptions,
  152. confirmedMemberInstitutions,
  153. managedInstitutions,
  154. managedPublishers,
  155. v1SubscriptionStatus
  156. } = results
  157. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  158. err,
  159. hasSubscription
  160. ) {
  161. if (error != null) {
  162. return next(error)
  163. }
  164. const fromPlansPage = req.query.hasSubscription
  165. const plans = SubscriptionViewModelBuilder.buildViewModel()
  166. const data = {
  167. title: 'your_subscription',
  168. plans,
  169. user,
  170. hasSubscription,
  171. fromPlansPage,
  172. personalSubscription,
  173. memberGroupSubscriptions,
  174. managedGroupSubscriptions,
  175. confirmedMemberInstitutions,
  176. managedInstitutions,
  177. managedPublishers,
  178. v1SubscriptionStatus
  179. }
  180. return res.render('subscriptions/dashboard', data)
  181. })
  182. }
  183. )
  184. },
  185. createSubscription(req, res, next) {
  186. const user = AuthenticationController.getSessionUser(req)
  187. const recurlyTokenIds = {
  188. billing: req.body.recurly_token_id,
  189. threeDSecureActionResult:
  190. req.body.recurly_three_d_secure_action_result_token_id
  191. }
  192. const { subscriptionDetails } = req.body
  193. return LimitationsManager.userHasV1OrV2Subscription(user, function(
  194. err,
  195. hasSubscription
  196. ) {
  197. if (err != null) {
  198. return next(err)
  199. }
  200. if (hasSubscription) {
  201. logger.warn({ user_id: user._id }, 'user already has subscription')
  202. res.sendStatus(409) // conflict
  203. }
  204. return SubscriptionHandler.createSubscription(
  205. user,
  206. subscriptionDetails,
  207. recurlyTokenIds,
  208. function(err) {
  209. if (!err) {
  210. return res.sendStatus(201)
  211. }
  212. if (err instanceof SubscriptionErrors.RecurlyTransactionError) {
  213. return next(
  214. new HttpErrors.UnprocessableEntityError({}).withCause(err)
  215. )
  216. } else if (err instanceof Errors.InvalidError) {
  217. return next(
  218. new HttpErrors.UnprocessableEntityError({}).withCause(err)
  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. successful_subscription(req, res, next) {
  231. const user = AuthenticationController.getSessionUser(req)
  232. return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
  233. user,
  234. function(error, { personalSubscription }) {
  235. if (error != null) {
  236. return next(error)
  237. }
  238. if (personalSubscription == null) {
  239. return res.redirect('/user/subscription/plans')
  240. }
  241. return res.render('subscriptions/successful_subscription', {
  242. title: 'thank_you',
  243. personalSubscription
  244. })
  245. }
  246. )
  247. },
  248. cancelSubscription(req, res, next) {
  249. const user = AuthenticationController.getSessionUser(req)
  250. logger.log({ user_id: user._id }, 'canceling subscription')
  251. return SubscriptionHandler.cancelSubscription(user, function(err) {
  252. if (err != null) {
  253. logger.warn(
  254. { err, user_id: user._id },
  255. 'something went wrong canceling subscription'
  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. logger.warn(
  276. { err, user_id },
  277. 'something went wrong canceling v1 subscription'
  278. )
  279. return next(err)
  280. }
  281. return res.redirect('/user/subscription')
  282. })
  283. },
  284. updateSubscription(req, res, next) {
  285. const _origin =
  286. __guard__(req != null ? req.query : undefined, x => x.origin) || null
  287. const user = AuthenticationController.getSessionUser(req)
  288. const planCode = req.body.plan_code
  289. if (planCode == null) {
  290. const err = new Error('plan_code is not defined')
  291. logger.warn(
  292. { user_id: user._id, err, planCode, origin: _origin, body: req.body },
  293. '[Subscription] error in updateSubscription form'
  294. )
  295. return next(err)
  296. }
  297. logger.log({ planCode, user_id: user._id }, 'updating subscription')
  298. return SubscriptionHandler.updateSubscription(
  299. user,
  300. planCode,
  301. null,
  302. function(err) {
  303. if (err != null) {
  304. logger.warn(
  305. { err, user_id: user._id },
  306. 'something went wrong updating subscription'
  307. )
  308. return next(err)
  309. }
  310. return res.redirect('/user/subscription')
  311. }
  312. )
  313. },
  314. reactivateSubscription(req, res, next) {
  315. const user = AuthenticationController.getSessionUser(req)
  316. logger.log({ user_id: user._id }, 'reactivating subscription')
  317. return SubscriptionHandler.reactivateSubscription(user, function(err) {
  318. if (err != null) {
  319. logger.warn(
  320. { err, user_id: user._id },
  321. 'something went wrong reactivating subscription'
  322. )
  323. return next(err)
  324. }
  325. return res.redirect('/user/subscription')
  326. })
  327. },
  328. recurlyCallback(req, res, next) {
  329. logger.log({ data: req.body }, 'received recurly callback')
  330. const event = Object.keys(req.body)[0]
  331. const eventData = req.body[event]
  332. if (
  333. [
  334. 'new_subscription_notification',
  335. 'updated_subscription_notification',
  336. 'expired_subscription_notification'
  337. ].includes(event)
  338. ) {
  339. const recurlySubscription = eventData.subscription
  340. return SubscriptionHandler.syncSubscription(
  341. recurlySubscription,
  342. { ip: req.ip },
  343. function(err) {
  344. if (err != null) {
  345. return next(err)
  346. }
  347. return res.sendStatus(200)
  348. }
  349. )
  350. } else if (event === 'billing_info_updated_notification') {
  351. const recurlyAccountCode = eventData.account.account_code
  352. return SubscriptionHandler.attemptPaypalInvoiceCollection(
  353. recurlyAccountCode,
  354. function(err) {
  355. if (err) {
  356. return next(err)
  357. }
  358. return res.sendStatus(200)
  359. }
  360. )
  361. } else {
  362. return res.sendStatus(200)
  363. }
  364. },
  365. renderUpgradeToAnnualPlanPage(req, res, next) {
  366. const user = AuthenticationController.getSessionUser(req)
  367. return LimitationsManager.userHasV2Subscription(user, function(
  368. err,
  369. hasSubscription,
  370. subscription
  371. ) {
  372. let planName
  373. if (err != null) {
  374. return next(err)
  375. }
  376. const planCode =
  377. subscription != null ? subscription.planCode.toLowerCase() : undefined
  378. if ((planCode != null ? planCode.indexOf('annual') : undefined) !== -1) {
  379. planName = 'annual'
  380. } else if (
  381. (planCode != null ? planCode.indexOf('student') : undefined) !== -1
  382. ) {
  383. planName = 'student'
  384. } else if (
  385. (planCode != null ? planCode.indexOf('collaborator') : undefined) !== -1
  386. ) {
  387. planName = 'collaborator'
  388. }
  389. if (!hasSubscription) {
  390. return res.redirect('/user/subscription/plans')
  391. }
  392. return res.render('subscriptions/upgradeToAnnual', {
  393. title: 'Upgrade to annual',
  394. planName
  395. })
  396. })
  397. },
  398. processUpgradeToAnnualPlan(req, res, next) {
  399. const user = AuthenticationController.getSessionUser(req)
  400. const { planName } = req.body
  401. const coupon_code = Settings.coupon_codes.upgradeToAnnualPromo[planName]
  402. const annualPlanName = `${planName}-annual`
  403. logger.log(
  404. { user_id: user._id, planName: annualPlanName },
  405. 'user is upgrading to annual billing with discount'
  406. )
  407. return SubscriptionHandler.updateSubscription(
  408. user,
  409. annualPlanName,
  410. coupon_code,
  411. function(err) {
  412. if (err != null) {
  413. logger.warn({ err, user_id: user._id }, 'error updating subscription')
  414. return next(err)
  415. }
  416. return res.sendStatus(200)
  417. }
  418. )
  419. },
  420. extendTrial(req, res, next) {
  421. const user = AuthenticationController.getSessionUser(req)
  422. return LimitationsManager.userHasV2Subscription(user, function(
  423. err,
  424. hasSubscription,
  425. subscription
  426. ) {
  427. if (err != null) {
  428. return next(err)
  429. }
  430. return SubscriptionHandler.extendTrial(subscription, 14, function(err) {
  431. if (err != null) {
  432. return res.send(500)
  433. } else {
  434. return res.send(200)
  435. }
  436. })
  437. })
  438. },
  439. recurlyNotificationParser(req, res, next) {
  440. let xml = ''
  441. req.on('data', chunk => (xml += chunk))
  442. return req.on('end', () =>
  443. RecurlyWrapper._parseXml(xml, function(error, body) {
  444. if (error != null) {
  445. return next(error)
  446. }
  447. req.body = body
  448. return next()
  449. })
  450. )
  451. },
  452. refreshUserFeatures(req, res, next) {
  453. const { user_id } = req.params
  454. return FeaturesUpdater.refreshFeatures(user_id, function(error) {
  455. if (error != null) {
  456. return next(error)
  457. }
  458. return res.sendStatus(200)
  459. })
  460. }
  461. }
  462. function __guard__(value, transform) {
  463. return typeof value !== 'undefined' && value !== null
  464. ? transform(value)
  465. : undefined
  466. }