SubscriptionController.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. confirmedMemberInstitutions,
  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. confirmedMemberInstitutions,
  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. 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. const event = Object.keys(req.body)[0]
  332. const eventData = req.body[event]
  333. if (
  334. [
  335. 'new_subscription_notification',
  336. 'updated_subscription_notification',
  337. 'expired_subscription_notification'
  338. ].includes(event)
  339. ) {
  340. const recurlySubscription = eventData.subscription
  341. return SubscriptionHandler.syncSubscription(
  342. recurlySubscription,
  343. { ip: req.ip },
  344. function(err) {
  345. if (err != null) {
  346. return next(err)
  347. }
  348. return res.sendStatus(200)
  349. }
  350. )
  351. } else if (event === 'billing_info_updated_notification') {
  352. const recurlyAccountCode = eventData.account.account_code
  353. return SubscriptionHandler.attemptPaypalInvoiceCollection(
  354. recurlyAccountCode,
  355. function(err) {
  356. if (err) {
  357. return next(err)
  358. }
  359. return res.sendStatus(200)
  360. }
  361. )
  362. } else {
  363. return res.sendStatus(200)
  364. }
  365. },
  366. renderUpgradeToAnnualPlanPage(req, res, next) {
  367. const user = AuthenticationController.getSessionUser(req)
  368. return LimitationsManager.userHasV2Subscription(user, function(
  369. err,
  370. hasSubscription,
  371. subscription
  372. ) {
  373. let planName
  374. if (err != null) {
  375. return next(err)
  376. }
  377. const planCode =
  378. subscription != null ? subscription.planCode.toLowerCase() : undefined
  379. if ((planCode != null ? planCode.indexOf('annual') : undefined) !== -1) {
  380. planName = 'annual'
  381. } else if (
  382. (planCode != null ? planCode.indexOf('student') : undefined) !== -1
  383. ) {
  384. planName = 'student'
  385. } else if (
  386. (planCode != null ? planCode.indexOf('collaborator') : undefined) !== -1
  387. ) {
  388. planName = 'collaborator'
  389. }
  390. if (!hasSubscription) {
  391. return res.redirect('/user/subscription/plans')
  392. }
  393. return res.render('subscriptions/upgradeToAnnual', {
  394. title: 'Upgrade to annual',
  395. planName
  396. })
  397. })
  398. },
  399. processUpgradeToAnnualPlan(req, res, next) {
  400. const user = AuthenticationController.getSessionUser(req)
  401. const { planName } = req.body
  402. const coupon_code = Settings.coupon_codes.upgradeToAnnualPromo[planName]
  403. const annualPlanName = `${planName}-annual`
  404. logger.log(
  405. { user_id: user._id, planName: annualPlanName },
  406. 'user is upgrading to annual billing with discount'
  407. )
  408. return SubscriptionHandler.updateSubscription(
  409. user,
  410. annualPlanName,
  411. coupon_code,
  412. function(err) {
  413. if (err != null) {
  414. logger.warn({ err, user_id: user._id }, 'error updating subscription')
  415. return next(err)
  416. }
  417. return res.sendStatus(200)
  418. }
  419. )
  420. },
  421. extendTrial(req, res, next) {
  422. const user = AuthenticationController.getSessionUser(req)
  423. return LimitationsManager.userHasV2Subscription(user, function(
  424. err,
  425. hasSubscription,
  426. subscription
  427. ) {
  428. if (err != null) {
  429. return next(err)
  430. }
  431. return SubscriptionHandler.extendTrial(subscription, 14, function(err) {
  432. if (err != null) {
  433. return res.send(500)
  434. } else {
  435. return res.send(200)
  436. }
  437. })
  438. })
  439. },
  440. recurlyNotificationParser(req, res, next) {
  441. let xml = ''
  442. req.on('data', chunk => (xml += chunk))
  443. return req.on('end', () =>
  444. RecurlyWrapper._parseXml(xml, function(error, body) {
  445. if (error != null) {
  446. return next(error)
  447. }
  448. req.body = body
  449. return next()
  450. })
  451. )
  452. },
  453. refreshUserFeatures(req, res, next) {
  454. const { user_id } = req.params
  455. return FeaturesUpdater.refreshFeatures(user_id, function(error) {
  456. if (error != null) {
  457. return next(error)
  458. }
  459. return res.sendStatus(200)
  460. })
  461. }
  462. }
  463. function __guard__(value, transform) {
  464. return typeof value !== 'undefined' && value !== null
  465. ? transform(value)
  466. : undefined
  467. }