subscription-dashboard.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. var 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 taxAmmount = totalPriceExTax * taxRate
  75. if (isNaN(taxAmmount)) {
  76. taxAmmount = 0
  77. }
  78. let total = totalPriceExTax + taxAmmount
  79. if (total % 1 !== 0) {
  80. total = total.toFixed(2)
  81. }
  82. resolve(`${currencySymbol}${total}`)
  83. })
  84. })
  85. },
  86. }
  87. })
  88. App.controller('ChangePlanToGroupFormController', function ($scope, $modal) {
  89. if (!ensureRecurlyIsSetup()) return
  90. const subscription = getMeta('ol-subscription')
  91. const currency = subscription.recurly.currency
  92. if (['USD', 'GBP', 'EUR'].includes(currency)) {
  93. $scope.isValidCurrencyForUpgrade = true
  94. }
  95. $scope.openGroupPlanModal = function () {
  96. const planCode = subscription.plan.planCode
  97. $scope.defaultGroupPlan = planCode.includes('professional')
  98. ? 'professional'
  99. : 'collaborator'
  100. $scope.currentPlanCurrency = currency
  101. $modal.open({
  102. templateUrl: 'groupPlanModalUpgradeTemplate',
  103. controller: 'GroupPlansModalUpgradeController',
  104. scope: $scope,
  105. })
  106. }
  107. })
  108. App.controller(
  109. 'GroupPlansModalUpgradeController',
  110. function ($scope, $modal, $location, $http) {
  111. $scope.options = {
  112. plan_codes: [
  113. {
  114. display: 'Collaborator',
  115. code: 'collaborator',
  116. },
  117. {
  118. display: 'Professional',
  119. code: 'professional',
  120. },
  121. ],
  122. currencies: [
  123. {
  124. display: 'USD ($)',
  125. code: 'USD',
  126. },
  127. {
  128. display: 'GBP (£)',
  129. code: 'GBP',
  130. },
  131. {
  132. display: 'EUR (€)',
  133. code: 'EUR',
  134. },
  135. ],
  136. currencySymbols: {
  137. USD: '$',
  138. EUR: '€',
  139. GBP: '£',
  140. },
  141. sizes: [2, 3, 4, 5, 10, 20, 50],
  142. usages: [
  143. {
  144. display: 'Enterprise',
  145. code: 'enterprise',
  146. },
  147. {
  148. display: 'Educational',
  149. code: 'educational',
  150. },
  151. ],
  152. }
  153. $scope.prices = getMeta('ol-groupPlans')
  154. const currency = $scope.currentPlanCurrency
  155. // default selected
  156. $scope.selected = {
  157. plan_code: $scope.defaultGroupPlan || 'collaborator',
  158. currency,
  159. size: '10',
  160. usage: 'enterprise',
  161. }
  162. $scope.recalculatePrice = function () {
  163. const { usage, plan_code, currency, size } = $scope.selected
  164. const price = $scope.prices[usage][plan_code][currency][size]
  165. const currencySymbol = $scope.options.currencySymbols[currency]
  166. $scope.displayPrice = `${currencySymbol}${price}`
  167. }
  168. $scope.$watch('selected', $scope.recalculatePrice, true)
  169. $scope.recalculatePrice()
  170. $scope.upgrade = function () {
  171. const { plan_code, size, usage } = $scope.selected
  172. const body = {
  173. _csrf: window.csrfToken,
  174. plan_code: `group_${plan_code}_${size}_${usage}`,
  175. }
  176. $scope.inflight = true
  177. $http
  178. .post(`/user/subscription/update`, body)
  179. .then(() => location.reload())
  180. }
  181. }
  182. )
  183. App.controller(
  184. 'ChangePlanFormController',
  185. function ($scope, $modal, RecurlyPricing) {
  186. if (!ensureRecurlyIsSetup()) return
  187. $scope.changePlan = () =>
  188. $modal.open({
  189. templateUrl: 'confirmChangePlanModalTemplate',
  190. controller: 'ConfirmChangePlanController',
  191. scope: $scope,
  192. })
  193. $scope.cancelPendingPlanChange = () =>
  194. $modal.open({
  195. templateUrl: 'cancelPendingPlanChangeModalTemplate',
  196. controller: 'CancelPendingPlanChangeController',
  197. scope: $scope,
  198. })
  199. $scope.$watch('plan', function (plan) {
  200. if (!plan) return
  201. const planCodesChangingAtTermEnd = getMeta(
  202. 'ol-planCodesChangingAtTermEnd'
  203. )
  204. $scope.planChangesAtTermEnd = false
  205. if (
  206. planCodesChangingAtTermEnd &&
  207. planCodesChangingAtTermEnd.indexOf(plan.planCode) > -1
  208. ) {
  209. $scope.planChangesAtTermEnd = true
  210. }
  211. const planCode = plan.planCode
  212. const subscription = getMeta('ol-subscription')
  213. const { currency, taxRate } = subscription.recurly
  214. $scope.price = '...' // Placeholder while we talk to recurly
  215. RecurlyPricing.loadDisplayPriceWithTax(planCode, currency, taxRate).then(
  216. price => {
  217. $scope.price = price
  218. }
  219. )
  220. })
  221. }
  222. )
  223. App.controller(
  224. 'ConfirmChangePlanController',
  225. function ($scope, $modalInstance, $http) {
  226. $scope.confirmChangePlan = function () {
  227. const body = {
  228. plan_code: $scope.plan.planCode,
  229. _csrf: window.csrfToken,
  230. }
  231. $scope.genericError = false
  232. $scope.inflight = true
  233. return $http
  234. .post(`${SUBSCRIPTION_URL}?origin=confirmChangePlan`, body)
  235. .then(() => location.reload())
  236. .catch(() => {
  237. $scope.genericError = true
  238. $scope.inflight = false
  239. })
  240. }
  241. return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
  242. }
  243. )
  244. App.controller(
  245. 'CancelPendingPlanChangeController',
  246. function ($scope, $modalInstance, $http) {
  247. $scope.confirmCancelPendingPlanChange = function () {
  248. const body = {
  249. _csrf: window.csrfToken,
  250. }
  251. $scope.genericError = false
  252. $scope.inflight = true
  253. return $http
  254. .post('/user/subscription/cancel-pending', body)
  255. .then(() => location.reload())
  256. .catch(() => {
  257. $scope.genericError = true
  258. $scope.inflight = false
  259. })
  260. }
  261. return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
  262. }
  263. )
  264. App.controller(
  265. 'LeaveGroupModalController',
  266. function ($scope, $modalInstance, $http) {
  267. $scope.confirmLeaveGroup = function () {
  268. $scope.inflight = true
  269. return $http({
  270. url: '/subscription/group/user',
  271. method: 'DELETE',
  272. params: {
  273. subscriptionId: $scope.subscriptionId,
  274. _csrf: window.csrfToken,
  275. },
  276. })
  277. .then(() => location.reload())
  278. .catch(() => console.log('something went wrong changing plan'))
  279. }
  280. return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
  281. }
  282. )
  283. App.controller('GroupMembershipController', function ($scope, $modal) {
  284. $scope.removeSelfFromGroup = function (subscriptionId) {
  285. $scope.subscriptionId = subscriptionId
  286. return $modal.open({
  287. templateUrl: 'LeaveGroupModalTemplate',
  288. controller: 'LeaveGroupModalController',
  289. scope: $scope,
  290. })
  291. }
  292. })
  293. App.controller('RecurlySubscriptionController', function ($scope) {
  294. const recurlyIsSetup = ensureRecurlyIsSetup()
  295. const subscription = getMeta('ol-subscription')
  296. $scope.showChangePlanButton = recurlyIsSetup && !subscription.groupPlan
  297. if (
  298. window.subscription.recurly.account.has_past_due_invoice &&
  299. window.subscription.recurly.account.has_past_due_invoice._ === 'true'
  300. ) {
  301. $scope.showChangePlanButton = false
  302. }
  303. $scope.recurlyLoadError = !recurlyIsSetup
  304. $scope.switchToDefaultView = () => {
  305. $scope.showCancellation = false
  306. $scope.showChangePlan = false
  307. }
  308. $scope.switchToDefaultView()
  309. $scope.switchToCancellationView = () => {
  310. $scope.showCancellation = true
  311. $scope.showChangePlan = false
  312. }
  313. $scope.switchToChangePlanView = () => {
  314. $scope.showCancellation = false
  315. $scope.showChangePlan = true
  316. }
  317. })
  318. App.controller(
  319. 'RecurlyCancellationController',
  320. function ($scope, RecurlyPricing, $http) {
  321. if (!ensureRecurlyIsSetup()) return
  322. const subscription = getMeta('ol-subscription')
  323. const sevenDaysTime = new Date()
  324. sevenDaysTime.setDate(sevenDaysTime.getDate() + 7)
  325. const freeTrialEndDate = new Date(subscription.recurly.trial_ends_at)
  326. const freeTrialInFuture = freeTrialEndDate > new Date()
  327. const freeTrialExpiresUnderSevenDays = freeTrialEndDate < sevenDaysTime
  328. const isMonthlyCollab =
  329. subscription.plan.planCode.indexOf('collaborator') !== -1 &&
  330. subscription.plan.planCode.indexOf('ann') === -1 &&
  331. !subscription.groupPlan
  332. const stillInFreeTrial = freeTrialInFuture && freeTrialExpiresUnderSevenDays
  333. if (isMonthlyCollab && stillInFreeTrial) {
  334. $scope.showExtendFreeTrial = true
  335. } else if (isMonthlyCollab && !stillInFreeTrial) {
  336. $scope.showDowngradeToStudent = true
  337. } else {
  338. $scope.showBasicCancel = true
  339. }
  340. const { currency, taxRate } = subscription.recurly
  341. $scope.studentPrice = '...' // Placeholder while we talk to recurly
  342. RecurlyPricing.loadDisplayPriceWithTax('student', currency, taxRate).then(
  343. price => {
  344. $scope.studentPrice = price
  345. }
  346. )
  347. $scope.downgradeToStudent = function () {
  348. const body = {
  349. plan_code: 'student',
  350. _csrf: window.csrfToken,
  351. }
  352. $scope.inflight = true
  353. return $http
  354. .post(`${SUBSCRIPTION_URL}?origin=downgradeToStudent`, body)
  355. .then(() => location.reload())
  356. .catch(() => console.log('something went wrong changing plan'))
  357. }
  358. $scope.cancelSubscription = function () {
  359. const body = { _csrf: window.csrfToken }
  360. $scope.inflight = true
  361. return $http
  362. .post('/user/subscription/cancel', body)
  363. .then(() => (location.href = '/user/subscription/canceled'))
  364. .catch(() => console.log('something went wrong changing plan'))
  365. }
  366. $scope.extendTrial = function () {
  367. const body = { _csrf: window.csrfToken }
  368. $scope.inflight = true
  369. return $http
  370. .put('/user/subscription/extend', body)
  371. .then(() => location.reload())
  372. .catch(() => console.log('something went wrong changing plan'))
  373. }
  374. }
  375. )