SubscriptionController.js 16 KB

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