UNPKG

@nuskin/ns-checkout

Version:

Ecomm3 Checkout module

823 lines (819 loc) • 36.3 kB
//'use strict'; //import '../app.js'; //import {BuyerCookieService,UserService, AccountManager, AuthenticationService} from '@nuskin/ns-account'; //import {ConfigService, RunConfigService, PaymentType, StringService, storage, events, StickyHeaderStack, StickyHeader, StickyHeaderBoundary, util, TransBankPaymentAdapter, CurrencyCodeToNumber} from '@nuskin/ns-util'; //import {CartService, ShopContextService, LocalStorageOrderService, AdrCookieService, AdrConstants, PersonalOffer} from '@nuskin/ns-shop'; //import {AdrUtil,CartUtil,ExternalPaymentStatusEnum,ModalUtil,OrderUtil,PaymentUtil,PromoCodeOffers,qasUtil,SectionUtil,ShippingAddressUtil,StringUtil,ThreatMatrixUtil,WaitingRoomUtil} from '@nuskin/ns-checkout-common'; //angular.module('checkout').controller('PaymentCardCtrl', ['$scope','$filter','$q','$http','$location','$timeout','nsAdrOptions','nsShipping','nsTimeDelivery','nsPayment','nsProduct','nsOrder','nsUtil','nsSection','nsWaitingRoom','nsExternalPayment','nsSections','nsDowntime', 'tdcService', 'nsADRType', 'nsAdrUtil', 'nsGuestSignup', 'nsPersonalOfferStep', function($scope,$filter,$q,$http,$location,$timeout,nsAdrOptions,nsShipping,nsTimeDelivery,nsPayment,nsProduct,nsOrder,nsUtil,nsSection,nsWaitingRoom,nsExternalPayment,nsSections,nsDowntime,tdcService,nsADRType,nsAdrUtil, nsGuestSignup, nsPersonalOfferStep) { // $scope.showCheckout = storage.getItem('receiving-items') !== true; // var EXTERNAL_PAYMENT_NEXT_ORDER = "externalPaymentNextOrder"; // if (!$scope.showCheckout) { // return; // } // // $scope.forms = {}; // $scope.runConfig = RunConfigService.getRunConfig(); // $scope.buyer = BuyerCookieService.getBuyer(); // $scope.user = UserService.getUser(); // $scope.editMode = checkoutSetup.editMode; // $scope.bruneiName = checkoutSetup.bruneiName; // $scope.indonesiaName = checkoutSetup.indonesiaName; // $scope.malaysiaName = checkoutSetup.malaysiaName; // $scope.philippinesName = checkoutSetup.philippinesName; // $scope.singaporeName = checkoutSetup.singaporeName; // $scope.thailandName = checkoutSetup.thailandName; // $scope.saveSAPAddresstoProfile = false; // $scope.transBankInstallmentsBusy = false; // $scope.transBankErrorMessage = ""; // // $scope.getCartUrl = function () { // if ($scope.runConfig.cartUrl && $scope.runConfig.cartUrl.length > 0) { // return $scope.runConfig.cartUrl; // } else { // return 'cart.html'; // } // }; // // if (nsAdrUtil.showAdrShipWhen()) { // $location.path("/adrShipWhen"); // return; // } // if (AccountManager.checkOPSFlag()) { // $.cookie(AdrConstants.OPSADRCOOKIE, null, {path:'/', expires: -1}); // var adr = AdrCookieService.getAdr(); // var adrOptions = adr ? nsAdrUtil.getAdrOptions() : null; // if (adrOptions) { // nsADRType.setADRType(adr.shipImmediate ? AdrConstants.IMMEDIATE : AdrConstants.FUTURE); // } // } // // // --------------------------------------------- // // // // Private Variables // // // // --------------------------------------------- // var buyer = $scope.buyer; // var user = $scope.user; // var cart = CartService.getCart(); // // // --------------------------------------------- // // // // Public Variables // // // // --------------------------------------------- // $scope.config = ConfigService.getMarketConfig(); // $scope.tdc = tdcService.getTdc('checkout'); // $scope.PaymentType = PaymentType; // $scope.isPitchCart = (cart && cart.hasOwnProperty("isPitchCart")) ? cart.isPitchCart : false; // $scope.isGuestCheckout = $scope.isPitchCart; // // $scope.chosen = {}; // $scope.chosen.element = null; // $scope.chosen.isValid = false; // // $scope.termsConditionsCheckbox = false; // $scope.globalHeader = null; // $scope.errorHeader = null; // $scope.paymentIsWire = false; // // $scope.deleteShippingDialogId = null; // $scope.deletePaymentDialogId = null; // $scope.emailOptIn = false; // // //The following properties on scope should not be modified in a isolate scope directive // $scope.contentLoaded = false; // $scope.buyForOther = false; // $scope.isBusy = false; // $scope.forceDisableOrderButton = false; // $scope.backdatingToggle = false; // $scope.showExtraPaymentInfo = false; // // $scope.usedPoints = cart.totalOrderPoints; // $scope.showPsv = ShopContextService.showPsv($scope.buyer ? $scope.buyer.accountType : 0); // // SectionUtil.initSections($scope, nsSections, nsAdrUtil, $timeout, nsPersonalOfferStep); // // var hideProcessingIndicators = function() { // $('#mobile-processing').hide(); // $scope.isBusy = false; // }; // // // If authentication is required and the user is not authenticated we redirect back to the cart with a force login. // if (ConfigService.getMarketConfig().authenticationRequired) { // var redirectToCartPage = false; // // if (UserService.isLTOSite()){ // if (!AuthenticationService.isLoggedIn()){ // redirectToCartPage = true; // } // } // else if (!AccountManager.isLoggedIn() && !$scope.isGuestCheckout){ // redirectToCartPage = true; // } // // if (redirectToCartPage){ // window.location = $scope.getCartUrl() + "#forceLogin"; // return; // } // } // // //Redirect to order confirmation if we have received a successful externalPayment // var needToHandleExternalPayment = nsExternalPayment.needToHandleExternalPayment(); // // if (needToHandleExternalPayment) { // hideProcessingIndicators(); // // if (nsExternalPayment.handlePayment($scope.tdc, $scope.sections)) { // hideProcessingIndicators(); // return; // exit here... skip the rest of the functions // } // } // // // --------------------------------------------- // // // // Public Methods // // // // --------------------------------------------- // $scope.initAndGo = function () { // $scope.isBusy = true; // // var simulatePromiseDependencies = []; // // if (cart.isPitchCart) { // $scope.PersonalOffer = getPersonalOffer(); // } // // OrderUtil.initOrders($scope, $location, $timeout, $q, $http, nsOrder, nsProduct, nsUtil, nsWaitingRoom, nsExternalPayment, cart, simulatePromiseDependencies); // PaymentUtil.initPayments($scope, $http, nsUtil, nsPayment, nsAdrUtil, simulatePromiseDependencies, nsPersonalOfferStep); // // Special case for JP with Business Portfolio.... // if ($scope.order.simulateWithoutShipping) { // CartUtil.initializeCart(); // // For fixing the P1 production issue // $('#orderSummaryRoot').css('display', 'block'); // } else { // ShippingAddressUtil.initShippingAddresses($scope, nsUtil, nsShipping, nsTimeDelivery, $timeout, simulatePromiseDependencies, nsGuestSignup, nsPersonalOfferStep); // loadCheckout(); // } // // $scope.cuotas = $scope.order.selectedPayment && $scope.order.selectedPayment.useInstallments ? $scope.order.selectedPayment.getInstallmentSelectedNumber() : 1; // // setTimeout(function () { // if (nuskin && ConfigService.getMarketConfig().enableThreatMetrics) { // ThreatMatrixUtil.initThreatMatrixScriptUrl($scope, nsUtil); // } // }, 2000); // }; // // $scope.initShippingAddresses = function() { // ShippingAddressUtil.initShippingAddresses($scope, nsUtil, nsShipping, nsTimeDelivery, $timeout, []); // }; // // $scope.$watch('contentLoaded', function(newValue, oldValue) { // if(newValue) { // $scope.buildStickyHeaders(); // hideProcessingIndicators(); // } // }); // // function simulateWithoutShippingForJapan() { // $scope.order.simulateWithoutShipping = true; // $scope.saveSAPAddresstoProfile = true; // CartUtil.initializeCart(); // // For fixing the P1 production issue // $('#orderSummaryRoot').css('display', 'block'); // } // // $scope.buildStickyHeaders = function () { // setTimeout(function () { // if (nuskin && StickyHeader && !$scope.busyHeader) { // // // If we're inside AgeLoc, we need to watch a different scroll element // if(document.querySelector('.ageloc-wrap')) { // StickyHeaderStack.scrollWatch= '.ageloc-wrap'; // } // // StickyHeaderStack.reinitialize(); // // var headerBoundary = new StickyHeaderBoundary('#header'); // // StickyHeaderStack.stackOffsetMobile = '#header'; // // StickyHeaderStack.containment = { // // get top() { // // return headerBoundary.bottom; // // } // // }; // // // StickyHeaderStack.stackOffsetMobile = '#header'; // $scope.errorHeader = new StickyHeader('#checkoutErrorSummary .errorDialogue', { // customLeftAlignment: true, // onClick: 'scrollToOrigin' // }); // $scope.shippingError = new StickyHeader('#checkout-shipping-address .errorDialogue', { // customLeftAlignment: true, // onClick: 'scrollToOrigin' // }); // $scope.paymentError = new StickyHeader('#checkout-edit-payment .errorDialogue', { // customLeftAlignment: true, // onClick: 'scrollToOrigin' // }); // $scope.busyHeader = new StickyHeader('#busyHeader', { // customLeftAlignment: true, // onClick: 'scrollToOrigin' // }); // $scope.reviewError = new StickyHeader('#checkout-review-order .errorDialogue', { // customLeftAlignment: true, // onClick: 'scrollToOrigin' // }); // // StickyHeaderStack.$stackProxy.addClass('ns-atomic'); // } // }, 5000); // }; // // $scope.processBackToCart = function () { // $('#mobile-processing').show(); // if(StickyHeaderStack) { // StickyHeaderStack.remove(); // } // sessionStorage.setItem('appChangeSpinner', true); // window.location = isSummerPromo() ? document.referrer : $scope.getCartUrl(); // }; // // $scope.onLoadTerms = function () { // util.sanitizeEmbeddedPage(); // }; // // $scope.updateUserEmailOptInStatus = function () { // //console.log("Email Opt In = " + $scope.emailOptIn); // var userId = user.id; // var countryCode = $scope.runConfig.country; // try { // var dataObject = {"ID":userId, "EmailStatus": "normal", "CountryCode": countryCode}; // // var extendedAccountUrl = util.getValue("ConfigService.getMarketConfig().nsurl_extendedAccount", "/account-service/api/v1/account/extended/"); // $.ajax({ // url: extendedAccountUrl + userId + "?eid=" + user.eid, // type: "PUT", // data: JSON.stringify(dataObject), // crossDomain: true, // withCredentials: true, // contentType: "application/json", // headers: { // "client_id": ConfigService.getMarketConfig().checkout.clientId, // "client_secret": ConfigService.getMarketConfig().checkout.clientSecret // }, // success: function () { // console.log("Email Opt In flag updated successfully."); // }, // error: function () { // console.log("Error updating email opt in flag."); // } // }); // } catch (err) { // } // }; // // //stuff for payWithPoints // $scope.showPointsBalance = function () { // return (cart.totalOrderPoints > 0); // }; // // $scope.pointsBalance = function () { // var usedPoints = cart.totalOrderPoints; // return $scope.remainingUserPoints(usedPoints); // }; // // $scope.remainingUserPoints = function (usedPoints) { // var remainingPoints = 0; // if (!$scope.isGuestCheckout && user) { // var userAvailablePoints = user.availablePoints; // remainingPoints = userAvailablePoints - usedPoints; // } // return remainingPoints; // }; // // $scope.clearInstallments = function () { // try { // var adr = AdrCookieService.getAdr(); // if ($scope.runConfig.country == 'AR' || $scope.order.adr) { // $scope.order.selectedPayment.setInstallmentSelectedNumber(0); // $scope.order.selectedPayment.useInstallments = false; // } // } catch(err) {} // }; // // $scope.installmentNumChanged = function () { // try { // if ($scope.config.checkout.enableTransBankInstallments) { // if ($.isEmptyObject($scope.order.selectedPayment.availableInstallmentPeriods)) { // getTransBankInstallments(); // } // } else { // if ($scope.runConfig.country == 'AR') { // $scope.simulateOrder(); // } // if($scope.order.selectedPayment.getUseInstallments()) { // if($scope.order.selectedPayment.getAvailableInstallmentPeriods().length == 1) { // $scope.order.selectedPayment.installmentSelectedNumber = $scope.order.selectedPayment.getAvailableInstallmentPeriods()[0]; // } // } // } // } catch(err) {} // }; // // function getPersonalOffer() { // var PERSONAL_OFFER_LS_KEY = "personalOffer"; // var personalOfferObject = localStorage.getItem(PERSONAL_OFFER_LS_KEY); // if (personalOfferObject) { // return new PersonalOffer(JSON.parse(personalOfferObject)); // } // return null; // } // // function getTransBankInstallments() { // $scope.transBankErrorMessage = ""; // if ($scope.order.selectedPayment.useInstallments && $scope.order.selectedPayment && $scope.order.paymentSecurityNumber) { // $scope.transBankInstallmentsBusy = true; // var selectedPayment = $scope.order.selectedPayment.toJSON(); // var country = $scope.runConfig.country === "CL" ? "CHL" : $scope.runConfig.country; // var config = ConfigService.getMarketConfig(); // var transBankUrl = "/external-payment/api/v1/pspInstallments"; // var dataObject = { // cardNumber: selectedPayment.paymentNumber, // cvv: $scope.order.paymentSecurityNumber, // expirationDate: selectedPayment.expYear + selectedPayment.expMonth, // productNumber: TransBankPaymentAdapter.adaptTransBankPayment(selectedPayment.paymentTypeId), // amount: parseInt($scope.order.orderTotals.grandTotal), // currency: CurrencyCodeToNumber.getNumber($scope.order.currencyCode), // country: country // }; // $.ajax({ // type: "PUT", // url: transBankUrl, // data: JSON.stringify(dataObject), // headers: { // "client_id": config.checkout.clientId, // "client_secret": config.checkout.clientSecret // }, // contentType: "application/json", // success: setupTransBankInstallments, // error: function(xhr) { // console.error("Trans Bank Installment Error: " , xhr); // $scope.transBankErrorMessage = $scope.tdc.transBankServiceError; // $scope.order.selectedPayment.useInstallments = false; // $scope.transBankInstallmentsBusy = false; // $scope.$apply(); // } // }); // } else { // $scope.order.selectedPayment.useInstallments = false; // $scope.forms.ccvform.ccv.$setDirty(); // $scope.forms.ccvform.ccv.$validate(); // } // } // // function setupTransBankInstallments(installmentData) { // if ($.isEmptyObject(installmentData)){ // $scope.transBankErrorMessage = $scope.tdc.transBankNoApprovedInstallments; // } else { // $scope.transBankErrorMessage = ""; // $scope.order.selectedPayment.availableInstallmentPeriods = installmentData; // $scope.order.selectedPayment.installmentSelectedNumber = installmentData[0]; // } // $scope.transBankInstallmentsBusy = false; // $scope.$apply(); // } // // $scope.hideBackToCartButton = function() { // return AccountManager.checkOPSFlag() || (!$scope.sections.pre.edit && ($scope.sections.shipping.adding || $scope.sections.shipping.editing || $scope.sections.shipping.selecting || $scope.sections.payment.adding || $scope.sections.payment.editing)) // }; // // $scope.isInstallmentPaymentType = function (p) { // var rv = false; // if (p) { // switch (p.paymentTypeId) { // case PaymentType.DBS: // case PaymentType.UOB: // case PaymentType.MBB: // case PaymentType.PBB: // case PaymentType.KBANK: // case PaymentType.BCA: // case PaymentType.BDO: // case PaymentType.APVN: // rv = true; // break; // } // } // // return rv; // }; // // // --------------------------------------------- // // // // Private Methods // // // // --------------------------------------------- // function checkForDowntime() { // // Check for downtime // nsDowntime.getDowntime($scope.runConfig.country).then(function() { // if (nsDowntime.isDown()) { // window.location = 'checkout.downtimeSelection.html#/downtime'; // } else { // var goingDownInMin = nsDowntime.isGoingDownSoon(); // if (goingDownInMin > 0) { // StringService.getString('downtimeText', $scope.runConfig.language + '_' + $scope.runConfig.country, 'Shopping is going down for maintenance soon', // function(downtimeText) { // $scope.sections.general.error.addErrorMessage("info",{text: downtimeText.replace("{0}", goingDownInMin), details: ""}); // // } // ); // } // } // }); // } // // function convertSkuMaxQty() { // // skuMaxQty adjustment... // // convert sku maxQty from array of strings to json object // // from [{'sku':'00000000', 'maxQty':2}, // // {'sku':'00000001', 'maxQty':3}, // // {'sku':'00000002', 'maxQty':4}] // // to {'00000000':2, '00000001':3, '00000002':4} // if ($scope.config.skuMaxQty) { // var temp = {}; // var jsonObj; // if ($scope.config.skuMaxQty instanceof Array) { // angular.forEach($scope.config.skuMaxQty, function(item) { // try { // jsonObj = JSON.parse(item); // temp[jsonObj['sku']] = jsonObj['maxQty']; // } catch (e) { // // skip the element // } // }); // } else { // // that means it has only one... // try { // jsonObj = JSON.parse($scope.config.skuMaxQty); // temp[jsonObj['sku']] = jsonObj['maxQty']; // } catch (e) { // // skip the element // } // } // $scope.config.skuMaxQty = temp; // } // } // // function loadCheckout() { // var finish = function(){ // $('#orderSummaryRoot').css('display', 'block'); // // if ($scope.shippingAddresses && $scope.shippingAddresses.length > 0) { // CartUtil.initializeCart(); // } else if ($scope.runConfig.country === "JP") { // simulateWithoutShippingForJapan(); // } else { // //No addresses found. Open the pre section for the user to enter an address. // $scope.sections.pre.edit = true; // $scope.sections.cart.edit = false; // $scope.sections.cart.pristine = true; // $scope.contentLoaded = true; // $scope.setupNewShippingAddress(); // } // }; // // //Make sure we are ready to initialize. If we have no addresses then we need to prompt the user for an address before initialization // if ($scope.isGuestCheckout || $scope.shippingAddresses) { // // if ($scope.isPitchCart) { // nsPersonalOfferStep.callShipping($scope.PersonalOffer.sapId, $scope.PersonalOffer.pitchID); // } // // if (user && !nsUtil.isEmpty(user.eid)) { // $scope.shippingAddresses.$promise.then(function () { // finish(); // }); // } else { // finish(); // } // } // else{ // $('#orderSummaryRoot').css('display', 'block'); // } // } // // $scope.getShippingStateName = function (stateValue) { // var optionValue = $('form[name="forms.preShippingForm"] select#new_form_shippingState').find('option[value="' + stateValue + '"]'); // var stateValueName = optionValue.text(); // return stateValueName; // }; // // function apply(_callback) { // var callback = _callback || function() {}; // // if ($scope.$$phase != '$apply' && $scope.$$phase != '$digest') { // $scope.$apply(callback); // } else { // callback(); // } // } // // function loadCommonStrings() { // // Get the PSV label from the common strings // var accountType = !$scope.isGuestCheckout ? $scope.buyer.accountType : "20"; // StringService.getPsvString(accountType, // $scope.runConfig.language + '_' + $scope.runConfig.country, // function(psvLabel) { // apply(function() { // $scope.psvLabel = psvLabel; // }); // } // ); // // if(typeof $scope.tdc.buttonTextSave === "undefined") { // $scope.tdc.buttonTextSave = 'Save'; // } // if(typeof $scope.tdc.savingsText === "undefined") { // $scope.tdc.savingsText = 'Savings:'; // } // } // // function addSkuToCartAsync(options) { // // return new Promise(function(resolve) { // // CartService.addSkuToCart(options, resolve); // // }); // var deferred = $q.defer(); // CartService.addSkuToCart(options, function(response) { // deferred.resolve(response); // }); // // return deferred.promise; // } // // function buildCheckoutCart(summerPromoCart) { // let promises = []; // CartService.setCart(null); // // summerPromoCart['categoryProducts'].forEach(function(product) { // let option = { // sku: product.sku, // userId: nuskin.newAccount.UserService.getUser().id, // cntryCd: nuskin.util.countryCode, // language: nuskin.util.languageCode, // qty: product.quantity, // region: "EMEA" // }; // promises.push(addSkuToCartAsync(option)); // }); // // summerPromoCart['promoProducts'].forEach(function(product) { // let option = { // sku: product.sku, // userId: nuskin.newAccount.UserService.getUser().id, // cntryCd: nuskin.util.countryCode, // language: nuskin.util.languageCode, // qty: product.quantity, // region: "EMEA" // }; // promises.push(addSkuToCartAsync(option)); // }); // // $q.all(promises).then(function(responses) { // let areAllSuccessfulResponses = responses.every(response => response.success && response.success === true); // // if (areAllSuccessfulResponses) { // cart = CartService.getCart(); // cart.summerPromo = true; // CartService.setCart(cart); // start(); // } else { // errorHandler(summerPromoCart, "orderCouldNotBeCompletedError"); // } // }); // } // // function errorHandler(summerPromoCartJSON, errorKey){ // summerPromoCartJSON.errorMsg = errorKey; // localStorage.setItem("summerPromoCart", JSON.stringify(summerPromoCartJSON)); // window.location = document.referrer; // } // // function checkSummerPromoCart() { // var url = document.referrer.substring(0, document.referrer.indexOf(".html")) + "/jcr:content/bodyContent/summerpromo.json", // summerPromoPromise = $.ajax({ // type: "GET", // url: url, // data: {}, // contentType: "json" // }); // // summerPromoPromise.done(function(response) { // var isPresaleCart = false, // categories = [1, 2, 3], // categoriesOK = [], // summerPromoCart = localStorage.getItem("summerPromoCart"); // if (response['jcr:productsCategory1'] && response['jcr:productsCategory2'] && response['jcr:productsCategory3'] && summerPromoCart) { // var summerPromoCartJSON = JSON.parse(summerPromoCart); // if(summerPromoCartJSON['errorMsg']) { // delete summerPromoCartJSON['errorMsg']; // } // if(summerPromoCartJSON['productsOutOfStock']) { // delete summerPromoCartJSON['productsOutOfStock']; // } // localStorage.setItem("summerPromoCart", JSON.stringify(summerPromoCartJSON)); // $.each(summerPromoCartJSON['categoryProducts'], function(key, value) { // $.each(categories, function(ckey, categoryNumber) { // $.each(response['jcr:productsCategory'+categoryNumber], function(pkey, pvalue) { // if (value.sku == pvalue && value.quantity > 0) { // categoriesOK.push(categoryNumber); // } // }); // }); // $.each(response['jcr:products24hPresales'], function(presaleKey, presaleValue){ // if (value.sku == presaleValue && value.quantity > 0) { // isPresaleCart = true; // } // }); // }); // if ($.inArray("1", categoriesOK) || $.inArray("2", categoriesOK) || $.inArray("3", categoriesOK) && categoriesOK.length == JSON.parse(summerPromoCart)['categoryProducts'].length ) { // if (categoriesOK.length >= 3 || (categoriesOK.length == 1 && isPresaleCart)) { // buildCheckoutCart(summerPromoCartJSON); // } else { // errorHandler(summerPromoCartJSON, "invalidCartError"); // } // } else { // errorHandler(summerPromoCartJSON, "invalidCartError"); // } // } // }); // // return summerPromoPromise; // } // // function isSummerPromo() { // return document.referrer.indexOf("collections") > -1 ? true : false; // } // // // --------------------------------------------- // // // // Runtime code // // // // --------------------------------------------- // function setCustomerTypeMessage($scope) { // var user = UserService.getUser(); // $scope.customerTypeMessage = ""; // if (user && typeof $scope.tdc !== "undefined") { // if (user.isDistributor() && $scope.tdc.distributorReviewMessage) { // $scope.customerTypeMessage = $scope.tdc.distributorReviewMessage; // } else if (user.isPreferredCustomer() && $scope.tdc.preferredCustomerReviewMessage) { // $scope.customerTypeMessage = $scope.tdc.preferredCustomerReviewMessage; // } else if (user.isCustomer() && $scope.tdc.customerReviewMessage) { // $scope.customerTypeMessage = $scope.tdc.customerReviewMessage; // } // } else if ($scope.tdc.customerReviewMessage){ // $scope.customerTypeMessage = $scope.tdc.customerReviewMessage; // } // } // // function initListeners() { // // since subscriptions remained from each time the controller is // // called unsubscribe needs to be called beforehand. // // $.unsubscribe(events.shop.CHECKOUT_FOCUS); // $.unsubscribe(events.shop.ADR_SHIP_DAYS_CHANGED); // // $.subscribe(events.shop.ADR_SHIP_DAYS_CHANGED, function() { // apply(function() { // $scope.sections.adrOptions.pristine = true; // AdrUtil.initAdrSection(); // }); // }); // $.subscribe(events.shop.CHECKOUT_FOCUS, function(elementId) { // $timeout(function() { // $(`#${elementId}:visible`).focus(); // }, 500) // }); // } // // function start() { // if (!needToHandleExternalPayment || nsExternalPayment.getUrlPaymentStatus() !== ExternalPaymentStatusEnum.SUCCESS) { // //remove external payment next order flag // localStorage.removeItem(EXTERNAL_PAYMENT_NEXT_ORDER); // // Get the cart and make sure there are items in it, else return to the cart. // if (nsUtil.isEmpty(cart) || nsUtil.isEmpty(cart.getItems({cartItems: true}))) { // // If there are no items in cart // window.location = $scope.getCartUrl(); // return; // } // // if (buyer && user && buyer.id != user.id) { // $scope.buyForOther = true; // } // // WaitingRoomUtil.initWaitingRoom($scope, nsWaitingRoom); // checkForDowntime(); // //checkForEmailOptIn(); // CartUtil.initCart($scope, $timeout); // // $scope.modalShown1 = false; // $scope.modalShown2 = false; // $scope.toggleModal1 = function (options) { // ModalUtil.toggleModal(options, $('#checkout-edit-shipping'), $scope.modalShown1); // $scope.modalShown1 = !$scope.modalShown1; // }; // // $scope.cancelDeleteShipping = function (id) { // $scope.deleteShippingDialog = false; // $('#deleteShippingDialogDiv' + id).hide(); // }; // $scope.cancelDeletePayment = function (id) { // $scope.deletePaymentDialog = false; // $('#deletePaymentDialogDiv' + id).hide(); // }; // // $scope.setDeletePaymentDialogId = function (id) { // $scope.deletePaymentDialogId = id; // }; // // $scope.showDeletePaymentDialog = function (id) { // return $scope.deletePaymentDialogId === id; // }; // // $scope.setDeleteShippingDialogId = function (id) { // $scope.deleteShippingDialogId = id; // }; // $scope.showDeleteShippingDialog = function (id) { // return ($scope.deleteShippingDialogId === id); // }; // $scope.disablePlaceMyOrderButton = function(){ // return $scope.forceDisableOrderButton || // !($scope.sections.readyToOrder($scope.isBusy)) || // $scope.sections.payment.selecting || // $scope.sections.payment.error.hasErrorsWhichMustBeResolved() || // $scope.isSelectedPaymentEmpty() || // $scope.sections.payment.promo || // $scope.sections.shipping.adding || // $scope.sections.shipping.editing || // $scope.sections.shipping.selecting || // $scope.sections.pre.edit; // }; // $scope.placeMyOrder = function(){ // if (!$scope.disablePlaceMyOrderButton()){ // hideProcessingIndicators(); // $scope.createOrder('createButton'); // } // }; // // $scope.hidePaymentPromoCodeTable = function() { // if ($scope.runConfig.assessmentApp && $scope.config.agelocme.hidePaymentPromoCodeTable) { // return true; // } // // return false; // }; // // AdrUtil.initAdrUtil($scope, nsAdrOptions, cart, $timeout, nsADRType, nsAdrUtil, needToHandleExternalPayment); // StringUtil.initStrings($scope); // // if ($scope.config.checkout.showPaymentPromoCodeOffers) { // PromoCodeOffers.initPromoCodeOffers($scope); // } else { // PromoCodeOffers.initBasicPromoCode($scope); // } // // loadCommonStrings(); // // // Convert the SKU maxQty to JSON object (from string array) in the config file // convertSkuMaxQty(); // // //Redirect to order confirmation if we have a completed order // $scope.orderList = LocalStorageOrderService.getOrders(); // if (!nsUtil.isEmpty($scope.orderList) && !nsUtil.isEmpty($scope.orderList.getLastCompletedOrder())) { // $scope.isBusy = false; // StickyHeaderStack.remove(); // $location.path("/orderconfirmation"); // return; // } // // setCustomerTypeMessage($scope); // $scope.initAndGo(); // // // If we have processed an external payment we check if we need to display an error. // if (nsExternalPayment.hasErrorMessageForCheckoutPage()) { // $scope.isBusy = false; // nsExternalPayment.displayErrorMsg($scope.sections); // } // } // } // // function run() { // initListeners(); // if (isSummerPromo()) { // checkSummerPromoCart(); // } else { // start(); // } // } // // run(); //}]);