SubscriptionController.js 15 KB

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