subscription-dashboard.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. import _ from 'lodash'
  2. /* global recurly */
  3. /* eslint-disable
  4. camelcase,
  5. max-len,
  6. no-return-assign,
  7. no-unused-vars,
  8. */
  9. // TODO: This file was created by bulk-decaffeinate.
  10. // Fix any style issues and re-enable lint.
  11. /*
  12. * decaffeinate suggestions:
  13. * DS102: Remove unnecessary code created because of implicit returns
  14. * DS104: Avoid inline assignments
  15. * DS204: Change includes calls to have a more natural evaluation order
  16. * DS207: Consider shorter variations of null checks
  17. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  18. */
  19. import App from '../base'
  20. import getMeta from '../utils/meta'
  21. const SUBSCRIPTION_URL = '/user/subscription/update'
  22. const ensureRecurlyIsSetup = _.once(() => {
  23. if (typeof recurly === 'undefined' || !recurly) {
  24. return false
  25. }
  26. recurly.configure(getMeta('ol-recurlyApiKey'))
  27. return true
  28. })
  29. App.controller('MetricsEmailController', function ($scope, $http) {
  30. $scope.institutionEmailSubscription = function (institutionId) {
  31. const inst = _.find(window.managedInstitutions, function (institution) {
  32. return institution.v1Id === parseInt(institutionId)
  33. })
  34. if (inst.metricsEmail.optedOutUserIds.includes(window.user_id)) {
  35. return 'Subscribe'
  36. } else {
  37. return 'Unsubscribe'
  38. }
  39. }
  40. $scope.changeInstitutionalEmailSubscription = function (institutionId) {
  41. $scope.subscriptionChanging = true
  42. return $http({
  43. method: 'POST',
  44. url: `/institutions/${institutionId}/emailSubscription`,
  45. headers: {
  46. 'X-CSRF-Token': window.csrfToken,
  47. },
  48. }).then(function successCallback(response) {
  49. window.managedInstitutions = _.map(
  50. window.managedInstitutions,
  51. function (institution) {
  52. if (institution.v1Id === parseInt(institutionId)) {
  53. institution.metricsEmail.optedOutUserIds = response.data
  54. }
  55. return institution
  56. }
  57. )
  58. $scope.subscriptionChanging = false
  59. })
  60. }
  61. })
  62. App.factory('RecurlyPricing', function ($q, MultiCurrencyPricing) {
  63. return {
  64. loadDisplayPriceWithTax: function (planCode, currency, taxRate) {
  65. if (!ensureRecurlyIsSetup()) return
  66. const currencySymbol = MultiCurrencyPricing.plans[currency].symbol
  67. const pricing = recurly.Pricing()
  68. return $q(function (resolve, reject) {
  69. pricing
  70. .plan(planCode, { quantity: 1 })
  71. .currency(currency)
  72. .done(function (price) {
  73. const totalPriceExTax = parseFloat(price.next.total)
  74. let taxAmount = totalPriceExTax * taxRate
  75. if (isNaN(taxAmount)) {
  76. taxAmount = 0
  77. }
  78. let total = totalPriceExTax + taxAmount
  79. if (total % 1 !== 0) {
  80. total = total.toFixed(2)
  81. }
  82. resolve({
  83. total: `${currencySymbol}${total}`,
  84. subtotal: `${currencySymbol}${totalPriceExTax.toFixed(2)}`,
  85. tax: `${currencySymbol}${taxAmount.toFixed(2)}`,
  86. includesTax: taxAmount !== 0,
  87. })
  88. })
  89. })
  90. },
  91. }
  92. })
  93. App.controller('ChangePlanToGroupFormController', function ($scope, $modal) {
  94. if (!ensureRecurlyIsSetup()) return
  95. const subscription = getMeta('ol-subscription')
  96. const currency = subscription.recurly.currency
  97. if (['USD', 'GBP', 'EUR'].includes(currency)) {
  98. $scope.isValidCurrencyForUpgrade = true
  99. }
  100. $scope.openGroupPlanModal = function () {
  101. const planCode = subscription.plan.planCode
  102. $scope.defaultGroupPlan = planCode.includes('professional')
  103. ? 'professional'
  104. : 'collaborator'
  105. $scope.currentPlanCurrency = currency
  106. $modal.open({
  107. templateUrl: 'groupPlanModalUpgradeTemplate',
  108. controller: 'GroupPlansModalUpgradeController',
  109. scope: $scope,
  110. })
  111. }
  112. })
  113. App.controller(
  114. 'GroupPlansModalUpgradeController',
  115. function ($scope, $modal, $location, $http, RecurlyPricing) {
  116. $scope.options = {
  117. plan_codes: [
  118. {
  119. display: 'Collaborator',
  120. code: 'collaborator',
  121. },
  122. {
  123. display: 'Professional',
  124. code: 'professional',
  125. },
  126. ],
  127. currencies: [
  128. {
  129. display: 'USD ($)',
  130. code: 'USD',
  131. },
  132. {
  133. display: 'GBP (£)',
  134. code: 'GBP',
  135. },
  136. {
  137. display: 'EUR (€)',
  138. code: 'EUR',
  139. },
  140. ],
  141. currencySymbols: {
  142. USD: '$',
  143. EUR: '€',
  144. GBP: '£',
  145. },
  146. sizes: [2, 3, 4, 5, 10, 20, 50],
  147. usages: [
  148. {
  149. display: 'Enterprise',
  150. code: 'enterprise',
  151. },
  152. {
  153. display: 'Educational',
  154. code: 'educational',
  155. },
  156. ],
  157. }
  158. $scope.prices = getMeta('ol-groupPlans')
  159. const currency = $scope.currentPlanCurrency
  160. // default selected
  161. $scope.selected = {
  162. plan_code: $scope.defaultGroupPlan || 'collaborator',
  163. currency,
  164. size: '10',
  165. usage: 'enterprise',
  166. }
  167. $scope.recalculatePrice = function () {
  168. const subscription = getMeta('ol-subscription')
  169. const { taxRate } = subscription.recurly
  170. const { usage, plan_code, currency, size } = $scope.selected
  171. const placeholder = { total: '...' }
  172. if (taxRate === 0) {
  173. const basePrice = $scope.prices[usage][plan_code][currency][size]
  174. const currencySymbol = $scope.options.currencySymbols[currency]
  175. placeholder.total = `${currencySymbol}${basePrice}`
  176. }
  177. $scope.displayPrice = placeholder // Placeholder while we talk to recurly
  178. const recurlyPlanCode = `group_${plan_code}_${size}_${usage}`
  179. RecurlyPricing.loadDisplayPriceWithTax(
  180. recurlyPlanCode,
  181. currency,
  182. taxRate
  183. ).then(price => {
  184. $scope.displayPrice = price
  185. })
  186. }
  187. $scope.$watch('selected', $scope.recalculatePrice, true)
  188. $scope.recalculatePrice()
  189. $scope.upgrade = function () {
  190. const { plan_code, size, usage } = $scope.selected
  191. const body = {
  192. _csrf: window.csrfToken,
  193. plan_code: `group_${plan_code}_${size}_${usage}`,
  194. }
  195. $scope.inflight = true
  196. $http
  197. .post(`/user/subscription/update`, body)
  198. .then(() => location.reload())
  199. }
  200. }
  201. )
  202. App.controller(
  203. 'ChangePlanFormController',
  204. function ($scope, $modal, RecurlyPricing) {
  205. if (!ensureRecurlyIsSetup()) return
  206. $scope.changePlan = () =>
  207. $modal.open({
  208. templateUrl: 'confirmChangePlanModalTemplate',
  209. controller: 'ConfirmChangePlanController',
  210. scope: $scope,
  211. })
  212. $scope.cancelPendingPlanChange = () =>
  213. $modal.open({
  214. templateUrl: 'cancelPendingPlanChangeModalTemplate',
  215. controller: 'CancelPendingPlanChangeController',
  216. scope: $scope,
  217. })
  218. $scope.$watch('plan', function (plan) {
  219. if (!plan) return
  220. const planCodesChangingAtTermEnd = getMeta(
  221. 'ol-planCodesChangingAtTermEnd'
  222. )
  223. $scope.planChangesAtTermEnd = false
  224. if (
  225. planCodesChangingAtTermEnd &&
  226. planCodesChangingAtTermEnd.indexOf(plan.planCode) > -1
  227. ) {
  228. $scope.planChangesAtTermEnd = true
  229. }
  230. const planCode = plan.planCode
  231. const subscription = getMeta('ol-subscription')
  232. const { currency, taxRate } = subscription.recurly
  233. $scope.price = '...' // Placeholder while we talk to recurly
  234. RecurlyPricing.loadDisplayPriceWithTax(planCode, currency, taxRate).then(
  235. price => {
  236. $scope.price = price.total
  237. }
  238. )
  239. })
  240. }
  241. )
  242. App.controller(
  243. 'ConfirmChangePlanController',
  244. function ($scope, $modalInstance, $http) {
  245. $scope.confirmChangePlan = function () {
  246. const body = {
  247. plan_code: $scope.plan.planCode,
  248. _csrf: window.csrfToken,
  249. }
  250. $scope.genericError = false
  251. $scope.inflight = true
  252. return $http
  253. .post(`${SUBSCRIPTION_URL}?origin=confirmChangePlan`, body)
  254. .then(() => location.reload())
  255. .catch(() => {
  256. $scope.genericError = true
  257. $scope.inflight = false
  258. })
  259. }
  260. return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
  261. }
  262. )
  263. App.controller(
  264. 'CancelPendingPlanChangeController',
  265. function ($scope, $modalInstance, $http) {
  266. $scope.confirmCancelPendingPlanChange = function () {
  267. const body = {
  268. _csrf: window.csrfToken,
  269. }
  270. $scope.genericError = false
  271. $scope.inflight = true
  272. return $http
  273. .post('/user/subscription/cancel-pending', body)
  274. .then(() => location.reload())
  275. .catch(() => {
  276. $scope.genericError = true
  277. $scope.inflight = false
  278. })
  279. }
  280. return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
  281. }
  282. )
  283. App.controller(
  284. 'LeaveGroupModalController',
  285. function ($scope, $modalInstance, $http) {
  286. $scope.confirmLeaveGroup = function () {
  287. $scope.inflight = true
  288. return $http({
  289. url: '/subscription/group/user',
  290. method: 'DELETE',
  291. params: {
  292. subscriptionId: $scope.subscriptionId,
  293. _csrf: window.csrfToken,
  294. },
  295. })
  296. .then(() => location.reload())
  297. .catch(() => console.log('something went wrong changing plan'))
  298. }
  299. return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
  300. }
  301. )
  302. App.controller('GroupMembershipController', function ($scope, $modal) {
  303. $scope.removeSelfFromGroup = function (subscriptionId) {
  304. $scope.subscriptionId = subscriptionId
  305. return $modal.open({
  306. templateUrl: 'LeaveGroupModalTemplate',
  307. controller: 'LeaveGroupModalController',
  308. scope: $scope,
  309. })
  310. }
  311. })
  312. App.controller('RecurlySubscriptionController', function ($scope) {
  313. const recurlyIsSetup = ensureRecurlyIsSetup()
  314. const subscription = getMeta('ol-subscription')
  315. $scope.showChangePlanButton = recurlyIsSetup && !subscription.groupPlan
  316. if (
  317. window.subscription.recurly.account.has_past_due_invoice &&
  318. window.subscription.recurly.account.has_past_due_invoice._ === 'true'
  319. ) {
  320. $scope.showChangePlanButton = false
  321. }
  322. $scope.recurlyLoadError = !recurlyIsSetup
  323. $scope.switchToDefaultView = () => {
  324. $scope.showCancellation = false
  325. $scope.showChangePlan = false
  326. }
  327. $scope.switchToDefaultView()
  328. $scope.switchToCancellationView = () => {
  329. $scope.showCancellation = true
  330. $scope.showChangePlan = false
  331. }
  332. $scope.switchToChangePlanView = () => {
  333. $scope.showCancellation = false
  334. $scope.showChangePlan = true
  335. }
  336. })
  337. App.controller(
  338. 'RecurlyCancellationController',
  339. function ($scope, RecurlyPricing, $http) {
  340. if (!ensureRecurlyIsSetup()) return
  341. const subscription = getMeta('ol-subscription')
  342. const sevenDaysTime = new Date()
  343. sevenDaysTime.setDate(sevenDaysTime.getDate() + 7)
  344. const freeTrialEndDate = new Date(subscription.recurly.trial_ends_at)
  345. const freeTrialInFuture = freeTrialEndDate > new Date()
  346. const freeTrialExpiresUnderSevenDays = freeTrialEndDate < sevenDaysTime
  347. const isMonthlyCollab =
  348. subscription.plan.planCode.indexOf('collaborator') !== -1 &&
  349. subscription.plan.planCode.indexOf('ann') === -1 &&
  350. !subscription.groupPlan
  351. const stillInFreeTrial = freeTrialInFuture && freeTrialExpiresUnderSevenDays
  352. if (isMonthlyCollab && stillInFreeTrial) {
  353. $scope.showExtendFreeTrial = true
  354. } else if (isMonthlyCollab && !stillInFreeTrial) {
  355. $scope.showDowngradeToStudent = true
  356. } else {
  357. $scope.showBasicCancel = true
  358. }
  359. const { currency, taxRate } = subscription.recurly
  360. $scope.studentPrice = '...' // Placeholder while we talk to recurly
  361. RecurlyPricing.loadDisplayPriceWithTax('student', currency, taxRate).then(
  362. price => {
  363. $scope.studentPrice = price.total
  364. }
  365. )
  366. $scope.downgradeToStudent = function () {
  367. const body = {
  368. plan_code: 'student',
  369. _csrf: window.csrfToken,
  370. }
  371. $scope.inflight = true
  372. return $http
  373. .post(`${SUBSCRIPTION_URL}?origin=downgradeToStudent`, body)
  374. .then(() => location.reload())
  375. .catch(() => console.log('something went wrong changing plan'))
  376. }
  377. $scope.cancelSubscription = function () {
  378. const body = { _csrf: window.csrfToken }
  379. $scope.inflight = true
  380. return $http
  381. .post('/user/subscription/cancel', body)
  382. .then(() => (location.href = '/user/subscription/canceled'))
  383. .catch(() => console.log('something went wrong changing plan'))
  384. }
  385. $scope.extendTrial = function () {
  386. const body = { _csrf: window.csrfToken }
  387. $scope.inflight = true
  388. return $http
  389. .put('/user/subscription/extend', body)
  390. .then(() => location.reload())
  391. .catch(() => console.log('something went wrong changing plan'))
  392. }
  393. }
  394. )