(function() { "use strict"; var app = angular.module("subscriptions"); var templatePath = modulesSharedResourcesUrl + "Modules/Subscriptions/Views/"; var symbols = { gbp: "£", usd: "$", eur: "€" }; var frequencyDict = { day: "Daily", month: "Monthly", year: "Annually" } app.directive("manageSubscription", [ "subscriptionsConfig", "common", "$location", "$modal", "$q", "subscriptionsService", "subscriptionsDataContext", function( config, common, $location, $modal, $q, subscriptionsService, subscriptionsDataContext ) { return { restrict: "E", templateUrl: templatePath + "manage.html", link: link }; function link($scope, elem, attrs) { var getLogFn = common.logger.getLogFn; var log = getLogFn("badgesDashboard"); var logSuccess = getLogFn("badgesDashboard", "success"); activate(); function activate() { NProgress.done(); log("Activated Subscriptions View"); } } } ]); app.directive("chooseSubscription", [ "subscriptionsConfig", "common", "$location", "$modal", "$q", "subscriptionsService", "subscriptionsDataContext", "paymentsDataContext", "$filter", function( config, common, $location, $modal, $q, subscriptionsService, subscriptionsDataContext, paymentsDataContext, $filter ) { return { restrict: "E", //TODO: Conditional templateUrl based on the appCode, eg OB. templateUrl: templatePath + "chooseOB.html", link: link }; function link($scope, elem, attrs) { var getLogFn = common.logger.getLogFn; var log = getLogFn("badgesDashboard"); var logSuccess = getLogFn("badgesDashboard", "success"); $scope.groups = {}; activate(); $scope.currency = "usd"; $scope.symbols = symbols; $scope.frequencies = frequencyDict; $scope.currentPlan = "Starter"; $scope.frequency = "month"; $scope.ready = false; $scope.cantChangeCurrency = false; $scope.cantChangeFrequency = false; function activate() { NProgress.done(); $q .all([ paymentsDataContext.getGroupedPlans(), paymentsDataContext.getCurrentPaymentDetails() ]) .then(function(data) { $scope.groups = data[0].plans; $scope.availableCurrencies = data[0].currencies; $scope.availableFrequencies = data[0].frequencies; $scope.ready = true; if (data[1]) { if (data[1].groupName != $scope.currentPlan) { $scope.paymentDetails = data[1]; $scope.currentPlan = $scope.paymentDetails.groupName; $scope.currency = $scope.paymentDetails.currency; $scope.frequency = $scope.paymentDetails.frequency; $scope.cantChangeCurrency = true; $scope.cantChangeFrequency = true; } } else { //get the free plan details } }); log("Activated Choose Subscriptions View"); } } } ]); app.directive("upgradeSubscription", [ "subscriptionsConfig", "common", "$location", "$modal", "$q", "subscriptionsService", "subscriptionsDataContext", "paymentsDataContext", "$filter", "$window", "OrganisationAdminService", "user", function( config, common, $location, $modal, $q, subscriptionsService, subscriptionsDataContext, paymentsDataContext, $filter, $window, orgAdminService, user ) { return { restrict: "E", //TODO: Conditional templateUrl based on the appCode, eg OB. templateUrl: templatePath + "upgrade.html", scope: { planId: "=" }, link: link }; function link($scope, elem, attrs) { var getLogFn = common.logger.getLogFn; var log = getLogFn("badgesDashboard"); var logSuccess = getLogFn("badgesDashboard", "success"); $scope.groups = {}; $scope.holder = {}; $scope.change = false; $scope.currency = "usd"; $scope.symbols = symbols; $scope.busy = true; $scope.currentPlan = "Starter"; $scope.frequency = "month"; $scope.date = moment().add(1,'day'); $scope.frequencies = frequencyDict; $scope.pricing = {}; $scope.costTotal = ""; $scope.discountAmount = 0; $scope.billing = {}; $scope.ready = false; $scope.cardIsValid = false; $scope.stripe = Stripe(config.publicKey); activate(); $scope.setValues = function() { var currency = $scope.symbols[$scope.currency]; $scope.NormalInvoice = $scope.pricing.Results.NormalInvoice; $scope.NextInvoice = $scope.pricing.Results.NextInvoice; if ($scope.frequency === "year") { $scope.discountAmount = $scope.groups[$scope.id].currency[$scope.currency]["month"].cost * 12 - $scope.pricing.Results.NextInvoice.SubTotal; $scope.discount = "-" + currency + $scope.discountAmount; $scope.NormalInvoice.SubTotal = $scope.NormalInvoice.SubTotal + $scope.discountAmount; } $scope.busy = false; }; $scope.setCountry = function(){ if (!$scope.billing.countryCode) { subscriptionsDataContext.getUsersCountry().then(function (data) { $scope.billing.countryCode = data.country; //$scope.calculateValues(); }); } } $scope.calculateValues = function() { $scope.busy = true; $scope.plan = $scope.groups[$scope.id].currency[$scope.currency][ $scope.frequency ]; //TODO: Communicate with stripe. paymentsDataContext .previewPlanUpgrade({ planId: $scope.plan.id, vatCode: $scope.billing.vatId, countryCode: $scope.billing.countryCode }) .then(function(data) { $scope.pricing = data; $scope.setValues(); }); }; $scope.purchase = function() { $scope.busy = true; if ($scope.change) { var stripe = $scope.stripe; return paymentsDataContext .planUpgrade($scope.pricing.Token) .then(function() { //Redirect to root window.location = sysUrl + "#!/dashboard?upgraded=" + $scope.plan.id; $scope.busy = false; return $window.location.reload(); }, function (error) { if (angular.isObject(error) && error.Status == "requires_action") { stripe.handleCardPayment( error.RedirectUrl ).then(function (result) { if (result.error) { // Show error in payment form } else { return paymentsDataContext .planUpgrade($scope.pricing.Token, error.ExternalId) .then(function () { //Redirect to root window.location = sysUrl + "#!/dashboard?upgraded=" + $scope.plan.id; $scope.busy = false; return $window.location.reload(); }, function (error) { $scope.busy = false; $scope.error = error; }); } }); } else { $scope.busy = false; $scope.error = error; } }); } else { var stripe = $scope.stripe; var card = $scope.card; stripe .createPaymentMethod('card', card, { billing_details: { name: $scope.billing.cardholderName, address: { line1: $scope.billing.line1, line2: $scope.billing.line2, city: $scope.billing.city, state: $scope.billing.region, postal_code: $scope.billing.postCode, country: $scope.billing.countryCode } } }) .then(function(result) { if (result.error) { // Inform the user if there was an error. var errorElement = document.getElementById("card-errors"); errorElement.textContent = result.error.message; } else { // Send the token to your server. var additionalProperties = paymentsDataContext.getAdditionalProperties(); additionalProperties["Token"] = result.paymentMethod.id; additionalProperties["countryCode"] = $scope.billing.countryCode; if ($scope.billing.vatId != '') { additionalProperties["vatCode"] = $scope.billing.vatId; } else { if (additionalProperties.hasOwnProperty('vatCode')) { delete additionalProperties.vatCode; } } paymentsDataContext.setAdditionalProperties( additionalProperties ); paymentsDataContext.setSelectedPlan($scope.plan); return paymentsDataContext.sendRequest(true).then(function() { //Redirect to root window.location = sysUrl + "#!/dashboard?upgraded=" + $scope.plan.id; $scope.busy = false; return $window.location.reload(); }, function (error) { if (angular.isObject(error) && error.Status == "requires_action") { stripe.handleCardPayment( error.RedirectUrl ).then(function (result) { if (result.error) { // Show error in payment form } else { return paymentsDataContext.sendRequest(true).then(function () { //Redirect to root window.location = sysUrl + "#!/dashboard?upgraded=" + $scope.plan.id; $scope.busy = false; return $window.location.reload(); }, function (error) { $scope.busy = false; $scope.error = error; }); } }); } else { $scope.busy = false; $scope.error = error; } }); } }); } }; function activate() { NProgress.done(); //At this point we need to create a stripe account if it doesn't exist. $q .all([ paymentsDataContext.getGroupedPlans(), paymentsDataContext.getPlan($scope.planId), paymentsDataContext.getCurrentPaymentDetails(), paymentsDataContext.previewPlanUpgrade({ planId: $scope.planId }), orgAdminService.getTopLevelOrg(), user.getProfile() ]) .then(function(data) { $scope.groups = data[0].plans; $scope.availableCurrencies = data[0].currencies; $scope.availableFrequencies = data[0].frequencies; $scope.plan = data[1]; $scope.id = data[1].groupName; $scope.currency = $scope.plan.currency; $scope.frequency = $scope.plan.frequency; $scope.change = false; if (data[2] != null) { if (data[2].groupName != $scope.currentPlan) { $scope.currentPlan = data[2].groupName; $scope.change = true; $scope.upgrade = data[3].Results.NextInvoice.Total > 0; $scope.cantChangeCurrency = true; $scope.cantChangeFrequency = true; $scope.last4 = data[2].lastFour; $scope.cardIsValid = true; //$scope.billingForm.$invalid = false; $scope.date = data[2].paymentAttemptDate } } $scope.pricing = data[3]; $scope.billing.organisationName = data[4].name; $scope.billing.cardholderName = data[5].firstName + " " + data[5].lastName; $scope.setValues(); angular.forEach($scope.groups, function(group, id) { if (group.freePlan) { group.disabled = true; } if (id == $scope.currentPlan) { group.disabled = true; } }); if (!$scope.change) { var stripe = $scope.stripe; var options = { cssSrc: 'https://fonts.googleapis.com/css?family=Open+Sans', family: 'Open Sans' } var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. // (Note that this demo uses a wider set of styles than the guide below.) var style = { base: { color: "#515151", lineHeight: "18px", fontFamily: "'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif", fontSmoothing: "antialiased", fontSize: "13px", "::placeholder": { color: "#8f9ea6" } }, invalid: { color: "#fa755a", iconColor: "#fa755a" } }; // Create an instance of the card Element. var card = elements.create("card", { style: style, hidePostalCode: true }); // Add an instance of the card Element into the `card-element`
. card.mount("#card-element"); // Handle real-time validation errors from the card Element. card.addEventListener("change", function(event) { var displayError = document.getElementById("card-errors"); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ""; } $scope.cardIsValid = event.complete; }); $scope.card = card; } $scope.busy = false; $scope.ready = true; }); log("Activated Choose Subscriptions View"); } } } ]); app.directive("viewSubscription", [ "subscriptionsConfig", "common", "$location", "$modal", "$q", "subscriptionsService", "subscriptionsDataContext", "paymentsDataContext", "$filter", "$window", "licencingAdminDataContext", "user", function( config, common, $location, $modal, $q, subscriptionsService, subscriptionsDataContext, paymentsDataContext, $filter, $window, licContext, user ) { return { restrict: "E", //TODO: Conditional templateUrl based on the appCode, eg OB. templateUrl: templatePath + "details.html", scope: { cantUpgradePlanId: "=" }, link: link }; function link($scope, elem, attrs) { var getLogFn = common.logger.getLogFn; var log = getLogFn("badgesDashboard"); var logSuccess = getLogFn("badgesDashboard", "success"); activate(); $scope.symbols = symbols; $scope.vm = $scope; $scope.billing = {}; $scope.stripe = Stripe(config.publicKey); var vm = $scope.vm; vm.ready = false; vm.canUpgrade = true; function activate() { NProgress.done(); //At this point we need to create a stripe account if it doesn't exist. $q .all([ licContext.getCurrentLicense(), paymentsDataContext.getCurrentPaymentDetails(), paymentsDataContext.getCurrencyOptions(), paymentsDataContext.getInvoices(), user.getProfile() ]) .then(function(data) { vm.licence = data[0]; if (data[1]) { vm.paymentDetails = data[1]; } else { //get the free plan details } //don't hardcode the planIds if (vm.paymentDetails.groupName == $scope.cantUpgradePlanId) { vm.canUpgrade = false; } vm.invoices = data[3]; vm.user = data[4]; vm.doesAccountPayVAT = vm.paymentDetails.taxRate != null; vm.ready = true; }); log("Activated View Subscription View"); } vm.cancel = function() { return licContext.showCancelModal(); }; vm.cancelDowngrade = function() { return licContext.showCancelDowngradeModal(); }; vm.upgrade = function(planId, userAmount) { return licContext.showSelectorModal(); }; vm.change = function() { return licContext.showUpgradeModal(); }; vm.enable = function() { return licContext.showReenableModal(); }; vm.restart = function() { return licContext.showRestartModal(); }; vm.confirmInvoice = function (invoice) { vm.ready = false; var stripe = $scope.stripe; return stripe.handleCardPayment( invoice.PaymentSecret ).then(function () { return paymentsDataContext.getInvoices().then(function (data) { vm.invoices = data; vm.ready = true; }); }); }; vm.changePaymentDetails = function(includeBillingAddress) { /*return paymentsDataContext.changeCard(vm.user.emailAddress).then(function () { return paymentsDataContext.getCurrentPaymentDetails().then(function (data) { vm.paymentDetails = data; }); });*/ //Stripe needs a redirect return paymentsDataContext.changeCard( vm.user.email.email, includeBillingAddress ); }; function getStatusShortcode(paymentDetails) { var status = paymentDetails.status.toLowerCase(); if (status.indexOf("active") >= 0) paymentDetails.statusShortCode = 1; else if (status.indexOf("cancelling") >= 0) paymentDetails.statusShortCode = 2; else paymentDetails.statusShortCode = 0; // free or cancelled we dont need to display differently currently } } } ]); })();