{"version":3,"file":"product-detail.bundle.js","sources":["webpack://neighborstore_b2b/./node_modules/sweetalert2/dist/sweetalert2.all.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/modal-helper.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/browser-communicator/alerts/domain/alert-types.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/checkout-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/app.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/wait-handler.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/effects-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/product-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/cart-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/journey/journey-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/handler/handler-base.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/url-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/proxies/ajax.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/proxies/ajax-proxy.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/services/tracker-service.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/domain/AnalyticsConstants.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/parameters-resolve/banner-parameters-resolve.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/singleton/firebaseApp.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/services/trackers/google/google-tracker.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/services/trackers/clevertap/clevertapApp.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/services/trackers/clevertap/related-product-parameters-resolve.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/services/trackers/clevertap/clevertap-tracker.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/helpers/trackerList.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/browser-communicator/alerts/plugin/plugins/sweetalert/helper.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/browser-communicator/alerts/plugin/plugins/sweetalert/sweetalert-alert-plugin.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/browser-communicator/alerts/plugin/plugins/sweetalert/sweetalert-toast-plugin.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/browser-communicator/alerts/service/alerts-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/enums/site-enum.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/service/service-base.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/services/shopping-cart-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/browser-communicator-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/shopping-cart-load-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/events/added-product-kit-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/replicate-order/events/order-replicated-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/favorite-list/events/added-product-favorite-list-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/update-product-prices-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/update-product-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/store/events/added-product-catalog-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/more-product-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/less-product-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/remove-product-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/set-quantity-product-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/empty-cart-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/related-product/events/added-product-related-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/product-card/events/added-product-detail-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/added-predictive-search-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/events/toggle-shopping-cart-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/shopping-cart/handlers/shopping-cart-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/account-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/application-monitoring/services/application-monitoring-service.js","webpack://neighborstore_b2b/./node_modules/apollo-web/dist/analytics/services/application-monitoring-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/app-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/helper/customer-analytics-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/notification-orders/services/notification-orders-services.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/notification-orders/handlers/notification-orders-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/address-management/events/load-view-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/menu-nav-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/product-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/index-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/bonus-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/bonus-loader-handler.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/bonus-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/store-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/cache/cache-service-base.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/culture/services/culture-settings-cache-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/culture/services/culture-formatter-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/constants/product-constants.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/predictive-search-product-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/events/add-product-kit-search-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/product-detail/services/product-detail-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/helper/product-analytics-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/app-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/components/wizard/wizard-form.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/customer-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/cancel-order/services/cancel-orders-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/cancel-order/shared/order-ids-storage.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/cancel-order/handlers/cancel-orders-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/coupons/events/on-checked-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/coupons/handlers/store-coupon-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/external-orders/services/external-order-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/rating/shared/services/rating-service-base.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/rating/services/rating-transporter-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/rating/shared/constants/rating-types.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/rating/shared/handlers/rating-handler-base.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/rating/handlers/rating-transporter-handler.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/external-orders/handlers/external-order-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/history-payments/services/history-payments-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/history-payments/handlers/history-payments-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/rating/services/rating-seller-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/rating/handlers/rating-seller-handler.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/replicate-order/handlers/replicate-orders-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/customer-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/chat-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/checkout-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/verification-code-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/verification-code-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/marking-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/marking-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/marking-byproduct-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/abstracts/twofa-servicebase.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/twofa-changepassword-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/abstract/twofa-handlerbase.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/twofa-changepassword-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/twofa-genericuser-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/twofa-genericuser-handler.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/twofa-additionalinformation-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/handlers/twofa-additionalinformation-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/helper/forgeryTokenHelper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/credit-card/services/credit-card-service.js","webpack://neighborstore_b2b/./node_modules/imask/esm/_rollupPluginBabelHelpers-6b3bd404.js","webpack://neighborstore_b2b/./node_modules/imask/esm/core/holder.js","webpack://neighborstore_b2b/./node_modules/imask/esm/core/change-details.js","webpack://neighborstore_b2b/./node_modules/imask/esm/core/utils.js","webpack://neighborstore_b2b/./node_modules/imask/esm/core/action-details.js","webpack://neighborstore_b2b/./node_modules/imask/esm/core/continuous-tail-details.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/base.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/factory.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/pattern/input-definition.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/pattern/fixed-definition.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/pattern/chunk-tail-details.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/pattern/cursor.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/regexp.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/pattern.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/range.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/date.js","webpack://neighborstore_b2b/./node_modules/imask/esm/controls/mask-element.js","webpack://neighborstore_b2b/./node_modules/imask/esm/controls/html-mask-element.js","webpack://neighborstore_b2b/./node_modules/imask/esm/controls/html-contenteditable-mask-element.js","webpack://neighborstore_b2b/./node_modules/imask/esm/controls/input.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/enum.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/number.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/function.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/dynamic.js","webpack://neighborstore_b2b/./node_modules/imask/esm/masked/pipe.js","webpack://neighborstore_b2b/./node_modules/imask/esm/index.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/credit-card/shared/handler/credit-card-handler-base.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/credit-card/my-account/handlers/credit-card-my-account-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/credit-card/checkout/handlers/credit-card-checkout-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/user-security/shared/handler/security-handler-base.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/user-security/account-activation/services/account-activation-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/user-security/account-activation/handlers/account-activation-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/services/dynamic-kit-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/events/add-product-kit-banner-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/checkout/events/load-checkout-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/events/load-product-kit-view-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/handlers/product-kit-shopping-cart-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/helpers/product-kit-helpers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/events/product-kit-setup-quantity-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/handlers/product-kit-components-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/handlers/product-kit-confirmation-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/dynamic-kits/handlers/dynamic-kit-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/streettypes-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/neighborhood-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/helper/email-validation-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/address-management/services/address-management-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/address-management/handlers/legacy-address-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/address-management/handlers/address-management-handler.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/checkout-summary-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/checkout-paymentlist-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/helpers/checkout-helper.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/components/radioButtons/radio-buttons.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/services/checkout-subtotals-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/filters/services/filters-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/filters/handlers/filters-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/favorite-list/services/favorite-list-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/favorite-list/events/add-product-to-list-event.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/favorite-list/handlers/favorite-list-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/handler/store-handler-base.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/product-card/handlers/product-card-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/related-product/services/related-product-service.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/related-product/handlers/related-product-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/suggested-promotion/handlers/suggested-promotion-handlers.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/product-detail/handlers/product-detail-handlers.js","webpack://neighborstore_b2b/./wwwroot/js/product-detail.js","webpack://neighborstore_b2b/./wwwroot/lib/modules/shared/config/page-config.js"],"sourcesContent":["/*!\n* sweetalert2 v11.4.17\n* Released under the MIT License.\n*/\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = global || self, global.Sweetalert2 = factory());\n}(this, function () { 'use strict';\n\n const consolePrefix = 'SweetAlert2:';\n /**\n * Filter the unique values into a new array\n * @param arr\n */\n\n const uniqueArray = arr => {\n const result = [];\n\n for (let i = 0; i < arr.length; i++) {\n if (result.indexOf(arr[i]) === -1) {\n result.push(arr[i]);\n }\n }\n\n return result;\n };\n /**\n * Capitalize the first letter of a string\n * @param {string} str\n * @returns {string}\n */\n\n const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);\n /**\n * @param {NodeList | HTMLCollection | NamedNodeMap | DOMTokenList} nodeList\n * @returns {array}\n */\n\n const toArray = nodeList => Array.prototype.slice.call(nodeList);\n /**\n * Standardize console warnings\n * @param {string | array} message\n */\n\n const warn = message => {\n console.warn(\"\".concat(consolePrefix, \" \").concat(typeof message === 'object' ? message.join(' ') : message));\n };\n /**\n * Standardize console errors\n * @param {string} message\n */\n\n const error = message => {\n console.error(\"\".concat(consolePrefix, \" \").concat(message));\n };\n /**\n * Private global state for `warnOnce`\n * @type {Array}\n * @private\n */\n\n const previousWarnOnceMessages = [];\n /**\n * Show a console warning, but only if it hasn't already been shown\n * @param {string} message\n */\n\n const warnOnce = message => {\n if (!previousWarnOnceMessages.includes(message)) {\n previousWarnOnceMessages.push(message);\n warn(message);\n }\n };\n /**\n * Show a one-time console warning about deprecated params/methods\n */\n\n const warnAboutDeprecation = (deprecatedParam, useInstead) => {\n warnOnce(\"\\\"\".concat(deprecatedParam, \"\\\" is deprecated and will be removed in the next major release. Please use \\\"\").concat(useInstead, \"\\\" instead.\"));\n };\n /**\n * If `arg` is a function, call it (with no arguments or context) and return the result.\n * Otherwise, just pass the value through\n * @param arg\n */\n\n const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;\n const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';\n const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);\n const isPromise = arg => arg && Promise.resolve(arg) === arg;\n const getRandomElement = arr => arr[Math.floor(Math.random() * arr.length)];\n\n const defaultParams = {\n title: '',\n titleText: '',\n text: '',\n html: '',\n footer: '',\n icon: undefined,\n iconColor: undefined,\n iconHtml: undefined,\n template: undefined,\n toast: false,\n showClass: {\n popup: 'swal2-show',\n backdrop: 'swal2-backdrop-show',\n icon: 'swal2-icon-show'\n },\n hideClass: {\n popup: 'swal2-hide',\n backdrop: 'swal2-backdrop-hide',\n icon: 'swal2-icon-hide'\n },\n customClass: {},\n target: 'body',\n color: undefined,\n backdrop: true,\n heightAuto: true,\n allowOutsideClick: true,\n allowEscapeKey: true,\n allowEnterKey: true,\n stopKeydownPropagation: true,\n keydownListenerCapture: false,\n showConfirmButton: true,\n showDenyButton: false,\n showCancelButton: false,\n preConfirm: undefined,\n preDeny: undefined,\n confirmButtonText: 'OK',\n confirmButtonAriaLabel: '',\n confirmButtonColor: undefined,\n denyButtonText: 'No',\n denyButtonAriaLabel: '',\n denyButtonColor: undefined,\n cancelButtonText: 'Cancel',\n cancelButtonAriaLabel: '',\n cancelButtonColor: undefined,\n buttonsStyling: true,\n reverseButtons: false,\n focusConfirm: true,\n focusDeny: false,\n focusCancel: false,\n returnFocus: true,\n showCloseButton: false,\n closeButtonHtml: '×',\n closeButtonAriaLabel: 'Close this dialog',\n loaderHtml: '',\n showLoaderOnConfirm: false,\n showLoaderOnDeny: false,\n imageUrl: undefined,\n imageWidth: undefined,\n imageHeight: undefined,\n imageAlt: '',\n timer: undefined,\n timerProgressBar: false,\n width: undefined,\n padding: undefined,\n background: undefined,\n input: undefined,\n inputPlaceholder: '',\n inputLabel: '',\n inputValue: '',\n inputOptions: {},\n inputAutoTrim: true,\n inputAttributes: {},\n inputValidator: undefined,\n returnInputValueOnDeny: false,\n validationMessage: undefined,\n grow: false,\n position: 'center',\n progressSteps: [],\n currentProgressStep: undefined,\n progressStepsDistance: undefined,\n willOpen: undefined,\n didOpen: undefined,\n didRender: undefined,\n willClose: undefined,\n didClose: undefined,\n didDestroy: undefined,\n scrollbarPadding: true\n };\n const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose'];\n const deprecatedParams = {};\n const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];\n /**\n * Is valid parameter\n * @param {string} paramName\n */\n\n const isValidParameter = paramName => {\n return Object.prototype.hasOwnProperty.call(defaultParams, paramName);\n };\n /**\n * Is valid parameter for Swal.update() method\n * @param {string} paramName\n */\n\n const isUpdatableParameter = paramName => {\n return updatableParams.indexOf(paramName) !== -1;\n };\n /**\n * Is deprecated parameter\n * @param {string} paramName\n */\n\n const isDeprecatedParameter = paramName => {\n return deprecatedParams[paramName];\n };\n\n const checkIfParamIsValid = param => {\n if (!isValidParameter(param)) {\n warn(\"Unknown parameter \\\"\".concat(param, \"\\\"\"));\n }\n };\n\n const checkIfToastParamIsValid = param => {\n if (toastIncompatibleParams.includes(param)) {\n warn(\"The parameter \\\"\".concat(param, \"\\\" is incompatible with toasts\"));\n }\n };\n\n const checkIfParamIsDeprecated = param => {\n if (isDeprecatedParameter(param)) {\n warnAboutDeprecation(param, isDeprecatedParameter(param));\n }\n };\n /**\n * Show relevant warnings for given params\n *\n * @param params\n */\n\n\n const showWarningsForParams = params => {\n if (!params.backdrop && params.allowOutsideClick) {\n warn('\"allowOutsideClick\" parameter requires `backdrop` parameter to be set to `true`');\n }\n\n for (const param in params) {\n checkIfParamIsValid(param);\n\n if (params.toast) {\n checkIfToastParamIsValid(param);\n }\n\n checkIfParamIsDeprecated(param);\n }\n };\n\n const swalPrefix = 'swal2-';\n /**\n * @param {string[]} items\n * @returns {object}\n */\n\n const prefix = items => {\n const result = {};\n\n for (const i in items) {\n result[items[i]] = swalPrefix + items[i];\n }\n\n return result;\n };\n const swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error', 'no-war']);\n const iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);\n\n /**\n * Gets the popup container which contains the backdrop and the popup itself.\n *\n * @returns {HTMLElement | null}\n */\n\n const getContainer = () => document.body.querySelector(\".\".concat(swalClasses.container));\n /**\n * @param {string} selectorString\n * @returns {HTMLElement | null}\n */\n\n const elementBySelector = selectorString => {\n const container = getContainer();\n return container ? container.querySelector(selectorString) : null;\n };\n /**\n * @param {string} className\n * @returns {HTMLElement | null}\n */\n\n const elementByClass = className => {\n return elementBySelector(\".\".concat(className));\n };\n /**\n * @returns {HTMLElement | null}\n */\n\n\n const getPopup = () => elementByClass(swalClasses.popup);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getIcon = () => elementByClass(swalClasses.icon);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getTitle = () => elementByClass(swalClasses.title);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getHtmlContainer = () => elementByClass(swalClasses['html-container']);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getImage = () => elementByClass(swalClasses.image);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getValidationMessage = () => elementByClass(swalClasses['validation-message']);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getConfirmButton = () => elementBySelector(\".\".concat(swalClasses.actions, \" .\").concat(swalClasses.confirm));\n /**\n * @returns {HTMLElement | null}\n */\n\n const getDenyButton = () => elementBySelector(\".\".concat(swalClasses.actions, \" .\").concat(swalClasses.deny));\n /**\n * @returns {HTMLElement | null}\n */\n\n const getInputLabel = () => elementByClass(swalClasses['input-label']);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getLoader = () => elementBySelector(\".\".concat(swalClasses.loader));\n /**\n * @returns {HTMLElement | null}\n */\n\n const getCancelButton = () => elementBySelector(\".\".concat(swalClasses.actions, \" .\").concat(swalClasses.cancel));\n /**\n * @returns {HTMLElement | null}\n */\n\n const getActions = () => elementByClass(swalClasses.actions);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getFooter = () => elementByClass(swalClasses.footer);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);\n /**\n * @returns {HTMLElement | null}\n */\n\n const getCloseButton = () => elementByClass(swalClasses.close); // https://github.com/jkup/focusable/blob/master/index.js\n\n const focusable = \"\\n a[href],\\n area[href],\\n input:not([disabled]),\\n select:not([disabled]),\\n textarea:not([disabled]),\\n button:not([disabled]),\\n iframe,\\n object,\\n embed,\\n [tabindex=\\\"0\\\"],\\n [contenteditable],\\n audio[controls],\\n video[controls],\\n summary\\n\";\n /**\n * @returns {HTMLElement[]}\n */\n\n const getFocusableElements = () => {\n const focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex=\"-1\"]):not([tabindex=\"0\"])')) // sort according to tabindex\n .sort((a, b) => {\n const tabindexA = parseInt(a.getAttribute('tabindex'));\n const tabindexB = parseInt(b.getAttribute('tabindex'));\n\n if (tabindexA > tabindexB) {\n return 1;\n } else if (tabindexA < tabindexB) {\n return -1;\n }\n\n return 0;\n });\n const otherFocusableElements = toArray(getPopup().querySelectorAll(focusable)).filter(el => el.getAttribute('tabindex') !== '-1');\n return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(el => isVisible(el));\n };\n /**\n * @returns {boolean}\n */\n\n const isModal = () => {\n return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);\n };\n /**\n * @returns {boolean}\n */\n\n const isToast = () => {\n return getPopup() && hasClass(getPopup(), swalClasses.toast);\n };\n /**\n * @returns {boolean}\n */\n\n const isLoading = () => {\n return getPopup().hasAttribute('data-loading');\n };\n\n const states = {\n previousBodyPadding: null\n };\n /**\n * Securely set innerHTML of an element\n * https://github.com/sweetalert2/sweetalert2/issues/1926\n *\n * @param {HTMLElement} elem\n * @param {string} html\n */\n\n const setInnerHtml = (elem, html) => {\n elem.textContent = '';\n\n if (html) {\n const parser = new DOMParser();\n const parsed = parser.parseFromString(html, \"text/html\");\n toArray(parsed.querySelector('head').childNodes).forEach(child => {\n elem.appendChild(child);\n });\n toArray(parsed.querySelector('body').childNodes).forEach(child => {\n elem.appendChild(child);\n });\n }\n };\n /**\n * @param {HTMLElement} elem\n * @param {string} className\n * @returns {boolean}\n */\n\n const hasClass = (elem, className) => {\n if (!className) {\n return false;\n }\n\n const classList = className.split(/\\s+/);\n\n for (let i = 0; i < classList.length; i++) {\n if (!elem.classList.contains(classList[i])) {\n return false;\n }\n }\n\n return true;\n };\n /**\n * @param {HTMLElement} elem\n * @param {SweetAlertOptions} params\n */\n\n const removeCustomClasses = (elem, params) => {\n toArray(elem.classList).forEach(className => {\n if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass).includes(className)) {\n elem.classList.remove(className);\n }\n });\n };\n /**\n * @param {HTMLElement} elem\n * @param {SweetAlertOptions} params\n * @param {string} className\n */\n\n\n const applyCustomClass = (elem, params, className) => {\n removeCustomClasses(elem, params);\n\n if (params.customClass && params.customClass[className]) {\n if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {\n return warn(\"Invalid type of customClass.\".concat(className, \"! Expected string or iterable object, got \\\"\").concat(typeof params.customClass[className], \"\\\"\"));\n }\n\n addClass(elem, params.customClass[className]);\n }\n };\n /**\n * @param {HTMLElement} popup\n * @param {import('./renderers/renderInput').InputClass} inputClass\n * @returns {HTMLInputElement | null}\n */\n\n const getInput = (popup, inputClass) => {\n if (!inputClass) {\n return null;\n }\n\n switch (inputClass) {\n case 'select':\n case 'textarea':\n case 'file':\n return popup.querySelector(\".\".concat(swalClasses.popup, \" > .\").concat(swalClasses[inputClass]));\n\n case 'checkbox':\n return popup.querySelector(\".\".concat(swalClasses.popup, \" > .\").concat(swalClasses.checkbox, \" input\"));\n\n case 'radio':\n return popup.querySelector(\".\".concat(swalClasses.popup, \" > .\").concat(swalClasses.radio, \" input:checked\")) || popup.querySelector(\".\".concat(swalClasses.popup, \" > .\").concat(swalClasses.radio, \" input:first-child\"));\n\n case 'range':\n return popup.querySelector(\".\".concat(swalClasses.popup, \" > .\").concat(swalClasses.range, \" input\"));\n\n default:\n return popup.querySelector(\".\".concat(swalClasses.popup, \" > .\").concat(swalClasses.input));\n }\n };\n /**\n * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input\n */\n\n const focusInput = input => {\n input.focus(); // place cursor at end of text in text input\n\n if (input.type !== 'file') {\n // http://stackoverflow.com/a/2345915\n const val = input.value;\n input.value = '';\n input.value = val;\n }\n };\n /**\n * @param {HTMLElement | HTMLElement[] | null} target\n * @param {string | string[] | readonly string[]} classList\n * @param {boolean} condition\n */\n\n const toggleClass = (target, classList, condition) => {\n if (!target || !classList) {\n return;\n }\n\n if (typeof classList === 'string') {\n classList = classList.split(/\\s+/).filter(Boolean);\n }\n\n classList.forEach(className => {\n if (Array.isArray(target)) {\n target.forEach(elem => {\n condition ? elem.classList.add(className) : elem.classList.remove(className);\n });\n } else {\n condition ? target.classList.add(className) : target.classList.remove(className);\n }\n });\n };\n /**\n * @param {HTMLElement | HTMLElement[] | null} target\n * @param {string | string[] | readonly string[]} classList\n */\n\n const addClass = (target, classList) => {\n toggleClass(target, classList, true);\n };\n /**\n * @param {HTMLElement | HTMLElement[] | null} target\n * @param {string | string[] | readonly string[]} classList\n */\n\n const removeClass = (target, classList) => {\n toggleClass(target, classList, false);\n };\n /**\n * Get direct child of an element by class name\n *\n * @param {HTMLElement} elem\n * @param {string} className\n * @returns {HTMLElement | null}\n */\n\n const getDirectChildByClass = (elem, className) => {\n const childNodes = toArray(elem.childNodes);\n\n for (let i = 0; i < childNodes.length; i++) {\n if (hasClass(childNodes[i], className)) {\n return childNodes[i];\n }\n }\n };\n /**\n * @param {HTMLElement} elem\n * @param {string} property\n * @param {*} value\n */\n\n const applyNumericalStyle = (elem, property, value) => {\n if (value === \"\".concat(parseInt(value))) {\n value = parseInt(value);\n }\n\n if (value || parseInt(value) === 0) {\n elem.style[property] = typeof value === 'number' ? \"\".concat(value, \"px\") : value;\n } else {\n elem.style.removeProperty(property);\n }\n };\n /**\n * @param {HTMLElement} elem\n * @param {string} display\n */\n\n const show = function (elem) {\n let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';\n elem.style.display = display;\n };\n /**\n * @param {HTMLElement} elem\n */\n\n const hide = elem => {\n elem.style.display = 'none';\n };\n /**\n * @param {HTMLElement} parent\n * @param {string} selector\n * @param {string} property\n * @param {string} value\n */\n\n const setStyle = (parent, selector, property, value) => {\n /** @type {HTMLElement} */\n const el = parent.querySelector(selector);\n\n if (el) {\n el.style[property] = value;\n }\n };\n /**\n * @param {HTMLElement} elem\n * @param {any} condition\n * @param {string} display\n */\n\n const toggle = function (elem, condition) {\n let display = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'flex';\n condition ? show(elem, display) : hide(elem);\n };\n /**\n * borrowed from jquery $(elem).is(':visible') implementation\n *\n * @param {HTMLElement} elem\n * @returns {boolean}\n */\n\n const isVisible = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));\n /**\n * @returns {boolean}\n */\n\n const allButtonsAreHidden = () => !isVisible(getConfirmButton()) && !isVisible(getDenyButton()) && !isVisible(getCancelButton());\n /**\n * @returns {boolean}\n */\n\n const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight);\n /**\n * borrowed from https://stackoverflow.com/a/46352119\n *\n * @param {HTMLElement} elem\n * @returns {boolean}\n */\n\n const hasCssAnimation = elem => {\n const style = window.getComputedStyle(elem);\n const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');\n const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');\n return animDuration > 0 || transDuration > 0;\n };\n /**\n * @param {number} timer\n * @param {boolean} reset\n */\n\n const animateTimerProgressBar = function (timer) {\n let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n const timerProgressBar = getTimerProgressBar();\n\n if (isVisible(timerProgressBar)) {\n if (reset) {\n timerProgressBar.style.transition = 'none';\n timerProgressBar.style.width = '100%';\n }\n\n setTimeout(() => {\n timerProgressBar.style.transition = \"width \".concat(timer / 1000, \"s linear\");\n timerProgressBar.style.width = '0%';\n }, 10);\n }\n };\n const stopTimerProgressBar = () => {\n const timerProgressBar = getTimerProgressBar();\n const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);\n timerProgressBar.style.removeProperty('transition');\n timerProgressBar.style.width = '100%';\n const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);\n const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;\n timerProgressBar.style.removeProperty('transition');\n timerProgressBar.style.width = \"\".concat(timerProgressBarPercent, \"%\");\n };\n\n /**\n * Detect Node env\n *\n * @returns {boolean}\n */\n const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';\n\n const RESTORE_FOCUS_TIMEOUT = 100;\n\n /** @type {GlobalState} */\n\n const globalState = {};\n\n const focusPreviousActiveElement = () => {\n if (globalState.previousActiveElement instanceof HTMLElement) {\n globalState.previousActiveElement.focus();\n globalState.previousActiveElement = null;\n } else if (document.body) {\n document.body.focus();\n }\n };\n /**\n * Restore previous active (focused) element\n *\n * @param {boolean} returnFocus\n * @returns {Promise}\n */\n\n\n const restoreActiveElement = returnFocus => {\n return new Promise(resolve => {\n if (!returnFocus) {\n return resolve();\n }\n\n const x = window.scrollX;\n const y = window.scrollY;\n globalState.restoreFocusTimeout = setTimeout(() => {\n focusPreviousActiveElement();\n resolve();\n }, RESTORE_FOCUS_TIMEOUT); // issues/900\n\n window.scrollTo(x, y);\n });\n };\n\n const sweetHTML = \"\\n
\\n \\n \\n
\\n \\n

\\n
\\n \\n \\n
\\n \\n \\n
\\n \\n
\\n \\n \\n
\\n
\\n
\\n \\n \\n \\n
\\n
\\n
\\n
\\n
\\n
\\n\").replace(/(^|\\n)\\s*/g, '');\n /**\n * @returns {boolean}\n */\n\n const resetOldContainer = () => {\n const oldContainer = getContainer();\n\n if (!oldContainer) {\n return false;\n }\n\n oldContainer.remove();\n removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);\n return true;\n };\n\n const resetValidationMessage = () => {\n globalState.currentInstance.resetValidationMessage();\n };\n\n const addInputChangeListeners = () => {\n const popup = getPopup();\n const input = getDirectChildByClass(popup, swalClasses.input);\n const file = getDirectChildByClass(popup, swalClasses.file);\n /** @type {HTMLInputElement} */\n\n const range = popup.querySelector(\".\".concat(swalClasses.range, \" input\"));\n /** @type {HTMLOutputElement} */\n\n const rangeOutput = popup.querySelector(\".\".concat(swalClasses.range, \" output\"));\n const select = getDirectChildByClass(popup, swalClasses.select);\n /** @type {HTMLInputElement} */\n\n const checkbox = popup.querySelector(\".\".concat(swalClasses.checkbox, \" input\"));\n const textarea = getDirectChildByClass(popup, swalClasses.textarea);\n input.oninput = resetValidationMessage;\n file.onchange = resetValidationMessage;\n select.onchange = resetValidationMessage;\n checkbox.onchange = resetValidationMessage;\n textarea.oninput = resetValidationMessage;\n\n range.oninput = () => {\n resetValidationMessage();\n rangeOutput.value = range.value;\n };\n\n range.onchange = () => {\n resetValidationMessage();\n rangeOutput.value = range.value;\n };\n };\n /**\n * @param {string | HTMLElement} target\n * @returns {HTMLElement}\n */\n\n\n const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;\n /**\n * @param {SweetAlertOptions} params\n */\n\n\n const setupAccessibility = params => {\n const popup = getPopup();\n popup.setAttribute('role', params.toast ? 'alert' : 'dialog');\n popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');\n\n if (!params.toast) {\n popup.setAttribute('aria-modal', 'true');\n }\n };\n /**\n * @param {HTMLElement} targetElement\n */\n\n\n const setupRTL = targetElement => {\n if (window.getComputedStyle(targetElement).direction === 'rtl') {\n addClass(getContainer(), swalClasses.rtl);\n }\n };\n /**\n * Add modal + backdrop + no-war message for Russians to DOM\n *\n * @param {SweetAlertOptions} params\n */\n\n\n const init = params => {\n // Clean up the old popup container if it exists\n const oldContainerExisted = resetOldContainer();\n /* istanbul ignore if */\n\n if (isNodeEnv()) {\n error('SweetAlert2 requires document to initialize');\n return;\n }\n\n const container = document.createElement('div');\n container.className = swalClasses.container;\n\n if (oldContainerExisted) {\n addClass(container, swalClasses['no-transition']);\n }\n\n setInnerHtml(container, sweetHTML);\n const targetElement = getTarget(params.target);\n targetElement.appendChild(container);\n setupAccessibility(params);\n setupRTL(targetElement);\n addInputChangeListeners();\n noWarMessageForRussians(container, params);\n };\n /**\n * @param {HTMLElement} container\n * @param {SweetAlertOptions} params\n */\n\n const noWarMessageForRussians = (container, params) => {\n if (params.toast) {\n return;\n } // This message is targeted at people who are corrupted by propaganda, everybody else\n // is already against war either silently or actively.\n //\n // The point is to wrap the truth-bomb into a patriotic title so they will actually click it\n // and listen to the uncomfortable truth about the war from the people they love or respect.\n\n\n const message = getRandomElement([{\n text: 'ШВАРЦЕНЕГГЕР обратился
к РУССКОМУ НАРОДУ о войне',\n // Arnold is loved in Russia by all people including those who are for this war\n // His speech might change the mind of those who are brainwashed by propaganda\n youtubeId: 'fWClXZd9c78'\n }, {\n text: 'РУССКИЙ ПАТРИОТ
открыл главную тайну спецоперации',\n // In this video one of the most famous Russian nationalist leaders, Dmitry Demushkin,\n // explains that this war has no sense and produces the exact opposite result of what\n // it was intended to do.\n youtubeId: '_RjBNkn88yA'\n }, {\n text: 'ГЕРОЙ НОВОРОССИИ СТРЕЛКОВ
дал оценку ходу спецоперации',\n // In this video Igor Girkin, who played a key role in the annexation of Crimea,\n // explains that this war has failed already and all possible outcomes are bad for Russia.\n youtubeId: 'yUmzQT4C8JY'\n }, {\n text: 'ФИНСКИЙ ДРУГ РОССИИ
говорит ПО-РУССКИ о спецоперации',\n youtubeId: 'hkCYb6edUrQ'\n }, {\n text: 'ЮРИЙ ПОДОЛЯКА честно
о генералах РУССКОЙ АРМИИ',\n youtubeId: 'w4-_8BJKfpk'\n }, {\n text: 'Полковник ФСБ СТРЕЛКОВ
об успехах РОССИИ в спецоперации',\n youtubeId: 'saK5UTKroDA'\n }]); // The message will only be shown to Russian users visiting Russian sites\n\n if (navigator.language === 'ru' && location.host.match(/\\.(ru|su|xn--p1ai)$/)) {\n const noWar = document.createElement('div');\n noWar.className = swalClasses['no-war'];\n setInnerHtml(noWar, \"\").concat(message.text, \"\"));\n container.appendChild(noWar);\n container.style.paddingTop = '4em';\n }\n };\n\n /**\n * @param {HTMLElement | object | string} param\n * @param {HTMLElement} target\n */\n\n const parseHtmlToContainer = (param, target) => {\n // DOM element\n if (param instanceof HTMLElement) {\n target.appendChild(param);\n } // Object\n else if (typeof param === 'object') {\n handleObject(param, target);\n } // Plain string\n else if (param) {\n setInnerHtml(target, param);\n }\n };\n /**\n * @param {object} param\n * @param {HTMLElement} target\n */\n\n const handleObject = (param, target) => {\n // JQuery element(s)\n if (param.jquery) {\n handleJqueryElem(target, param);\n } // For other objects use their string representation\n else {\n setInnerHtml(target, param.toString());\n }\n };\n /**\n * @param {HTMLElement} target\n * @param {HTMLElement} elem\n */\n\n\n const handleJqueryElem = (target, elem) => {\n target.textContent = '';\n\n if (0 in elem) {\n for (let i = 0; (i in elem); i++) {\n target.appendChild(elem[i].cloneNode(true));\n }\n } else {\n target.appendChild(elem.cloneNode(true));\n }\n };\n\n /**\n * @returns {'webkitAnimationEnd' | 'animationend' | false}\n */\n\n const animationEndEvent = (() => {\n // Prevent run in Node env\n\n /* istanbul ignore if */\n if (isNodeEnv()) {\n return false;\n }\n\n const testEl = document.createElement('div');\n const transEndEventNames = {\n WebkitAnimation: 'webkitAnimationEnd',\n // Chrome, Safari and Opera\n animation: 'animationend' // Standard syntax\n\n };\n\n for (const i in transEndEventNames) {\n if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {\n return transEndEventNames[i];\n }\n }\n\n return false;\n })();\n\n /**\n * Measure scrollbar width for padding body during modal show/hide\n * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js\n *\n * @returns {number}\n */\n\n const measureScrollbar = () => {\n const scrollDiv = document.createElement('div');\n scrollDiv.className = swalClasses['scrollbar-measure'];\n document.body.appendChild(scrollDiv);\n const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;\n document.body.removeChild(scrollDiv);\n return scrollbarWidth;\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderActions = (instance, params) => {\n const actions = getActions();\n const loader = getLoader(); // Actions (buttons) wrapper\n\n if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {\n hide(actions);\n } else {\n show(actions);\n } // Custom class\n\n\n applyCustomClass(actions, params, 'actions'); // Render all the buttons\n\n renderButtons(actions, loader, params); // Loader\n\n setInnerHtml(loader, params.loaderHtml);\n applyCustomClass(loader, params, 'loader');\n };\n /**\n * @param {HTMLElement} actions\n * @param {HTMLElement} loader\n * @param {SweetAlertOptions} params\n */\n\n function renderButtons(actions, loader, params) {\n const confirmButton = getConfirmButton();\n const denyButton = getDenyButton();\n const cancelButton = getCancelButton(); // Render buttons\n\n renderButton(confirmButton, 'confirm', params);\n renderButton(denyButton, 'deny', params);\n renderButton(cancelButton, 'cancel', params);\n handleButtonsStyling(confirmButton, denyButton, cancelButton, params);\n\n if (params.reverseButtons) {\n if (params.toast) {\n actions.insertBefore(cancelButton, confirmButton);\n actions.insertBefore(denyButton, confirmButton);\n } else {\n actions.insertBefore(cancelButton, loader);\n actions.insertBefore(denyButton, loader);\n actions.insertBefore(confirmButton, loader);\n }\n }\n }\n /**\n * @param {HTMLElement} confirmButton\n * @param {HTMLElement} denyButton\n * @param {HTMLElement} cancelButton\n * @param {SweetAlertOptions} params\n */\n\n\n function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {\n if (!params.buttonsStyling) {\n return removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);\n }\n\n addClass([confirmButton, denyButton, cancelButton], swalClasses.styled); // Buttons background colors\n\n if (params.confirmButtonColor) {\n confirmButton.style.backgroundColor = params.confirmButtonColor;\n addClass(confirmButton, swalClasses['default-outline']);\n }\n\n if (params.denyButtonColor) {\n denyButton.style.backgroundColor = params.denyButtonColor;\n addClass(denyButton, swalClasses['default-outline']);\n }\n\n if (params.cancelButtonColor) {\n cancelButton.style.backgroundColor = params.cancelButtonColor;\n addClass(cancelButton, swalClasses['default-outline']);\n }\n }\n /**\n * @param {HTMLElement} button\n * @param {'confirm' | 'deny' | 'cancel'} buttonType\n * @param {SweetAlertOptions} params\n */\n\n\n function renderButton(button, buttonType, params) {\n toggle(button, params[\"show\".concat(capitalizeFirstLetter(buttonType), \"Button\")], 'inline-block');\n setInnerHtml(button, params[\"\".concat(buttonType, \"ButtonText\")]); // Set caption text\n\n button.setAttribute('aria-label', params[\"\".concat(buttonType, \"ButtonAriaLabel\")]); // ARIA label\n // Add buttons custom classes\n\n button.className = swalClasses[buttonType];\n applyCustomClass(button, params, \"\".concat(buttonType, \"Button\"));\n addClass(button, params[\"\".concat(buttonType, \"ButtonClass\")]);\n }\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderContainer = (instance, params) => {\n const container = getContainer();\n\n if (!container) {\n return;\n }\n\n handleBackdropParam(container, params.backdrop);\n handlePositionParam(container, params.position);\n handleGrowParam(container, params.grow); // Custom class\n\n applyCustomClass(container, params, 'container');\n };\n /**\n * @param {HTMLElement} container\n * @param {SweetAlertOptions['backdrop']} backdrop\n */\n\n function handleBackdropParam(container, backdrop) {\n if (typeof backdrop === 'string') {\n container.style.background = backdrop;\n } else if (!backdrop) {\n addClass([document.documentElement, document.body], swalClasses['no-backdrop']);\n }\n }\n /**\n * @param {HTMLElement} container\n * @param {SweetAlertOptions['position']} position\n */\n\n\n function handlePositionParam(container, position) {\n if (position in swalClasses) {\n addClass(container, swalClasses[position]);\n } else {\n warn('The \"position\" parameter is not valid, defaulting to \"center\"');\n addClass(container, swalClasses.center);\n }\n }\n /**\n * @param {HTMLElement} container\n * @param {SweetAlertOptions['grow']} grow\n */\n\n\n function handleGrowParam(container, grow) {\n if (grow && typeof grow === 'string') {\n const growClass = \"grow-\".concat(grow);\n\n if (growClass in swalClasses) {\n addClass(container, swalClasses[growClass]);\n }\n }\n }\n\n /**\n * This module contains `WeakMap`s for each effectively-\"private property\" that a `Swal` has.\n * For example, to set the private property \"foo\" of `this` to \"bar\", you can `privateProps.foo.set(this, 'bar')`\n * This is the approach that Babel will probably take to implement private methods/fields\n * https://github.com/tc39/proposal-private-methods\n * https://github.com/babel/babel/pull/7555\n * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*\n * then we can use that language feature.\n */\n var privateProps = {\n awaitingPromise: new WeakMap(),\n promise: new WeakMap(),\n innerParams: new WeakMap(),\n domCache: new WeakMap()\n };\n\n /// \n /** @type {InputClass[]} */\n\n const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderInput = (instance, params) => {\n const popup = getPopup();\n const innerParams = privateProps.innerParams.get(instance);\n const rerender = !innerParams || params.input !== innerParams.input;\n inputClasses.forEach(inputClass => {\n const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]); // set attributes\n\n setAttributes(inputClass, params.inputAttributes); // set class\n\n inputContainer.className = swalClasses[inputClass];\n\n if (rerender) {\n hide(inputContainer);\n }\n });\n\n if (params.input) {\n if (rerender) {\n showInput(params);\n } // set custom class\n\n\n setCustomClass(params);\n }\n };\n /**\n * @param {SweetAlertOptions} params\n */\n\n const showInput = params => {\n if (!renderInputType[params.input]) {\n return error(\"Unexpected type of input! Expected \\\"text\\\", \\\"email\\\", \\\"password\\\", \\\"number\\\", \\\"tel\\\", \\\"select\\\", \\\"radio\\\", \\\"checkbox\\\", \\\"textarea\\\", \\\"file\\\" or \\\"url\\\", got \\\"\".concat(params.input, \"\\\"\"));\n }\n\n const inputContainer = getInputContainer(params.input);\n const input = renderInputType[params.input](inputContainer, params);\n show(inputContainer); // input autofocus\n\n setTimeout(() => {\n focusInput(input);\n });\n };\n /**\n * @param {HTMLInputElement} input\n */\n\n\n const removeAttributes = input => {\n for (let i = 0; i < input.attributes.length; i++) {\n const attrName = input.attributes[i].name;\n\n if (!['type', 'value', 'style'].includes(attrName)) {\n input.removeAttribute(attrName);\n }\n }\n };\n /**\n * @param {InputClass} inputClass\n * @param {SweetAlertOptions['inputAttributes']} inputAttributes\n */\n\n\n const setAttributes = (inputClass, inputAttributes) => {\n const input = getInput(getPopup(), inputClass);\n\n if (!input) {\n return;\n }\n\n removeAttributes(input);\n\n for (const attr in inputAttributes) {\n input.setAttribute(attr, inputAttributes[attr]);\n }\n };\n /**\n * @param {SweetAlertOptions} params\n */\n\n\n const setCustomClass = params => {\n const inputContainer = getInputContainer(params.input);\n\n if (typeof params.customClass === 'object') {\n addClass(inputContainer, params.customClass.input);\n }\n };\n /**\n * @param {HTMLInputElement | HTMLTextAreaElement} input\n * @param {SweetAlertOptions} params\n */\n\n\n const setInputPlaceholder = (input, params) => {\n if (!input.placeholder || params.inputPlaceholder) {\n input.placeholder = params.inputPlaceholder;\n }\n };\n /**\n * @param {Input} input\n * @param {Input} prependTo\n * @param {SweetAlertOptions} params\n */\n\n\n const setInputLabel = (input, prependTo, params) => {\n if (params.inputLabel) {\n input.id = swalClasses.input;\n const label = document.createElement('label');\n const labelClass = swalClasses['input-label'];\n label.setAttribute('for', input.id);\n label.className = labelClass;\n\n if (typeof params.customClass === 'object') {\n addClass(label, params.customClass.inputLabel);\n }\n\n label.innerText = params.inputLabel;\n prependTo.insertAdjacentElement('beforebegin', label);\n }\n };\n /**\n * @param {SweetAlertOptions['input']} inputType\n * @returns {HTMLElement}\n */\n\n\n const getInputContainer = inputType => {\n return getDirectChildByClass(getPopup(), swalClasses[inputType] || swalClasses.input);\n };\n /**\n * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input\n * @param {SweetAlertOptions['inputValue']} inputValue\n */\n\n\n const checkAndSetInputValue = (input, inputValue) => {\n if (['string', 'number'].includes(typeof inputValue)) {\n input.value = \"\".concat(inputValue);\n } else if (!isPromise(inputValue)) {\n warn(\"Unexpected type of inputValue! Expected \\\"string\\\", \\\"number\\\" or \\\"Promise\\\", got \\\"\".concat(typeof inputValue, \"\\\"\"));\n }\n };\n /** @type Record Input> */\n\n\n const renderInputType = {};\n /**\n * @param {HTMLInputElement} input\n * @param {SweetAlertOptions} params\n * @returns {HTMLInputElement}\n */\n\n renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = (input, params) => {\n checkAndSetInputValue(input, params.inputValue);\n setInputLabel(input, input, params);\n setInputPlaceholder(input, params);\n input.type = params.input;\n return input;\n };\n /**\n * @param {HTMLInputElement} input\n * @param {SweetAlertOptions} params\n * @returns {HTMLInputElement}\n */\n\n\n renderInputType.file = (input, params) => {\n setInputLabel(input, input, params);\n setInputPlaceholder(input, params);\n return input;\n };\n /**\n * @param {HTMLInputElement} range\n * @param {SweetAlertOptions} params\n * @returns {HTMLInputElement}\n */\n\n\n renderInputType.range = (range, params) => {\n const rangeInput = range.querySelector('input');\n const rangeOutput = range.querySelector('output');\n checkAndSetInputValue(rangeInput, params.inputValue);\n rangeInput.type = params.input;\n checkAndSetInputValue(rangeOutput, params.inputValue);\n setInputLabel(rangeInput, range, params);\n return range;\n };\n /**\n * @param {HTMLSelectElement} select\n * @param {SweetAlertOptions} params\n * @returns {HTMLSelectElement}\n */\n\n\n renderInputType.select = (select, params) => {\n select.textContent = '';\n\n if (params.inputPlaceholder) {\n const placeholder = document.createElement('option');\n setInnerHtml(placeholder, params.inputPlaceholder);\n placeholder.value = '';\n placeholder.disabled = true;\n placeholder.selected = true;\n select.appendChild(placeholder);\n }\n\n setInputLabel(select, select, params);\n return select;\n };\n /**\n * @param {HTMLInputElement} radio\n * @returns {HTMLInputElement}\n */\n\n\n renderInputType.radio = radio => {\n radio.textContent = '';\n return radio;\n };\n /**\n * @param {HTMLLabelElement} checkboxContainer\n * @param {SweetAlertOptions} params\n * @returns {HTMLInputElement}\n */\n\n\n renderInputType.checkbox = (checkboxContainer, params) => {\n const checkbox = getInput(getPopup(), 'checkbox');\n checkbox.value = '1';\n checkbox.id = swalClasses.checkbox;\n checkbox.checked = Boolean(params.inputValue);\n const label = checkboxContainer.querySelector('span');\n setInnerHtml(label, params.inputPlaceholder);\n return checkbox;\n };\n /**\n * @param {HTMLTextAreaElement} textarea\n * @param {SweetAlertOptions} params\n * @returns {HTMLTextAreaElement}\n */\n\n\n renderInputType.textarea = (textarea, params) => {\n checkAndSetInputValue(textarea, params.inputValue);\n setInputPlaceholder(textarea, params);\n setInputLabel(textarea, textarea, params);\n /**\n * @param {HTMLElement} el\n * @returns {number}\n */\n\n const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight); // https://github.com/sweetalert2/sweetalert2/issues/2291\n\n\n setTimeout(() => {\n // https://github.com/sweetalert2/sweetalert2/issues/1699\n if ('MutationObserver' in window) {\n const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);\n\n const textareaResizeHandler = () => {\n const textareaWidth = textarea.offsetWidth + getMargin(textarea);\n\n if (textareaWidth > initialPopupWidth) {\n getPopup().style.width = \"\".concat(textareaWidth, \"px\");\n } else {\n getPopup().style.width = null;\n }\n };\n\n new MutationObserver(textareaResizeHandler).observe(textarea, {\n attributes: true,\n attributeFilter: ['style']\n });\n }\n });\n return textarea;\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderContent = (instance, params) => {\n const htmlContainer = getHtmlContainer();\n applyCustomClass(htmlContainer, params, 'htmlContainer'); // Content as HTML\n\n if (params.html) {\n parseHtmlToContainer(params.html, htmlContainer);\n show(htmlContainer, 'block');\n } // Content as plain text\n else if (params.text) {\n htmlContainer.textContent = params.text;\n show(htmlContainer, 'block');\n } // No content\n else {\n hide(htmlContainer);\n }\n\n renderInput(instance, params);\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderFooter = (instance, params) => {\n const footer = getFooter();\n toggle(footer, params.footer);\n\n if (params.footer) {\n parseHtmlToContainer(params.footer, footer);\n } // Custom class\n\n\n applyCustomClass(footer, params, 'footer');\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderCloseButton = (instance, params) => {\n const closeButton = getCloseButton();\n setInnerHtml(closeButton, params.closeButtonHtml); // Custom class\n\n applyCustomClass(closeButton, params, 'closeButton');\n toggle(closeButton, params.showCloseButton);\n closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderIcon = (instance, params) => {\n const innerParams = privateProps.innerParams.get(instance);\n const icon = getIcon(); // if the given icon already rendered, apply the styling without re-rendering the icon\n\n if (innerParams && params.icon === innerParams.icon) {\n // Custom or default content\n setContent(icon, params);\n applyStyles(icon, params);\n return;\n }\n\n if (!params.icon && !params.iconHtml) {\n hide(icon);\n return;\n }\n\n if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {\n error(\"Unknown icon! Expected \\\"success\\\", \\\"error\\\", \\\"warning\\\", \\\"info\\\" or \\\"question\\\", got \\\"\".concat(params.icon, \"\\\"\"));\n hide(icon);\n return;\n }\n\n show(icon); // Custom or default content\n\n setContent(icon, params);\n applyStyles(icon, params); // Animate icon\n\n addClass(icon, params.showClass.icon);\n };\n /**\n * @param {HTMLElement} icon\n * @param {SweetAlertOptions} params\n */\n\n const applyStyles = (icon, params) => {\n for (const iconType in iconTypes) {\n if (params.icon !== iconType) {\n removeClass(icon, iconTypes[iconType]);\n }\n }\n\n addClass(icon, iconTypes[params.icon]); // Icon color\n\n setColor(icon, params); // Success icon background color\n\n adjustSuccessIconBackgroundColor(); // Custom class\n\n applyCustomClass(icon, params, 'icon');\n }; // Adjust success icon background color to match the popup background color\n\n\n const adjustSuccessIconBackgroundColor = () => {\n const popup = getPopup();\n const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');\n /** @type {NodeListOf} */\n\n const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');\n\n for (let i = 0; i < successIconParts.length; i++) {\n successIconParts[i].style.backgroundColor = popupBackgroundColor;\n }\n };\n\n const successIconHtml = \"\\n
\\n \\n
\\n
\\n\";\n const errorIconHtml = \"\\n \\n \\n \\n \\n\";\n /**\n * @param {HTMLElement} icon\n * @param {SweetAlertOptions} params\n */\n\n const setContent = (icon, params) => {\n let oldContent = icon.innerHTML;\n let newContent;\n\n if (params.iconHtml) {\n newContent = iconContent(params.iconHtml);\n } else if (params.icon === 'success') {\n newContent = successIconHtml;\n oldContent = oldContent.replace(/ style=\".*?\"/g, ''); // undo adjustSuccessIconBackgroundColor()\n } else if (params.icon === 'error') {\n newContent = errorIconHtml;\n } else {\n const defaultIconHtml = {\n question: '?',\n warning: '!',\n info: 'i'\n };\n newContent = iconContent(defaultIconHtml[params.icon]);\n }\n\n if (oldContent.trim() !== newContent.trim()) {\n setInnerHtml(icon, newContent);\n }\n };\n /**\n * @param {HTMLElement} icon\n * @param {SweetAlertOptions} params\n */\n\n\n const setColor = (icon, params) => {\n if (!params.iconColor) {\n return;\n }\n\n icon.style.color = params.iconColor;\n icon.style.borderColor = params.iconColor;\n\n for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {\n setStyle(icon, sel, 'backgroundColor', params.iconColor);\n }\n\n setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor);\n };\n /**\n * @param {string} content\n * @returns {string}\n */\n\n\n const iconContent = content => \"
\").concat(content, \"
\");\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderImage = (instance, params) => {\n const image = getImage();\n\n if (!params.imageUrl) {\n return hide(image);\n }\n\n show(image, ''); // Src, alt\n\n image.setAttribute('src', params.imageUrl);\n image.setAttribute('alt', params.imageAlt); // Width, height\n\n applyNumericalStyle(image, 'width', params.imageWidth);\n applyNumericalStyle(image, 'height', params.imageHeight); // Class\n\n image.className = swalClasses.image;\n applyCustomClass(image, params, 'image');\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderProgressSteps = (instance, params) => {\n const progressStepsContainer = getProgressSteps();\n\n if (!params.progressSteps || params.progressSteps.length === 0) {\n return hide(progressStepsContainer);\n }\n\n show(progressStepsContainer);\n progressStepsContainer.textContent = '';\n\n if (params.currentProgressStep >= params.progressSteps.length) {\n warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');\n }\n\n params.progressSteps.forEach((step, index) => {\n const stepEl = createStepElement(step);\n progressStepsContainer.appendChild(stepEl);\n\n if (index === params.currentProgressStep) {\n addClass(stepEl, swalClasses['active-progress-step']);\n }\n\n if (index !== params.progressSteps.length - 1) {\n const lineEl = createLineElement(params);\n progressStepsContainer.appendChild(lineEl);\n }\n });\n };\n /**\n * @param {string} step\n * @returns {HTMLLIElement}\n */\n\n const createStepElement = step => {\n const stepEl = document.createElement('li');\n addClass(stepEl, swalClasses['progress-step']);\n setInnerHtml(stepEl, step);\n return stepEl;\n };\n /**\n * @param {SweetAlertOptions} params\n * @returns {HTMLLIElement}\n */\n\n\n const createLineElement = params => {\n const lineEl = document.createElement('li');\n addClass(lineEl, swalClasses['progress-step-line']);\n\n if (params.progressStepsDistance) {\n applyNumericalStyle(lineEl, 'width', params.progressStepsDistance);\n }\n\n return lineEl;\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderTitle = (instance, params) => {\n const title = getTitle();\n toggle(title, params.title || params.titleText, 'block');\n\n if (params.title) {\n parseHtmlToContainer(params.title, title);\n }\n\n if (params.titleText) {\n title.innerText = params.titleText;\n } // Custom class\n\n\n applyCustomClass(title, params, 'title');\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const renderPopup = (instance, params) => {\n const container = getContainer();\n const popup = getPopup(); // Width\n // https://github.com/sweetalert2/sweetalert2/issues/2170\n\n if (params.toast) {\n applyNumericalStyle(container, 'width', params.width);\n popup.style.width = '100%';\n popup.insertBefore(getLoader(), getIcon());\n } else {\n applyNumericalStyle(popup, 'width', params.width);\n } // Padding\n\n\n applyNumericalStyle(popup, 'padding', params.padding); // Color\n\n if (params.color) {\n popup.style.color = params.color;\n } // Background\n\n\n if (params.background) {\n popup.style.background = params.background;\n }\n\n hide(getValidationMessage()); // Classes\n\n addClasses(popup, params);\n };\n /**\n * @param {HTMLElement} popup\n * @param {SweetAlertOptions} params\n */\n\n const addClasses = (popup, params) => {\n // Default Class + showClass when updating Swal.update({})\n popup.className = \"\".concat(swalClasses.popup, \" \").concat(isVisible(popup) ? params.showClass.popup : '');\n\n if (params.toast) {\n addClass([document.documentElement, document.body], swalClasses['toast-shown']);\n addClass(popup, swalClasses.toast);\n } else {\n addClass(popup, swalClasses.modal);\n } // Custom class\n\n\n applyCustomClass(popup, params, 'popup');\n\n if (typeof params.customClass === 'string') {\n addClass(popup, params.customClass);\n } // Icon class (#1842)\n\n\n if (params.icon) {\n addClass(popup, swalClasses[\"icon-\".concat(params.icon)]);\n }\n };\n\n /**\n * @param {SweetAlert2} instance\n * @param {SweetAlertOptions} params\n */\n\n const render = (instance, params) => {\n renderPopup(instance, params);\n renderContainer(instance, params);\n renderProgressSteps(instance, params);\n renderIcon(instance, params);\n renderImage(instance, params);\n renderTitle(instance, params);\n renderCloseButton(instance, params);\n renderContent(instance, params);\n renderActions(instance, params);\n renderFooter(instance, params);\n\n if (typeof params.didRender === 'function') {\n params.didRender(getPopup());\n }\n };\n\n const DismissReason = Object.freeze({\n cancel: 'cancel',\n backdrop: 'backdrop',\n close: 'close',\n esc: 'esc',\n timer: 'timer'\n });\n\n // Adding aria-hidden=\"true\" to elements outside of the active modal dialog ensures that\n // elements not within the active modal dialog will not be surfaced if a user opens a screen\n // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.\n\n const setAriaHidden = () => {\n const bodyChildren = toArray(document.body.children);\n bodyChildren.forEach(el => {\n if (el === getContainer() || el.contains(getContainer())) {\n return;\n }\n\n if (el.hasAttribute('aria-hidden')) {\n el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));\n }\n\n el.setAttribute('aria-hidden', 'true');\n });\n };\n const unsetAriaHidden = () => {\n const bodyChildren = toArray(document.body.children);\n bodyChildren.forEach(el => {\n if (el.hasAttribute('data-previous-aria-hidden')) {\n el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));\n el.removeAttribute('data-previous-aria-hidden');\n } else {\n el.removeAttribute('aria-hidden');\n }\n });\n };\n\n const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];\n const getTemplateParams = params => {\n const template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template;\n\n if (!template) {\n return {};\n }\n /** @type {DocumentFragment} */\n\n\n const templateContent = template.content;\n showWarningsForElements(templateContent);\n const result = Object.assign(getSwalParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));\n return result;\n };\n /**\n * @param {DocumentFragment} templateContent\n */\n\n const getSwalParams = templateContent => {\n const result = {};\n toArray(templateContent.querySelectorAll('swal-param')).forEach(param => {\n showWarningsForAttributes(param, ['name', 'value']);\n const paramName = param.getAttribute('name');\n const value = param.getAttribute('value');\n\n if (typeof defaultParams[paramName] === 'boolean' && value === 'false') {\n result[paramName] = false;\n }\n\n if (typeof defaultParams[paramName] === 'object') {\n result[paramName] = JSON.parse(value);\n }\n });\n return result;\n };\n /**\n * @param {DocumentFragment} templateContent\n */\n\n\n const getSwalButtons = templateContent => {\n const result = {};\n toArray(templateContent.querySelectorAll('swal-button')).forEach(button => {\n showWarningsForAttributes(button, ['type', 'color', 'aria-label']);\n const type = button.getAttribute('type');\n result[\"\".concat(type, \"ButtonText\")] = button.innerHTML;\n result[\"show\".concat(capitalizeFirstLetter(type), \"Button\")] = true;\n\n if (button.hasAttribute('color')) {\n result[\"\".concat(type, \"ButtonColor\")] = button.getAttribute('color');\n }\n\n if (button.hasAttribute('aria-label')) {\n result[\"\".concat(type, \"ButtonAriaLabel\")] = button.getAttribute('aria-label');\n }\n });\n return result;\n };\n /**\n * @param {DocumentFragment} templateContent\n */\n\n\n const getSwalImage = templateContent => {\n const result = {};\n /** @type {HTMLElement} */\n\n const image = templateContent.querySelector('swal-image');\n\n if (image) {\n showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);\n\n if (image.hasAttribute('src')) {\n result.imageUrl = image.getAttribute('src');\n }\n\n if (image.hasAttribute('width')) {\n result.imageWidth = image.getAttribute('width');\n }\n\n if (image.hasAttribute('height')) {\n result.imageHeight = image.getAttribute('height');\n }\n\n if (image.hasAttribute('alt')) {\n result.imageAlt = image.getAttribute('alt');\n }\n }\n\n return result;\n };\n /**\n * @param {DocumentFragment} templateContent\n */\n\n\n const getSwalIcon = templateContent => {\n const result = {};\n /** @type {HTMLElement} */\n\n const icon = templateContent.querySelector('swal-icon');\n\n if (icon) {\n showWarningsForAttributes(icon, ['type', 'color']);\n\n if (icon.hasAttribute('type')) {\n result.icon = icon.getAttribute('type');\n }\n\n if (icon.hasAttribute('color')) {\n result.iconColor = icon.getAttribute('color');\n }\n\n result.iconHtml = icon.innerHTML;\n }\n\n return result;\n };\n /**\n * @param {DocumentFragment} templateContent\n */\n\n\n const getSwalInput = templateContent => {\n const result = {};\n /** @type {HTMLElement} */\n\n const input = templateContent.querySelector('swal-input');\n\n if (input) {\n showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);\n result.input = input.getAttribute('type') || 'text';\n\n if (input.hasAttribute('label')) {\n result.inputLabel = input.getAttribute('label');\n }\n\n if (input.hasAttribute('placeholder')) {\n result.inputPlaceholder = input.getAttribute('placeholder');\n }\n\n if (input.hasAttribute('value')) {\n result.inputValue = input.getAttribute('value');\n }\n }\n\n const inputOptions = templateContent.querySelectorAll('swal-input-option');\n\n if (inputOptions.length) {\n result.inputOptions = {};\n toArray(inputOptions).forEach(option => {\n showWarningsForAttributes(option, ['value']);\n const optionValue = option.getAttribute('value');\n const optionName = option.innerHTML;\n result.inputOptions[optionValue] = optionName;\n });\n }\n\n return result;\n };\n /**\n * @param {DocumentFragment} templateContent\n * @param {string[]} paramNames\n */\n\n\n const getSwalStringParams = (templateContent, paramNames) => {\n const result = {};\n\n for (const i in paramNames) {\n const paramName = paramNames[i];\n /** @type {HTMLElement} */\n\n const tag = templateContent.querySelector(paramName);\n\n if (tag) {\n showWarningsForAttributes(tag, []);\n result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();\n }\n }\n\n return result;\n };\n /**\n * @param {DocumentFragment} templateContent\n */\n\n\n const showWarningsForElements = templateContent => {\n const allowedElements = swalStringParams.concat(['swal-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);\n toArray(templateContent.children).forEach(el => {\n const tagName = el.tagName.toLowerCase();\n\n if (allowedElements.indexOf(tagName) === -1) {\n warn(\"Unrecognized element <\".concat(tagName, \">\"));\n }\n });\n };\n /**\n * @param {HTMLElement} el\n * @param {string[]} allowedAttributes\n */\n\n\n const showWarningsForAttributes = (el, allowedAttributes) => {\n toArray(el.attributes).forEach(attribute => {\n if (allowedAttributes.indexOf(attribute.name) === -1) {\n warn([\"Unrecognized attribute \\\"\".concat(attribute.name, \"\\\" on <\").concat(el.tagName.toLowerCase(), \">.\"), \"\".concat(allowedAttributes.length ? \"Allowed attributes are: \".concat(allowedAttributes.join(', ')) : 'To set the value, use HTML within the element.')]);\n }\n });\n };\n\n var defaultInputValidators = {\n /**\n * @param {string} string\n * @param {string} validationMessage\n * @returns {Promise}\n */\n email: (string, validationMessage) => {\n return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z0-9-]{2,24}$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');\n },\n\n /**\n * @param {string} string\n * @param {string} validationMessage\n * @returns {Promise}\n */\n url: (string, validationMessage) => {\n // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013\n return /^https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-z]{2,63}\\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');\n }\n };\n\n /**\n * @param {SweetAlertOptions} params\n */\n\n function setDefaultInputValidators(params) {\n // Use default `inputValidator` for supported input types if not provided\n if (!params.inputValidator) {\n Object.keys(defaultInputValidators).forEach(key => {\n if (params.input === key) {\n params.inputValidator = defaultInputValidators[key];\n }\n });\n }\n }\n /**\n * @param {SweetAlertOptions} params\n */\n\n\n function validateCustomTargetElement(params) {\n // Determine if the custom target element is valid\n if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {\n warn('Target parameter is not valid, defaulting to \"body\"');\n params.target = 'body';\n }\n }\n /**\n * Set type, text and actions on popup\n *\n * @param {SweetAlertOptions} params\n */\n\n\n function setParameters(params) {\n setDefaultInputValidators(params); // showLoaderOnConfirm && preConfirm\n\n if (params.showLoaderOnConfirm && !params.preConfirm) {\n warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\\n' + 'https://sweetalert2.github.io/#ajax-request');\n }\n\n validateCustomTargetElement(params); // Replace newlines with
in title\n\n if (typeof params.title === 'string') {\n params.title = params.title.split('\\n').join('
');\n }\n\n init(params);\n }\n\n class Timer {\n constructor(callback, delay) {\n this.callback = callback;\n this.remaining = delay;\n this.running = false;\n this.start();\n }\n\n start() {\n if (!this.running) {\n this.running = true;\n this.started = new Date();\n this.id = setTimeout(this.callback, this.remaining);\n }\n\n return this.remaining;\n }\n\n stop() {\n if (this.running) {\n this.running = false;\n clearTimeout(this.id);\n this.remaining -= new Date().getTime() - this.started.getTime();\n }\n\n return this.remaining;\n }\n\n increase(n) {\n const running = this.running;\n\n if (running) {\n this.stop();\n }\n\n this.remaining += n;\n\n if (running) {\n this.start();\n }\n\n return this.remaining;\n }\n\n getTimerLeft() {\n if (this.running) {\n this.stop();\n this.start();\n }\n\n return this.remaining;\n }\n\n isRunning() {\n return this.running;\n }\n\n }\n\n const fixScrollbar = () => {\n // for queues, do not do this more than once\n if (states.previousBodyPadding !== null) {\n return;\n } // if the body has overflow\n\n\n if (document.body.scrollHeight > window.innerHeight) {\n // add padding so the content doesn't shift after removal of scrollbar\n states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));\n document.body.style.paddingRight = \"\".concat(states.previousBodyPadding + measureScrollbar(), \"px\");\n }\n };\n const undoScrollbar = () => {\n if (states.previousBodyPadding !== null) {\n document.body.style.paddingRight = \"\".concat(states.previousBodyPadding, \"px\");\n states.previousBodyPadding = null;\n }\n };\n\n /* istanbul ignore file */\n\n const iOSfix = () => {\n const iOS = // @ts-ignore\n /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;\n\n if (iOS && !hasClass(document.body, swalClasses.iosfix)) {\n const offset = document.body.scrollTop;\n document.body.style.top = \"\".concat(offset * -1, \"px\");\n addClass(document.body, swalClasses.iosfix);\n lockBodyScroll();\n addBottomPaddingForTallPopups();\n }\n };\n /**\n * https://github.com/sweetalert2/sweetalert2/issues/1948\n */\n\n const addBottomPaddingForTallPopups = () => {\n const ua = navigator.userAgent;\n const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);\n const webkit = !!ua.match(/WebKit/i);\n const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);\n\n if (iOSSafari) {\n const bottomPanelHeight = 44;\n\n if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) {\n getContainer().style.paddingBottom = \"\".concat(bottomPanelHeight, \"px\");\n }\n }\n };\n /**\n * https://github.com/sweetalert2/sweetalert2/issues/1246\n */\n\n\n const lockBodyScroll = () => {\n const container = getContainer();\n let preventTouchMove;\n\n container.ontouchstart = e => {\n preventTouchMove = shouldPreventTouchMove(e);\n };\n\n container.ontouchmove = e => {\n if (preventTouchMove) {\n e.preventDefault();\n e.stopPropagation();\n }\n };\n };\n\n const shouldPreventTouchMove = event => {\n const target = event.target;\n const container = getContainer();\n\n if (isStylus(event) || isZoom(event)) {\n return false;\n }\n\n if (target === container) {\n return true;\n }\n\n if (!isScrollable(container) && target.tagName !== 'INPUT' && // #1603\n target.tagName !== 'TEXTAREA' && // #2266\n !(isScrollable(getHtmlContainer()) && // #1944\n getHtmlContainer().contains(target))) {\n return true;\n }\n\n return false;\n };\n /**\n * https://github.com/sweetalert2/sweetalert2/issues/1786\n *\n * @param {*} event\n * @returns {boolean}\n */\n\n\n const isStylus = event => {\n return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';\n };\n /**\n * https://github.com/sweetalert2/sweetalert2/issues/1891\n *\n * @param {TouchEvent} event\n * @returns {boolean}\n */\n\n\n const isZoom = event => {\n return event.touches && event.touches.length > 1;\n };\n\n const undoIOSfix = () => {\n if (hasClass(document.body, swalClasses.iosfix)) {\n const offset = parseInt(document.body.style.top, 10);\n removeClass(document.body, swalClasses.iosfix);\n document.body.style.top = '';\n document.body.scrollTop = offset * -1;\n }\n };\n\n const SHOW_CLASS_TIMEOUT = 10;\n /**\n * Open popup, add necessary classes and styles, fix scrollbar\n *\n * @param params\n */\n\n const openPopup = params => {\n const container = getContainer();\n const popup = getPopup();\n\n if (typeof params.willOpen === 'function') {\n params.willOpen(popup);\n }\n\n const bodyStyles = window.getComputedStyle(document.body);\n const initialBodyOverflow = bodyStyles.overflowY;\n addClasses$1(container, popup, params); // scrolling is 'hidden' until animation is done, after that 'auto'\n\n setTimeout(() => {\n setScrollingVisibility(container, popup);\n }, SHOW_CLASS_TIMEOUT);\n\n if (isModal()) {\n fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);\n setAriaHidden();\n }\n\n if (!isToast() && !globalState.previousActiveElement) {\n globalState.previousActiveElement = document.activeElement;\n }\n\n if (typeof params.didOpen === 'function') {\n setTimeout(() => params.didOpen(popup));\n }\n\n removeClass(container, swalClasses['no-transition']);\n };\n\n const swalOpenAnimationFinished = event => {\n const popup = getPopup();\n\n if (event.target !== popup) {\n return;\n }\n\n const container = getContainer();\n popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);\n container.style.overflowY = 'auto';\n };\n\n const setScrollingVisibility = (container, popup) => {\n if (animationEndEvent && hasCssAnimation(popup)) {\n container.style.overflowY = 'hidden';\n popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);\n } else {\n container.style.overflowY = 'auto';\n }\n };\n\n const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {\n iOSfix();\n\n if (scrollbarPadding && initialBodyOverflow !== 'hidden') {\n fixScrollbar();\n } // sweetalert2/issues/1247\n\n\n setTimeout(() => {\n container.scrollTop = 0;\n });\n };\n\n const addClasses$1 = (container, popup, params) => {\n addClass(container, params.showClass.backdrop); // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059\n\n popup.style.setProperty('opacity', '0', 'important');\n show(popup, 'grid');\n setTimeout(() => {\n // Animate popup right after showing it\n addClass(popup, params.showClass.popup); // and remove the opacity workaround\n\n popup.style.removeProperty('opacity');\n }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062\n\n addClass([document.documentElement, document.body], swalClasses.shown);\n\n if (params.heightAuto && params.backdrop && !params.toast) {\n addClass([document.documentElement, document.body], swalClasses['height-auto']);\n }\n };\n\n /**\n * Shows loader (spinner), this is useful with AJAX requests.\n * By default the loader be shown instead of the \"Confirm\" button.\n */\n\n const showLoading = buttonToReplace => {\n let popup = getPopup();\n\n if (!popup) {\n new Swal(); // eslint-disable-line no-new\n }\n\n popup = getPopup();\n const loader = getLoader();\n\n if (isToast()) {\n hide(getIcon());\n } else {\n replaceButton(popup, buttonToReplace);\n }\n\n show(loader);\n popup.setAttribute('data-loading', 'true');\n popup.setAttribute('aria-busy', 'true');\n popup.focus();\n };\n\n const replaceButton = (popup, buttonToReplace) => {\n const actions = getActions();\n const loader = getLoader();\n\n if (!buttonToReplace && isVisible(getConfirmButton())) {\n buttonToReplace = getConfirmButton();\n }\n\n show(actions);\n\n if (buttonToReplace) {\n hide(buttonToReplace);\n loader.setAttribute('data-button-to-replace', buttonToReplace.className);\n }\n\n loader.parentNode.insertBefore(loader, buttonToReplace);\n addClass([popup, actions], swalClasses.loading);\n };\n\n const handleInputOptionsAndValue = (instance, params) => {\n if (params.input === 'select' || params.input === 'radio') {\n handleInputOptions(instance, params);\n } else if (['text', 'email', 'number', 'tel', 'textarea'].includes(params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {\n showLoading(getConfirmButton());\n handleInputValue(instance, params);\n }\n };\n const getInputValue = (instance, innerParams) => {\n const input = instance.getInput();\n\n if (!input) {\n return null;\n }\n\n switch (innerParams.input) {\n case 'checkbox':\n return getCheckboxValue(input);\n\n case 'radio':\n return getRadioValue(input);\n\n case 'file':\n return getFileValue(input);\n\n default:\n return innerParams.inputAutoTrim ? input.value.trim() : input.value;\n }\n };\n\n const getCheckboxValue = input => input.checked ? 1 : 0;\n\n const getRadioValue = input => input.checked ? input.value : null;\n\n const getFileValue = input => input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;\n\n const handleInputOptions = (instance, params) => {\n const popup = getPopup();\n\n const processInputOptions = inputOptions => populateInputOptions[params.input](popup, formatInputOptions(inputOptions), params);\n\n if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {\n showLoading(getConfirmButton());\n asPromise(params.inputOptions).then(inputOptions => {\n instance.hideLoading();\n processInputOptions(inputOptions);\n });\n } else if (typeof params.inputOptions === 'object') {\n processInputOptions(params.inputOptions);\n } else {\n error(\"Unexpected type of inputOptions! Expected object, Map or Promise, got \".concat(typeof params.inputOptions));\n }\n };\n\n const handleInputValue = (instance, params) => {\n const input = instance.getInput();\n hide(input);\n asPromise(params.inputValue).then(inputValue => {\n input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : \"\".concat(inputValue);\n show(input);\n input.focus();\n instance.hideLoading();\n }).catch(err => {\n error(\"Error in inputValue promise: \".concat(err));\n input.value = '';\n show(input);\n input.focus();\n instance.hideLoading();\n });\n };\n\n const populateInputOptions = {\n select: (popup, inputOptions, params) => {\n const select = getDirectChildByClass(popup, swalClasses.select);\n\n const renderOption = (parent, optionLabel, optionValue) => {\n const option = document.createElement('option');\n option.value = optionValue;\n setInnerHtml(option, optionLabel);\n option.selected = isSelected(optionValue, params.inputValue);\n parent.appendChild(option);\n };\n\n inputOptions.forEach(inputOption => {\n const optionValue = inputOption[0];\n const optionLabel = inputOption[1]; // spec:\n // https://www.w3.org/TR/html401/interact/forms.html#h-17.6\n // \"...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)...\"\n // check whether this is a \n\n if (Array.isArray(optionLabel)) {\n // if it is an array, then it is an \n const optgroup = document.createElement('optgroup');\n optgroup.label = optionValue;\n optgroup.disabled = false; // not configurable for now\n\n select.appendChild(optgroup);\n optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));\n } else {\n // case of \n valueFormatted = formatInputOptions(valueFormatted);\n }\n\n result.push([key, valueFormatted]);\n });\n } else {\n Object.keys(inputOptions).forEach(key => {\n let valueFormatted = inputOptions[key];\n\n if (typeof valueFormatted === 'object') {\n // case of \n valueFormatted = formatInputOptions(valueFormatted);\n }\n\n result.push([key, valueFormatted]);\n });\n }\n\n return result;\n };\n\n const isSelected = (optionValue, inputValue) => {\n return inputValue && inputValue.toString() === optionValue.toString();\n };\n\n /**\n * Hides loader and shows back the button which was hidden by .showLoading()\n */\n\n function hideLoading() {\n // do nothing if popup is closed\n const innerParams = privateProps.innerParams.get(this);\n\n if (!innerParams) {\n return;\n }\n\n const domCache = privateProps.domCache.get(this);\n hide(domCache.loader);\n\n if (isToast()) {\n if (innerParams.icon) {\n show(getIcon());\n }\n } else {\n showRelatedButton(domCache);\n }\n\n removeClass([domCache.popup, domCache.actions], swalClasses.loading);\n domCache.popup.removeAttribute('aria-busy');\n domCache.popup.removeAttribute('data-loading');\n domCache.confirmButton.disabled = false;\n domCache.denyButton.disabled = false;\n domCache.cancelButton.disabled = false;\n }\n\n const showRelatedButton = domCache => {\n const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));\n\n if (buttonToReplace.length) {\n show(buttonToReplace[0], 'inline-block');\n } else if (allButtonsAreHidden()) {\n hide(domCache.actions);\n }\n };\n\n /**\n * Gets the input DOM node, this method works with input parameter.\n * @returns {HTMLElement | null}\n */\n\n function getInput$1(instance) {\n const innerParams = privateProps.innerParams.get(instance || this);\n const domCache = privateProps.domCache.get(instance || this);\n\n if (!domCache) {\n return null;\n }\n\n return getInput(domCache.popup, innerParams.input);\n }\n\n /**\n * This module contains `WeakMap`s for each effectively-\"private property\" that a `Swal` has.\n * For example, to set the private property \"foo\" of `this` to \"bar\", you can `privateProps.foo.set(this, 'bar')`\n * This is the approach that Babel will probably take to implement private methods/fields\n * https://github.com/tc39/proposal-private-methods\n * https://github.com/babel/babel/pull/7555\n * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*\n * then we can use that language feature.\n */\n var privateMethods = {\n swalPromiseResolve: new WeakMap(),\n swalPromiseReject: new WeakMap()\n };\n\n /*\n * Global function to determine if SweetAlert2 popup is shown\n */\n\n const isVisible$1 = () => {\n return isVisible(getPopup());\n };\n /*\n * Global function to click 'Confirm' button\n */\n\n const clickConfirm = () => getConfirmButton() && getConfirmButton().click();\n /*\n * Global function to click 'Deny' button\n */\n\n const clickDeny = () => getDenyButton() && getDenyButton().click();\n /*\n * Global function to click 'Cancel' button\n */\n\n const clickCancel = () => getCancelButton() && getCancelButton().click();\n\n /**\n * @param {GlobalState} globalState\n */\n\n const removeKeydownHandler = globalState => {\n if (globalState.keydownTarget && globalState.keydownHandlerAdded) {\n globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {\n capture: globalState.keydownListenerCapture\n });\n globalState.keydownHandlerAdded = false;\n }\n };\n /**\n * @param {SweetAlert2} instance\n * @param {GlobalState} globalState\n * @param {SweetAlertOptions} innerParams\n * @param {*} dismissWith\n */\n\n const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => {\n removeKeydownHandler(globalState);\n\n if (!innerParams.toast) {\n globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith);\n\n globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();\n globalState.keydownListenerCapture = innerParams.keydownListenerCapture;\n globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {\n capture: globalState.keydownListenerCapture\n });\n globalState.keydownHandlerAdded = true;\n }\n };\n /**\n * @param {SweetAlertOptions} innerParams\n * @param {number} index\n * @param {number} increment\n */\n\n const setFocus = (innerParams, index, increment) => {\n const focusableElements = getFocusableElements(); // search for visible elements and select the next possible match\n\n if (focusableElements.length) {\n index = index + increment; // rollover to first item\n\n if (index === focusableElements.length) {\n index = 0; // go to last item\n } else if (index === -1) {\n index = focusableElements.length - 1;\n }\n\n return focusableElements[index].focus();\n } // no visible focusable elements, focus the popup\n\n\n getPopup().focus();\n };\n const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];\n const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];\n /**\n * @param {SweetAlert2} instance\n * @param {KeyboardEvent} e\n * @param {function} dismissWith\n */\n\n const keydownHandler = (instance, e, dismissWith) => {\n const innerParams = privateProps.innerParams.get(instance);\n\n if (!innerParams) {\n return; // This instance has already been destroyed\n } // Ignore keydown during IME composition\n // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition\n // https://github.com/sweetalert2/sweetalert2/issues/720\n // https://github.com/sweetalert2/sweetalert2/issues/2406\n\n\n if (e.isComposing || e.keyCode === 229) {\n return;\n }\n\n if (innerParams.stopKeydownPropagation) {\n e.stopPropagation();\n } // ENTER\n\n\n if (e.key === 'Enter') {\n handleEnter(instance, e, innerParams);\n } // TAB\n else if (e.key === 'Tab') {\n handleTab(e, innerParams);\n } // ARROWS - switch focus between buttons\n else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(e.key)) {\n handleArrows(e.key);\n } // ESC\n else if (e.key === 'Escape') {\n handleEsc(e, innerParams, dismissWith);\n }\n };\n /**\n * @param {SweetAlert2} instance\n * @param {KeyboardEvent} e\n * @param {SweetAlertOptions} innerParams\n */\n\n\n const handleEnter = (instance, e, innerParams) => {\n // https://github.com/sweetalert2/sweetalert2/issues/2386\n if (!callIfFunction(innerParams.allowEnterKey)) {\n return;\n }\n\n if (e.target && instance.getInput() && e.target instanceof HTMLElement && e.target.outerHTML === instance.getInput().outerHTML) {\n if (['textarea', 'file'].includes(innerParams.input)) {\n return; // do not submit\n }\n\n clickConfirm();\n e.preventDefault();\n }\n };\n /**\n * @param {KeyboardEvent} e\n * @param {SweetAlertOptions} innerParams\n */\n\n\n const handleTab = (e, innerParams) => {\n const targetElement = e.target;\n const focusableElements = getFocusableElements();\n let btnIndex = -1;\n\n for (let i = 0; i < focusableElements.length; i++) {\n if (targetElement === focusableElements[i]) {\n btnIndex = i;\n break;\n }\n } // Cycle to the next button\n\n\n if (!e.shiftKey) {\n setFocus(innerParams, btnIndex, 1);\n } // Cycle to the prev button\n else {\n setFocus(innerParams, btnIndex, -1);\n }\n\n e.stopPropagation();\n e.preventDefault();\n };\n /**\n * @param {string} key\n */\n\n\n const handleArrows = key => {\n const confirmButton = getConfirmButton();\n const denyButton = getDenyButton();\n const cancelButton = getCancelButton();\n\n if (document.activeElement instanceof HTMLElement && ![confirmButton, denyButton, cancelButton].includes(document.activeElement)) {\n return;\n }\n\n const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';\n let buttonToFocus = document.activeElement;\n\n for (let i = 0; i < getActions().children.length; i++) {\n buttonToFocus = buttonToFocus[sibling];\n\n if (!buttonToFocus) {\n return;\n }\n\n if (buttonToFocus instanceof HTMLButtonElement && isVisible(buttonToFocus)) {\n break;\n }\n }\n\n if (buttonToFocus instanceof HTMLButtonElement) {\n buttonToFocus.focus();\n }\n };\n /**\n * @param {KeyboardEvent} e\n * @param {SweetAlertOptions} innerParams\n * @param {function} dismissWith\n */\n\n\n const handleEsc = (e, innerParams, dismissWith) => {\n if (callIfFunction(innerParams.allowEscapeKey)) {\n e.preventDefault();\n dismissWith(DismissReason.esc);\n }\n };\n\n /*\n * Instance method to close sweetAlert\n */\n\n function removePopupAndResetState(instance, container, returnFocus, didClose) {\n if (isToast()) {\n triggerDidCloseAndDispose(instance, didClose);\n } else {\n restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));\n removeKeydownHandler(globalState);\n }\n\n const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); // workaround for #2088\n // for some reason removing the container in Safari will scroll the document to bottom\n\n if (isSafari) {\n container.setAttribute('style', 'display:none !important');\n container.removeAttribute('class');\n container.innerHTML = '';\n } else {\n container.remove();\n }\n\n if (isModal()) {\n undoScrollbar();\n undoIOSfix();\n unsetAriaHidden();\n }\n\n removeBodyClasses();\n }\n\n function removeBodyClasses() {\n removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);\n }\n\n function close(resolveValue) {\n resolveValue = prepareResolveValue(resolveValue);\n const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);\n const didClose = triggerClosePopup(this);\n\n if (this.isAwaitingPromise()) {\n // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335\n if (!resolveValue.isDismissed) {\n handleAwaitingPromise(this);\n swalPromiseResolve(resolveValue);\n }\n } else if (didClose) {\n // Resolve Swal promise\n swalPromiseResolve(resolveValue);\n }\n }\n function isAwaitingPromise() {\n return !!privateProps.awaitingPromise.get(this);\n }\n\n const triggerClosePopup = instance => {\n const popup = getPopup();\n\n if (!popup) {\n return false;\n }\n\n const innerParams = privateProps.innerParams.get(instance);\n\n if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {\n return false;\n }\n\n removeClass(popup, innerParams.showClass.popup);\n addClass(popup, innerParams.hideClass.popup);\n const backdrop = getContainer();\n removeClass(backdrop, innerParams.showClass.backdrop);\n addClass(backdrop, innerParams.hideClass.backdrop);\n handlePopupAnimation(instance, popup, innerParams);\n return true;\n };\n\n function rejectPromise(error) {\n const rejectPromise = privateMethods.swalPromiseReject.get(this);\n handleAwaitingPromise(this);\n\n if (rejectPromise) {\n // Reject Swal promise\n rejectPromise(error);\n }\n }\n const handleAwaitingPromise = instance => {\n if (instance.isAwaitingPromise()) {\n privateProps.awaitingPromise.delete(instance); // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335\n\n if (!privateProps.innerParams.get(instance)) {\n instance._destroy();\n }\n }\n };\n\n const prepareResolveValue = resolveValue => {\n // When user calls Swal.close()\n if (typeof resolveValue === 'undefined') {\n return {\n isConfirmed: false,\n isDenied: false,\n isDismissed: true\n };\n }\n\n return Object.assign({\n isConfirmed: false,\n isDenied: false,\n isDismissed: false\n }, resolveValue);\n };\n\n const handlePopupAnimation = (instance, popup, innerParams) => {\n const container = getContainer(); // If animation is supported, animate\n\n const animationIsSupported = animationEndEvent && hasCssAnimation(popup);\n\n if (typeof innerParams.willClose === 'function') {\n innerParams.willClose(popup);\n }\n\n if (animationIsSupported) {\n animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);\n } else {\n // Otherwise, remove immediately\n removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);\n }\n };\n\n const animatePopup = (instance, popup, container, returnFocus, didClose) => {\n globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);\n popup.addEventListener(animationEndEvent, function (e) {\n if (e.target === popup) {\n globalState.swalCloseEventFinishedCallback();\n delete globalState.swalCloseEventFinishedCallback;\n }\n });\n };\n\n const triggerDidCloseAndDispose = (instance, didClose) => {\n setTimeout(() => {\n if (typeof didClose === 'function') {\n didClose.bind(instance.params)();\n }\n\n instance._destroy();\n });\n };\n\n function setButtonsDisabled(instance, buttons, disabled) {\n const domCache = privateProps.domCache.get(instance);\n buttons.forEach(button => {\n domCache[button].disabled = disabled;\n });\n }\n\n function setInputDisabled(input, disabled) {\n if (!input) {\n return false;\n }\n\n if (input.type === 'radio') {\n const radiosContainer = input.parentNode.parentNode;\n const radios = radiosContainer.querySelectorAll('input');\n\n for (let i = 0; i < radios.length; i++) {\n radios[i].disabled = disabled;\n }\n } else {\n input.disabled = disabled;\n }\n }\n\n function enableButtons() {\n setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);\n }\n function disableButtons() {\n setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);\n }\n function enableInput() {\n return setInputDisabled(this.getInput(), false);\n }\n function disableInput() {\n return setInputDisabled(this.getInput(), true);\n }\n\n function showValidationMessage(error) {\n const domCache = privateProps.domCache.get(this);\n const params = privateProps.innerParams.get(this);\n setInnerHtml(domCache.validationMessage, error);\n domCache.validationMessage.className = swalClasses['validation-message'];\n\n if (params.customClass && params.customClass.validationMessage) {\n addClass(domCache.validationMessage, params.customClass.validationMessage);\n }\n\n show(domCache.validationMessage);\n const input = this.getInput();\n\n if (input) {\n input.setAttribute('aria-invalid', true);\n input.setAttribute('aria-describedby', swalClasses['validation-message']);\n focusInput(input);\n addClass(input, swalClasses.inputerror);\n }\n } // Hide block with validation message\n\n function resetValidationMessage$1() {\n const domCache = privateProps.domCache.get(this);\n\n if (domCache.validationMessage) {\n hide(domCache.validationMessage);\n }\n\n const input = this.getInput();\n\n if (input) {\n input.removeAttribute('aria-invalid');\n input.removeAttribute('aria-describedby');\n removeClass(input, swalClasses.inputerror);\n }\n }\n\n function getProgressSteps$1() {\n const domCache = privateProps.domCache.get(this);\n return domCache.progressSteps;\n }\n\n /**\n * Updates popup parameters.\n */\n\n function update(params) {\n const popup = getPopup();\n const innerParams = privateProps.innerParams.get(this);\n\n if (!popup || hasClass(popup, innerParams.hideClass.popup)) {\n return warn(\"You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.\");\n }\n\n const validUpdatableParams = filterValidParams(params);\n const updatedParams = Object.assign({}, innerParams, validUpdatableParams);\n render(this, updatedParams);\n privateProps.innerParams.set(this, updatedParams);\n Object.defineProperties(this, {\n params: {\n value: Object.assign({}, this.params, params),\n writable: false,\n enumerable: true\n }\n });\n }\n\n const filterValidParams = params => {\n const validUpdatableParams = {};\n Object.keys(params).forEach(param => {\n if (isUpdatableParameter(param)) {\n validUpdatableParams[param] = params[param];\n } else {\n warn(\"Invalid parameter to update: \".concat(param));\n }\n });\n return validUpdatableParams;\n };\n\n function _destroy() {\n const domCache = privateProps.domCache.get(this);\n const innerParams = privateProps.innerParams.get(this);\n\n if (!innerParams) {\n disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335\n\n return; // This instance has already been destroyed\n } // Check if there is another Swal closing\n\n\n if (domCache.popup && globalState.swalCloseEventFinishedCallback) {\n globalState.swalCloseEventFinishedCallback();\n delete globalState.swalCloseEventFinishedCallback;\n }\n\n if (typeof innerParams.didDestroy === 'function') {\n innerParams.didDestroy();\n }\n\n disposeSwal(this);\n }\n /**\n * @param {SweetAlert2} instance\n */\n\n const disposeSwal = instance => {\n disposeWeakMaps(instance); // Unset this.params so GC will dispose it (#1569)\n // @ts-ignore\n\n delete instance.params; // Unset globalState props so GC will dispose globalState (#1569)\n\n delete globalState.keydownHandler;\n delete globalState.keydownTarget; // Unset currentInstance\n\n delete globalState.currentInstance;\n };\n /**\n * @param {SweetAlert2} instance\n */\n\n\n const disposeWeakMaps = instance => {\n // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335\n // @ts-ignore\n if (instance.isAwaitingPromise()) {\n unsetWeakMaps(privateProps, instance);\n privateProps.awaitingPromise.set(instance, true);\n } else {\n unsetWeakMaps(privateMethods, instance);\n unsetWeakMaps(privateProps, instance);\n }\n };\n /**\n * @param {object} obj\n * @param {SweetAlert2} instance\n */\n\n\n const unsetWeakMaps = (obj, instance) => {\n for (const i in obj) {\n obj[i].delete(instance);\n }\n };\n\n\n\n var instanceMethods = /*#__PURE__*/Object.freeze({\n hideLoading: hideLoading,\n disableLoading: hideLoading,\n getInput: getInput$1,\n close: close,\n isAwaitingPromise: isAwaitingPromise,\n rejectPromise: rejectPromise,\n handleAwaitingPromise: handleAwaitingPromise,\n closePopup: close,\n closeModal: close,\n closeToast: close,\n enableButtons: enableButtons,\n disableButtons: disableButtons,\n enableInput: enableInput,\n disableInput: disableInput,\n showValidationMessage: showValidationMessage,\n resetValidationMessage: resetValidationMessage$1,\n getProgressSteps: getProgressSteps$1,\n update: update,\n _destroy: _destroy\n });\n\n const handleConfirmButtonClick = instance => {\n const innerParams = privateProps.innerParams.get(instance);\n instance.disableButtons();\n\n if (innerParams.input) {\n handleConfirmOrDenyWithInput(instance, 'confirm');\n } else {\n confirm(instance, true);\n }\n };\n const handleDenyButtonClick = instance => {\n const innerParams = privateProps.innerParams.get(instance);\n instance.disableButtons();\n\n if (innerParams.returnInputValueOnDeny) {\n handleConfirmOrDenyWithInput(instance, 'deny');\n } else {\n deny(instance, false);\n }\n };\n const handleCancelButtonClick = (instance, dismissWith) => {\n instance.disableButtons();\n dismissWith(DismissReason.cancel);\n };\n\n const handleConfirmOrDenyWithInput = (instance, type\n /* 'confirm' | 'deny' */\n ) => {\n const innerParams = privateProps.innerParams.get(instance);\n\n if (!innerParams.input) {\n return error(\"The \\\"input\\\" parameter is needed to be set when using returnInputValueOn\".concat(capitalizeFirstLetter(type)));\n }\n\n const inputValue = getInputValue(instance, innerParams);\n\n if (innerParams.inputValidator) {\n handleInputValidator(instance, inputValue, type);\n } else if (!instance.getInput().checkValidity()) {\n instance.enableButtons();\n instance.showValidationMessage(innerParams.validationMessage);\n } else if (type === 'deny') {\n deny(instance, inputValue);\n } else {\n confirm(instance, inputValue);\n }\n };\n\n const handleInputValidator = (instance, inputValue, type\n /* 'confirm' | 'deny' */\n ) => {\n const innerParams = privateProps.innerParams.get(instance);\n instance.disableInput();\n const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));\n validationPromise.then(validationMessage => {\n instance.enableButtons();\n instance.enableInput();\n\n if (validationMessage) {\n instance.showValidationMessage(validationMessage);\n } else if (type === 'deny') {\n deny(instance, inputValue);\n } else {\n confirm(instance, inputValue);\n }\n });\n };\n\n const deny = (instance, value) => {\n const innerParams = privateProps.innerParams.get(instance || undefined);\n\n if (innerParams.showLoaderOnDeny) {\n showLoading(getDenyButton());\n }\n\n if (innerParams.preDeny) {\n privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received\n\n const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));\n preDenyPromise.then(preDenyValue => {\n if (preDenyValue === false) {\n instance.hideLoading();\n handleAwaitingPromise(instance);\n } else {\n instance.closePopup({\n isDenied: true,\n value: typeof preDenyValue === 'undefined' ? value : preDenyValue\n });\n }\n }).catch(error$$1 => rejectWith(instance || undefined, error$$1));\n } else {\n instance.closePopup({\n isDenied: true,\n value\n });\n }\n };\n\n const succeedWith = (instance, value) => {\n instance.closePopup({\n isConfirmed: true,\n value\n });\n };\n\n const rejectWith = (instance, error$$1) => {\n instance.rejectPromise(error$$1);\n };\n\n const confirm = (instance, value) => {\n const innerParams = privateProps.innerParams.get(instance || undefined);\n\n if (innerParams.showLoaderOnConfirm) {\n showLoading();\n }\n\n if (innerParams.preConfirm) {\n instance.resetValidationMessage();\n privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received\n\n const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));\n preConfirmPromise.then(preConfirmValue => {\n if (isVisible(getValidationMessage()) || preConfirmValue === false) {\n instance.hideLoading();\n handleAwaitingPromise(instance);\n } else {\n succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);\n }\n }).catch(error$$1 => rejectWith(instance || undefined, error$$1));\n } else {\n succeedWith(instance, value);\n }\n };\n\n const handlePopupClick = (instance, domCache, dismissWith) => {\n const innerParams = privateProps.innerParams.get(instance);\n\n if (innerParams.toast) {\n handleToastClick(instance, domCache, dismissWith);\n } else {\n // Ignore click events that had mousedown on the popup but mouseup on the container\n // This can happen when the user drags a slider\n handleModalMousedown(domCache); // Ignore click events that had mousedown on the container but mouseup on the popup\n\n handleContainerMousedown(domCache);\n handleModalClick(instance, domCache, dismissWith);\n }\n };\n\n const handleToastClick = (instance, domCache, dismissWith) => {\n // Closing toast by internal click\n domCache.popup.onclick = () => {\n const innerParams = privateProps.innerParams.get(instance);\n\n if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {\n return;\n }\n\n dismissWith(DismissReason.close);\n };\n };\n /**\n * @param {*} innerParams\n * @returns {boolean}\n */\n\n\n const isAnyButtonShown = innerParams => {\n return innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton;\n };\n\n let ignoreOutsideClick = false;\n\n const handleModalMousedown = domCache => {\n domCache.popup.onmousedown = () => {\n domCache.container.onmouseup = function (e) {\n domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't\n // have any other direct children aside of the popup\n\n if (e.target === domCache.container) {\n ignoreOutsideClick = true;\n }\n };\n };\n };\n\n const handleContainerMousedown = domCache => {\n domCache.container.onmousedown = () => {\n domCache.popup.onmouseup = function (e) {\n domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup\n\n if (e.target === domCache.popup || domCache.popup.contains(e.target)) {\n ignoreOutsideClick = true;\n }\n };\n };\n };\n\n const handleModalClick = (instance, domCache, dismissWith) => {\n domCache.container.onclick = e => {\n const innerParams = privateProps.innerParams.get(instance);\n\n if (ignoreOutsideClick) {\n ignoreOutsideClick = false;\n return;\n }\n\n if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {\n dismissWith(DismissReason.backdrop);\n }\n };\n };\n\n const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;\n\n const isElement = elem => elem instanceof Element || isJqueryElement(elem);\n\n const argsToParams = args => {\n const params = {};\n\n if (typeof args[0] === 'object' && !isElement(args[0])) {\n Object.assign(params, args[0]);\n } else {\n ['title', 'html', 'icon'].forEach((name, index) => {\n const arg = args[index];\n\n if (typeof arg === 'string' || isElement(arg)) {\n params[name] = arg;\n } else if (arg !== undefined) {\n error(\"Unexpected type of \".concat(name, \"! Expected \\\"string\\\" or \\\"Element\\\", got \").concat(typeof arg));\n }\n });\n }\n\n return params;\n };\n\n function fire() {\n const Swal = this; // eslint-disable-line @typescript-eslint/no-this-alias\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return new Swal(...args);\n }\n\n /**\n * Returns an extended version of `Swal` containing `params` as defaults.\n * Useful for reusing Swal configuration.\n *\n * For example:\n *\n * Before:\n * const textPromptOptions = { input: 'text', showCancelButton: true }\n * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })\n * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })\n *\n * After:\n * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })\n * const {value: firstName} = await TextPrompt('What is your first name?')\n * const {value: lastName} = await TextPrompt('What is your last name?')\n *\n * @param mixinParams\n */\n function mixin(mixinParams) {\n class MixinSwal extends this {\n _main(params, priorityMixinParams) {\n return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));\n }\n\n }\n\n return MixinSwal;\n }\n\n /**\n * If `timer` parameter is set, returns number of milliseconds of timer remained.\n * Otherwise, returns undefined.\n */\n\n const getTimerLeft = () => {\n return globalState.timeout && globalState.timeout.getTimerLeft();\n };\n /**\n * Stop timer. Returns number of milliseconds of timer remained.\n * If `timer` parameter isn't set, returns undefined.\n */\n\n const stopTimer = () => {\n if (globalState.timeout) {\n stopTimerProgressBar();\n return globalState.timeout.stop();\n }\n };\n /**\n * Resume timer. Returns number of milliseconds of timer remained.\n * If `timer` parameter isn't set, returns undefined.\n */\n\n const resumeTimer = () => {\n if (globalState.timeout) {\n const remaining = globalState.timeout.start();\n animateTimerProgressBar(remaining);\n return remaining;\n }\n };\n /**\n * Resume timer. Returns number of milliseconds of timer remained.\n * If `timer` parameter isn't set, returns undefined.\n */\n\n const toggleTimer = () => {\n const timer = globalState.timeout;\n return timer && (timer.running ? stopTimer() : resumeTimer());\n };\n /**\n * Increase timer. Returns number of milliseconds of an updated timer.\n * If `timer` parameter isn't set, returns undefined.\n */\n\n const increaseTimer = n => {\n if (globalState.timeout) {\n const remaining = globalState.timeout.increase(n);\n animateTimerProgressBar(remaining, true);\n return remaining;\n }\n };\n /**\n * Check if timer is running. Returns true if timer is running\n * or false if timer is paused or stopped.\n * If `timer` parameter isn't set, returns undefined\n */\n\n const isTimerRunning = () => {\n return globalState.timeout && globalState.timeout.isRunning();\n };\n\n let bodyClickListenerAdded = false;\n const clickHandlers = {};\n function bindClickHandler() {\n let attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';\n clickHandlers[attr] = this;\n\n if (!bodyClickListenerAdded) {\n document.body.addEventListener('click', bodyClickListener);\n bodyClickListenerAdded = true;\n }\n }\n\n const bodyClickListener = event => {\n for (let el = event.target; el && el !== document; el = el.parentNode) {\n for (const attr in clickHandlers) {\n const template = el.getAttribute(attr);\n\n if (template) {\n clickHandlers[attr].fire({\n template\n });\n return;\n }\n }\n }\n };\n\n\n\n var staticMethods = /*#__PURE__*/Object.freeze({\n isValidParameter: isValidParameter,\n isUpdatableParameter: isUpdatableParameter,\n isDeprecatedParameter: isDeprecatedParameter,\n argsToParams: argsToParams,\n isVisible: isVisible$1,\n clickConfirm: clickConfirm,\n clickDeny: clickDeny,\n clickCancel: clickCancel,\n getContainer: getContainer,\n getPopup: getPopup,\n getTitle: getTitle,\n getHtmlContainer: getHtmlContainer,\n getImage: getImage,\n getIcon: getIcon,\n getInputLabel: getInputLabel,\n getCloseButton: getCloseButton,\n getActions: getActions,\n getConfirmButton: getConfirmButton,\n getDenyButton: getDenyButton,\n getCancelButton: getCancelButton,\n getLoader: getLoader,\n getFooter: getFooter,\n getTimerProgressBar: getTimerProgressBar,\n getFocusableElements: getFocusableElements,\n getValidationMessage: getValidationMessage,\n isLoading: isLoading,\n fire: fire,\n mixin: mixin,\n showLoading: showLoading,\n enableLoading: showLoading,\n getTimerLeft: getTimerLeft,\n stopTimer: stopTimer,\n resumeTimer: resumeTimer,\n toggleTimer: toggleTimer,\n increaseTimer: increaseTimer,\n isTimerRunning: isTimerRunning,\n bindClickHandler: bindClickHandler\n });\n\n let currentInstance;\n\n class SweetAlert {\n constructor() {\n // Prevent run in Node env\n if (typeof window === 'undefined') {\n return;\n }\n\n currentInstance = this; // @ts-ignore\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n const outerParams = Object.freeze(this.constructor.argsToParams(args));\n Object.defineProperties(this, {\n params: {\n value: outerParams,\n writable: false,\n enumerable: true,\n configurable: true\n }\n }); // @ts-ignore\n\n const promise = currentInstance._main(currentInstance.params);\n\n privateProps.promise.set(this, promise);\n }\n\n _main(userParams) {\n let mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n showWarningsForParams(Object.assign({}, mixinParams, userParams));\n\n if (globalState.currentInstance) {\n // @ts-ignore\n globalState.currentInstance._destroy();\n\n if (isModal()) {\n unsetAriaHidden();\n }\n }\n\n globalState.currentInstance = currentInstance;\n const innerParams = prepareParams(userParams, mixinParams);\n setParameters(innerParams);\n Object.freeze(innerParams); // clear the previous timer\n\n if (globalState.timeout) {\n globalState.timeout.stop();\n delete globalState.timeout;\n } // clear the restore focus timeout\n\n\n clearTimeout(globalState.restoreFocusTimeout);\n const domCache = populateDomCache(currentInstance);\n render(currentInstance, innerParams);\n privateProps.innerParams.set(currentInstance, innerParams);\n return swalPromise(currentInstance, domCache, innerParams);\n } // `catch` cannot be the name of a module export, so we define our thenable methods here instead\n\n\n then(onFulfilled) {\n const promise = privateProps.promise.get(this);\n return promise.then(onFulfilled);\n }\n\n finally(onFinally) {\n const promise = privateProps.promise.get(this);\n return promise.finally(onFinally);\n }\n\n }\n\n const swalPromise = (instance, domCache, innerParams) => {\n return new Promise((resolve, reject) => {\n // functions to handle all closings/dismissals\n const dismissWith = dismiss => {\n instance.closePopup({\n isDismissed: true,\n dismiss\n });\n };\n\n privateMethods.swalPromiseResolve.set(instance, resolve);\n privateMethods.swalPromiseReject.set(instance, reject);\n\n domCache.confirmButton.onclick = () => handleConfirmButtonClick(instance);\n\n domCache.denyButton.onclick = () => handleDenyButtonClick(instance);\n\n domCache.cancelButton.onclick = () => handleCancelButtonClick(instance, dismissWith);\n\n domCache.closeButton.onclick = () => dismissWith(DismissReason.close);\n\n handlePopupClick(instance, domCache, dismissWith);\n addKeydownHandler(instance, globalState, innerParams, dismissWith);\n handleInputOptionsAndValue(instance, innerParams);\n openPopup(innerParams);\n setupTimer(globalState, innerParams, dismissWith);\n initFocus(domCache, innerParams); // Scroll container to top on open (#1247, #1946)\n\n setTimeout(() => {\n domCache.container.scrollTop = 0;\n });\n });\n };\n\n const prepareParams = (userParams, mixinParams) => {\n const templateParams = getTemplateParams(userParams);\n const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131\n\n params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);\n params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);\n return params;\n };\n /**\n * @param {SweetAlert2} instance\n * @returns {DomCache}\n */\n\n\n const populateDomCache = instance => {\n const domCache = {\n popup: getPopup(),\n container: getContainer(),\n actions: getActions(),\n confirmButton: getConfirmButton(),\n denyButton: getDenyButton(),\n cancelButton: getCancelButton(),\n loader: getLoader(),\n closeButton: getCloseButton(),\n validationMessage: getValidationMessage(),\n progressSteps: getProgressSteps()\n };\n privateProps.domCache.set(instance, domCache);\n return domCache;\n };\n /**\n * @param {GlobalState} globalState\n * @param {SweetAlertOptions} innerParams\n * @param {function} dismissWith\n */\n\n\n const setupTimer = (globalState$$1, innerParams, dismissWith) => {\n const timerProgressBar = getTimerProgressBar();\n hide(timerProgressBar);\n\n if (innerParams.timer) {\n globalState$$1.timeout = new Timer(() => {\n dismissWith('timer');\n delete globalState$$1.timeout;\n }, innerParams.timer);\n\n if (innerParams.timerProgressBar) {\n show(timerProgressBar);\n applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');\n setTimeout(() => {\n if (globalState$$1.timeout && globalState$$1.timeout.running) {\n // timer can be already stopped or unset at this point\n animateTimerProgressBar(innerParams.timer);\n }\n });\n }\n }\n };\n /**\n * @param {DomCache} domCache\n * @param {SweetAlertOptions} innerParams\n */\n\n\n const initFocus = (domCache, innerParams) => {\n if (innerParams.toast) {\n return;\n }\n\n if (!callIfFunction(innerParams.allowEnterKey)) {\n return blurActiveElement();\n }\n\n if (!focusButton(domCache, innerParams)) {\n setFocus(innerParams, -1, 1);\n }\n };\n /**\n * @param {DomCache} domCache\n * @param {SweetAlertOptions} innerParams\n * @returns {boolean}\n */\n\n\n const focusButton = (domCache, innerParams) => {\n if (innerParams.focusDeny && isVisible(domCache.denyButton)) {\n domCache.denyButton.focus();\n return true;\n }\n\n if (innerParams.focusCancel && isVisible(domCache.cancelButton)) {\n domCache.cancelButton.focus();\n return true;\n }\n\n if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) {\n domCache.confirmButton.focus();\n return true;\n }\n\n return false;\n };\n\n const blurActiveElement = () => {\n if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {\n document.activeElement.blur();\n }\n }; // Assign instance methods from src/instanceMethods/*.js to prototype\n\n\n Object.assign(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor\n\n Object.assign(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility\n\n Object.keys(instanceMethods).forEach(key => {\n SweetAlert[key] = function () {\n if (currentInstance) {\n return currentInstance[key](...arguments);\n }\n };\n });\n SweetAlert.DismissReason = DismissReason;\n SweetAlert.version = '11.4.17';\n\n const Swal = SweetAlert; // @ts-ignore\n\n Swal.default = Swal;\n\n return Swal;\n\n}));\nif (typeof this !== 'undefined' && this.Sweetalert2){ this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}\n\n\"undefined\"!=typeof document&&function(e,t){var n=e.createElement(\"style\");if(e.getElementsByTagName(\"head\")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,\".swal2-popup.swal2-toast{box-sizing:border-box;grid-column:1/4!important;grid-row:1/4!important;grid-template-columns:1fr 99fr 1fr;padding:1em;overflow-y:hidden;background:#fff;box-shadow:0 0 1px hsla(0deg,0%,0%,.075),0 1px 2px hsla(0deg,0%,0%,.075),1px 2px 4px hsla(0deg,0%,0%,.075),1px 3px 8px hsla(0deg,0%,0%,.075),2px 4px 16px hsla(0deg,0%,0%,.075);pointer-events:all}.swal2-popup.swal2-toast>*{grid-column:2}.swal2-popup.swal2-toast .swal2-title{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-loading{justify-content:center}.swal2-popup.swal2-toast .swal2-input{height:2em;margin:.5em;font-size:1em}.swal2-popup.swal2-toast .swal2-validation-message{font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-popup.swal2-toast .swal2-html-container{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-html-container:empty{padding:0}.swal2-popup.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-popup.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:700}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-popup.swal2-toast .swal2-styled{margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.8em;left:-.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-toast-animate-success-line-tip .75s;animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-toast-animate-success-line-long .75s;animation:swal2-toast-animate-success-line-long .75s}.swal2-popup.swal2-toast.swal2-show{-webkit-animation:swal2-toast-show .5s;animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{-webkit-animation:swal2-toast-hide .1s forwards;animation:swal2-toast-hide .1s forwards}.swal2-container{display:grid;position:fixed;z-index:1060;top:0;right:0;bottom:0;left:0;box-sizing:border-box;grid-template-areas:\\\"top-start top top-end\\\" \\\"center-start center center-end\\\" \\\"bottom-start bottom-center bottom-end\\\";grid-template-rows:minmax(-webkit-min-content,auto) minmax(-webkit-min-content,auto) minmax(-webkit-min-content,auto);grid-template-rows:minmax(min-content,auto) minmax(min-content,auto) minmax(min-content,auto);height:100%;padding:.625em;overflow-x:hidden;transition:background-color .1s;-webkit-overflow-scrolling:touch}.swal2-container.swal2-backdrop-show,.swal2-container.swal2-noanimation{background:rgba(0,0,0,.4)}.swal2-container.swal2-backdrop-hide{background:0 0!important}.swal2-container.swal2-bottom-start,.swal2-container.swal2-center-start,.swal2-container.swal2-top-start{grid-template-columns:minmax(0,1fr) auto auto}.swal2-container.swal2-bottom,.swal2-container.swal2-center,.swal2-container.swal2-top{grid-template-columns:auto minmax(0,1fr) auto}.swal2-container.swal2-bottom-end,.swal2-container.swal2-center-end,.swal2-container.swal2-top-end{grid-template-columns:auto auto minmax(0,1fr)}.swal2-container.swal2-top-start>.swal2-popup{align-self:start}.swal2-container.swal2-top>.swal2-popup{grid-column:2;align-self:start;justify-self:center}.swal2-container.swal2-top-end>.swal2-popup,.swal2-container.swal2-top-right>.swal2-popup{grid-column:3;align-self:start;justify-self:end}.swal2-container.swal2-center-left>.swal2-popup,.swal2-container.swal2-center-start>.swal2-popup{grid-row:2;align-self:center}.swal2-container.swal2-center>.swal2-popup{grid-column:2;grid-row:2;align-self:center;justify-self:center}.swal2-container.swal2-center-end>.swal2-popup,.swal2-container.swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;align-self:center;justify-self:end}.swal2-container.swal2-bottom-left>.swal2-popup,.swal2-container.swal2-bottom-start>.swal2-popup{grid-column:1;grid-row:3;align-self:end}.swal2-container.swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;justify-self:center;align-self:end}.swal2-container.swal2-bottom-end>.swal2-popup,.swal2-container.swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;align-self:end;justify-self:end}.swal2-container.swal2-grow-fullscreen>.swal2-popup,.swal2-container.swal2-grow-row>.swal2-popup{grid-column:1/4;width:100%}.swal2-container.swal2-grow-column>.swal2-popup,.swal2-container.swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}.swal2-container.swal2-no-transition{transition:none!important}.swal2-popup{display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0,100%);width:32em;max-width:100%;padding:0 0 1.25em;border:none;border-radius:5px;background:#fff;color:#545454;font-family:inherit;font-size:1rem}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-title{position:relative;max-width:100%;margin:0;padding:.8em 1em 0;color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-actions{display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:center;width:auto;margin:1.25em auto 0;padding:0}.swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0,0,0,.1),rgba(0,0,0,.1))}.swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0,0,0,.2),rgba(0,0,0,.2))}.swal2-loader{display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 transparent #2778c4 transparent}.swal2-styled{margin:.3125em;padding:.625em 1.1em;transition:box-shadow .1s;box-shadow:0 0 0 3px transparent;font-weight:500}.swal2-styled:not([disabled]){cursor:pointer}.swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#7066e0;color:#fff;font-size:1em}.swal2-styled.swal2-confirm:focus{box-shadow:0 0 0 3px rgba(112,102,224,.5)}.swal2-styled.swal2-deny{border:0;border-radius:.25em;background:initial;background-color:#dc3741;color:#fff;font-size:1em}.swal2-styled.swal2-deny:focus{box-shadow:0 0 0 3px rgba(220,55,65,.5)}.swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#6e7881;color:#fff;font-size:1em}.swal2-styled.swal2-cancel:focus{box-shadow:0 0 0 3px rgba(110,120,129,.5)}.swal2-styled.swal2-default-outline:focus{box-shadow:0 0 0 3px rgba(100,150,200,.5)}.swal2-styled:focus{outline:0}.swal2-styled::-moz-focus-inner{border:0}.swal2-footer{justify-content:center;margin:1em 0 0;padding:1em 1em 0;border-top:1px solid #eee;color:inherit;font-size:1em}.swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto!important;overflow:hidden;border-bottom-right-radius:5px;border-bottom-left-radius:5px}.swal2-timer-progress-bar{width:100%;height:.25em;background:rgba(0,0,0,.2)}.swal2-image{max-width:100%;margin:2em auto 1em}.swal2-close{z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:color .1s,box-shadow .1s;border:none;border-radius:5px;background:0 0;color:#ccc;font-family:serif;font-family:monospace;font-size:2.5em;cursor:pointer;justify-self:end}.swal2-close:hover{transform:none;background:0 0;color:#f27474}.swal2-close:focus{outline:0;box-shadow:inset 0 0 0 3px rgba(100,150,200,.5)}.swal2-close::-moz-focus-inner{border:0}.swal2-html-container{z-index:1;justify-content:center;margin:1em 1.6em .3em;padding:0;overflow:auto;color:inherit;font-size:1.125em;font-weight:400;line-height:normal;text-align:center;word-wrap:break-word;word-break:break-word}.swal2-checkbox,.swal2-file,.swal2-input,.swal2-radio,.swal2-select,.swal2-textarea{margin:1em 2em 3px}.swal2-file,.swal2-input,.swal2-textarea{box-sizing:border-box;width:auto;transition:border-color .1s,box-shadow .1s;border:1px solid #d9d9d9;border-radius:.1875em;background:0 0;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px transparent;color:inherit;font-size:1.125em}.swal2-file.swal2-inputerror,.swal2-input.swal2-inputerror,.swal2-textarea.swal2-inputerror{border-color:#f27474!important;box-shadow:0 0 2px #f27474!important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{border:1px solid #b4dbed;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(100,150,200,.5)}.swal2-file::-moz-placeholder,.swal2-input::-moz-placeholder,.swal2-textarea::-moz-placeholder{color:#ccc}.swal2-file:-ms-input-placeholder,.swal2-input:-ms-input-placeholder,.swal2-textarea:-ms-input-placeholder{color:#ccc}.swal2-file::placeholder,.swal2-input::placeholder,.swal2-textarea::placeholder{color:#ccc}.swal2-range{margin:1em 2em 3px;background:#fff}.swal2-range input{width:80%}.swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}.swal2-range input,.swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}.swal2-input{height:2.625em;padding:0 .75em}.swal2-file{width:75%;margin-right:auto;margin-left:auto;background:0 0;font-size:1.125em}.swal2-textarea{height:6.75em;padding:.75em}.swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:0 0;color:inherit;font-size:1.125em}.swal2-checkbox,.swal2-radio{align-items:center;justify-content:center;background:#fff;color:inherit}.swal2-checkbox label,.swal2-radio label{margin:0 .6em;font-size:1.125em}.swal2-checkbox input,.swal2-radio input{flex-shrink:0;margin:0 .4em}.swal2-input-label{display:flex;justify-content:center;margin:1em auto 0}.swal2-validation-message{align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:#f0f0f0;color:#666;font-size:1em;font-weight:300}.swal2-validation-message::before{content:\\\"!\\\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}.swal2-icon{position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;border:.25em solid transparent;border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474;color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}.swal2-icon.swal2-error.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-error.swal2-icon-show .swal2-x-mark{-webkit-animation:swal2-animate-error-x-mark .5s;animation:swal2-animate-error-x-mark .5s}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-warning.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-warning.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-i-mark .5s;animation:swal2-animate-i-mark .5s}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-info.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-info.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-i-mark .8s;animation:swal2-animate-i-mark .8s}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-question.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-question.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-question-mark .8s;animation:swal2-animate-question-mark .8s}.swal2-icon.swal2-success{border-color:#a5dc86;color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-.25em;left:-.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-animate-success-line-tip .75s;animation:swal2-animate-success-line-tip .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-animate-success-line-long .75s;animation:swal2-animate-success-line-long .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-circular-line-right{-webkit-animation:swal2-rotate-success-circular-line 4.25s ease-in;animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:0 0;font-weight:600}.swal2-progress-steps li{display:inline-block;position:relative}.swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}.swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}[class^=swal2]{-webkit-tap-highlight-color:transparent}.swal2-show{-webkit-animation:swal2-show .3s;animation:swal2-show .3s}.swal2-hide{-webkit-animation:swal2-hide .15s forwards;animation:swal2-hide .15s forwards}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}.swal2-no-war{display:flex;position:fixed;z-index:1061;top:0;left:0;align-items:center;justify-content:center;width:100%;height:3.375em;background:#20232a;color:#fff;text-align:center}.swal2-no-war a{color:#61dafb;text-decoration:none}.swal2-no-war a:hover{text-decoration:underline}@-webkit-keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@-webkit-keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@-webkit-keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@-webkit-keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@-webkit-keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@-webkit-keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@-webkit-keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@-webkit-keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@-webkit-keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@-webkit-keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@-webkit-keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@-webkit-keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@-webkit-keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@-webkit-keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto!important}body.swal2-no-backdrop .swal2-container{background-color:transparent!important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:all}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}@media print{body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:scroll!important}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container{position:static!important}}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:transparent;pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-left,body.swal2-toast-shown .swal2-container.swal2-top-start{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-left,body.swal2-toast-shown .swal2-container.swal2-center-start{top:50%;right:auto;bottom:auto;left:0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;transform:translate(-50%,-50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-left,body.swal2-toast-shown .swal2-container.swal2-bottom-start{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}\");","class ModalHelper {\n\n static clearBody(modal) {\n modal.find('.modal-body').html('');\n }\n\n static setHtmlBody(modal, html) {\n modal.find('.modal-body').html(html);\n }\n\n /**\n * \n * @param {JQuery} modal\n * @param {string} title\n */\n static setTitle(modal, title) {\n modal.find('.modal-title').text(title);\n }\n\n /**\n * \n * @param {JQuery} modal\n * @param {string} footer\n */\n static setFooter(modal, footer) {\n modal.find(\".modal-footer\").html(footer)\n }\n\n static alert(modalOptions) {\n bootbox.alert(modalOptions)\n .find('.modal-content').css({\n 'background-color': '#c4c4c4',\n 'margin-top': function () {\n var b = 0;\n\n if ($('.modal-dialog').length > 0) {\n for (var i = 0; i < $('.modal-dialog').length; i++) {\n if ($($('.modal-dialog')[1]).height() > 0) {\n b = $($('.modal-dialog')[1]).height();\n break;\n }\n }\n } else {\n b = $('.modal-dialog').height();\n }\n\n var w = $(window).height();\n var h = (w - b) / 2;\n return h + 'px';\n }\n });\n }\n\n static confirm(modalOptions) {\n bootbox.confirm(modalOptions)\n .find('.modal-content').css({\n 'background-color': '#eeeeee',\n 'margin-top': function () {\n var w = $(window).height();\n var b = $('.modal-dialog').height();\n var h = (w - b) / 2;\n return h + 'px';\n }\n });\n }\n};\n\nexport default ModalHelper;","/**\r\n * An enum of possible reasons that can explain an alert dismissal.\r\n */\r\nexport var AlertDismissReason;\r\n(function (AlertDismissReason) {\r\n AlertDismissReason[AlertDismissReason[\"cancel\"] = 0] = \"cancel\";\r\n AlertDismissReason[AlertDismissReason[\"backdrop\"] = 1] = \"backdrop\";\r\n AlertDismissReason[AlertDismissReason[\"close\"] = 2] = \"close\";\r\n AlertDismissReason[AlertDismissReason[\"esc\"] = 3] = \"esc\";\r\n AlertDismissReason[AlertDismissReason[\"timer\"] = 4] = \"timer\";\r\n})(AlertDismissReason || (AlertDismissReason = {}));\r\n//# sourceMappingURL=alert-types.js.map","import { appConstants } from '../enums/site-enum.js';\nimport { catchError, switchMap, map, finalize } from 'rxjs/operators'\nimport ShoppingCartService from '../shared/shopping-cart/services/shopping-cart-service.js';\nimport CheckoutSummaryService from '../services/checkout-summary-service';\nimport { CheckoutPaymentListService } from '../services/checkout-paymentlist-service';\nimport CheckoutHelper from '../helpers/checkout-helper.js'\nimport BonusHandlers from './bonus-handlers.js';\nimport { forkJoin, from, of, iif, EMPTY } from 'rxjs';\nimport { RadioButtons } from '../components/radioButtons/radio-buttons.js';\nimport { analytics } from 'apollo-web'\nimport { BrowserCommunicatorService } from '../services/browser-communicator-service.js';\nimport { CultureFormatterService } from '../shared/culture'\nimport { $applicationMonitoringService } from \"../shared/application-monitoring\"\nimport { CheckoutSubTotalsService } from \"../services/checkout-subtotals-service.js\"\nimport LoadedCheckoutEvent from \"../checkout/events/load-checkout-event.js\"\nimport AddedProductKitEvent from \"../shared/dynamic-kits/events/added-product-kit-event.js\"\nimport { DynamicKitHandlers } from \"../shared/dynamic-kits/handlers/dynamic-kit-handlers.js\";\nimport { WizardForm } from '../components/wizard/wizard-form.js';\nimport ModalHelper from '../helpers/modal-helper.js'\nimport CheckoutService from \"../services/checkout-service.js\"\nimport UpdateProductPricesEvent from \"../shared/shopping-cart/events/update-product-prices-event\"\n\nconst creditInternalCode = \"CRE\";\n\nconst creditCardInternalCode = \"TCR\";\nconst surtiCreditInternalCode = \"SCR\";\n\n/**\n * @type {ShoppingCartService}\n * */\nvar _shoppingCartService = null;\n\n/**\n * @type {BonusHandlers}\n * */\nlet bonusHandlers = new BonusHandlers();\n\n/** @type{CheckoutSummaryService} */\nvar _checkoutSummaryService = null\n\n/** @type {CheckoutPaymentListService} */\nvar _checkoutPaymentListService = null;\n\n/** @type {CheckoutSubTotalsService} */\nvar _checkoutSubTotalsService = null;\n\n/** Radio buttons for payment methods\n * @type {RadioButtons} */\nvar _paymentMethodsRadioButtons = null;\n\n/** Radio buttons for surticredito\n * @type {RadioButtons} */\nvar _surtiCreditoRadioButtons = null;\n\n/** Redio buttons for address\n * @type {RadioButtons} */\nvar _addressRadioButtons = null;\n\n/** @type {WizardForm} */\nvar _wizard = null;\n\n//TODO: Pending Delete\n/** @type {DynamicKitHandlers}*/\nvar _dynamicKitHandlers = null;\n\nconst browserCommunicatorService = new BrowserCommunicatorService()\n\nconst cultureFormatterService = new CultureFormatterService()\n\nconst _couponModal = $(\"#coupon-modal\");\n\n/** @type {CheckoutService} */\nvar _checkoutService;\n\nclass CheckoutHandlers {\n\n constructor() {\n }\n\n static init() {\n _shoppingCartService = new ShoppingCartService();\n _checkoutSummaryService = new CheckoutSummaryService();\n _checkoutPaymentListService = new CheckoutPaymentListService();\n _checkoutSubTotalsService = new CheckoutSubTotalsService();\n _dynamicKitHandlers = new DynamicKitHandlers();\n _checkoutService = new CheckoutService();\n bindShoppinCartControl();\n bindWizard()\n\n AddedProductKitEvent.event$.subscribe(async e => {\n \n const internalId = e.internalId;\n const productQuantity = e.shoppingCartItemChanged.ProductQuantity;\n\n // set product quantity\n const productElement = $(`[data-internal-id=\"${internalId}\"]`)\n const quantityElement = productElement.find(\".controls__number\")\n quantityElement.html(productQuantity);\n\n let priceProduct = parseFloat($('#price-' + internalId).val());\n\n if (priceProduct != e.productKit.TotalAmount) {\n priceProduct = e.productKit.TotalAmount;\n\n $('#price-' + internalId).val(e.productKit.TotalAmount);\n\n // Update price the this product\n const priceProductFormatted = await cultureFormatterService.formatCurrencyAsync(priceProduct)\n _updateDisplayPriceByInternalId(\n internalId, priceProduct, priceProductFormatted)\n }\n\n let totalProduct = productQuantity * priceProduct;\n\n // Update total price the this product\n const totalProductFormatted = await cultureFormatterService.formatCurrencyAsync(totalProduct)\n _updateDisplayTotalPriceByInternalId(\n internalId, totalProduct, totalProductFormatted)\n\n _computeSubTotals()\n })\n\n $('[data-bs-toggle=\"popover\"]').popover()\n }\n}\n\nexport default CheckoutHandlers;\n\nfunction bindShoppinCartControl() {\n\n $('#OrderScheduler').off('change');\n $('#OrderScheduler').on('change', orderScheduler);\n\n // Handle the increase product quantity from the Cart\n $('.controls__more').off('click');\n $('.controls__more').on('click', moreProduct);\n\n // Handle the decrease product quantity from the Cart\n $('.controls__less').off('click');\n $('.controls__less').on('click', lessProduct);\n\n $('.controls__number').off('click');\n $('.controls__number').on('click', switchToInput);\n\n // Handle the decrease product quantity from the Cart\n $('.controls__remove-button').off('click');\n $('.controls__remove-button').on('click', removeProduct);\n\n // Save Checkout\n $('.btn-checkout-save').off('click');\n $('.btn-checkout-save').on('click', saveCheckout);\n\n //Handle promo codes\n bindShoppingCartCoupons()\n\n LoadedCheckoutEvent.loaded();\n\n _dynamicKitHandlers.bindOrderControls();\n}\n\nfunction bindShoppingCartCoupons() {\n $('.btn-promo-code').off(\"click\")\n $(\".apply-coupon\").off(\"click\")\n $(\".remove-coupon\").off(\"click\")\n\n $('.btn-promo-code').on('click', loadCoupons);\n $(\".apply-coupon\").on(\"click\", validatePromoCode);\n $(\".remove-coupon\").on(\"click\", removePromoCode);\n $(\"#promocode\").on(\"keyup\", e => {\n e.preventDefault();\n const couponSelected = $(`[name=\"coupon-selected\"]:checked`)[0];\n if (couponSelected) {\n couponSelected.checked = false;\n }\n })\n}\n\nasync function lessProduct(event) {\n var parent = $(this).parent();\n var productId = app.productHelper.getProductId(parent);\n var internalId = app.productHelper.getInternalId(parent);\n var isKit = app.productHelper.getIsKit(parent);\n\n _toggleLoading(true);\n _checkoutService.decreaseProductQuantity(productId, internalId, isKit).pipe(\n catchError(async response => {\n console.error(response);\n await _handleShoppingCartResponse(response);\n await _updateProductQuantity(productId);\n throw `Error decrease quantity \\n${response}`;\n }),\n switchMap(response => forkJoin({\n decreaseResponse: of(response.response),\n ..._getCheckoutViewsForkJoin()\n })),\n catchError(err => {\n console.error(err);\n throw `Error decrease quantity \\n${err}`;\n }),\n finalize(_ => _toggleLoading(false))\n ).subscribe(async responses => {\n const shoppingCartItemChangedResponse = responses.decreaseResponse.Value.shoppingCartItemChanged;\n if (shoppingCartItemChangedResponse.Successed) {\n\n if (shoppingCartItemChangedResponse.Message) {\n await browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n\n processShoppingCartItemChangedResponse(parent, 'lessProduct', {\n shoppingCartItemChangedResponse: shoppingCartItemChangedResponse\n }, productId, internalId, isKit, false);\n\n bindCheckoutViews(responses.checkoutSummary);\n\n } else {\n await browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n })\n}\n\nasync function moreProduct(event) {\n var parent = $(this).parent();\n var productId = app.productHelper.getProductId(parent);\n var internalId = app.productHelper.getInternalId(parent);\n var isKit = app.productHelper.getIsKit(parent);\n\n _toggleLoading(true);\n\n _checkoutService.increaseProductQuantity(productId, internalId, isKit).pipe(\n catchError(async response => {\n console.error(response);\n await _handleShoppingCartResponse(response);\n await _updateProductQuantity(productId);\n throw `Error increase quantity \\n${response}`;\n }),\n switchMap(response => forkJoin({\n increaseResponse: of(response.response),\n ..._getCheckoutViewsForkJoin()\n })),\n catchError(err => {\n console.error(err);\n throw `Error increase quantity \\n${err}`;\n }),\n finalize(_ => _toggleLoading(false))\n ).subscribe(async responses => {\n const shoppingCartItemChangedResponse = responses.increaseResponse.Value.shoppingCartItemChanged;\n if (shoppingCartItemChangedResponse.Successed) {\n if (shoppingCartItemChangedResponse.Message) {\n await browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n\n processShoppingCartItemChangedResponse(parent, 'moreProduct', {\n shoppingCartItemChangedResponse: shoppingCartItemChangedResponse\n }, productId, internalId, isKit, false);\n\n bindCheckoutViews(responses.checkoutSummary);\n } else {\n await browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n })\n}\n\nasync function removeProduct(event) {\n var parent = $(this).parent();\n\n const confirmResult = await browserCommunicatorService.displayQuestionAlert({\n description: '¿Seguro quieres quitar el producto de tu carrito de compras?'\n })\n\n if (!confirmResult.isConfirmed) {\n return;\n }\n\n var productId = app.productHelper.getProductId(parent);\n var internalId = app.productHelper.getInternalId(parent);\n var isKit = app.productHelper.getIsKit(parent);\n\n _toggleLoading(true);\n\n _checkoutService.removeProductQuantity(productId).pipe(\n catchError(async response => {\n console.error(response);\n await _handleShoppingCartResponse(response);\n await _updateProductQuantity(productId);\n throw `Error remove quantity \\n${response}`;\n }),\n switchMap(response => forkJoin({\n removeResponse: of(response.response),\n ..._getCheckoutViewsForkJoin()\n })),\n catchError(err => {\n console.error(err);\n throw `Error remove quantity \\n${err}`;\n }),\n finalize(_ => _toggleLoading(false))\n ).subscribe(async responses => {\n const shoppingCartItemChangedResponse = responses.removeResponse.Value.shoppingCartItemChanged;\n if (shoppingCartItemChangedResponse.Successed) {\n\n if (shoppingCartItemChangedResponse.Message) {\n await browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n\n processShoppingCartItemChangedResponse(parent, 'removeProduct', {\n shoppingCartItemChangedResponse: shoppingCartItemChangedResponse\n }, productId, internalId, isKit, false);\n\n bindCheckoutViews(responses.checkoutSummary);\n } else {\n await browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n })\n}\n\n/**\n * \n * @param {any} sender\n * @param {any} typeProcess\n * @param {{shoppingCartItemChangedResponse: {}}} result\n * @param {any} productId\n * @param {any} internalId\n * @param {boolean} isKit\n */\nasync function processShoppingCartItemChangedResponse(sender, typeProcess, result, productId, internalId, isKit, computeSubtotals = true) {\n // Total quantity products\n const productQuantity = result.shoppingCartItemChangedResponse.ProductQuantity;\n const productQuantityElement = sender.find('.controls__number');\n\n switch (typeProcess) {\n case 'moreProduct':\n productQuantityElement.html(productQuantity);\n break;\n case 'lessProduct':\n productQuantityElement.html(productQuantity);\n if (productQuantity <= 0) {\n\n // dispatch analitycs event \"remove_from_cart\"\n let productEl = document.querySelector(`.checkout__products-item[data-product=\"${productId}\"]`)\n let orderItemDTO = JSON.parse(productEl.getAttribute(\"data-json\"))\n if (orderItemDTO) {\n try {\n app.applicationMonitoringService()\n .then(function (service) {\n service.trackCart(\n 'remove', orderItemDTO.Product.Price, [{\n itemId: orderItemDTO.Product.ReferenceCode,\n itemName: orderItemDTO.Product.Name,\n currency: appConstants.currency,\n discount: orderItemDTO.Product.Discount,\n itemCategory: orderItemDTO.Product.ProductCategory,\n itemCategory2: orderItemDTO.Product.ProductGroup,\n classification: orderItemDTO.Product.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: orderItemDTO.Product.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: orderItemDTO.Product.Price,\n quantity: 1 // always remove last product.\n }], appConstants.currency, 'Catalog')\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n }\n productQuantityElement.parent().parent().fadeOutAndRemove();\n }\n break;\n case 'removeProduct':\n\n // dispatch analytics event \"remove_from_cart\"\n let productEl = document.querySelector(`.checkout__products-item[data-product=\"${productId}\"]`);\n if (productEl) {\n let orderItemDTO = JSON.parse(productEl.getAttribute(\"data-json\"))\n try {\n let totalPriceEl = document.querySelector(`#total-${productId}`)\n let totalPriceValue = 0;\n if (totalPriceEl) {\n totalPriceValue = parseFloat(totalPriceEl.getAttribute(\"data-value\"));\n }\n app.applicationMonitoringService()\n .then(function (service) {\n service.trackCart('remove', totalPriceValue, [{\n itemId: orderItemDTO.Product.ReferenceCode,\n itemName: orderItemDTO.Product.Name,\n currency: appConstants.currency,\n discount: orderItemDTO.Product.Discount,\n itemCategory: orderItemDTO.Product.ProductCategory,\n itemCategory2: orderItemDTO.Product.ProductGroup,\n classification: orderItemDTO.Product.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: orderItemDTO.Product.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: orderItemDTO.Product.Price,\n quantity: orderItemDTO.Quantity\n }], appConstants.currency, 'Catalog')\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n }\n\n var productRemoveElement = sender.parent().find('.controls__number');\n productRemoveElement.html(productQuantity);\n\n sender.parent().fadeOutAndRemove();\n break;\n }\n\n // Total item value \n // empty string always falsy else truthy \n if (productId || intertnalId) {\n var selector = isKit === \"True\" ? '#price-' + internalId : '#price-' + productId;\n\n let priceProduct = parseFloat($(selector).val());\n let totalProduct = productQuantity * priceProduct;\n const totalProductFormatted = await cultureFormatterService.formatCurrencyAsync(totalProduct)\n\n if (isKit === \"True\") {\n // Update total price the this kit\n _updateDisplayTotalPriceByInternalId(\n internalId, totalProduct, totalProductFormatted)\n } else {\n // Update total price the this product\n _updateDisplayTotalPrice(\n productId, totalProduct, totalProductFormatted)\n\n // Update prices for shoppingcart\n _updateShoppingCartPrices(productId, result.shoppingCartItemChangedResponse);\n }\n\n // Update quantity of data-json\n _updateQuantityOfDataJson(productId, productQuantity)\n }\n\n // compute the shoppingcart subtotals\n if (computeSubtotals) {\n _computeSubTotals()\n }\n\n let totalItems = countProductsQuantity();\n\n // Update all total items elements\n let totalItemEls = document.querySelectorAll('.total-items');\n totalItemEls?.forEach((el) => {\n el.textContent = `Productos (${totalItems}): `;\n })\n\n await _updateProductMessage();\n\n //await _configureCheckoutButtons();\n}\n\nasync function _configureCheckoutButtons() {\n const response = await _checkoutSubTotalsService.getMinimunOrderAmount();\n\n if (!response.ok) {\n return;\n }\n\n const minimunOrderResult = await response.json()\n if (!minimunOrderResult.Successful) {\n await browserCommunicatorService.displayErrorAlert({\n description: minimunOrderResult.UserMessage,\n html: true\n })\n return;\n }\n\n const minimunOrderValue = minimunOrderResult.Value;\n\n // select firts button for next\n const nextButton = document.querySelector(\"button#nextCheckout\");\n const saveOrderButton = document.querySelector(\"button.btn-checkout-save\");\n if (!minimunOrderValue.ShowMinimunOrderAmount) {\n\n // Next\n nextButton.textContent = 'Continuar';\n nextButton.classList.add(\"checkout-next\");\n _wizard.init()\n\n // Save Checkout\n saveOrderButton.textContent = \"¡COMPRAR YA!\";\n $(saveOrderButton).off('click');\n $(saveOrderButton).on('click', saveCheckout);\n }\n else {\n\n // Save Checkout\n saveOrderButton.textContent = minimunOrderValue.MinimunOrderAmountMessage;\n $(saveOrderButton).off(\"click\");\n\n // Next\n nextButton.textContent = minimunOrderValue.MinimunOrderAmountMessage;\n $(nextButton).off(\"click\");\n }\n \n}\n\nasync function _updateProductMessage() {\n const response = await _shoppingCartService.getAsync()\n if (!response.ok) {\n return;\n }\n const shoppingCart = (await response.json()).Value\n if (shoppingCart.Items.length > 0) {\n document.querySelector(\"#checkoutProductMessage\").classList.add(\"d-none\");\n } else {\n document.querySelector(\"#checkoutProductMessage\").classList.remove(\"d-none\");\n }\n}\n\nfunction switchToInput(event) {\n var $input = $(\"\", {\n val: $(this).text(),\n type: \"number\",\n min: 1\n });\n $input.addClass(\"cart-number-input\");\n $(this).replaceWith($input);\n $input.on(\"blur\", switchToSpan);\n $input.select();\n}\n\nfunction switchToSpan(event) {\n let quantityElement = $(this);\n let productQuantityElement = quantityElement.val();\n\n var $span = $(\"\", {\n text: productQuantityElement\n });\n\n $span.addClass(\"controls__number\");\n $(this).replaceWith($span);\n $span.on(\"click\", switchToInput);\n addProductDetail($span);\n}\n\nasync function saveCheckout(event) {\n\n // Validate Wizard form\n if (!await validateForm(\"#checkoutProcess\")) {\n return;\n }\n const paymentMethodEl = $(\"input[name='paymentMethod']:checked\");\n let paymentMethodStr = paymentMethodEl.siblings(\"h5\").text();\n let paymentMethodInternalCode = paymentMethodEl.attr(\"InternalCode\")\n \n if (paymentMethodInternalCode === creditInternalCode && $('.form-checkbox-Credit').length > 0) {\n var creditPayment = $('.form-checkbox-Credit');\n var payment = creditPayment[0].checked;\n\n if (paymentMethodInternalCode === creditInternalCode && !payment) {\n await browserCommunicatorService.displayWarningAlert({\n description: 'Para realizar tu compra a ' + paymentMethodStr + ' debes aceptar la política de descuento por nómina.'\n })\n return;\n }\n }\n\n\n var termsControl = $('.form-checkbox-Terms');\n var terms = termsControl[0].checked;\n if (!terms) {\n await browserCommunicatorService.displayWarningAlert({\n description: 'Para realizar tu compra debes aceptar los términos y condiciones.'\n })\n return;\n }\n\n let totalProductsPriceStr = document.getElementsByClassName('total-products-price')[0].dataset.total;\n let totalProductsPrice = parseFloat(totalProductsPriceStr);\n\n let totalOrderPriceStr = document.getElementsByClassName('total-order-price')[0].dataset.total;\n let totalOrderPrice = parseFloat(totalOrderPriceStr);\n\n if (totalOrderPrice < 0) {\n const confirmResult = await browserCommunicatorService.displayQuestionAlert({\n description: 'El saldo a favor es mayor al valor del pedido y no podrá ser aplicado en esta compra, deseas continuar?',\n denyButtonText: 'Cancelar',\n confirmButtonText: 'Aceptar'\n })\n if (confirmResult.isConfirmed) {\n messagesPendingByUserAnswer();\n }\n return;\n } else if (totalProductsPrice > 0) {\n const confirmResult = await browserCommunicatorService.displayQuestionAlert({\n description: '¿Estás listo para realizar tu compra?'\n })\n if (confirmResult.isConfirmed) {\n messagesPendingByUserAnswer();\n }\n return;\n } else {\n await browserCommunicatorService.displayInfoAlert({\n description: 'Al parecer tu orden esta vacia, agregar algunos productos para que podamos continuar.'\n })\n return;\n }\n}\n\nfunction messagesPendingByUserAnswer() {\n app.checkoutService.messagesPendingByUserAnswer(async function (response) {\n if (response.Successful) {\n if (response.UIMessages.length > 0) {\n response.UIMessages.forEach(async element => await showMessage(element));\n }\n else {\n await saveOrder();\n }\n }\n else {\n await browserCommunicatorService.displayErrorAlert({\n description: 'No se pudo generar el mensaje de validación, intente más tarde'\n })\n }\n }, async function (response) {\n await browserCommunicatorService.displayErrorAlert({ description: 'Hubo problemas con el pago, intente más tarde' })\n });\n}\n\n\nasync function showMessage(element) {\n\n const confirmResult = await browserCommunicatorService.displayQuestionAlert({\n description: element.CheckOutValidationMessage,\n confirmButtonText: element.Options[0].AnswerText,\n denyButtonText: element.Options[1].AnswerText,\n html: true\n })\n if (confirmResult.isConfirmed) {\n var answer = {\n AnswerText: element.Options[0].AnswerText,\n UianswerByValidationMessageId: element.Options[0].Id,\n UimessageByClassificationId: element.Options[0].UimessageByClassificationId\n };\n app.checkoutService.saveUserAnswerByValidationMessage(answer, async function (response) {\n if (response.Successful) {\n await saveOrder();\n }\n else {\n await browserCommunicatorService.displayErrorAlert({ description: 'No se pudo guardar la respuesta de validación, intente más tarde' })\n }\n }, async function (response) {\n await browserCommunicatorService.displayErrorAlert({ description: 'Hubo problemas con el pago, intente más tarde' })\n });\n return;\n } else {\n $(\"#form-message-by-answer\").submit();\n return;\n }\n}\n\nasync function saveOrder() {\n var orderNotes = $(\"#Comment\").val();\n var acceptancePoliciesId = $(\"#acceptancePoliciesId\").val()\n var acceptancePoliciesGroup = $(\"#acceptancePoliciesGroup\").val()\n var acceptancePoliciesText = $(\"#acceptancePoliciesText\").val()\n var orderAddress = $(\"input[name='addressSeleted']:checked\").val();\n var orderScheduler = $(\"#OrderScheduler option:selected\").val();\n\n const paymentMethodEl = $(\"input[name='paymentMethod']:checked\");\n var paymentMethod = paymentMethodEl.val();\n let paymentMethodStr = paymentMethodEl.siblings(\"h5\").text();\n let paymentMethodInternalCode = paymentMethodEl.attr(\"InternalCode\")\n\n let creditCardQuota = \"0\";\n let creditCardNumber = \"\";\n let creditCardType = \"\";\n let creditCardToken = \"\";\n\n if (paymentMethodInternalCode === creditCardInternalCode && $(\"div.credit-card-selected\").length > 0) {\n creditCardQuota = $(\"div.credit-card-selected\").attr(\"data-quota\");\n creditCardNumber = $(\"div.credit-card-selected\").attr(\"data-number\");\n creditCardType = $(\"div.credit-card-selected\").attr(\"data-type\");\n creditCardToken = $(\"div.credit-card-selected\").attr(\"data-token\");\n }\n\n // dispatch analytics event \"purcharse\"\n let productsEl = document.querySelectorAll(\".checkout__products-item\")\n if (productsEl) {\n let products = [...productsEl].map(function (value, index) {\n\n let orderItemDTO = JSON.parse(value.getAttribute(\"data-json\"))\n if (!orderItemDTO) {\n console.error(\"Missing data-json in products\")\n return;\n }\n\n return {\n itemId: orderItemDTO.Product.ReferenceCode,\n itemName: orderItemDTO.Product.Name,\n currency: appConstants.currency,\n discount: orderItemDTO.Product.Discount,\n itemCategory: orderItemDTO.Product.ProductCategory,\n itemCategory2: orderItemDTO.Product.ProductGroup,\n classification: orderItemDTO.Product.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: orderItemDTO.Product.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: orderItemDTO.Product.Price,\n quantity: orderItemDTO.Quantity\n }\n })\n\n let totalPriceOrder = CheckoutHelper.getTotalPriceFromDataTotal();\n\n let totalDeliveryEl = document.querySelector(\".delivery-price\")\n let totalDelivery = parseFloat(totalDeliveryEl.getAttribute(\"data-total\"))\n\n let couponCode = \"\";\n let couponCodeEl = document.querySelector(\".total-discountcoupon\")\n if (couponCodeEl != undefined) {\n couponCode = couponCodeEl.getAttribute(\"data-code\")\n }\n\n let cartIdEl = document.querySelector(\".checkout__products-list\")\n let cartId = cartIdEl.getAttribute(\"data-cart-id\")\n\n try {\n app.applicationMonitoringService()\n .then(function (service) {\n service.trackPurcharse({\n products: products,\n value: totalPriceOrder,\n transactionId: cartId,\n tax: analytics.AnalyticsConstants.DefaultParameterValue,\n shipping: totalDelivery,\n coupon: couponCode,\n affiliation: analytics.AnalyticsConstants.DefaultParameterValue,\n currency: appConstants.currency,\n paymentType: paymentMethodStr\n });\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n }\n\n if (orderAddress == null || orderScheduler == null || paymentMethod == null)\n await browserCommunicatorService.displayWarningAlert({\n description: \"Recuerde que debe seleccionar: la dirección, el horario y el método de pago.\"\n })\n else {\n $('#modalSocial').modal('show');\n\n var order = {\n notes: orderNotes,\n address: orderAddress,\n scheduler: orderScheduler,\n paymentmethod: paymentMethod,\n acceptancePoliciesId: acceptancePoliciesId,\n acceptancePoliciesGroup: acceptancePoliciesGroup,\n acceptancePoliciesText: acceptancePoliciesText,\n PaymentMethodInternalCode: paymentMethodInternalCode,\n CreditCardToken: creditCardToken,\n CreditCardNumber: creditCardNumber,\n CreditCardType: creditCardType,\n QuotasNumber: creditCardQuota,\n CreditRequestId: $(`[name=\"creditRequestId\"]`).val(),\n CreditDays: $(`[name=\"surtiCreditDays\"]`).val()\n };\n\n app.checkoutService.saveOrder(order, async function (response) {\n if (response.successful === true) {\n // analytics event \"order_completed\"\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackOrder({\n action: 'completed',\n orderId: '',\n customerIdentification: ''\n })\n })\n .catch(function (err) {\n console.error(err);\n })\n\n // analytics event \"setUserId\" for update ECommerceStatus\n try {\n let applicationMonitoringService = await $applicationMonitoringService;\n let customerResponse = await app.customerService.getCustomer();\n if (customerResponse.ok) {\n let json = await customerResponse.json();\n let customerResponseValue = json.Value;\n let customerDto = customerResponseValue.Customer;\n applicationMonitoringService.trackUser(customerDto.Identification, {\n [analytics.AnalyticsConstants.Parameters.CustomerEmail]: customerDto.Email,\n [analytics.AnalyticsConstants.Parameters.ecommerce_status]: 'On line'\n });\n }\n } catch (e) {\n console.error(e);\n }\n\n window.location.href = response.urlToPay;\n } else {\n await browserCommunicatorService.displayInfoAlert({\n description: response.urlToPay,\n html: true\n })\n $('#modalSocial').modal('hide');\n }\n }, async function (response) {\n await browserCommunicatorService.displayErrorAlert({\n description: 'Hubo problemas con el pago, intente más tarde'\n })\n $('#modalSocial').modal('hide');\n });\n }\n}\n\nfunction orderScheduler(event) {\n var element = document.getElementById('deliveryId');\n var selected = $(\"#OrderScheduler option:selected\").text();\n element.innerText = selected;\n}\n\nfunction countProductsQuantity() {\n var totalProducts = 0;\n var currentItems = $('.product__controls').find('.controls__number');\n\n if (currentItems.length > 0) {\n currentItems.each(function (index, element) {\n totalProducts += parseInt(element.innerHTML);\n });\n }\n\n return totalProducts;\n}\n\nasync function addProductDetail(span) {\n _toggleLoading(true)\n\n const parent = span.parent().parent();\n\n const productId = parent[0].dataset.product;\n const internalId = parent[0].dataset.internalId;\n const isKit = parent[0].dataset.isKit;\n const quantity = span[0].innerText;\n\n _checkoutService.updateProductQuantity(productId, quantity, internalId, isKit).pipe(\n catchError(async response => {\n console.error(response);\n await _handleShoppingCartResponse(response);\n await _updateProductQuantity(productId);\n throw `Error update quantity \\n${response}`;\n }),\n switchMap(response => forkJoin({\n updateResponse: of(response.response),\n ..._getCheckoutViewsForkJoin()\n })),\n catchError(err => {\n console.error(err);\n throw `Error update quantity \\n${err}`;\n }),\n finalize(_ => _toggleLoading(false))\n ).subscribe(async responses => {\n const shoppingCartItemChangedResponse = responses.updateResponse.Value.shoppingCartItemChanged\n if (!shoppingCartItemChangedResponse.Successed) {\n await browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n } else if (shoppingCartItemChangedResponse.Message) {\n await browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n\n var typeProcess = '';\n let newQuantity = shoppingCartItemChangedResponse.ProductQuantity;\n\n if (newQuantity <= 0) {\n typeProcess = 'removeProduct';\n }\n\n span[0].innerText = newQuantity;\n processShoppingCartItemChangedResponse(span.parent(), typeProcess, { shoppingCartItemChangedResponse: shoppingCartItemChangedResponse }, productId, internalId, isKit, false);\n\n bindCheckoutViews(responses.checkoutSummary);\n });\n}\n\n/**\n * \n * @param {Response} response\n */\nasync function _handleShoppingCartResponse(response) {\n if (response.status === 400) {\n console.debug(await response.json())\n await browserCommunicatorService.displayErrorAlert({\n description: \"Occurrieron errores de validación, por favor intente nuevamente\"\n })\n }\n}\n\n\n/**\n * \n * @param {any} e\n */\nfunction loadCoupons(e) {\n e.preventDefault();\n const modal = _couponModal;\n // show modal\n modal.modal('show')\n bindCouponsEvent();\n}\n\nfunction bindCouponsEvent() {\n\n $(\".checkout-coupon__card\").off(\"click\")\n const containerButtons = document.querySelectorAll(\".checkout-coupon__card\")\n containerButtons?.forEach((container) => container.addEventListener('click', (e) => {\n e.stopPropagation();\n onCheckedCoupon(e.currentTarget);\n }))\n}\n\n/**\n * \n * @param {HTMLElement} container\n */\nfunction onCheckedCoupon(container) {\n\n $(\"#promocode\").val(\"\");\n\n /** @type {HTMLInputElement} */\n const inputCheckbox = container.querySelector(\"input\")\n inputCheckbox.checked = true\n}\n\nasync function validatePromoCode() {\n\n var promoCode = $('#promocode').val();\n // validate radiobuttons\n const selectedCode = $(\".checkout-coupon__left input:checked\").val()\n if (!promoCode) {\n promoCode = selectedCode;\n }\n\n if (promoCode == null || promoCode == \"\")\n await browserCommunicatorService.displayWarningAlert({\n description: \"Recuerde que debe ingresar un código promocional.\"\n })\n else {\n\n _showCouponsLoading(true)\n \n _shoppingCartService.validatePromotionalCode(promoCode, async function (result) {\n\n _showCouponsLoading(false)\n\n if (!result.Successful) {\n await browserCommunicatorService.displayWarningAlert({\n description: result.UserMessage,\n html: true\n })\n return;\n }\n else {\n $(\"#promocode\").val(\"\")\n await browserCommunicatorService.displaySuccessAlertAsync({\n description: result.UserMessage\n })\n\n // Analytics event: \"add_promo_code\"\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackPromoCode({\n action: 'add',\n coupon: promoCode\n });\n })\n .catch(function (err) {\n console.error(err);\n })\n\n _loadCheckoutViews()\n _couponModal.modal(\"hide\")\n }\n });\n }\n}\n\nasync function removePromoCode() {\n _toggleLoading(true);\n try {\n const response = await _checkoutService.removePromoCode();\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n await browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage\n });\n return;\n }\n _computeSubTotals();\n } catch (e) {\n console.log(e);\n }\n}\n\n/**\n * Update total price for the product\n * @param {string} productId\n * @param {number} value\n * @param {string} valueFormatted\n */\nfunction _updateDisplayTotalPrice(productId, value, valueFormatted) {\n let productEl = document.querySelector(`#total-${productId}`)\n if (productEl) {\n productEl.textContent = `${valueFormatted}`\n productEl.setAttribute(\"data-value\", value)\n }\n}\n\n/**\n * Update total price for the product\n * @param {string} internalId\n * @param {number} value\n * @param {string} valueFormatted\n */\nfunction _updateDisplayTotalPriceByInternalId(internalId, value, valueFormatted) {\n let productEl = document.querySelector(`#total-${internalId}`)\n if (productEl) {\n productEl.textContent = `${valueFormatted}`\n productEl.setAttribute(\"data-value\", value)\n }\n}\n\n/**\n * Update price for the product\n * @param {string} internalId\n * @param {number} value\n * @param {string} valueFormatted\n */\nfunction _updateDisplayPriceByInternalId(internalId, value, valueFormatted) {\n let productEl = document.querySelector(`#price-label-${internalId}`)\n if (productEl) {\n productEl.textContent = `${valueFormatted}`\n productEl.setAttribute(\"data-value\", value)\n }\n}\n\n/**\n * Update quantity of data-json.\n * @param {any} productId\n * @param {any} quantity\n */\nfunction _updateQuantityOfDataJson(productId, quantity) {\n let productEl = document.querySelector(`.checkout__products-item[data-product=\"${productId}\"]`)\n if (productEl) {\n let orderItemDTO = JSON.parse(productEl.getAttribute(\"data-json\"))\n orderItemDTO.Quantity = quantity;\n productEl.setAttribute(\"data-json\", JSON.stringify(orderItemDTO));\n }\n}\n\n/**\n * Compute the subtotals\n * @param {boolean} [loadProducts=false] \n * @param {boolean} [loadPaymentMethods=false] \n * @returns {void}\n * */\nfunction _computeSubTotals(loadProducts = false, loadPaymentMethods = false) {\n _toggleLoading(true);\n _computeSubTotals$(loadProducts, loadPaymentMethods).pipe(\n finalize(_ => _toggleLoading(false))\n ).subscribe(async responses => {\n await _bindComputeSubTotals(responses);\n });\n}\n\n/**\n * \n * @param {boolean} loadProducts \n * @param {boolean} loadPaymentMethods \n * @returns \n */\nfunction _computeSubTotals$(loadProducts, loadPaymentMethods) {\n return _checkoutSubTotalsService.computeSubTotals().pipe(\n switchMap(response => forkJoin({\n computeSubTotals: of(response.response),\n ..._getCheckoutViewsForkJoin(),\n paymentMethodsHtml: iif(\n () => loadPaymentMethods,\n _paymentMethodsLoad$(),\n EMPTY\n ),\n productListHtml: iif(\n () => loadProducts,\n _loadProductListView$(),\n EMPTY\n )\n })),\n catchError(err => {\n console.error(err);\n throw `Error compute subtotals \\n${err}`;\n })\n );\n}\n\n\n/**\n * \n * @param {*} responses \n */\nasync function _bindComputeSubTotals(responses) {\n if (responses.computeSubTotals.Successful) {\n bindCheckoutViews(responses.checkoutSummary, responses.paymentList);\n }\n else {\n await browserCommunicatorService.displayErrorAlert({\n description: responses.computeSubTotals.UserMessage,\n html: true\n });\n }\n if (responses.paymentMethodsHtml) {\n _bindPaymentMethods(responses.paymentMethodsHtml);\n }\n if(responses.productListHtml){\n _bindProductList(responses.productListHtml);\n }\n}\n\nfunction _paymentMethods() {\n _toggleLoading(true);\n _paymentMethodsLoad$().pipe(\n finalize(_ => _toggleLoading(false)),\n ).subscribe(async response => {\n _bindPaymentMethods(response);\n })\n}\n\nfunction _bindPaymentMethods(response) {\n $(\".checkout__payment-list\").html(response);\n // init radio buttons\n renderEventsPaymentMethod();\n _paymentMethodsRadioButtons.init();\n}\n\nfunction _paymentMethodsLoad$() {\n return _checkoutPaymentListService.getView().pipe(\n map(response => response.response),\n catchError(err => {\n console.error(err);\n throw `Error compute payment list \\n${err}`;\n })\n )\n}\n\nfunction _loadCheckoutViews() {\n _toggleLoading(true);\n forkJoin({\n ..._getCheckoutViewsForkJoin()\n }).pipe(\n catchError(err => {\n console.error(err);\n throw `Error load views \\n${err}`;\n }),\n finalize(_ => _toggleLoading(false))\n ).subscribe(responses => {\n bindCheckoutViews(responses.checkoutSummary);\n })\n}\n\nfunction _getCheckoutViewsForkJoin() {\n return {\n checkoutSummary: _checkoutSummaryService.getView().pipe(map(response => response.response)),\n showMinimunOrder: from(_configureCheckoutButtons()),\n couponViews: from(_loadCouponsViews()),\n }\n}\n\nfunction bindCheckoutViews(checkoutSummary) {\n $(\"#checkoutSummaryList\").html(checkoutSummary);\n}\n\nfunction _toggleLoading(loading = true) {\n kendo.ui.progress($(\".checkout__wrapper\"), loading);\n}\n\nfunction acceptancePoliciesCheck(event) {\n event.preventDefault()\n _loadAcceptancePolicies();\n}\n\n/**\n * \n * @param {{paymentMethod: string}} param0\n */\nfunction validateCheckboxCredit({ paymentMethod }) {\n if ($(\"#checkboxCredit\").length === 0) {\n return;\n }\n\n switch (paymentMethod) {\n case creditInternalCode:\n $(\"#checkboxCredit\").prop(\"checked\", false);\n $(\"#checkboxCredit\").show();\n $(\"#labelCheckboxCredit\").show();\n\n break;\n\n default:\n $(\"#checkboxCredit\").hide();\n $(\"#labelCheckboxCredit\").hide();\n }\n}\n\n/**\n * \n * @param {{paymentMethod: string}} param0\n */\nfunction validateCheckboxCreditCard({ paymentMethod }) {\n if (paymentMethod === creditCardInternalCode) {\n $(\"#checkout-credit-card-list\").modal(\"show\");\n }\n}\n\nfunction _surtiCreditPaymentModal() {\n return $(\"#surticredit-payment-modal\");\n}\n\nasync function validateCheckboxSurticredito({ paymentMethod }) {\n if (paymentMethod === surtiCreditInternalCode) {\n _showLoading(true)\n let totalOrderPriceStr = document.getElementsByClassName('total-order-price')[0].dataset.total;\n let totalOrderPrice = parseFloat(totalOrderPriceStr);\n try {\n\n const response = await _checkoutService.getSurticreditoBalanceView(totalOrderPrice);\n if (!response.ok) {\n return;\n }\n\n const scriptHtml = await response.text();\n const modalEl = _surtiCreditPaymentModal();\n\n ModalHelper.clearBody(modalEl);\n ModalHelper.setHtmlBody(modalEl, scriptHtml);\n\n // init radio buttons\n _surtiCreditoRadioButtons = new RadioButtons({\n el: \"#surticredit-radiobuttons\",\n onChange: function (e) { }\n })\n\n // show surticredito payment\n const modal = bootstrap.Modal.getOrCreateInstance(modalEl[0])\n modal.show();\n\n $(\"#surticredit-payment-modal-submit\").off(\"click\")\n $(\"#surticredit-payment-modal-submit\").on(\"click\", (e) => {\n\n const surtiCreditMethod = $(`[name=\"surtiCredit-payment\"]:checked`).val();\n if (!surtiCreditMethod) {\n browserCommunicatorService.displayErrorAlert({\n description: \"Debe indicar un crédito\"\n })\n return;\n }\n\n $(\".payyourbills_payment-arrow i\").show();\n $(`[name=\"creditRequestId\"]`).val(surtiCreditMethod)\n $(`[name=\"surtiCreditDays\"]`).val($(\"#surticredit-days\").val())\n modal.hide();\n })\n\n $(\"#surticredit-payment-modal-cancel\").off(\"click\");\n $(\"#surticredit-payment-modal-cancel\").on(\"click\", (e) => {\n $(`[name=\"creditRequestId\"]`).val(\"\")\n $(`[name=\"surtiCreditDays\"]`).val(\"\")\n $(\"input[name='paymentMethod']:checked\").parent().removeClass('checked');\n $(\"input[name='paymentMethod']:checked\").prop('checked', false);\n modal.hide();\n })\n\n } finally {\n _showLoading(false)\n }\n }\n else {\n $(`[name=\"creditRequestId\"]`).val(\"\")\n $(`[name=\"surtiCreditDays\"]`).val(\"\")\n }\n}\n\n/**\n * \n * @param {{paymentType: string}} param0\n */\nfunction trackPaymentInfo({ paymentType }) {\n\n app.applicationMonitoringService()\n .then((service) => {\n service.trackPaymentInfo({\n currency: appConstants.currency,\n paymentType: paymentType\n })\n })\n .catch(function (err) {\n console.error(err)\n })\n}\n\nfunction renderEventsPaymentMethod() {\n $(`#acceptancePoliciesCheck`).off(\"click\");\n $(`#acceptancePoliciesCheck`).click(acceptancePoliciesCheck);\n}\n\nfunction bindWizard() {\n\n _paymentMethodsRadioButtons = new RadioButtons({\n el: \".checkout__payment-list\",\n onChange: async function (e) {\n /** @type {HTMLInputElement} */\n const inputElement = e.detail.checkedTarget;\n const internalCode = inputElement.getAttribute(\"InternalCode\")\n const name = inputElement.getAttribute(\"Name\")\n validateCheckboxCredit({ paymentMethod: internalCode })\n validateCheckboxCreditCard({ paymentMethod: internalCode })\n await validateCheckboxSurticredito({ paymentMethod: internalCode })\n trackPaymentInfo({ paymentType: name })\n }\n })\n\n _addressRadioButtons = new RadioButtons({\n el: \".checkout__address-list\",\n onChange: changeAddress2\n })\n\n new RadioButtons({\n el: \"#summaryShippingSelected\"\n })\n\n new RadioButtons({\n el: \"#summaryPaymentSelected\"\n })\n\n _wizard = new WizardForm({\n nextButton: \".checkout-next\",\n previousButton: \".checkout-previous\",\n id: \"#checkoutProcess\",\n onLeaveStep: async (stepNumber, direction, button) => {\n return await _leaveStepAsync(stepNumber, direction, button);\n },\n });\n\n _wizard.init();\n}\n\nasync function _scrollTop(element) {\n $('html, body').animate({ scrollTop: 0 }, 'slow')\n}\n/**\n * \n * @param {number} stepNumber\n * @param {'next' | 'previous' } direction\n * @param {HTMLElement} button\n */\nasync function _leaveStepAsync(stepNumber, direction, button) {\n _showLoading(true)\n try {\n if (direction === 'next') {\n\n if (stepNumber == 1) {\n _displayMultipleControls(true)\n _nextStep()\n return true;\n }\n if (stepNumber == 2) {\n _paymentMethods()\n var isFormValid = await validateForm(\"#form-step-2\")\n if (isFormValid) {\n _nextStep()\n }\n else {\n _scrollTop();\n }\n return isFormValid;\n }\n if (stepNumber == 3) {\n var isFormValid = await validateForm(\"#form-step-3\")\n if (isFormValid) {\n _displayBuyControls(true)\n _nextStep()\n // load checkout summary\n _loadCheckoutSummary({\n addressSelector: `[name=\"addressSeleted\"]:checked`,\n paymentSelector: `[name=\"paymentMethod\"]:checked`,\n orderSchedulerSelector: `#OrderScheduler`\n })\n }\n else {\n _scrollTop();\n }\n return isFormValid;\n }\n if (stepNumber == 4) {\n return true;\n }\n\n return true\n } else if (direction === 'previous') {\n previousStep();\n if (stepNumber == 2) {\n _displayMultipleControls(false)\n return true\n }\n if (stepNumber == 4) {\n _displayBuyControls(false)\n return true;\n }\n\n return true;\n }\n return true;\n } catch (e) {\n console.error(e);\n } finally {\n _showLoading(false);\n }\n\n /** update the previous data-step value */\n function previousStep() {\n $(\".checkout-previous\").data(\"step\", stepNumber - 1);\n $(\".checkout-next\").data(\"step\", stepNumber - 1);\n }\n\n /** Update the previous data-step value */\n function _nextStep() {\n $(\".checkout-previous\").data(\"step\", stepNumber + 1);\n $(\".checkout-next\").data(\"step\", stepNumber + 1);\n }\n\n /**\n * \n * @param {{addressSelector: string, paymentSelector: string, orderSchedulerSelector: string}} loadSummaryRequest\n */\n function _loadCheckoutSummary(loadSummaryRequest) {\n try {\n _showLoading(true)\n\n // address\n const addressSelectedEl = document.querySelector(loadSummaryRequest.addressSelector);\n const summaryAddressSelected = addressSelectedEl.parentElement.cloneNode(true)\n summaryAddressSelected.querySelector(\"input\").name = \"summaryAddress\"\n $(\"#summaryShippingSelected\").html(summaryAddressSelected)\n\n // payment method\n const paymentSelectedEl = document.querySelector(loadSummaryRequest.paymentSelector)\n const summaryPaymentSelected = paymentSelectedEl.parentElement.cloneNode(true)\n summaryPaymentSelected.querySelector(\"input\").name = \"summaryPaymentMethod\"\n $(\"#summaryPaymentSelected\").html(summaryPaymentSelected)\n\n // order scheduler\n const summaryOrderScheduler = document.querySelector('#summaryOrderScheduler');\n summaryOrderScheduler.value = $(loadSummaryRequest.orderSchedulerSelector).val()\n\n // products\n const productsEl = document.querySelector(\"#checkoutProductList\")\n /** @type {HTMLElement} */\n const summaryProducts = productsEl.cloneNode(true)\n\n summaryProducts.querySelectorAll(\".controls__less\").forEach(el => el.classList.add(\"d-none\"))\n summaryProducts.querySelectorAll(\".controls__more\").forEach(el => el.classList.add(\"d-none\"))\n summaryProducts.querySelectorAll(\".controls__remove--middle\").forEach(el => el.classList.add(\"d-none\"))\n $(\"#summaryProductSeleted\").html(summaryProducts)\n\n } catch (e) {\n console.error(e)\n } finally {\n _showLoading(false)\n }\n }\n}\n\n/**\n * \n * @param {boolean} display\n */\nfunction _displayMultipleControls(display = true) {\n $(\".wizard__control--multiple\").toggleClass(\"d-none\", !display)\n $(\".wizard__control--individual\").toggleClass(\"d-none\", display)\n}\n\n/**\n * \n * @param {boolean} display\n */\nfunction _displayBuyControls(display = true) {\n $(\".btn-checkout-save\").toggleClass(\"d-none\", !display);\n $(\".checkout-next\").toggleClass(\"d-none\", display);\n}\n\nfunction _showLoading(show = true) {\n kendo.ui.progress($(\"#checkoutProcess\"), show);\n}\n\nfunction _showCouponsLoading(show = true) {\n kendo.ui.progress($(\"#coupon-modal\"), show);\n}\n\n/**\n * \n * @param {string} target\n * @returns {boolean}\n */\nasync function validateForm(target) {\n let formCommonRules = {\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredOrderScheduler: function (input) {\n if (input.is(`[name=\"OrderScheduler\"]`)) {\n let orderScheduler = $(\"#OrderScheduler\").val();\n if (orderScheduler) {\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n */\n requiredAddress: function (input) {\n if (input.is(`[name=\"addressSeleted\"]`)) {\n var selected = $(`[name=\"addressSeleted\"]:checked`).val();\n if (selected) {\n return true;\n } else {\n return false\n }\n }\n else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n */\n requiredPaymentMethod: function (input) {\n if (input.is(`[name=\"paymentMethod\"]`)) {\n var selected = $(`[name=\"paymentMethod\"]:checked`).val();\n if (selected) {\n return true;\n } else {\n return false\n }\n }\n else {\n return true;\n }\n }\n }\n let formCommonMessages = {\n requiredOrderScheduler: \"Debe seleccionar un horario de entrega\",\n requiredAddress: \"Debe selecionar una dirección\",\n requiredPaymentMethod: \"Debe seleccionar un medio de pago\"\n }\n\n let validator = $(target).kendoValidator({\n rules: {\n ...formCommonRules\n },\n messages: {\n ...formCommonMessages\n }\n }).data(\"kendoValidator\");\n\n return validator.validate();\n}\n\n/**\n * \n * @param event {Event}\n * */\nasync function changeAddress2(event) {\n const addressId = event.detail.value\n _toggleLoading(true)\n _checkoutService.changeAddress(addressId).pipe(\n map(response => response.response),\n switchMap(changeResponse => forkJoin({\n subTotals: _computeSubTotals$(true, true),\n changeAddressResponse: of(changeResponse)\n })),\n finalize(_ => _toggleLoading(false))\n ).subscribe(responses => {\n _bindComputeSubTotals(responses.subTotals)\n\n //hide credit policies\n $(\"#checkboxCredit\").prop(\"checked\", false);\n $(\"#checkboxCredit\").hide();\n $(\"#labelCheckboxCredit\").hide();\n })\n}\n\nfunction _loadAcceptancePolicies() {\n _toggleLoading(true);\n _checkoutService.acceptancePoliciesView().pipe(\n catchError(err => {\n console.error(err);\n throw `Error load acceptance policies \\n${err}`;\n }),\n finalize(() => _toggleLoading(false))\n ).subscribe(res => {\n // display modal and load html\n const html = res.response;\n\n const modalEl = $(\"#acceptancePolicies\");\n ModalHelper.clearBody(modalEl);\n ModalHelper.setHtmlBody(modalEl, html);\n\n const modal = bootstrap.Modal.getOrCreateInstance(modalEl[0])\n modal.show();\n\n //bind events\n $('.acceptance-policies-code-button').off('click');\n $('.acceptance-policies-code-button').on('click', (e) => {\n $(\"#checkboxCredit\").prop(\"checked\", true);\n modal.hide();\n });\n })\n}\n\n/**\n * update product quantity from shopping cart item\n * @param {string} productId\n */\nasync function _updateProductQuantity(productId) {\n\n if (!productId) {\n return\n }\n\n _showLoading(true)\n try {\n\n const response = await _shoppingCartService.getItemFetch(productId)\n if (!response.ok) {\n return;\n }\n\n const shoppingCartItem = (await response.json()).Value;\n const productQuantitySpan = $(`li[data-product=\"${productId}\"] span.controls__number`)\n productQuantitySpan.text(shoppingCartItem.Quantity)\n } catch (e) {\n console.error(e)\n } finally {\n _showLoading(false)\n }\n\n\n}\n\n/**\n* \n* @param {string} productId\n* @param {any} shoppingCartResponseJson\n*/\nfunction _updateShoppingCartPrices(productId, shoppingCartResponseJson) {\n\n // dispatch shopping cart event\n UpdateProductPricesEvent.update({\n productBranchOfficeId: productId,\n shoppingCartResponse: shoppingCartResponseJson\n })\n\n var element = $(`.checkout__products-item[data-product=\"${productId}\"]`);\n let productPriceEl = element.find(\".product__price\");\n let productNewPriceEl = element.find(\".product__price--old\");\n\n if (shoppingCartResponseJson.ProductNewPrice > 0 && productNewPriceEl.length > 0) {\n productNewPriceEl.html(renderNewPrice(shoppingCartResponseJson.ProductPrice, shoppingCartResponseJson.ProductPriceFormatted));\n }\n else {\n productNewPriceEl.html(\"\");\n }\n\n if (productPriceEl.length > 0 && shoppingCartResponseJson.ProductNewPrice > 0) {\n productPriceEl.html(renderPrice(shoppingCartResponseJson.ProductNewPrice, shoppingCartResponseJson.ProductNewPriceFormatted, productId));\n }\n else if (productPriceEl.length > 0) {\n productPriceEl.html(renderPrice(shoppingCartResponseJson.ProductPrice, shoppingCartResponseJson.ProductPriceFormatted, productId));\n }\n}\n\n\nasync function _loadCouponsViews() {\n await _loadCouponListView();\n await _loadCouponButtonView();\n}\n\nasync function _loadCouponButtonView() {\n try {\n const response = await _checkoutService.getCouponButtonView();\n if (!response.ok) {\n return;\n }\n const html = await response.text()\n $(\"#coupon-selector-button\").html(html);\n\n //events\n bindCouponsEvent();\n bindShoppingCartCoupons();\n } catch (e) {\n console.error(e);\n }\n}\n\nasync function _loadCouponListView() {\n try {\n const [response1, response2] = [\n await _checkoutService.getCouponListView(),\n await _checkoutService.getExpiredCouponListView()\n ];\n if (!response1.ok || !response2.ok) {\n return;\n }\n\n const html1 = await response1.text();\n const html2 = await response2.text();\n $(\"#coupons-available-list\").html(html1);\n $(\"#coupons-expired-list\").html(html2);\n\n //events\n bindCouponsEvent();\n bindShoppingCartCoupons();\n } catch (e) {\n console.error(e);\n }\n}\n\nfunction renderNewPrice(price, priceFormatted) {\n return `\n \n \n ${priceFormatted}\n \n \n `;\n}\n\n/**\n * \n * @param {number} price\n * @param {string} priceFormatted\n * @returns\n */\nfunction renderPrice(price, priceFormatted, productId) {\n return `\n \n \n ${priceFormatted}\n \n \n `\n}\n\nfunction _loadProductListView$() {\n return _checkoutService.getProductListView().pipe(\n map(response => response.response),\n catchError(err => {\n console.error(err);\n throw `Error compute product list \\n${err}`;\n })\n );\n}\n\n/**\n * \n * @param {string} html \n */\nfunction _bindProductList(html) {\n $(\".checkout__details-wrapper\").html(html);\n bindShoppinCartControl();\n}","import ModalHelper from './helpers/modal-helper.js';\nimport WaitHandler from './handlers/wait-handler.js';\nimport EffectHelper from './helpers/effects-helper.js';\nimport ProductHelper from './helpers/product-helper.js';\nimport CartHelper from './helpers/cart-helper.js';\n\nimport { PredictiveSearchProductHandlers } from './handlers/predictive-search-product-handlers.js';\nimport AppHandlers from './handlers/app-handlers.js';\n\nimport CustomerHandlers from './handlers/customer-handlers.js'\n\nimport ChatService from './services/chat-service.js';\nimport StoreService from './services/store-service.js';\nimport CustomerService from './services/customer-service.js'\nimport CheckoutService from './services/checkout-service.js'\n\nimport VerificationCode from './services/verification-code-service.js';\nimport VerificationCodeType from './helpers/verification-code-helper.js';\n\nimport SiteEnum from './enums/site-enum.js';\nimport { MarkingHandlers } from './handlers/marking-handlers';\nimport { MarkingByProductHandlers } from './handlers/marking-byproduct-handlers';\nimport { TwoFaChangePasswordHandlers } from './handlers/twofa-changepassword-handlers.js';\nimport { TwoFaGenericUserHandlers } from './handlers/twofa-genericuser-handler.js';\nimport { TwoFaAdditionalInformationHandlers } from './handlers/twofa-additionalinformation-handlers.js';\nimport { ChangeAddressReminerHandler } from './handlers/changeaddressreminer-handler.js';\nimport { PageConfig } from \"./shared/config/page-config\";\nimport { $applicationMonitoringService } from './shared/application-monitoring'\n\nimport { CreditCardMyAccountHandler } from \"./credit-card/my-account/handlers/credit-card-my-account-handlers\"\nimport { CreditCardCheckoutHandler } from \"./credit-card/checkout/handlers/credit-card-checkout-handlers\"\n\nimport { AccountActivationHandlers } from \"./user-security/account-activation/handlers/account-activation-handlers\";\nimport { DynamicKitHandlers } from \"./shared/dynamic-kits/handlers/dynamic-kit-handlers.js\"\n\nimport { AddressManagementHandler } from \"./shared/address-management/handlers/address-management-handler.js\"\nimport CheckoutHandlers from './handlers/checkout-handlers.js';\n\nlet _storeService = null;\nlet _checkoutService = null;\nlet _productDetailService = null;\nlet _effectHelper = new EffectHelper();\n\n/** @type {TwoFaChangePasswordHandlers} */\nlet _twofaChangePasswordHandlers;\n\n/** @type {TwoFaGenericUserHandlers} */\nlet _twofaGenericUserHandlers;\n\n/** @type {TwoFaAdditionalInformationHandlers} */\nlet _twofaAdditionalInfoHandlers;\n\n/** @type {AddressManagementHandler} */\nlet _addressManagementHandler;\n\nclass App {\n\n /**\n * @param pageConfig {PageConfig}\n * */\n constructor(pageConfig) {\n this._pageConfig = pageConfig;\n this.initialize()\n }\n\n initialize() {\n // when load page\n $(() => {\n this.handler.init();\n if (this._pageConfig.initChat) {\n ChatService.init();\n }\n\n this.initTooltips()\n this.initPopovers()\n })\n }\n\n initTooltips() {\n var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle=\"tooltip\"]'));\n tooltipTriggerList.map(function (tooltipTriggerEl) {\n return new bootstrap.Tooltip(tooltipTriggerEl);\n });\n }\n\n initPopovers() {\n var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle=\"popover\"]'))\n popoverTriggerList.map(function (popoverTriggerEl) {\n return new bootstrap.Popover(popoverTriggerEl)\n })\n }\n\n get handler() {\n return new Proxy(this._pageConfig.handler, {\n get: (handler, prop) => {\n if (typeof handler[prop] === 'function') {\n return handler[prop].bind(handler);\n }\n else {\n return handler[prop];\n }\n },\n })\n }\n\n get code() {\n return this._pageConfig.internalCode;\n }\n\n applicationMonitoringService() {\n return $applicationMonitoringService\n }\n\n /***\n * @type {TwoFaHandlers}\n * */\n static _twoFaHandlers;\n\n /**\n * Handlers of Customer\n * @type CustomerHandlers\n * */\n static _customerHandlers;\n\n static _markingHandlers;\n\n static _markingbyproductHandlers\n /** @type {AddressManagementHandler} */\n static _addressManagementHandler;\n\n /** @type {DynamicKitHandlers} */\n static _dynamicKitHandlers;\n\n static init(module) {\n $(document).ready(() => {\n switch (module) {\n case SiteEnum.Checkout:\n _checkoutService = new CheckoutService()\n CheckoutHandlers.init();\n this._customerHandlers = new CustomerHandlers()\n\n this._creditCardCheckoutHandler = new CreditCardCheckoutHandler();\n this._creditCardCheckoutHandler.init();\n\n break;\n case SiteEnum.Account:\n this._customerHandlers = new CustomerHandlers();\n\n this._creditCardHandler = new CreditCardMyAccountHandler();\n this._creditCardHandler.init();\n this._addressManagementHandler = new AddressManagementHandler();\n _addressManagementHandler.init();\n\n this._dynamicKitHandlers = new DynamicKitHandlers();\n this._dynamicKitHandlers.init()\n\n break;\n case SiteEnum.Security:\n _storeService = new StoreService();\n PredictiveSearchProductHandlers.init(App);\n AppHandlers.init();\n this._customerHandlers = new CustomerHandlers();\n\n this._addressManagementHandler = new AddressManagementHandler();\n this._addressManagementHandler.init();\n\n this._creditCardHandler = new CreditCardMyAccountHandler();\n this._creditCardHandler.init();\n\n this._accountActivationHandler = new AccountActivationHandlers();\n this._accountActivationHandler.init();\n\n this._dynamicKitHandlers = new DynamicKitHandlers();\n this._dynamicKitHandlers.init()\n\n break;\n case SiteEnum.SecurityWithoutLoginB2B:\n _storeService = new StoreService();\n PredictiveSearchProductHandlers.init(App);\n AppHandlers.init();\n this._customerHandlers = new CustomerHandlers()\n\n this._addressManagementHandler = new AddressManagementHandler();\n this._addressManagementHandler.init();\n\n this._creditCardHandler = new CreditCardMyAccountHandler();\n this._creditCardHandler.init();\n\n this._dynamicKitHandlers = new DynamicKitHandlers();\n this._dynamicKitHandlers.init()\n break;\n case SiteEnum.TwoFARequired:\n _storeService = new StoreService();\n PredictiveSearchProductHandlers.init(App);\n AppHandlers.init();\n this._customerHandlers = new CustomerHandlers()\n this._twoFaHandlers = new TwoFaHandlers();\n break;\n case SiteEnum.Marking:\n AppHandlers.init();\n this._markingHandlers = new MarkingHandlers();\n break;\n case SiteEnum.MarkingByProduct:\n AppHandlers.init();\n this._markingbyproductHandlers = new MarkingByProductHandlers();\n break;\n case SiteEnum.TwoFARequiredChangePassword:\n this._customerHandlers = new CustomerHandlers();\n _twofaChangePasswordHandlers = new TwoFaChangePasswordHandlers()\n break;\n case SiteEnum.TwoFARequiredGeneriUser:\n this._customerHandlers = new CustomerHandlers();\n _twofaGenericUserHandlers = new TwoFaGenericUserHandlers()\n break;\n case SiteEnum.TwoFARequiredAdditionalInformation:\n this._customerHandlers = new CustomerHandlers();\n _twofaAdditionalInfoHandlers = new TwoFaAdditionalInformationHandlers()\n break;\n case SiteEnum.ChangePassword:\n this._customerHandlers = new CustomerHandlers();\n break;\n }\n\n ChatService.init();\n\n // Service Workers\n //_loadSW();\n\n });\n\n return this;\n }\n\n static get storeService() {\n return _storeService;\n }\n\n static get checkoutService() {\n return _checkoutService;\n }\n\n static get ProductDetailService() {\n return _productDetailService;\n }\n\n static get CustomerHandlers() {\n return this._customerHandlers;\n }\n\n static get modalHelper() {\n return ModalHelper;\n }\n\n static get waitHandler() {\n return WaitHandler;\n }\n\n static get effectHelper() {\n return _effectHelper;\n }\n\n static get eventHandlers() {\n return AppHandlers;\n }\n\n static get productHelper() {\n return ProductHelper;\n }\n\n static get cartHelper() {\n return CartHelper;\n }\n\n /**\n * @returns {CustomerService} customer service\n */\n static get customerService() {\n return this._customerHandlers.customerService;\n }\n\n static get addressManagementHandler() {\n return this._addressManagementHandler;\n }\n\n static applicationMonitoringService() {\n return $applicationMonitoringService;\n }\n\n static get verificationCodeType() {\n return VerificationCodeType;\n }\n\n static get verificationCodeService() {\n return new VerificationCode();\n }\n\n static get markingHandler() {\n return this._markingHandlers;\n }\n\n static get markingByProductHandler() {\n return this._markingbyproductHandlers;\n }\n\n static get TwoFaChangePasswordHandlers() {\n return _twofaChangePasswordHandlers;\n }\n\n static get TwoFaGenericUserHandlers() {\n return _twofaGenericUserHandlers;\n }\n\n}\n\nexport default App;\n\n/**Load services Workers */\nfunction _loadSW() {\n if ('serviceWorker' in navigator) {\n // App SW\n navigator.serviceWorker.register(\"/clevertap_sw.js\")\n .catch(err => console.error(err))\n }\n}","class WaitHandler {\n\n constructor() {\n this._wait = false;\n }\n\n static startWaiting(milliseconds) {\n\n if (this._wait) {\n return;\n }\n\n this._wait = true;\n\n var start = new Date().getTime();\n var end = start;\n while (this.wait && end < start + milliseconds) {\n end = new Date().getTime();\n\n if (end >= start + milliseconds) {\n this._wait = false;\n }\n }\n }\n\n static stopWaiting() {\n this._wait = false;\n }\n}\n\nexport default WaitHandler;\n","export default class EffectHelper {\n\n constructor() {\n jQuery.fn.fadeOutAndRemove = function (options) {\n EffectHelper.doEffect($(this), 'fadeOut', 'remove', options);\n };\n\n jQuery.fn.fadeInAndShow = function (options) {\n EffectHelper.doEffect($(this), 'fadeIn', 'show', options);\n };\n\n jQuery.fn.fadeOutAndHide = function (options) {\n EffectHelper.doEffect($(this), 'fadeOut', 'hide', options);\n };\n }\n\n static doEffect(element, effectFunction, elementFuction, options) {\n if (!options) {\n options = { speed: 300, callback: null };\n }\n\n if (!options.speed) { options.speed = 300; }\n\n $(element)[effectFunction](options.speed, function () {\n element[elementFuction]();\n if (options.callback) {\n options.callback();\n }\n });\n }\n}\n\nexport const effectHelper = new EffectHelper();","class ProductHelper {\n\n constructor() {\n }\n\n static getProductId(element) {\n return $(element).parent().data('product');\n }\n\n /**\n * \n * @param {JQuery} element\n * @returns\n */\n static getIsKit(element) {\n return element.parent().data(\"is-kit\");\n }\n\n static getInternalId(element) {\n return element.parent().data(\"internal-id\");\n }\n\n static getProductIds(items) {\n let productIds = [];\n\n $(items).each(function (index, item) {\n let productId = $(item).data('product');\n productIds.push(productId);\n });\n\n return productIds;\n }\n}\n\nexport default ProductHelper;","class CartHelper {\n\n constructor() {\n\n }\n\n static updateCart(imgtodrag) {\n var isMobile = false;\n // device detection\n if (/(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)\n || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i.test(navigator.userAgent.substr(0, 4))) {\n isMobile = true;\n }\n if (!isMobile) {\n CartHelper.sendProductImageToCar(imgtodrag);\n } else {\n CartHelper.animateCart();\n }\n }\n static animateCart(cart) {\n if (!cart) {\n cart = $('.mh__cart-trigger');\n }\n\n setTimeout(function () {\n cart.effect(\"shake\", {\n times: 2,\n distance: 5\n }, 200);\n }, 1500);\n }\n static animateCartForBanner(cart) {\n if (!cart) {\n cart = $('.mh__cart-trigger');\n }\n cart.effect(\"bounce\", {\n times: 2,\n distance: 5\n }, 200);\n }\n static sendProductImageToCar(imgtodrag) {\n var cart = $('.mh__cart-trigger');\n if (imgtodrag) {\n var imgclone = imgtodrag.clone()\n .offset({\n top: imgtodrag.offset().top,\n left: imgtodrag.offset().left\n })\n .css({\n 'opacity': '0.5',\n 'position': 'absolute',\n 'height': '150px',\n 'width': '150px',\n 'z-index': '100'\n })\n .appendTo($('body'))\n .animate({\n 'top': cart.offset().top + 10,\n 'left': $(window).width() - 50,\n 'width': 75,\n 'height': 75\n }, 1000, 'easeInOutExpo');\n\n CartHelper.animateCart(cart);\n\n imgclone.animate({\n 'width': 0,\n 'height': 0\n }, function () {\n $(this).detach()\n });\n }\n }\n static getProductFromDataJson(target = 'cart__product') {\n let productsEls = document.getElementsByClassName(target)\n return [...productsEls]?.map((value, index) => JSON.parse(value.getAttribute(\"data-json\")))\n }\n\n static getTotalValueFromDataValue(target = \"span.total-price\") {\n let priceEl = document.querySelector(target);\n if (!priceEl.hasAttribute(\"data-value\")) {\n return -1;\n }\n return parseFloat(priceEl.getAttribute(\"data-value\"));\n }\n}\n\nexport default CartHelper;","export class JourneyService {\n\n /** */\n get _journeyArea() {\n return document.querySelector('meta[name=\"journey-type-area\"]');\n }\n\n constructor() { }\n\n /**\n * \n * @returns {string | null}\n */\n getJourneyArea() {\n var journeyMeta = this._journeyArea;\n if (journeyMeta) {\n return journeyMeta.getAttribute(\"content\");\n } else {\n return JOURNEY_TYPES.Standard;\n }\n }\n}\n\nexport const JOURNEY_TYPES = Object.freeze({\n WithoutLoginB2B: \"WithoutLoginB2B\",\n WithoutLoginB2C: \"WithoutLoginB2C\",\n Standard: \"Standard\"\n})","import 'jquery'\nimport { JOURNEY_TYPES, JourneyService } from '../../shared/journey/journey-service';\n\n/**\n * Implement the handlers\n * */\nexport class HandlerBase {\n\n isBusy = false;\n\n constructor() {\n if (this.constructor == HandlerBase) {\n throw new Error(\"Object of Abstract Class cannot be created\");\n }\n\n this._journeyService = new JourneyService();\n }\n\n init() {\n this._throwNoImplementError();\n }\n\n _throwNoImplementError() {\n throw new Error(\"Method not implement\");\n }\n\n /**\n * \n * @param loading {boolean}\n * @param target {string | HTMLElement}\n * */\n _loading(loading, target) {\n this.isBusy = loading;\n kendo.ui.progress($(target), loading)\n }\n\n /**\n * Get current journey type area\n * @returns\n */\n _getJourneyArea() {\n return this._journeyService.getJourneyArea();\n }\n}","class UrlHelper {\n \n constructor() {\n }\n\n static get urlBase() {\n return '?handler=';\n }\n\n static get apiUrlBase() {\n return '/api/'\n }\n\n static get addProductToCartUrl() {\n return `${this.apiUrlBase}ShoppingCart/AddProductToCart`;\n }\n\n static get addProductsToCartUrl() {\n return `${this.apiUrlBase}ShoppingCart/AddProductsToCart`;\n }\n\n\n static get getShoppingCartItemUrl() {\n return `${this.apiUrlBase}ShoppingCart/GetShoppingCartItem`;\n }\n\n static get getShoppingCart() {\n return `${this.apiUrlBase}ShoppingCart`;\n }\n\n static get getDeliveryPrice() {\n return `${this.apiUrlBase}ShoppingCart/GetDeliveryPrice`;\n }\n\n static get addProductQuantityUrl() {\n return `${this.apiUrlBase}ShoppingCart/AddProductQuantity`;\n }\n\n static get changeAddressUrl() {\n return `${UrlHelper.urlBase}ChangeAddress`;\n }\n\n static get increaseProductQuantityUrl() {\n return `${this.apiUrlBase}ShoppingCart/IncreaseProductQuantity`;\n }\n\n static get decreaseProductQuantityUrl() {\n return `${this.apiUrlBase}ShoppingCart/DecreaseProductQuantity`;\n }\n\n static get replicateOrderUrl() {\n return `${this.apiUrlBase}ShoppingCart/ReplicateOrder`;\n }\n\n static get getShoppingCartViewUrl() {\n return `/Store/ShoppingCart`;\n }\n\n static get getSelectedProductDetailViewUrl() {\n return `${UrlHelper.urlBase}GetSelectedProductDetailView`;\n }\n\n static get getProductsByNameUrl() {\n return `${UrlHelper.urlBase}GetProductsByName`;\n }\n\n static get getFavoriteLists() {\n return `${UrlHelper.urlBase}GetFavoriteLists`;\n }\n\n static get createFavoriteList() {\n return `${UrlHelper.urlBase}CreateFavoriteList`;\n }\n\n static get updateFavoriteList() {\n return `${UrlHelper.urlBase}UpdateFavoriteList`;\n }\n\n static get getFavoriteList() {\n return `${UrlHelper.urlBase}GetFavoriteList`;\n }\n\n static get getFavoriteListItemHtml() {\n return `${UrlHelper.urlBase}GetFavoriteListItemHtml`;\n }\n\n static get deleteProductFavoriteList() {\n return `${UrlHelper.urlBase}DeleteProductFavoriteList`;\n }\n\n static get addProductFavoriteList() {\n return `${UrlHelper.urlBase}AddProductFavoriteList`;\n }\n\n static get emptyShoppingCart() {\n return `${this.apiUrlBase}ShoppingCart/EmptyCart`;\n }\n\n static get saveCustomer() {\n return `${UrlHelper.urlBase}SaveCustomer`;\n }\n\n static get getAddressView() {\n return `${UrlHelper.urlBase}GetAddressView`;\n }\n\n static get saveAddress() {\n return `/Security/MyAccount/Options/Address?handler=SaveAddress`;\n }\n\n static get deleteAddress() {\n return `/Security/MyAccount/Options/Address?handler=DeleteAddress`;\n }\n\n static get updatePassword() {\n return `${UrlHelper.urlBase}UpdatePassword`;\n }\n\n static get signUp() {\n return `${UrlHelper.urlBase}SignUp`;\n }\n\n static get authenticate() {\n return `${UrlHelper.urlBase}Authenticate`;\n }\n\n static get getCitiesByState() {\n return `${UrlHelper.urlBase}GetCitiesByState`;\n } \n\n static get getNeighborhoodsByCityId() {\n return `${UrlHelper.urlBase}GetNeighborhoodsByCityId`;\n }\n\n static get validationCode() {\n return `${UrlHelper.urlBase}ValidationCode`;\n }\n\n static get reSendValidationCode() {\n return `${UrlHelper.urlBase}ReSendValidationCode`;\n }\n\n static get validatePassword() {\n return `${UrlHelper.urlBase}ValidatePassword`;\n }\n\n static get removeProductUrl() {\n return `${this.apiUrlBase}ShoppingCart/RemoveItemSC`;\n }\n\n static get saveOrderUrl() {\n return `${UrlHelper.urlBase}OrderSave`;\n }\n\n static get pagesTotalsUrl() {\n return `${UrlHelper.urlBase}ShowButtonLoadMore`;\n }\n \n static get setBranchOfficeSelected() {\n return `${UrlHelper.urlBase}SetBranchOfficeSelected`;\n }\n\n static get setBranchOfficeWithoutRegistrationSelected() {\n return `${UrlHelper.urlBase}SetBranchOfficeWithoutRegistrationSelected`;\n }\n\n static get updateReceivePromotionalCommunications() {\n return `${UrlHelper.urlBase}UpdateReceivePromotionalCommunications`;\n }\n\n static get validatePromotionalCodeUrl() {\n return `${UrlHelper.urlBase}ValidatePromotionalCode`;\n }\n\n static get rememberPasswordUrl() {\n return `${UrlHelper.urlBase}Remember`;\n }\n\n static get markingSaveUrl() {\n return `${UrlHelper.urlBase}MarkingSave`;\n }\n\n static get postMarkingSave() {\n return `${UrlHelper.urlBase}Save`;\n }\n\n static get markingSaveConfirmUrl() {\n return `${UrlHelper.urlBase}MarkingSaveConfirm`;\n }\n\n static get markingDeleteUrl() {\n return `${UrlHelper.urlBase}MarkingDelete`;\n }\n\n static get postMarkingDelete() {\n return `${UrlHelper.urlBase}MarkingDelete`;\n }\n\n static get markingSaveImageUrl() {\n return `${UrlHelper.urlBase}MarkingSaveImage`;\n }\n\n static get customerValidate() {\n return `${UrlHelper.urlBase}CustomerValidate`;\n }\n\n static get messagesPendingByUserAnswer() {\n return `${UrlHelper.urlBase}MessagesPendingByUserAnswer`;\n }\n\n static get saveUserAnswerByValidationMessage() {\n return `${UrlHelper.urlBase}SaveUserAnswerByValidationMessage`;\n }\n\n static get loginByMobileNumber() {\n return `${UrlHelper.urlBase}LoginByMobile`;\n }\n\n static get realodAddressList() {\n return `/Security/MyAccount/Options/Address?handler=ReloadAddressList`;\n }\n \n static get confirmationSendingPassword() {\n return `${UrlHelper.urlBase}MessageSendingMethodPassword`;\n }\n\n static get confirmationMessageSending() {\n return `${UrlHelper.urlBase}MessageSendingMethodActivation`;\n }\n\n static get rememberPasswordWithMethod() {\n return `${UrlHelper.urlBase}RememberWithMethod`;\n }\n\n static get getCheckoutSummaryView() {\n return `${this.urlBase}\\GetCheckoutSummaryView`\n }\n\n static get saveInvoicesSelectedUrl() {\n return `${UrlHelper.urlBase}SaveInvoicesSelected`;\n }\n static get bonusByCustomer() {\n return `${this.urlBase}BonusByCustomer`;\n }\n\n static get applyBonusInShoppingCart() {\n return `${this.urlBase}ApplyBonusInOrder`;\n }\n\n static get isAuthenticated() {\n return `${this.urlBase}IsAuthenticated`\n }\n\n static get getCustomer() {\n return `${this.urlBase}Customer`\n }\n\n\n static get realodBillList() {\n return `${UrlHelper.urlBase}ReloadInvoicesView`;\n }\n\n static get goToPayBills() {\n return `${UrlHelper.urlBase}SaveInvoicesSelected`;\n }\n\n static get reloadPayments() {\n return `${UrlHelper.urlBase}ReloadPaymentsView`;\n }\n static get codeAccessValidation() {\n return `${UrlHelper.urlBase}CodeAccessValidation`;\n }\n\n static get postChangePassword() {\n return `${this.urlBase}ChangePassword`\n }\n\n static get postSendVerificationCode() {\n return `${UrlHelper.urlBase}SendVerificationCode`;\n }\n\n static get postVerifyAccount() {\n return `${UrlHelper.urlBase}VerifyAccount`;\n }\n\n //#region Verification Code\n\n static get postSendVerificationCode() {\n return `${UrlHelper.urlBase}SendVerificationCode`;\n }\n\n static get postValidateCode() {\n return `${UrlHelper.urlBase}ValidateCode`;\n }\n\n static get postDataUser() {\n return `${UrlHelper.urlBase}DataUser`;\n }\n\n static get postRenderVerificationCode() {\n return `${UrlHelper.urlBase}RenderVerificationCode`;\n }\n\n static get postRenderSendingMethodSelection() {\n return `${UrlHelper.urlBase}RenderSendingMethodSelection`;\n }\n\n //#endregion\n\n static get twoFARequiredPageModelBase() {\n return {\n postValidateCodeProcess2FA: `${this.urlBase}ValidateCodeProcess2FA`,\n postValidationCodeProcess2FA: `${this.urlBase}ValidationCodeProcess2FA`,\n postReValidationCodeProcess2FA: `${this.urlBase}ReValidationCodeProcess2FA`\n }\n }\n\n static get twoFARequiredAdditionalInformationPageModelbase() {\n return {\n postValidationAdditionalInformationProcess2FA: `${this.urlBase}ValidationAdditionalInformationProcess2FA`\n }\n }\n\n\n static get getCheckoutPaymentListView() {\n return `${this.urlBase}GetCheckoutPaymentListView`\n }\n\n static get postDeleteAccount() {\n return `${this.urlBase}DeleteAccount`\n }\n\n static get postCloseCityPopoverStatus() {\n return `${this.urlBase}CloseCityPopoverStatus`\n }\n\n static get getCityPopoverStatus() {\n return `${this.urlBase}CityPopoverStatus`\n }\n\n static get markingByProductModel() {\n return {\n postGetMarkingPriceById: `${this.urlBase}GetMarkingPriceById`\n }\n }\n\n static get getChangeAddressReminerStatus() {\n return `${this.apiUrlBase}AddressReminder/GetStatus`\n }\n\n static get postDeleteChangePasswordReminer() {\n return `${this.apiUrlBase}AddressReminder/DeleteStatus`\n }\n static get validateEmail() {\n return `${UrlHelper.urlBase}ValidateEmail`;\n }\n\n static get validateAgreementCode() {\n return `${UrlHelper.urlBase}ValidateAgreementCode`;\n }\n\n static get recoveryPassword() {\n return `${UrlHelper.urlBase}Recover`;\n }\n\n static get getFullInfoNotification() {\n return `${this.urlBase}GetFullInfoNotification`\n }\n\n static get getAllNotifications() {\n return `${this.urlBase}GetAllNotifications`\n }\n\n static get pdfContentBase64() {\n return `${UrlHelper.urlBase}PdfContentBase64`\n }\n\n static get xmlContentBase64() {\n return `${UrlHelper.urlBase}XmlContentBase64`\n }\n\n static get getPayYourBillsPaymentMethodsView() {\n return `${this.urlBase}PaymentMethods`\n }\n\n static get getSurticreditoBalanceView() {\n return `${this.urlBase}SurtiCreditoBalance`\n }\n \n static get postCurrencyFormatter(){\n return `${this.apiUrlBase}Cultures/CurrencyFormatter`\n }\n\n static get getCultureSettings(){\n return `${this.apiUrlBase}Cultures/CultureSettings`\n }\n\n static get postRateSaleView() {\n return `${this.urlBase}RateSellerView`\n }\n\n static get postRateSeller() {\n return `${this.urlBase}RateSeller`\n }\n}\n\nexport default UrlHelper;","import { Observable } from 'rxjs';\nimport { ajax, AjaxResponse, AjaxRequest } from 'rxjs/ajax'\n\nclass Ajax {\n\n static call(request = {}) {\n if (!request) {\n return null;\n }\n\n if (!request.dataType) {\n request.dataType = 'json';\n }\n\n $.ajax({\n url: request.url,\n type: request.method,\n dataType: request.dataType,\n data: request.data,\n headers: {\n RequestVerificationToken:\n $('input:hidden[name=\"__RequestVerificationToken\"]').val()\n },\n success: function (data) {\n if (request.callback) {\n request.callback(data);\n }\n },\n fail: function (data) {\n if (request.failCallback) {\n request.failCallback(data);\n }\n },\n error: function (data) {\n if (request.errorCallback) {\n request.errorCallback(data);\n }\n }\n });\n }\n\n static callWithContentType(request = {}) {\n if (!request) {\n return null;\n }\n\n if (!request.dataType) {\n request.dataType = 'json';\n }\n\n $.ajax({\n url: request.url,\n type: request.method,\n dataType: request.dataType,\n data: request.data,\n processData: false,\n contentType: false,\n headers: {\n RequestVerificationToken:\n $('input:hidden[name=\"__RequestVerificationToken\"]').val()\n },\n success: function (data) {\n if (request.callback) {\n request.callback(data);\n }\n },\n fail: function (data) {\n if (request.failCallback) {\n request.failCallback(data);\n }\n },\n error: function (data) {\n if (request.errorCallback) {\n request.errorCallback(data);\n }\n }\n });\n }\n\n /**\n * \n * @param {AjaxRequest} request\n * @returns {Observable}\n */\n static callRx(request) {\n return ajax({\n ...request,\n headers: {\n ...request.headers,\n RequestVerificationToken:\n $('input:hidden[name=\"__RequestVerificationToken\"]').val()\n }\n });\n }\n\n /**\n * \n * @param {string} url\n * @param {RequestInit} request\n * @returns\n */\n static callFetch(url, request) {\n if (!request.headers) {\n request.headers = new Headers({})\n }\n request.headers.append(\"RequestVerificationToken\", $('input:hidden[name=\"__RequestVerificationToken\"]').val())\n return fetch(url, request);\n }\n}\n\nexport default Ajax","import Ajax from './ajax.js';\nimport { of, throwError } from 'rxjs'\nimport { AjaxConfig, AjaxResponse, AjaxRequest } from 'rxjs/ajax'\nimport { Observable } from 'rxjs'\nimport { catchError } from 'rxjs/operators'\n\nclass AjaxProxy {\n\n static post(request = {}) {\n request.method = 'POST';\n Ajax.call(request);\n }\n\n static potsRx(request = {}) {\n return Ajax.callRx(request);\n }\n\n /**\n * \n * @param {AjaxRequest} request\n * @returns {Observable}\n */\n static postRxJson(request) {\n request.method = 'POST';\n request.headers = { 'Content-Type': 'application/json' }\n return Ajax.callRx(request).pipe(\n catchError(err => {\n if (err.status === 0) {\n console.log('Request is not complete: ', err.message)\n return of({})\n }\n else {\n return throwError(err)\n }\n })\n );\n }\n \n /**\n *\n * @param {AjaxRequest} request\n * @returns {Observable}\n */\n static postRxHtml(request) {\n request.method = 'POST'\n request.headers = { 'Content-Type': 'application/json' }\n request.responseType = 'html'\n return Ajax.callRx(request).pipe(\n catchError(err => {\n if (err.status === 0) {\n console.log('Request is not complete: ', err.message)\n return of({})\n }\n else {\n return throwError(err)\n }\n })\n );\n }\n\n /**\n * \n * @param {AjaxRequest} request\n * @returns {Observable}\n */\n static getRxJson(request) {\n request.method = 'GET'\n request.headers = { 'Content-Type': 'application/json' }\n request.responseType = \"json\"\n return Ajax.callRx(request).pipe(\n catchError(err => {\n if (err.status === 0) {\n console.log('Request is not complete: ', err.message)\n return of({})\n }\n else {\n return throwError(err)\n }\n })\n );\n }\n\n static postWithContentType(request = {}) {\n request.method = 'POST';\n Ajax.callWithContentType(request);\n }\n\n /**\n * \n * @param {string} url\n * @param {RequestInit} request\n * @returns\n */\n static postFetch(url, request) {\n request.method = 'POST'\n return Ajax.callFetch(url, request);\n }\n\n /**\n * \n * @param {string} url\n * @param {RequestInit} request\n * @param {{}} json \n * @returns\n */\n static postFetchJson(url, json, request) {\n request.method = 'POST'\n if (!request.headers) {\n request.headers = new Headers({})\n }\n request.headers.append(\"Content-Type\", \"application/json\");\n request.body = JSON.stringify(json);\n return Ajax.callFetch(url, request);\n }\n\n /**\n * \n * @param {string} url\n * @param {RequestInfo} request\n * @returns\n */\n static getFetch(url, request) {\n request.method = 'GET'\n return Ajax.callFetch(url, request);\n }\n\n /**\n * \n * @param {AjaxRequest} request\n * @returns {Observable}\n */\n static postRx(request) {\n request.method = 'POST';\n request.responseType = \"json\"\n return Ajax.callRx(request).pipe(\n catchError(err => {\n if (err.status === 0) {\n console.log('Request is not complete: ', err.message)\n return of({})\n }\n else {\n return throwError(err)\n }\n })\n );\n }\n}\n\nexport default AjaxProxy","export class TrackerService {\r\n constructor(trackers) {\r\n this.trackers = trackers || [];\r\n }\r\n /**\r\n * Track the event for each trackers.\r\n * @summary\r\n * Spanish:\r\n * Activa lo eventos para todos los trackers configurados. Si el nombre del evento no se incluye en el tracker, se omitira.\r\n * @param eventName\r\n * @param params\r\n */\r\n trackEvent(eventName, params) {\r\n try {\r\n for (const tracker of this.trackers) {\r\n if (!tracker.enable) {\r\n console.debug(`The ${tracker.friendlyName} is disabled`);\r\n continue;\r\n }\r\n if (Object.prototype.hasOwnProperty.call(tracker.events, eventName)) {\r\n let analtycsParams = this._resolveParams(tracker, params || {});\r\n if (tracker.resolveParams) {\r\n let resolves = tracker.resolveParams.filter(r => r.eventName === eventName);\r\n for (const resolve of resolves) {\r\n analtycsParams = resolve.resolve(tracker, analtycsParams);\r\n }\r\n }\r\n tracker.logEvent(tracker.events[eventName], analtycsParams);\r\n }\r\n else {\r\n console.debug(`The event name ${eventName} missing in the ${tracker.friendlyName} tracker.`);\r\n }\r\n }\r\n }\r\n catch (error) {\r\n console.error(`Error in the track event ${eventName}. trackers : ${this.trackers.map(t => t.friendlyName).join(\",\")}`, error);\r\n throw error;\r\n }\r\n }\r\n /**\r\n * Set user profile\r\n * @param userId\r\n * @param params\r\n */\r\n setUserId(userId, params) {\r\n for (const tracker of this.trackers) {\r\n if (!tracker.enable) {\r\n console.debug(`The ${tracker.friendlyName} is disabled`);\r\n continue;\r\n }\r\n let userParams = this._resolveParams(tracker, params || {});\r\n if (userParams) {\r\n tracker.setUserId(userId, userParams);\r\n }\r\n }\r\n }\r\n setUserProperties(params) {\r\n for (const tracker of this.trackers) {\r\n if (!tracker.enable) {\r\n console.debug(`The ${tracker.friendlyName} is disabled`);\r\n continue;\r\n }\r\n let userParams = this._resolveParams(tracker, params || {});\r\n if (userParams) {\r\n tracker.setUserProperties(userParams);\r\n }\r\n }\r\n }\r\n clearUserId() {\r\n for (const tracker of this.trackers) {\r\n if (!tracker.enable) {\r\n continue;\r\n }\r\n tracker.clearUserId();\r\n }\r\n }\r\n /**\r\n * Resolve the params of the event.\r\n * @param tracker\r\n * @param params\r\n * @returns\r\n */\r\n _resolveParams(tracker, params) {\r\n let result = {};\r\n for (const key in params) {\r\n let trackerParams = tracker.params;\r\n if (Object.prototype.hasOwnProperty.call(trackerParams, key)) {\r\n if (params[key] != null || params[key] != undefined) {\r\n if (typeof params[key] === 'object') {\r\n if (typeof params[key][Symbol.iterator] === 'function') {\r\n let paramsArray = [];\r\n for (const valueParam of params[key]) {\r\n let objParam = this._resolveParams(tracker, valueParam);\r\n paramsArray.push(objParam);\r\n }\r\n result[trackerParams[key]] = paramsArray;\r\n }\r\n else {\r\n result[trackerParams[key]] = this._resolveParams(tracker, params[key]);\r\n }\r\n }\r\n else {\r\n result[trackerParams[key]] = params[key];\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n}\r\n//# sourceMappingURL=tracker-service.js.map","export const AnalyticsConstants = Object.freeze({\r\n MethodAuth: 'Custom',\r\n DefaultParameterValue: 'NO_VALUE_EVENT_PARAMETER',\r\n Events: Object.freeze({\r\n DetailProduct: 'DetailProduct',\r\n FavoriteList: 'FavoriteList',\r\n AddCart: 'AddCart',\r\n RemoveCart: 'RemoveCart',\r\n Search: 'Search',\r\n Login: 'Login',\r\n SignUp: 'SignUp',\r\n Checkout: 'Checkout',\r\n Purcharse: 'Purcharse',\r\n Scroll: 'Scroll',\r\n ZoomImage: 'ZoomImage',\r\n RecoverPassword: 'RecoverPassword',\r\n ChangePassword: 'ChangePassword',\r\n PasswordSuccess: 'PasswordSuccess',\r\n ChatHelp: 'ChatHelp',\r\n CreateFavorite: 'CreateFavorite',\r\n AddShippingInfo: 'AddShippingInfo',\r\n ProductImage: 'ProductImage',\r\n FilterActivate: 'FilterActivate',\r\n FilterClear: 'FilterClear',\r\n FilterOption: 'FilterOption',\r\n ActivateAccount: 'ActivateAccount',\r\n GuestSession: 'GuestSession',\r\n Category: 'Category',\r\n AddPromoCode: 'AddPromoCode',\r\n RemovePromoCode: 'RemovePromoCode',\r\n ViewCart: 'ViewCart',\r\n IntentVerificationAccount: 'IntentVerificationAccount',\r\n SuccessVerificationAccount: 'SuccessVerificationAccount',\r\n FailedVerificationAccount: 'FailedVerificationAccount',\r\n OrderCompleted: 'OrderCompleted',\r\n main_tabbed_click: 'main_tabbed_click',\r\n add_payment_info: 'add_payment_info',\r\n banner_click: 'banner_click',\r\n related_product: 'related_product',\r\n screen_view: 'screen_view',\r\n deep_link_redirect: 'deep_link_redirect'\r\n }),\r\n Parameters: Object.freeze({\r\n Value: 'Value',\r\n Currency: 'Currency',\r\n Items: 'Items',\r\n SearchTerm: 'SearchTerm',\r\n Method: 'Method',\r\n Coupon: 'Coupon',\r\n TransactionId: 'TransactionId',\r\n Affiliation: 'Affiliation',\r\n Shipping: 'Shipping',\r\n Tax: 'Tax',\r\n ViewName: 'ViewName',\r\n ViewClass: 'ViewClass',\r\n ProductImageName: 'ProductImageName',\r\n ProductImageNumber: 'ProductImageNumber',\r\n CustomerUsername: 'CustomerUsername',\r\n Action: 'Action',\r\n ListName: 'ListName',\r\n PreviousListName: 'PreviousListName',\r\n ShippingTier: 'ShippingTier',\r\n ProductName: 'ProductName',\r\n ProductReference: 'ProductReference',\r\n ProductPrice: 'ProductPrice',\r\n ProductDiscount: 'ProductDiscount',\r\n ProductDiscountPrice: 'ProductDiscountPrice',\r\n ProductSource: 'ProductSource',\r\n ItemId: 'ItemId',\r\n ItemName: 'ItemName',\r\n Discount: 'Discount',\r\n ItemCategory: 'ItemCategory',\r\n ItemCategory2: 'ItemCategory2',\r\n Price: 'Price',\r\n Quantity: 'Quantity',\r\n CustomerIdentification: 'CustomerIdentification',\r\n CustomerEmail: 'CustomerEmail',\r\n CustomerName: 'CustomerName',\r\n CustomerPhone: 'CustomerPhone',\r\n CustomerAddress: 'CustomerAddress',\r\n CustomerAddressCityCode: 'CustomerAddressCityCode',\r\n CustomerAddressCityName: 'CustomerAddressCityName',\r\n CustomerAddressStateCode: 'CustomerAddressStateCode',\r\n CustomerAddressStateName: 'CustomerAddressStateName',\r\n CustomerAddressLatitude: 'CustomerAddressLatitude',\r\n CustomerAddressLongitude: 'CustomerAddressLongitude',\r\n customer_birthdate: 'customer_birthdate',\r\n customer_age: 'customer_age',\r\n MSGEmail: 'MSGEmail',\r\n MSGPush: 'MSGPush',\r\n MSGSms: 'MSGSms',\r\n MSGWhatsapp: 'MSGWhatsapp',\r\n clevertap_dnd_phone: \"clevertap_dnd_phone\",\r\n clevertap_dnd_email: \"clevertap_dnd_email\",\r\n CategoryName: 'CategoryName',\r\n PageNumber: 'PageNumber',\r\n PageSize: 'PageSize',\r\n PageCount: 'PageCount',\r\n EmptyCart: 'EmptyCart',\r\n OrderId: 'OrderId',\r\n CustomerBranchOfficeCode: 'CustomerBranchOfficeCode',\r\n CustomerBranchOfficeDescription: 'CustomerBranchOfficeDescription',\r\n CustomerCluster: 'CustomerCluster',\r\n UserType: 'UserType',\r\n payment_type: 'payment_type',\r\n ecommerce_status: 'ecommerce_status',\r\n department: 'department',\r\n classification: 'classification',\r\n created_at: 'created_at',\r\n type: 'type',\r\n name: 'name',\r\n item: 'item',\r\n bannerProduct: 'bannerProduct',\r\n bannerDescription: 'bannerDescription',\r\n bannerCategory: 'bannerCategory',\r\n categoryId: 'categoryId',\r\n departmentName: 'departmentName',\r\n departmentId: 'departmentId',\r\n bannerByProduct: 'bannerByProduct',\r\n bannerByCategory: 'bannerByCategory',\r\n bannerId: 'bannerId',\r\n bannerType: 'bannerType',\r\n related_product_type: 'related_product_type',\r\n clevertap_identity: 'clevertap_identity',\r\n related_product_product_source: 'related_product_product_source',\r\n firebase_screen: 'firebase_screen',\r\n manufacture_name: 'manufacture_name',\r\n redirect_to_url: 'redirect_to_url'\r\n })\r\n});\r\n//# sourceMappingURL=AnalyticsConstants.js.map","import { AnalyticsConstants } from \"../domain/AnalyticsConstants\";\r\nexport class BannerParametersResolve {\r\n constructor() {\r\n this.eventName = AnalyticsConstants.Events.banner_click;\r\n }\r\n resolve(tracker, params) {\r\n // product\r\n const keyBannerProduct = tracker.params[AnalyticsConstants.Parameters.bannerProduct];\r\n if (params.hasOwnProperty(keyBannerProduct)) {\r\n const bannerProduct = params[keyBannerProduct];\r\n for (const key in bannerProduct) {\r\n if (Object.prototype.hasOwnProperty.call(bannerProduct, key)) {\r\n if (key === tracker.params[AnalyticsConstants.Parameters.manufacture_name]) {\r\n params[`${key}`] = bannerProduct[key];\r\n }\r\n else {\r\n params[`${keyBannerProduct}${key}`] = bannerProduct[key];\r\n }\r\n }\r\n }\r\n delete params[keyBannerProduct];\r\n }\r\n // category\r\n const keyBannerCategory = tracker.params[AnalyticsConstants.Parameters.bannerCategory];\r\n if (params.hasOwnProperty(keyBannerCategory)) {\r\n const bannerCategory = params[keyBannerCategory];\r\n for (const key in bannerCategory) {\r\n if (Object.prototype.hasOwnProperty.call(bannerCategory, key)) {\r\n params[`${key}`] = bannerCategory[key];\r\n }\r\n }\r\n delete params[keyBannerCategory];\r\n }\r\n return params;\r\n }\r\n}\r\n//# sourceMappingURL=banner-parameters-resolve.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n};\r\nimport firebase from \"firebase/app\";\r\nimport 'firebase/analytics';\r\nexport class firebaseApp {\r\n constructor() {\r\n }\r\n static initializeApp(options) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n if (options) {\r\n this.app = firebase.initializeApp(options);\r\n }\r\n else {\r\n try {\r\n let reponse = yield fetch(\"/resources/configuration/firebaseApp.config.json\");\r\n let configJSON = yield reponse.json();\r\n this.app = firebase.initializeApp(configJSON);\r\n }\r\n catch (error) {\r\n console.error(\"Error Initialize firebase config JSON\", error);\r\n throw error;\r\n }\r\n }\r\n });\r\n }\r\n static getApp() {\r\n if (!this.app) {\r\n throw new Error(\"firebase app is not initialized.\");\r\n }\r\n return this.app;\r\n }\r\n}\r\n//# sourceMappingURL=firebaseApp.js.map","import 'firebase/analytics';\r\nimport { AnalyticsConstants } from \"../../../domain/AnalyticsConstants\";\r\nimport { BannerParametersResolve } from \"../../../parameters-resolve/banner-parameters-resolve\";\r\nimport { firebaseApp } from \"../../../singleton/firebaseApp\";\r\n/**\r\n * Google tracker for analytics events.\r\n * @summary\r\n * Configure firebases analytics before run this.\r\n */\r\nexport class GoogleTracker {\r\n /**\r\n *\r\n */\r\n constructor() {\r\n this.enable = true;\r\n this.resolveParams = [\r\n new BannerParametersResolve()\r\n ];\r\n this.friendlyName = \"Google Tracker\";\r\n this.events = {\r\n DetailProduct: 'view_item',\r\n FavoriteList: 'add_to_wishlist',\r\n AddCart: 'add_to_cart',\r\n RemoveCart: 'remove_from_cart',\r\n Search: 'search',\r\n Login: 'login',\r\n SignUp: 'sign_up',\r\n Checkout: 'begin_checkout',\r\n Purcharse: 'purchase',\r\n Scroll: 'scroll',\r\n ZoomImage: 'zoom_image',\r\n RecoverPassword: 'recover_password',\r\n ChangePassword: 'change_password',\r\n PasswordSuccess: 'password_success',\r\n ChatHelp: 'chat_help',\r\n CreateFavorite: 'create_favorites',\r\n AddShippingInfo: 'add_shipping_info',\r\n ProductImage: 'product_image',\r\n FilterActivate: 'filter_activate',\r\n FilterClear: 'filter_clear',\r\n FilterOption: 'filter_option',\r\n ActivateAccount: 'activate_account',\r\n GuestSession: 'guest_session',\r\n main_tabbed_click: 'main_tabbed_click',\r\n Category: 'view_category',\r\n [AnalyticsConstants.Events.banner_click]: 'banner_click',\r\n [AnalyticsConstants.Events.related_product]: 'related_product',\r\n [AnalyticsConstants.Events.screen_view]: 'screen_view',\r\n [AnalyticsConstants.Events.deep_link_redirect]: 'deep_link_redirect'\r\n };\r\n this.params = {\r\n Value: 'value',\r\n Currency: 'currency',\r\n Items: 'items',\r\n SearchTerm: 'search_term',\r\n Method: 'method',\r\n Coupon: 'coupon',\r\n TransactionId: 'transaction_id',\r\n Affiliation: 'affiliation',\r\n Shipping: 'shipping',\r\n Tax: 'tax',\r\n ViewName: 'view_name',\r\n ViewClass: 'view_class',\r\n ProductImageName: 'product_image_name',\r\n ProductImageNumber: 'product_image_number',\r\n CustomerUsername: 'customer_user_name',\r\n Action: 'action',\r\n ListName: 'list_name',\r\n PreviousListName: 'previous_list_name',\r\n ShippingTier: 'shipping_tier',\r\n ProductName: 'product_name',\r\n ProductReference: 'product_reference',\r\n ProductPrice: 'product_price',\r\n ProductDiscount: 'product_discount',\r\n ProductDiscountPrice: 'product_discount_price',\r\n ProductSource: 'product_source',\r\n ItemId: 'item_id',\r\n ItemName: 'item_name',\r\n Discount: 'discount',\r\n ItemCategory: 'item_category',\r\n ItemCategory2: 'item_category2',\r\n Price: 'price',\r\n Quantity: 'quantity',\r\n CustomerIdentification: 'customer_identification',\r\n CustomerEmail: 'customer_email',\r\n CustomerName: 'customer_name',\r\n CustomerPhone: 'customer_phone',\r\n CustomerAddress: 'customer_address',\r\n CustomerAddressCityCode: 'customer_city_code',\r\n CustomerAddressCityName: 'customer_city_name',\r\n CustomerAddressStateCode: 'customer_state_code',\r\n CustomerAddressStateName: 'customer_state_name',\r\n CustomerAddressLatitude: 'customer_address_latitude',\r\n CustomerAddressLongitude: 'customer_address_longitude',\r\n [AnalyticsConstants.Parameters.customer_birthdate]: 'customer_birthdate',\r\n [AnalyticsConstants.Parameters.customer_age]: 'age',\r\n PageNumber: 'index',\r\n PageSize: 'page_size',\r\n PageCount: 'page_count',\r\n department: 'department',\r\n classification: 'classification',\r\n [AnalyticsConstants.Parameters.CategoryName]: 'category',\r\n [AnalyticsConstants.Parameters.type]: 'type',\r\n [AnalyticsConstants.Parameters.name]: 'name',\r\n [AnalyticsConstants.Parameters.bannerDescription]: \"banner_description\",\r\n [AnalyticsConstants.Parameters.bannerProduct]: 'banner_product_',\r\n [AnalyticsConstants.Parameters.bannerCategory]: 'banner_category_',\r\n [AnalyticsConstants.Parameters.bannerByCategory]: 'by_category',\r\n [AnalyticsConstants.Parameters.bannerByProduct]: 'by_product',\r\n [AnalyticsConstants.Parameters.categoryId]: 'category_id',\r\n [AnalyticsConstants.Parameters.departmentId]: 'deparment_id',\r\n [AnalyticsConstants.Parameters.departmentName]: 'deparment_name',\r\n [AnalyticsConstants.Parameters.bannerId]: 'banner_id',\r\n [AnalyticsConstants.Parameters.bannerType]: 'banner_type',\r\n [AnalyticsConstants.Parameters.related_product_type]: 'type',\r\n [AnalyticsConstants.Parameters.firebase_screen]: 'firebase_screen',\r\n [AnalyticsConstants.Parameters.manufacture_name]: 'manufacturer',\r\n [AnalyticsConstants.Parameters.redirect_to_url]: \"url\"\r\n };\r\n this._firebaseAnalytics = firebaseApp.getApp().analytics();\r\n }\r\n logEvent(eventName, params) {\r\n console.debug(`${this.friendlyName}`, eventName, params);\r\n this._firebaseAnalytics.logEvent(eventName, params);\r\n }\r\n setUserId(userId, params) {\r\n console.debug(`${this.friendlyName}: setUserId`, params);\r\n this._firebaseAnalytics.setUserId(userId);\r\n if (params) {\r\n this._firebaseAnalytics.setUserProperties(params);\r\n }\r\n }\r\n clearUserId() {\r\n console.debug(`${this.friendlyName}: clear user information`);\r\n }\r\n setUserProperties(params) { }\r\n}\r\n//# sourceMappingURL=google-tracker.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n};\r\nconst clevertap = require(\"clevertap-web-sdk/clevertap.js\");\r\nexport class clevertapApp {\r\n constructor() {\r\n }\r\n static initializeApp(options) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n if (options) {\r\n this.enable = options.enable;\r\n }\r\n else {\r\n try {\r\n let reponse = yield fetch(\"/resources/configuration/clevertapApp.config.json\");\r\n if (reponse.ok) {\r\n let configJSON = (yield reponse.json());\r\n this.enable = configJSON.enable;\r\n options = configJSON;\r\n }\r\n }\r\n catch (error) {\r\n console.error(\"Error Initialize clevertap config JSON\", error);\r\n throw error;\r\n }\r\n }\r\n if (options && this.enable) {\r\n clevertap.init(options.accountId, options.region, options.targetDomain);\r\n this.clevertap = clevertap;\r\n clevertap.privacy.push({ optOut: false }); // Set the flag to true, if the user of the device opts out of sharing their data\r\n clevertap.privacy.push({ useIP: true }); // Set the flag to true, if the user agrees to share their IP data\r\n // Ref : https://github.com/CleverTap/clevertap-web-sdk#debugging\r\n // Here Log Levels is an integer that can be any of the folowing: \r\n // 0: disable all logs\r\n // 1: display only errors\r\n // 2: display errors and info\r\n // 3: display all logs\r\n clevertap.setLogLevel(1);\r\n }\r\n else {\r\n console.debug(`The clevertap analytics is disabled`);\r\n }\r\n });\r\n }\r\n static getClevertap() {\r\n if (!this.clevertap) {\r\n throw new Error(\"clevertap app is not initialized, please initialize app.\");\r\n }\r\n return this.clevertap;\r\n }\r\n}\r\nclevertapApp.enable = false;\r\n//# sourceMappingURL=clevertapApp.js.map","import { AnalyticsConstants } from \"../../../domain/AnalyticsConstants\";\r\nexport class RelatedProductParametersResolve {\r\n constructor() {\r\n this.eventName = AnalyticsConstants.Events.related_product;\r\n }\r\n resolve(tracker, params) {\r\n const itemsKey = tracker.params[AnalyticsConstants.Parameters.Items];\r\n for (const productSourceParam of params[itemsKey]) {\r\n const productSourceKey = tracker.params[AnalyticsConstants.Parameters.related_product_product_source];\r\n if (productSourceParam.hasOwnProperty(productSourceKey)) {\r\n const relatedProductSource = productSourceParam[productSourceKey];\r\n for (const key in relatedProductSource) {\r\n if (Object.prototype.hasOwnProperty.call(relatedProductSource, key)) {\r\n productSourceParam[`${productSourceKey} ${key}`] = relatedProductSource[key];\r\n }\r\n }\r\n delete productSourceParam[productSourceKey];\r\n }\r\n }\r\n return params;\r\n }\r\n}\r\n//# sourceMappingURL=related-product-parameters-resolve.js.map","import { AnalyticsConstants } from \"../../../domain/AnalyticsConstants\";\r\nimport { clevertapApp } from \"./clevertapApp\";\r\nimport { BannerParametersResolve } from \"../../../parameters-resolve/banner-parameters-resolve\";\r\nimport { RelatedProductParametersResolve } from \"./related-product-parameters-resolve\";\r\nexport class ClevertapTracker {\r\n /**\r\n *\r\n */\r\n constructor() {\r\n this.friendlyName = \"CleverTap Tracker\";\r\n this.params = {\r\n Value: 'Amount',\r\n Currency: 'Currency',\r\n Items: 'Items',\r\n SearchTerm: 'Search Term',\r\n Method: 'Method',\r\n Coupon: 'Coupon',\r\n TransactionId: 'Charged ID',\r\n Shipping: 'Shipping',\r\n Tax: 'Tax',\r\n ViewName: 'View Name',\r\n ViewClass: 'View Class',\r\n ProductImageName: 'Image Name',\r\n ProductImageNumber: 'Image Number',\r\n Action: 'Action',\r\n ListName: 'List Name',\r\n PreviousListName: 'Previous List Name',\r\n ShippingTier: 'Shipping Tier',\r\n ProductName: 'Name',\r\n ProductReference: 'Reference',\r\n ProductPrice: 'Price',\r\n ProductDiscount: 'Discount',\r\n ProductDiscountPrice: 'Discount Price',\r\n ProductSource: 'Product Source',\r\n ItemId: 'Id',\r\n ItemName: 'Name',\r\n Discount: 'Discount',\r\n ItemCategory: 'Category',\r\n ItemCategory2: 'SubCategory',\r\n Price: 'Price',\r\n Quantity: 'Quantity',\r\n CustomerIdentification: 'Identification',\r\n CustomerUsername: 'Username',\r\n CustomerEmail: 'Email',\r\n CustomerName: 'Name',\r\n CustomerPhone: 'Phone',\r\n CustomerAddress: 'Address',\r\n CustomerAddressCityCode: 'City Code',\r\n CustomerAddressCityName: 'City Name',\r\n CustomerAddressStateCode: 'State Code',\r\n CustomerAddressStateName: 'State Name',\r\n CustomerAddressLatitude: 'Latitude',\r\n CustomerAddressLongitude: 'Longitude',\r\n MSGEmail: 'MSG-email',\r\n MSGPush: 'MSG-push',\r\n MSGSms: 'MSG-sms',\r\n MSGWhatsapp: 'MSG-whatsapp',\r\n [AnalyticsConstants.Parameters.clevertap_dnd_email]: \"MSG-dndEmail\",\r\n [AnalyticsConstants.Parameters.clevertap_dnd_phone]: \"MSG-dndPhone\",\r\n CategoryName: \"Category\",\r\n PageNumber: 'Index',\r\n PageSize: 'Page Size',\r\n PageCount: 'Page Count',\r\n EmptyCart: 'Empty Cart',\r\n OrderId: 'Order Id',\r\n CustomerBranchOfficeCode: 'Store Id',\r\n CustomerBranchOfficeDescription: 'Store Name',\r\n CustomerCluster: 'Cluster Is',\r\n UserType: 'User Type',\r\n payment_type: 'Payment Type',\r\n ecommerce_status: 'ECommerceStatus',\r\n department: 'Department',\r\n classification: 'Classification',\r\n created_at: 'Created At',\r\n [AnalyticsConstants.Parameters.type]: 'Type',\r\n [AnalyticsConstants.Parameters.name]: 'Name',\r\n [AnalyticsConstants.Parameters.bannerDescription]: 'Banner Description',\r\n [AnalyticsConstants.Parameters.bannerByProduct]: 'By Product',\r\n [AnalyticsConstants.Parameters.bannerByCategory]: 'By Category',\r\n [AnalyticsConstants.Parameters.bannerProduct]: 'Product ',\r\n [AnalyticsConstants.Parameters.bannerCategory]: 'Category ',\r\n [AnalyticsConstants.Parameters.bannerId]: 'Banner Id',\r\n [AnalyticsConstants.Parameters.categoryId]: 'Category Id',\r\n [AnalyticsConstants.Parameters.departmentId]: 'Department Id',\r\n [AnalyticsConstants.Parameters.departmentName]: 'Department Name',\r\n [AnalyticsConstants.Parameters.bannerType]: \"Banner Type\",\r\n [AnalyticsConstants.Parameters.related_product_type]: 'Type',\r\n [AnalyticsConstants.Parameters.related_product_product_source]: 'Related Product Source',\r\n [AnalyticsConstants.Parameters.clevertap_identity]: 'Identity',\r\n [AnalyticsConstants.Parameters.manufacture_name]: 'Manufacturer',\r\n [AnalyticsConstants.Parameters.redirect_to_url]: \"Url\"\r\n };\r\n this.events = {\r\n DetailProduct: 'Product Viewed',\r\n FavoriteList: 'Add To Wishlist',\r\n AddCart: 'Add To Cart',\r\n RemoveCart: 'Remove From Cart',\r\n Search: 'Searched',\r\n Login: 'Login',\r\n SignUp: 'Sign Up',\r\n Checkout: 'Begin Checkout',\r\n Purcharse: 'Charged',\r\n Scroll: 'Scroll',\r\n ZoomImage: 'Zoom Image',\r\n RecoverPassword: 'Recover Password',\r\n ChangePassword: 'Change Password',\r\n PasswordSuccess: 'Password Success',\r\n ChatHelp: 'Chat Help',\r\n CreateFavorite: 'Create Favorites',\r\n AddShippingInfo: 'Add Shipping Info',\r\n ProductImage: 'Product Image',\r\n FilterActivate: 'Filter Activate',\r\n FilterClear: 'Filter Clear',\r\n FilterOption: 'Filter Option',\r\n ActivateAccount: 'Activate Account',\r\n GuestSession: 'Guest Session',\r\n Category: \"Category Viewed\",\r\n AddPromoCode: 'Add Promo Code',\r\n RemovePromoCode: 'Remove PromoCode',\r\n ViewCart: 'View Shopping Cart',\r\n FailedVerificationAccount: 'Failed Verification Account',\r\n IntentVerificationAccount: 'Intent Verification Account',\r\n SuccessVerificationAccount: 'Success Verification Account',\r\n OrderCompleted: 'Order Completed',\r\n main_tabbed_click: 'Click on Main Page',\r\n add_payment_info: 'Add Payment Info',\r\n [AnalyticsConstants.Events.banner_click]: 'Banner Click',\r\n [AnalyticsConstants.Events.related_product]: 'Related Product',\r\n [AnalyticsConstants.Events.deep_link_redirect]: 'DeepLink Redirect'\r\n };\r\n this.resolveParams = [\r\n new BannerParametersResolve(),\r\n new RelatedProductParametersResolve()\r\n ];\r\n this.enable = clevertapApp.enable;\r\n }\r\n logEvent(eventName, params) {\r\n console.debug(`${this.friendlyName}`, eventName, params);\r\n const keyItems = this.params[AnalyticsConstants.Parameters.Items];\r\n if (params\r\n && eventName !== this.events[AnalyticsConstants.Events.Purcharse]\r\n && params.hasOwnProperty(keyItems)) {\r\n if (Array.isArray(params[keyItems])) {\r\n for (const item of params[keyItems]) {\r\n delete params[keyItems];\r\n let paramsItem = Object.assign(Object.assign({}, item), params);\r\n console.log(`${this.friendlyName}`, eventName, paramsItem);\r\n clevertapApp.getClevertap().event.push(eventName, paramsItem);\r\n }\r\n }\r\n }\r\n else {\r\n clevertapApp.getClevertap().event.push(eventName, params);\r\n }\r\n }\r\n setUserId(userId, params) {\r\n console.debug(`${this.friendlyName}: setUserId`, params);\r\n clevertapApp.getClevertap().onUserLogin.push({\r\n \"Site\": Object.assign({ [this.params[AnalyticsConstants.Parameters.clevertap_identity]]: userId }, params)\r\n });\r\n }\r\n clearUserId() {\r\n console.debug(`${this.friendlyName}: clear user information`);\r\n clevertapApp.getClevertap().clear();\r\n }\r\n setUserProperties(params) {\r\n console.debug(`${this.friendlyName}: setUserProperties`, params);\r\n clevertapApp.getClevertap().profile.push({\r\n \"Site\": Object.assign({}, params)\r\n });\r\n }\r\n}\r\n//# sourceMappingURL=clevertap-tracker.js.map","import { GoogleTracker } from \"../services/trackers/google/google-tracker\";\r\nimport { ClevertapTracker } from \"../services/trackers/clevertap/clevertap-tracker\";\r\nexport const trakerList = () => [\r\n new GoogleTracker(),\r\n new ClevertapTracker(),\r\n];\r\n//# sourceMappingURL=trackerList.js.map","import { AlertDismissReason } from \"../../../domain/alert-types\";\r\nimport Swl from \"sweetalert2\";\r\nexport class SweetalertHelper {\r\n static computeDismissReason(result) {\r\n let dismissReason = AlertDismissReason.close;\r\n switch (result.dismiss) {\r\n case Swl.DismissReason.backdrop:\r\n dismissReason = AlertDismissReason.backdrop;\r\n break;\r\n case Swl.DismissReason.cancel:\r\n dismissReason = AlertDismissReason.cancel;\r\n break;\r\n case Swl.DismissReason.close:\r\n dismissReason = AlertDismissReason.close;\r\n break;\r\n case Swl.DismissReason.esc:\r\n dismissReason = AlertDismissReason.esc;\r\n break;\r\n case Swl.DismissReason.timer:\r\n dismissReason = AlertDismissReason.timer;\r\n break;\r\n }\r\n return dismissReason;\r\n }\r\n}\r\n//# sourceMappingURL=helper.js.map","import Swl from 'sweetalert2';\r\nimport { SweetalertHelper } from './helper';\r\nexport class SweetalertAlertPlugin {\r\n parametersEngineAsync(options) {\r\n return new Promise((resolve, reject) => {\r\n let swlOption = {\r\n title: options.title,\r\n text: options.description,\r\n icon: options.icon,\r\n customClass: options.customClass,\r\n showCancelButton: options.showCancelButton,\r\n cancelButtonText: options.cancelButtonText,\r\n showConfirmButton: options.showConfirmButton,\r\n confirmButtonColor: options.confirmButtonColor,\r\n confirmButtonText: options.confirmButtonText,\r\n showDenyButton: options.showDenyButton,\r\n denyButtonText: options.denyButtonText,\r\n denyButtonColor: options.denyButtonColor,\r\n showCloseButton: options.showCloseButton,\r\n timer: options.timer,\r\n timerProgressBar: options.timerProgressBar,\r\n showClass: options.showClass,\r\n hideClass: options.hideClass,\r\n position: options.position,\r\n reverseButtons: options.reverseButtons\r\n };\r\n if (options.pluginOption) {\r\n options.pluginOption = Object.assign(Object.assign({}, swlOption), options.pluginOption);\r\n }\r\n else {\r\n options.pluginOption = swlOption;\r\n }\r\n return resolve(options);\r\n });\r\n }\r\n fireAsync(options) {\r\n return Swl.fire(options.pluginOption);\r\n }\r\n resultEngineAsync(pluginResult) {\r\n return new Promise((resolve, reject) => {\r\n let result = pluginResult;\r\n return resolve({\r\n isConfirmed: result.isConfirmed,\r\n isDenied: result.isDenied,\r\n isDismissed: result.isDismissed,\r\n dismiss: SweetalertHelper.computeDismissReason(result),\r\n pluginResult: result\r\n });\r\n });\r\n }\r\n}\r\n//# sourceMappingURL=sweetalert-alert-plugin.js.map","import Swl from 'sweetalert2';\r\nimport { SweetalertHelper } from './helper';\r\nexport class SweetalertToastPlugin {\r\n constructor() {\r\n this._toastSwl = Swl.mixin({\r\n toast: true,\r\n position: 'top',\r\n showConfirmButton: false,\r\n timer: 2500,\r\n timerProgressBar: true,\r\n didOpen: (toast) => {\r\n toast.addEventListener('mouseenter', Swl.stopTimer);\r\n toast.addEventListener('mouseleave', Swl.resumeTimer);\r\n }\r\n });\r\n }\r\n parametersEngineAsync(options) {\r\n return new Promise((resolve, reject) => {\r\n let swlOption = {\r\n title: options.title,\r\n icon: options.icon,\r\n customClass: options.customClass,\r\n };\r\n if (options.pluginOption) {\r\n options.pluginOption = Object.assign(Object.assign({}, swlOption), options.pluginOption);\r\n }\r\n else {\r\n options.pluginOption = swlOption;\r\n }\r\n return resolve(options);\r\n });\r\n }\r\n fireAsync(options) {\r\n return this._toastSwl.fire(options.pluginOption);\r\n }\r\n resultEngineAsync(pluginResult) {\r\n return new Promise((resolve, reject) => {\r\n let result = pluginResult;\r\n return resolve({\r\n isConfirmed: result.isConfirmed,\r\n isDenied: result.isDenied,\r\n isDismissed: result.isDismissed,\r\n dismiss: SweetalertHelper.computeDismissReason(result),\r\n pluginResult: result\r\n });\r\n });\r\n }\r\n}\r\n//# sourceMappingURL=sweetalert-toast-plugin.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n};\r\nexport class AlertService {\r\n constructor(alertPlugin, toastPlugin) {\r\n this._alertPlugin = alertPlugin;\r\n this._toastPlugin = toastPlugin;\r\n }\r\n displayToastAsync(options) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n let alertOptions = yield this._toastPlugin.parametersEngineAsync(options);\r\n let result = yield this._toastPlugin.fireAsync(alertOptions);\r\n return yield this._toastPlugin.resultEngineAsync(result);\r\n });\r\n }\r\n displayAlertAsync(options) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n let alertOptions = yield this._alertPlugin.parametersEngineAsync(options);\r\n let result = yield this._alertPlugin.fireAsync(alertOptions);\r\n return yield this._alertPlugin.resultEngineAsync(result);\r\n });\r\n }\r\n}\r\n//# sourceMappingURL=alerts-service.js.map","class SiteEnum {\n\n static get Store() {\n return 'STORE';\n }\n\n static get Checkout() {\n return 'CHECKOUT';\n }\n\n static get Account() {\n return 'ACCOUNT';\n }\n\n static get Index() {\n return 'INDEX';\n }\n\n static get Security() {\n return 'SECURITY'\n }\n static get SecurityWithoutLoginB2B() {\n return 'SECURITYWITHOUTLOGINB2B'\n }\n static get TwoFARequiredChangePassword() {\n return 'TWOFACREQUIREDCHANGEPASSWORD'\n }\n static get TwoFARequiredGeneriUser() {\n return 'TWOFACREQUIREDGENERICUSER'\n }\n static get TwoFARequired() {\n return 'TWOFACREQUIRED'\n }\n static get Marking() {\n return 'MARKING'\n }\n static get MarkingByProduct() {\n return 'MARKINGBYPRODUCT'\n }\n static get TwoFARequiredAdditionalInformation() {\n return 'TWOFACREQUIREDADDITIONALINFORMATION'\n }\n \n static get ChangePassword(){\n return 'CHANGEPASSWORD'\n }\n}\n\nexport default SiteEnum;\n\nexport const appConstants = Object.freeze({\n currency: \"COP\",\n codePhoneNumber: \"+57\",\n mql: 1024\n})\n","\n/**\n * Implementation for services.\n * all the methods services retunrs ResponseBase\n * */\nexport class ServiceBase {\n constructor() {\n if (this.constructor == ServiceBase) {\n throw new Error(\"Object of Abstract Class cannot be created\");\n }\n }\n}","import { map, Observable } from 'rxjs';\nimport UrlHelper from '../../../helpers/url-helper.js';\nimport AjaxProxy from '../../../proxies/ajax-proxy.js';\nimport { ServiceBase } from '../../service/service-base'\n\nexport default class ShoppingCartService extends ServiceBase {\n\n _endpoints = {\n getUimessageView: \"/Store/ShoppingCart?handler=UiMessageView\",\n postValidateCustomerBlocked: \"/Store/ShoppingCart?handler=ValidateCustomerBlocked\"\n }\n\n constructor() {\n super()\n }\n\n /**\n * \n * @param {number} quantity\n * @param {string} productId\n * @param {boolean} overrideQuantity\n * @returns\n */\n addItemAsync(quantity, productId, overrideQuantity) {\n const requestData = new FormData()\n requestData.append(\"quantity\", quantity);\n requestData.append(\"productId\", productId);\n requestData.append(\"overrideQuantity\", overrideQuantity);\n return AjaxProxy.postFetch(UrlHelper.addProductToCartUrl, { body: requestData });\n }\n\n /**\n * \n * @param {[]} items\n */\n addItemsAsync(items) {\n const requestData = new FormData()\n for (var i = 0; i < items.length; i++) {\n for (var key in items[i]) {\n if (key === 'Product') {\n for (var productKey in items[i][key]) {\n requestData.append(`products[${i}][${key}][${productKey}]`, items[i][key][productKey])\n }\n }\n else {\n requestData.append(`products[${i}][${key}]`, items[i][key])\n }\n }\n }\n return AjaxProxy.postFetch(UrlHelper.addProductsToCartUrl, { body: requestData });\n }\n\n getItem(productId, callback) {\n let url = UrlHelper.getShoppingCartItemUrl;\n let requestData = { productId: productId };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n getItemFetch(productId) {\n let requestData = new FormData()\n requestData.append(\"productId\", productId)\n let request = {\n body: requestData\n };\n\n return AjaxProxy.postFetch(UrlHelper.getShoppingCartItemUrl, request);\n }\n\n getViewAsync(productId) {\n return AjaxProxy.getFetch(UrlHelper.getShoppingCartViewUrl, {});\n }\n\n getViewWithCacheAsync() {\n return AjaxProxy.getFetch(`${UrlHelper.getShoppingCartViewUrl}?loadFromCache=true`, {})\n }\n\n addProductQuantity(productId, quantity, callback) {\n let url = UrlHelper.addProductQuantityUrl;\n let requestData = { productId: productId, quantity: quantity };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n addProductQuantityFetch(productId, quantity, internalId = null, isKit = false) {\n\n const requestData = new FormData()\n requestData.append(\"productId\", productId)\n requestData.append(\"quantity\", quantity)\n if (internalId) {\n requestData.append(\"internalId\", internalId);\n }\n requestData.append(\"isKit\", isKit);\n\n let request = {\n body: requestData,\n };\n\n return AjaxProxy.postFetch(UrlHelper.addProductQuantityUrl, request);\n }\n\n increaseProductQuantity(productId, callback) {\n let requestData = { productId: productId };\n let request = {\n url: UrlHelper.increaseProductQuantityUrl,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n /**\n * \n * @param productId {string}\n * @param {boolean} [isKit=false] \n * @param {string} [internalId=null] \n * */\n increaseProductQuantityFetch(productId, internalId = null, isKit = false) {\n\n const requestData = new FormData()\n requestData.append(\"productId\", productId);\n if (internalId) {\n requestData.append(\"internalId\", internalId);\n }\n requestData.append(\"isKit\", isKit);\n\n let request = {\n body: requestData,\n };\n return AjaxProxy.postFetch(UrlHelper.increaseProductQuantityUrl, request);\n }\n\n decreaseProductQuantity(productId, callback) {\n let url = UrlHelper.decreaseProductQuantityUrl;\n let requestData = { productId: productId };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n decreaseProductQuantityFetch(productId, internalId = null, isKit = false) {\n\n const requestData = new FormData()\n requestData.append(\"productId\", productId)\n if (internalId) {\n requestData.append(\"internalId\", internalId);\n }\n requestData.append(\"isKit\", isKit);\n\n let request = {\n body: requestData\n };\n return AjaxProxy.postFetch(UrlHelper.decreaseProductQuantityUrl, request);\n }\n\n empty(callback) {\n let url = UrlHelper.emptyShoppingCart;\n let request = {\n url: url,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n removeProductQuantity(productId, callback) {\n let url = UrlHelper.removeProductUrl;\n let requestData = { productId: productId };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n removeProductQuantityFetch(productId) {\n const formData = new FormData()\n formData.append(\"productId\", productId);\n\n let request = {\n body: formData\n };\n\n return AjaxProxy.postFetch(UrlHelper.removeProductUrl, request);\n }\n\n validatePromotionalCode(promoCode, callback) {\n let url = UrlHelper.validatePromotionalCodeUrl;\n let requestData = { promoCode: promoCode };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n \n /**\n * \n * @param {FormData} markingFormData\n */\n markingSave(markingFormData) {\n return AjaxProxy.postFetch(UrlHelper.postMarkingSave, {body: markingFormData})\n }\n\n markingSaveConfirm(marking, oldMarking, isEdit, callback) {\n let url = UrlHelper.markingSaveConfirmUrl;\n let requestData = { marking: marking, oldMarking: oldMarking, isEdit: isEdit };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n \n /**\n * \n * @param {FormData} formData\n */\n markingDelete(formData) {\n return AjaxProxy.postFetch(UrlHelper.postMarkingDelete, {body: formData})\n }\n\n /**\n * \n * @returns {Observable}\n * */\n getViewRx() {\n return AjaxProxy.postRxHtml({\n url: UrlHelper.getShoppingCartViewUrl\n }).pipe(\n map(ajaxResponse => ajaxResponse.response)\n );\n }\n\n getAsync() {\n let request = {\n };\n return AjaxProxy.getFetch(UrlHelper.getShoppingCart, request);\n }\n\n getDeliveryPriceAsync() {\n let request = {\n };\n return AjaxProxy.getFetch(UrlHelper.getDeliveryPrice, request);\n }\n\n replicateOrder(orderId) {\n const requestData = new FormData()\n requestData.append(\"orderId\", orderId)\n let request = {\n body: requestData\n };\n return AjaxProxy.postFetch(UrlHelper.replicateOrderUrl, request);\n }\n\n getUiMessageView() {\n return AjaxProxy.getFetch(this._endpoints.getUimessageView, {})\n }\n\n postValidateCustomerBlocked() {\n return AjaxProxy.postFetch(this._endpoints.postValidateCustomerBlocked, {})\n }\n}\n","import { browserCommunicator } from 'apollo-web'\n\n/**\n * */\nexport class BrowserCommunicatorService {\n \n constructor() {\n let sweetalertPlugin = new browserCommunicator.SweetalertAlertPlugin()\n let sweetalertToastPlugin = new browserCommunicator.SweetalertToastPlugin()\n this._alertService = new browserCommunicator.AlertService(sweetalertPlugin, sweetalertToastPlugin)\n\n this._commonAlertOption = {\n customClass: {\n popup: \"alert__popup--border-radius\",\n confirmButton: 'button button--primary',\n cancelButton: 'button button--secondary-reverse me-1',\n denyButton: \"button button--secondary-reverse me-1\"\n },\n showClass: {\n popup: 'animate__animated animate__headShake'\n },\n pluginOption: {\n buttonsStyling: false\n }\n }\n\n this._autoClosingTimer = 3000\n this._confirmButtonText = \"Aceptar\"\n this._denyButtonText = \"Cancelar\"\n }\n\n /**\n * \n * @param options {browserCommunicator.IAlertOption}\n * */\n displayAlert(options) {\n return this._alertService.displayAlert({\n ...options,\n ...this._commonAlertOption\n })\n }\n\n /**\n * \n * @param options {{title: string, description: string, autoclosing: boolean, html: boolean, timer: number | undefined | null}}\n * @returns {Promise}\n * */\n displaySuccessAlertAsync(options) {\n const html = {}\n if (options.html) {\n html.html = options.description\n options.description = undefined\n }\n\n const autoClosing = {}\n if (options.autoclosing) {\n autoClosing.timerProgressBar = true\n autoClosing.timer = options.timer ?? this._autoClosingTimer\n }\n\n return this._alertService.displayAlertAsync({\n icon: 'success',\n title: options.title,\n description: options.description,\n showConfirmButton: true,\n showCloseButton: true,\n confirmButtonText: this._confirmButtonText,\n ...this._commonAlertOption,\n pluginOption: {\n ...autoClosing,\n ...this._commonAlertOption.pluginOption,\n ...html\n }\n })\n }\n\n\n /**\n * \n * @param options {{title: string, description: string, html: boolean }}\n * @returns {Promise}\n * */\n displayPermanetSuccessAlertAsync(options) {\n const html = {}\n if (options.html) {\n html.html = options.description\n options.description = undefined\n }\n \n return this._alertService.displayAlertAsync({\n icon: 'success',\n title: options.title,\n description: options.description,\n showConfirmButton: false,\n showCloseButton: false,\n ...this._commonAlertOption,\n pluginOption: {\n ...this._commonAlertOption.pluginOption,\n ...html,\n allowOutsideClick: false,\n allowEscapeKey: false\n }\n })\n }\n\n /**\n * \n * @param options {{title: string, description: string, html: boolean}}\n * @returns {Promise}\n * */\n displayErrorAlert(options) {\n const html = {}\n if (options.html) {\n html.html = options.description\n options.description = undefined\n }\n\n return this._alertService.displayAlertAsync({\n icon: 'error',\n title: options.title,\n description: options.description,\n showConfirmButton: true,\n confirmButtonText: this._confirmButtonText,\n showCloseButton: true,\n ...this._commonAlertOption,\n showClass: {\n popup: \"animate__animated animate__wobble\",\n },\n pluginOption: {\n ...this._commonAlertOption.pluginOption,\n ...html\n }\n })\n }\n\n /**\n * \n * @param options {{title: string, description: string, autoclosing: boolean, html: boolean, timer: number | undefined | null}}\n * */\n displayWarningAlert(options) {\n const html = {}\n if (options.html) {\n html.html = options.description\n options.description = undefined\n }\n\n const autoClosing = {}\n if (options.autoclosing) {\n autoClosing.timerProgressBar = true\n autoClosing.timer = options.timer ?? this._autoClosingTimer\n }\n\n return this._alertService.displayAlertAsync({\n icon: 'warning',\n title: options.title,\n description: options.description,\n showConfirmButton: true,\n confirmButtonText: this._confirmButtonText,\n showCloseButton: true,\n ...this._commonAlertOption,\n pluginOption: {\n ...autoClosing,\n ...this._commonAlertOption.pluginOption,\n ...html\n }\n })\n }\n\n /**\n * \n * @param options {{title:string, description:string, confirmButtonText:string, denyButtonText:string, html: boolean}}\n * */\n displayQuestionAlert(options) {\n const html = {}\n if (options.html) {\n html.html = options.description\n options.description = undefined\n }\n return this._alertService.displayAlertAsync({\n icon: 'question',\n title: options.title,\n description: options.description,\n showConfirmButton: true,\n confirmButtonText: options.confirmButtonText ?? this._confirmButtonText,\n showDenyButton: true,\n denyButtonText: options.denyButtonText ?? this._denyButtonText,\n showCloseButton: true,\n reverseButtons: true,\n ...this._commonAlertOption,\n pluginOption: {\n ...this._commonAlertOption.pluginOption,\n ...html\n }\n })\n }\n\n /**\n * \n * @param options {{title:string, description:string, autoclosing: boolean, html: boolean, timer: number | undefined | null}}\n * */\n displayInfoAlert(options) {\n const html = {}\n if (options.html) {\n html.html = options.description\n options.description = undefined\n }\n\n const autoClosing = {}\n if (options.autoclosing) {\n autoClosing.timerProgressBar = true\n autoClosing.timer = options.timer ?? this._autoClosingTimer\n }\n\n return this._alertService.displayAlertAsync({\n icon: 'info',\n title: options.title,\n description: options.description,\n showConfirmButton: true,\n confirmButtonText: this._confirmButtonText,\n showCloseButton: true,\n ...this._commonAlertOption,\n pluginOption: {\n ...autoClosing,\n ...this._commonAlertOption.pluginOption,\n ...html\n },\n })\n }\n\n /**\n * \n * @param {{title: string}} options \n * @returns\n */\n displaySuccessToastAsync(options) {\n return this._alertService.displayToastAsync({\n icon: \"success\",\n title: options.title,\n pluginOption: {\n position: \"bottom-left\",\n timer: this._autoClosingTimer\n }\n })\n }\n\n /**\n * \n * @param {{title: string}} options \n * @returns\n */\n displayErrorToastAsync(options) {\n return this._alertService.displayToastAsync({\n icon: \"error\",\n title: options.title,\n pluginOption: {\n position: \"bottom-left\",\n timer: this._autoClosingTimer\n }\n })\n }\n}","import { Subject } from 'rxjs'\n\nexport class ShoppingCartLoadEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n loaded() {\n this._loading.next();\n }\n}\nconst event = new ShoppingCartLoadEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class AddedProductKitEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{productId: string, internalId: string, shoppingCartItemChanged: any, productKit: any} args\n */\n added(args) {\n this._subject.next({\n productBranchOfficeId: args.productId,\n internalId: args.internalId,\n shoppingCartItemChanged: args.shoppingCartItemChanged,\n productKit: args.productKit\n });\n }\n}\n\nconst event = new AddedProductKitEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class OrderReplicatedEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{shoppingCartItemChanged: any} args\n */\n orderReplicated(args) {\n this._subject.next({\n shoppingCartItemChanged: args.shoppingCartItemChanged\n });\n }\n}\n\nconst event = new OrderReplicatedEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class AddedProductFavoriteListEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{productId: string, internalId: string, shoppingCartItemChanged: any, productKit: any, refreshShoppingCart: boolean} args\n */\n added(args) {\n this._subject.next({\n productBranchOfficeId: args.productId,\n internalId: args.internalId,\n shoppingCartItemChanged: args.shoppingCartItemChanged,\n productKit: args.productKit,\n refreshShoppingCart: args.refreshShoppingCart\n });\n }\n}\n\nconst event = new AddedProductFavoriteListEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class UpdateProductPriceEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n /**\n * \n * @param {{productBranchOfficeId: string, shoppingCartResponse: {}}} args\n */\n update(args) {\n this._loading.next(args);\n }\n}\nconst event = new UpdateProductPriceEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class UpdateProductEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n /**\n * \n * @param {{productBranchOfficeId: string, shoppingCartResponse: {}, options:{ action: \"more\" | \"less\" | \"setQuantity\" , dispatchEvent: boolean}}} args\n */\n update(args) {\n this._loading.next(args);\n }\n}\nconst event = new UpdateProductEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class AddedProductCatalogEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{productId: string, shoppingCartItemChanged: any} args\n */\n added(args) {\n this._subject.next({\n productBranchOfficeId: args.productId,\n shoppingCartItemChanged: args.shoppingCartItemChanged\n });\n }\n}\n\nconst event = new AddedProductCatalogEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class MoreProductEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n /**\n * \n * @param {{productBranchOfficeId: string, shoppingCartResponse: {}}} args\n */\n more(args) {\n this._loading.next(args);\n }\n}\nconst event = new MoreProductEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class LessProductEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n /**\n * \n * @param {{productBranchOfficeId: string, shoppingCartResponse: {}}} args\n */\n less(args) {\n this._loading.next(args);\n }\n}\nconst event = new LessProductEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class RemoveProductEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n /**\n * \n * @param {{productBranchOfficeId: string, shoppingCartResponse: {}}} args\n */\n remove(args) {\n this._loading.next(args);\n }\n}\nconst event = new RemoveProductEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class SetQuantityProductEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n /**\n * \n * @param {{productBranchOfficeId: string, shoppingCartResponse: {}}} args\n */\n setQuantity(args) {\n this._loading.next(args);\n }\n}\nconst event = new SetQuantityProductEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class EmptyCartEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n /**\n * \n * @param {*} args\n */\n empty(args) {\n this._loading.next(args);\n }\n}\nconst event = new EmptyCartEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class AddedProductRelatedEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{productId: string, shoppingCartItemChanged: any} args\n */\n added(args) {\n this._subject.next({\n productBranchOfficeId: args.productId,\n shoppingCartItemChanged: args.shoppingCartItemChanged\n });\n }\n}\n\nconst event = new AddedProductRelatedEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class AddedProductDetailEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{productId: string, shoppingCartItemChanged: any} args\n */\n added(args) {\n this._subject.next({\n productBranchOfficeId: args.productId,\n shoppingCartItemChanged: args.shoppingCartItemChanged\n });\n }\n}\n\nconst event = new AddedProductDetailEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class AddedPredictiveSearchEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{productId: string, shoppingCartItemChanged: any} args\n */\n added(args) {\n this._subject.next({\n productBranchOfficeId: args.productId,\n shoppingCartItemChanged: args.shoppingCartItemChanged\n });\n }\n}\n\nconst event = new AddedPredictiveSearchEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class ToggleShoppingCartEvent {\n\n constructor() {\n this._loading = new Subject();\n this.$ = this._loading.asObservable();\n }\n\n toggle() {\n this._loading.next();\n }\n}\nconst event = new ToggleShoppingCartEvent();\nexport default event;","import { analytics } from \"apollo-web\";\nimport { appConstants } from \"../../../enums/site-enum.js\";\nimport ShoppingCartService from \"../services/shopping-cart-service.js\";\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service.js\";\nimport { HandlerBase } from '../../handler/handler-base'\nimport ProductHelper from \"../../../helpers/product-helper\"\nimport 'jquery'\nimport ShoppingCartLoadEvent from \"../events/shopping-cart-load-event.js\";\nimport AddedProductKitEvent from \"../../dynamic-kits/events/added-product-kit-event.js\"\nimport OrderReplicatedEvent from \"../../replicate-order/events/order-replicated-event.js\"\nimport AddedProductFavoriteListEvent from \"../../favorite-list/events/added-product-favorite-list-event\"\nimport UpdateProductPriceEvent from \"../events/update-product-prices-event.js\";\nimport UpdateProductEvent from \"../events/update-product-event.js\";\nimport AddedProductCatalogEvent from \"../../../store/events/added-product-catalog-event\"\nimport MoreProductEvent from \"../events/more-product-event\"\nimport LessProductEvent from \"../events/less-product-event\"\nimport RemoveProductEvent from \"../events/remove-product-event\"\nimport SetQuantityProductEvent from \"../events/set-quantity-product-event\"\nimport EmptyCartEvent from \"../events/empty-cart-event\"\nimport AddedProductRelatedEvent from \"../../related-product/events/added-product-related-event\"\nimport AddedProductDetailEvent from \"../../product-card/events/added-product-detail-event\"\nimport AddedPredictiveSearchEvent from \"../events/added-predictive-search-event\"\nimport ToggleShoppingCartEvent from \"../events/toggle-shopping-cart-event\";\nimport { filter } from \"rxjs\"\n\nexport default class ShoppingCartHandlers extends HandlerBase {\n\n get _isCartVisible() {\n return $('.cart__container').hasClass('is-visible')\n };\n\n get _shoppingCartContainer() {\n return $(\".cart__container\");\n }\n\n get _loadedEvent$() {\n return ShoppingCartLoadEvent.$;\n }\n\n constructor() {\n super()\n\n this._shoppingCartService = new ShoppingCartService();\n this._browserCommunicatorService = new BrowserCommunicatorService()\n }\n\n init() {\n \n AddedProductKitEvent.event$.subscribe(async (args) => {\n this.updateShoppingCartQuantity(args.shoppingCartItemChanged.TotalItems);\n })\n\n OrderReplicatedEvent.event$.subscribe(async _ => {\n await this.loadShoppingCart();\n this.bindShoppinCartControlHandlers();\n })\n\n AddedProductFavoriteListEvent.event$.subscribe(async (args) => {\n if (args.refreshShoppingCart) {\n await this.loadShoppingCart();\n this.bindShoppinCartControlHandlers();\n }\n else {\n this.updateShoppingCartQuantity(args.shoppingCartItemChanged.TotalItems);\n }\n })\n\n UpdateProductPriceEvent.$.subscribe(async (args) => {\n this.updateShoppingCartPricesFromProductId(args.productBranchOfficeId, args.shoppingCartResponse);\n })\n\n UpdateProductEvent.$.subscribe(async (args) => {\n this.updateShoppingCartPricesFromProductId(args.productBranchOfficeId, args.shoppingCartResponse);\n this.updateShoppingCartQuantityFromProductId(args.productBranchOfficeId, args.shoppingCartResponse)\n\n if (args.options && args.options.dispatchEvent) {\n this._dispatchShoppingCartEvent(args.options.action, args.productBranchOfficeId, args.shoppingCartResponse)\n }\n })\n\n AddedProductCatalogEvent.event$.subscribe(async (args) => {\n this.updateShoppingCartQuantity(args.shoppingCartItemChanged.TotalItems);\n })\n\n AddedProductRelatedEvent.event$.subscribe(async (agrs) => {\n this.updateShoppingCartQuantity(args.shoppingCartItemChanged.TotalItems);\n })\n\n AddedProductDetailEvent.event$.subscribe(async (args) => {\n this.updateShoppingCartQuantity(args.shoppingCartItemChanged.TotalItems);\n })\n \n AddedPredictiveSearchEvent.event$.subscribe(async args => {\n await this.loadShoppingCart();\n this.bindShoppinCartControlHandlers();\n })\n\n ToggleShoppingCartEvent.$.pipe(\n filter(_ => this._isCartVisible)\n ).subscribe(async _ => {\n await this.loadShoppingCartFromCacheWithEventsAsync();\n })\n\n // load shopping cart\n this.loadShoppingCartFromCacheWithEventsAsync()\n .then(_ => { });\n }\n\n /**\n * \n * @param {\"more\" | \"less\" | \"remove\" | \"setQuantity\"} action\n * @param {string} productBranchOfficeId\n * @param {string} shoppingCartResponse\n */\n _dispatchShoppingCartEvent(action, productBranchOfficeId, shoppingCartResponse) {\n switch (action) {\n case \"more\":\n MoreProductEvent.more({\n productBranchOfficeId: productBranchOfficeId,\n shoppingCartResponse: shoppingCartResponse\n })\n break;\n case \"less\":\n LessProductEvent.less({\n productBranchOfficeId: productBranchOfficeId,\n shoppingCartResponse: shoppingCartResponse\n })\n break\n case \"remove\":\n RemoveProductEvent.remove({\n productBranchOfficeId: productBranchOfficeId,\n shoppingCartResponse: shoppingCartResponse\n })\n break;\n case \"setQuantity\":\n SetQuantityProductEvent.setQuantity({\n productBranchOfficeId: productBranchOfficeId,\n shoppingCartResponse: shoppingCartResponse\n })\n break;\n }\n }\n\n bindShoppinCartControlHandlers() {\n\n this.bindShoppinCartControl();\n this.displayEmptyCart();\n this.updateShoppingCartQuantity();\n }\n\n displayEmptyCart() {\n var rows = $('.cart__body').find('div.cart__product');\n if (rows.length === 0) {\n $('.cart__empty-wrapper').fadeInAndShow();\n } else {\n $('.cart__empty-wrapper').fadeOutAndHide();\n }\n }\n\n updateShoppingCartQuantity(totalItems = 0) {\n\n var totalProducts = 0;\n if (totalItems !== 0) {\n totalProducts = totalItems;\n }\n else {\n var currentItems = $('.cart__container').find('.controls__number');\n\n if (currentItems.length > 0) {\n currentItems.each(function (index, element) {\n totalProducts += parseInt(element.innerHTML);\n });\n }\n }\n $('.mh__cart-trigger .badge.badge-red').each(function (index, element) {\n element.innerHTML = totalProducts;\n });\n }\n\n updateShoppingCartTotal(value, valueFormatted) {\n this.updateDisplayTotalPrice(value, valueFormatted);\n }\n\n /**\n * Update total price for all products\n * @param {number} value\n * @param {string} valueFormatted\n */\n updateDisplayTotalPrice(value, valueFormatted) {\n\n let totalPriceEl = document.querySelector(\"span.total-price\")\n if (totalPriceEl && totalPriceEl.hasAttribute(\"data-value\")) {\n totalPriceEl.setAttribute(\"data-value\", value);\n totalPriceEl.textContent = valueFormatted;\n }\n\n }\n\n async loadShoppingCart() {\n try {\n this._loadingCart(true)\n // send null for legacy compatibility\n const response = await this._shoppingCartService.getViewAsync(null)\n if (!response.ok) {\n return;\n }\n const responseHtml = await response.text()\n $('.cart__container').html(responseHtml);\n this.invokeLoadedEvent();\n } catch (e) {\n console.error(e);\n } finally {\n this._loadingCart(false)\n }\n }\n\n async loadShoppingCartFromCacheAsync() {\n try {\n this._loadingCart(true)\n const response = await this._shoppingCartService.getViewWithCacheAsync()\n if (!response.ok) {\n return;\n }\n const responseHtml = await response.text()\n $('.cart__container').html(responseHtml);\n this.invokeLoadedEvent();\n } catch (e) {\n console.error(e);\n } finally {\n this._loadingCart(false)\n }\n }\n\n async loadShoppingCartWithEvents() {\n await this.loadShoppingCart();\n this.bindMainControls();\n this.bindShoppinCartControl();\n }\n\n async loadShoppingCartFromCacheWithEventsAsync() {\n await this.loadShoppingCartFromCacheAsync();\n this.bindMainControls();\n this.bindShoppinCartControl();\n this.updateShoppingCartQuantity();\n }\n\n invokeLoadedEvent() {\n ShoppingCartLoadEvent.loaded();\n }\n\n bindShoppinCartControl() {\n // Handle the increase product quantity from the Cart\n $('.controls__more').off('click');\n $('.controls__more').on('click', this.moreProduct.bind(this));\n\n // Handle the decrease product quantity from the Cart\n $('.controls__less').off('click');\n $('.controls__less').on('click', this.lessProduct.bind(this));\n\n // Handle change product quantity from the Cart\n $('.controls__number').off('click');\n $('.controls__number').on('click', this.switchToInput.bind(this));\n\n // Handle the go to Checkout button\n $('.go-checkout').off('click');\n $('.go-checkout').on('click', async (e) => {\n // user without address\n if (this.hasBillingAddress(e.currentTarget)) {\n return;\n }\n\n e.preventDefault();\n await this.goCheckuot(e)\n\n });\n\n // Handle the empty cart button\n $('.cart__remove-button').off('click');\n $('.cart__remove-button').on('click', this.emptyCart.bind(this));\n\n // Handle the empty cart button\n $('.controls__remove-button').off('click');\n $('.controls__remove-button').on('click', this.removeItemCart.bind(this));\n\n // Handle the behavior button click\n $('.add-to-cart').removeAttr(\"disabled\");\n $('.add-to-cart .spinner-border-sm').addClass(\"d-none\");\n\n }\n\n bindMainControls() {\n\n // Shipment Datetime picker\n $.fn.datetimepicker.Constructor.Default = $.extend({}, $.fn.datetimepicker.Constructor.Default, {\n icons: {\n time: 'fa fa-clock',\n date: 'fa fa-calendar',\n up: 'fa fa-arrow-up',\n down: 'fa fa-arrow-down',\n previous: 'fa fa-chevron-left',\n next: 'fa fa-chevron-right',\n today: 'fa fa-calendar-check',\n clear: 'fa fa-trash',\n close: 'fa fa-times'\n }\n });\n\n $('#datetimepicker1').datetimepicker();\n }\n\n /**\n * \n * @param {JQuery.ClickEvent} event\n */\n async lessProduct(event) {\n const parent = $(event.currentTarget).parent().parent();\n const productId = app.productHelper.getProductId(parent);\n const isKit = ProductHelper.getIsKit(parent);\n const internalId = ProductHelper.getInternalId(parent);\n\n this._loadingCart(true);\n try {\n const response = await this._shoppingCartService.decreaseProductQuantityFetch(productId, internalId, isKit);\n\n if (!response.ok) {\n await this._handleShoppingCartResponse(response);\n return;\n }\n\n const json = await response.json();\n const shoppingCartItemChangedResponse = json.Value\n if (shoppingCartItemChangedResponse.Successed) {\n\n if (shoppingCartItemChangedResponse.Message) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n\n await this._updateUiMessages(shoppingCartItemChangedResponse.HasUiMessage);\n\n const productQuantityElement = parent.find('.controls__number');\n if (shoppingCartItemChangedResponse.ProductQuantity > 0) {\n\n productQuantityElement.html(shoppingCartItemChangedResponse.ProductQuantity);\n this.updateShoppingCartQuantity(shoppingCartItemChangedResponse.TotalItems);\n this.updateShoppingCartPricesFromInternalId(internalId, shoppingCartItemChangedResponse);\n\n //Update data-json\n this.updateQuantityOfDataJson(productId, shoppingCartItemChangedResponse.ProductQuantity)\n } else {\n\n // dispatch analytics event \"remove_from_cart\" when user dicrease using button.\n let orderItemEl = document.querySelector(`div.cart__product[data-internal-id=\"${internalId}\"]`)\n if (orderItemEl) {\n let orderItemDTO = JSON.parse(orderItemEl.getAttribute(\"data-json\"))\n if (orderItemDTO) {\n try {\n let priceEl = document.querySelector(\"span.total-price\");\n let pricevalue = 0\n if (priceEl.hasAttribute(\"data-value\")) {\n pricevalue = parseInt(priceEl.getAttribute(\"data-value\"));\n }\n\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackCart(\n 'remove', pricevalue, [{\n itemId: orderItemDTO.Product.ReferenceCode,\n itemName: orderItemDTO.Product.Name,\n currency: appConstants.currency,\n discount: orderItemDTO.Product.Discount,\n itemCategory: orderItemDTO.Product.ProductCategory,\n itemCategory2: orderItemDTO.Product.ProductGroup,\n classification: orderItemDTO.Product.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: orderItemDTO.Product.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: orderItemDTO.Product.Price,\n quantity: orderItemDTO.Quantity\n }], appConstants.currency, 'Catalog')\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e);\n }\n }\n }\n\n productQuantityElement.parents('div.cart__product').fadeOutAndRemove({\n callback: () => {\n app.storeService.displayEmptyCart();\n this.updateShoppingCartQuantity(shoppingCartItemChangedResponse.TotalItems);\n }\n });\n }\n this.updateDisplayTotalPrice(shoppingCartItemChangedResponse.Total, shoppingCartItemChangedResponse.TotalProductsPriceFormatted)\n this.invokeLoadedEvent();\n\n // less product event\n this._dispatchShoppingCartEvent(\"less\", productId, shoppingCartItemChangedResponse)\n\n } else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n\n } catch (e) {\n\n } finally {\n this._loadingCart(false);\n }\n }\n\n /**\n * \n * @param {JQuery.ClickEvent} event\n */\n async moreProduct(event) {\n const parent = $(event.currentTarget).parent().parent();\n const productId = app.productHelper.getProductId(parent);\n const isKit = ProductHelper.getIsKit(parent);\n const internalId = ProductHelper.getInternalId(parent);\n\n this._loadingCart(true);\n try {\n const response = await this._shoppingCartService.increaseProductQuantityFetch(productId, internalId, isKit);\n if (!response.ok) {\n await this._handleShoppingCartResponse(response)\n return;\n }\n\n const json = await response.json();\n const shoppingCartItemChangedResponse = json.Value;\n if (shoppingCartItemChangedResponse.Successed) {\n \n if (shoppingCartItemChangedResponse.Message) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message\n })\n }\n await this._updateUiMessages(shoppingCartItemChangedResponse.HasUiMessage);\n const productQuantityElement = parent.find('.controls__number');\n productQuantityElement.html(shoppingCartItemChangedResponse.ProductQuantity);\n this.updateShoppingCartPricesFromInternalId(internalId, shoppingCartItemChangedResponse);\n\n this.updateDisplayTotalPrice(shoppingCartItemChangedResponse.Total, shoppingCartItemChangedResponse.TotalProductsPriceFormatted)\n this.updateShoppingCartQuantity(shoppingCartItemChangedResponse.TotalItems);\n\n //Update data-json\n this.updateQuantityOfDataJson(productId, shoppingCartItemChangedResponse.ProductQuantity)\n this.invokeLoadedEvent();\n\n //more product event\n this._dispatchShoppingCartEvent(\"more\", productId, shoppingCartItemChangedResponse)\n\n } else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n } catch (e) {\n console.error(e);\n } finally {\n this._loadingCart(false);\n }\n }\n\n /**\n * \n * @param {any} event\n */\n switchToInput(event) {\n var $input = $(\"\", {\n val: $(event.currentTarget).text(),\n type: \"number\",\n min: 1\n });\n $input.addClass(\"cart-number-input\");\n $(event.currentTarget).replaceWith($input);\n $input.on(\"blur\", this.switchToSpan.bind(this));\n $input.select();\n }\n\n /**\n * \n * @param {any} event\n */\n switchToSpan(event) {\n let quantityElement = $(event.currentTarget);\n let productQuantityElement = quantityElement.val();\n\n var $span = $(\"\", {\n text: productQuantityElement\n });\n\n $span.addClass(\"controls__number\");\n $(event.currentTarget).replaceWith($span);\n $span.on(\"click\", this.switchToInput.bind(this));\n this.addProductDetail($span).then(_ => { });\n }\n\n /**\n * \n * @param {HTMLElement} buttonEl\n */\n hasBillingAddress(buttonEl) {\n if ($(buttonEl).attr(\"data-bs-target\")) {\n return true;\n } else {\n return false;\n }\n }\n\n async validateCustomerBlockedAsync() {\n const response = await this._shoppingCartService.postValidateCustomerBlocked();\n if (!response.ok) {\n return false;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n return false;\n }\n\n const value = json.Value\n if (value.CustomerLocked) {\n await this._browserCommunicatorService.displayWarningAlert({\n description: json.UserMessage\n });\n return false;\n }\n\n return true;\n }\n\n /**\n * \n * @param {Event} event\n * @returns\n */\n async goCheckuot(event) {\n kendo.ui.progress($(\".cart__container\"), true)\n try {\n\n if (this.isCartEmpty()) {\n this._browserCommunicatorService.displayInfoAlert({\n description: 'Tu carrito esta vacio, agrega algunos productos.'\n })\n return;\n }\n \n if (!(await this.validateCustomerBlockedAsync())) {\n return\n }\n\n this.trackCheckout();\n\n // redirect to checkout\n const href = event.currentTarget.href;\n window.location.href = href;\n\n } catch (e) {\n console.error(e);\n } finally {\n kendo.ui.progress($(\".cart__container\"), false)\n }\n }\n\n trackCheckout() {\n // dispatch analytics event \"begin_checkout\"\n try {\n let priceEl = document.querySelector(\"span.total-price\")\n let pricevalue = 0\n if (priceEl) {\n pricevalue = parseFloat(priceEl.getAttribute(\"data-value\"))\n }\n\n let productsEls = document.getElementsByClassName(\"cart__product\")\n let listProductsDTO = [...productsEls].map(function (value, index) {\n\n let orderItemDTO = JSON.parse(value.getAttribute(\"data-json\"))\n return {\n itemId: orderItemDTO.Product.ReferenceCode,\n itemName: orderItemDTO.Product.Name,\n currency: appConstants.currency,\n discount: orderItemDTO.Product.Discount,\n itemCategory: orderItemDTO.Product.ProductCategory,\n itemCategory2: orderItemDTO.Product.ProductGroup,\n classification: orderItemDTO.Product.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: orderItemDTO.Product.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: orderItemDTO.Product.Price,\n quantity: orderItemDTO.Quantity\n }\n })\n app.applicationMonitoringService()\n .then(function (service) {\n service.trackCheckout(pricevalue, listProductsDTO, appConstants.currency)\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n\n }\n\n async emptyCart(event) {\n\n if (this.isCartEmpty()) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: 'Tu carrito esta ya vacio.',\n autoclosing: true\n })\n return;\n }\n\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({ description: '¿Seguro quieres quitar todos los productos de tu carrito de compras?' })\n\n if (confirmResult.isConfirmed) {\n app.storeService.emptyCart((response) => {\n if (response) {\n\n // dispatch remove_from_cart analytics event for clear cart\n try {\n let productsEls = document.getElementsByClassName(\"cart__product\")\n let listProductsDTO = [...productsEls].map(function (value, index) {\n\n let orderItemDTOStr = JSON.parse(value.getAttribute(\"data-json\"))\n\n return {\n itemId: orderItemDTOStr.Product.ReferenceCode,\n itemName: orderItemDTOStr.Product.Name,\n currency: appConstants.currency,\n discount: orderItemDTOStr.Product.Discount,\n itemCategory: orderItemDTOStr.Product.ProductCategory,\n itemCategory2: orderItemDTOStr.Product.ProductGroup,\n classification: orderItemDTOStr.Product.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: orderItemDTOStr.Product.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: orderItemDTOStr.Product.Price,\n quantity: orderItemDTOStr.Quantity\n }\n })\n let priceEl = document.querySelector(\"span.total-price\");\n if (priceEl.hasAttribute(\"data-value\")) {\n let pricevalue = parseInt(priceEl.getAttribute(\"data-value\"));\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackCart(\n 'empty', pricevalue, listProductsDTO, appConstants.currency, 'Catalog')\n })\n .catch(function (err) {\n console.error(err);\n })\n }\n } catch (e) {\n console.error(e)\n }\n\n $('.cart__products').fadeOutAndRemove({\n callback: () => {\n this.displayEmptyCart()\n this.updateShoppingCartQuantity();\n this.updateDisplayTotalPrice(0, \"$ 0\")\n this._updateUiMessages(false)\n EmptyCartEvent.empty({})\n }\n });\n }\n });\n }\n }\n\n async _updateUiMessages(show) {\n if (show) {\n // load ui message view\n const response = await this._shoppingCartService.getUiMessageView()\n if (!response.ok) {\n return;\n }\n\n const html = await response.text();\n $(\".cart__ui-messages\").html(html)\n $(\".cart__ui-messages\").fadeInAndShow();\n }\n else {\n $(\".cart__ui-messages\").fadeOutAndHide()\n }\n }\n\n isCartEmpty() {\n var rows = $('.cart__body').find('div.cart__product');\n return rows.length === 0;\n }\n\n /**\n * \n * @param {JQuery.ClickEvent} event\n */\n async removeItemCart(event) {\n var parent = $(event.currentTarget).parent().parent();\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: '¿Seguro quieres quitar el producto de tu carrito de compras?'\n })\n\n if (confirmResult.isConfirmed) {\n var productId = app.productHelper.getProductId(parent);\n const internalId = ProductHelper.getInternalId(parent);\n var productQuantityElement = parent.find('.controls__number');\n\n // dispatch remove_from_cart analytics event\n let productEl = document.querySelector(`div.cart__product[data-internal-id=\"${internalId}\"]`)\n if (productEl && productEl.hasAttribute(\"data-json\")) {\n try {\n\n let orderItemDTO = JSON.parse(productEl.getAttribute(\"data-json\"))\n let totalPricevalue = orderItemDTO.Product.NewPrice ? orderItemDTO.Product.NewPrice : orderItemDTO.Product.Price * orderItemDTO.Quantity\n\n app.applicationMonitoringService()\n .then(function (service) {\n service.trackCart('remove', totalPricevalue, [{\n itemId: orderItemDTO.Product.ReferenceCode,\n itemName: orderItemDTO.Product.Name,\n currency: appConstants.currency,\n discount: orderItemDTO.Product.Discount,\n itemCategory: orderItemDTO.Product.ProductCategory,\n itemCategory2: orderItemDTO.Product.ProductGroup,\n classification: orderItemDTO.Product.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: orderItemDTO.Product.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: orderItemDTO.Product.Price,\n quantity: orderItemDTO.Quantity\n }], appConstants.currency, 'Catalog')\n })\n .catch(function (err) {\n console.error(err);\n })\n\n\n } catch (e) {\n console.error(e)\n }\n }\n\n this._shoppingCartService.removeProductQuantity(productId, async (response) => {\n const shoppingCartItemChangedResponse = response.Value\n await this._updateUiMessages(shoppingCartItemChangedResponse.HasUiMessage)\n if (shoppingCartItemChangedResponse.Successed) {\n\n if (shoppingCartItemChangedResponse.Message) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message\n })\n }\n\n productQuantityElement.parents('div.cart__product').fadeOutAndRemove({\n callback: () => {\n this.displayEmptyCart();\n this.updateShoppingCartQuantity(shoppingCartItemChangedResponse.TotalItems);\n }\n });\n this.updateDisplayTotalPrice(shoppingCartItemChangedResponse.Total, shoppingCartItemChangedResponse.TotalProductsPriceFormatted)\n\n //remove event\n this._dispatchShoppingCartEvent(\"remove\", productId, shoppingCartItemChangedResponse);\n\n } else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n });\n }\n }\n\n /**\n * \n * @param {JQuery} span\n */\n async addProductDetail(span) {\n\n var parent = span.parent().parent();\n var productId = ProductHelper.getProductId(parent);\n const isKit = ProductHelper.getIsKit(parent);\n const internalId = ProductHelper.getInternalId(parent);\n\n var quantity = span[0].innerText;\n\n this._loadingCart(true);\n try {\n const response = await this._shoppingCartService.addProductQuantityFetch(productId, quantity, internalId, isKit)\n\n if (!response.ok) {\n await this._handleShoppingCartResponse(response);\n return;\n }\n\n const responseJson = await response.json();\n if (!responseJson.Successful) {\n await this._handleShoppingCartNotSuccessful(responseJson)\n return;\n }\n\n const shoppingCartItemChangedResponse = responseJson.Value\n if (!shoppingCartItemChangedResponse) {\n return;\n }\n\n if (!shoppingCartItemChangedResponse.Successed) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n return;\n }\n\n if (shoppingCartItemChangedResponse.Message) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message\n })\n }\n\n await this._updateUiMessages(shoppingCartItemChangedResponse.HasUiMessage)\n\n let cartProductQuantityElement = parent.find('.controls__number');\n\n let newQuantity = shoppingCartItemChangedResponse.ProductQuantity;\n\n if (newQuantity <= 0) {\n\n // dispatch analytics event \"remove_from_cart\" when user dicrease usign control number.\n try {\n let orderItemEl = document.querySelector(`div.cart__product[data-internal-id=\"${internalId}\"]`)\n if (orderItemEl) {\n let orderItemDTO = JSON.parse(orderItemEl.getAttribute(\"data-json\"))\n if (orderItemDTO) {\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackCart(\n 'remove', orderItemDTO.Quantity, [{\n itemId: orderItemDTO.Product.ReferenceCode,\n itemName: orderItemDTO.Product.Name,\n currency: appConstants.currency,\n discount: orderItemDTO.Product.Discount,\n itemCategory: orderItemDTO.Product.ProductCategory,\n itemCategory2: orderItemDTO.Product.ProductGroup,\n classification: orderItemDTO.Product.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: orderItemDTO.Product.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: orderItemDTO.Product.Price,\n quantity: orderItemDTO.Quantity\n }], appConstants.currency, 'Catalog')\n })\n .catch(function (err) {\n console.error(err);\n })\n }\n }\n } catch (e) {\n console.error(e)\n }\n\n cartProductQuantityElement.parents('div.cart__product').fadeOutAndRemove({\n callback: () => {\n this.displayEmptyCart();\n this.updateShoppingCartQuantity(shoppingCartItemChangedResponse.TotalItems);\n }\n });\n }\n\n cartProductQuantityElement.html(newQuantity);\n span[0].innerText = newQuantity;\n this.updateDisplayTotalPrice(shoppingCartItemChangedResponse.Total, shoppingCartItemChangedResponse.TotalProductsPriceFormatted)\n /*$('.quantity_display').html(shoppingCartItemChangedResponse.ProductQuantity);*/\n this.updateQuantityOfDataJson(productId, newQuantity);\n this.updateShoppingCartQuantity(shoppingCartItemChangedResponse.TotalItems);\n this.updateShoppingCartPricesFromInternalId(internalId, shoppingCartItemChangedResponse);\n\n // set quantity event\n this._dispatchShoppingCartEvent(\"setQuantity\", productId, shoppingCartItemChangedResponse);\n\n } catch (e) {\n console.error(e)\n } finally {\n this._loadingCart(false);\n }\n }\n\n /**\n * \n * @param {Response} response\n */\n async _handleShoppingCartResponse(response) {\n if (response.status === 400) {\n console.debug(await response.json())\n await this._browserCommunicatorService.displayErrorAlert({\n description: \"Occurrieron errores de validación, por favor intente nuevamente\"\n })\n await this.loadShoppingCartWithEvents()\n }\n }\n\n async _handleShoppingCartNotSuccessful(responseJson) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: responseJson.UserMessage,\n html: true\n })\n }\n\n /**\n * Update quantity of data-json of product.\n * @param {string} productId\n * @param {number} quantity\n */\n updateQuantityOfDataJson(productId, quantity) {\n let orderEl = document.querySelector(`div.cart__product[data-product=\"${productId}\"]`)\n if (orderEl && orderEl.hasAttribute(\"data-json\")) {\n let orderItemDTO = JSON.parse(orderEl.getAttribute(\"data-json\"))\n orderItemDTO.Quantity = quantity\n orderEl.setAttribute(\"data-json\", JSON.stringify(orderItemDTO))\n }\n }\n\n /**\n * \n * @param {boolean} loading\n */\n _loadingCart(loading) {\n this._loading(loading, this._shoppingCartContainer[0])\n }\n\n /**\n * \n * @param {string} productBranchOfficeId\n * @param {any} shoppingCartResponseJson\n */\n updateShoppingCartPricesFromProductId(productBranchOfficeId, shoppingCartResponseJson) {\n const element = $(`.cart__product[data-product=\"${productBranchOfficeId}\"]`);\n this._updateShoppingCartPrices(element, shoppingCartResponseJson);\n }\n\n /**\n * \n * @param {string} productBranchOfficeId\n * @param {any} shoppingCartResponseJson\n */\n updateShoppingCartQuantityFromProductId(productBranchOfficeId, shoppingCartResponseJson) {\n const element = $(`.cart__product[data-product=\"${productBranchOfficeId}\"]`);\n this._updateShoppingCartQuantity(element, shoppingCartResponseJson);\n }\n\n /**\n * \n * @param {string} internalId\n * @param {any} shoppingCartResponseJson\n */\n updateShoppingCartPricesFromInternalId(internalId, shoppingCartResponseJson) {\n const element = $(`.cart__product[data-internal-id=\"${internalId}\"]`);\n this._updateShoppingCartPrices(element, shoppingCartResponseJson);\n }\n\n /**\n * \n * @param {JQuery} element\n * @param {any} shoppingCartResponseJson\n */\n _updateShoppingCartPrices(element, shoppingCartResponseJson) {\n let productPriceEl = element.find(\".product__price\");\n let productNewPriceEl = element.find(\".product__price--old\");\n\n if (shoppingCartResponseJson.ProductNewPrice > 0 && productNewPriceEl.length > 0) {\n productNewPriceEl.html(this.renderNewPrice(shoppingCartResponseJson.ProductPrice, shoppingCartResponseJson.ProductPriceFormatted));\n }\n else {\n productNewPriceEl.html(\"\");\n }\n\n if (productPriceEl.length > 0 && shoppingCartResponseJson.ProductNewPrice > 0) {\n productPriceEl.html(this.renderPrice(shoppingCartResponseJson.ProductNewPrice, shoppingCartResponseJson.ProductNewPriceFormatted));\n }\n else if (productPriceEl.length > 0) {\n productPriceEl.html(this.renderPrice(shoppingCartResponseJson.ProductPrice, shoppingCartResponseJson.ProductPriceFormatted));\n }\n }\n\n /**\n * \n * @param {JQuery} elementCard\n * @param {any} shoppingCartResponseJson\n */\n _updateShoppingCartQuantity(elementCard, shoppingCartResponseJson) {\n let productQuantity = elementCard.find(\".controls__number\");\n if (shoppingCartResponseJson.ProductQuantity <= 0) {\n elementCard.fadeOutAndRemove({\n callback: () => {\n this.displayEmptyCart();\n this.updateShoppingCartQuantity(shoppingCartResponseJson.TotalItems);\n }\n });\n }\n else {\n productQuantity.html(shoppingCartResponseJson.ProductQuantity);\n this.updateShoppingCartQuantity(shoppingCartResponseJson.TotalItems);\n }\n }\n\n renderNewPrice(price, priceFormatted) {\n return `\n \n ${priceFormatted}\n \n `;\n }\n\n /**\n * \n * @param {number} price\n * @param {string} priceFormatted\n * @returns\n */\n renderPrice(price, priceFormatted) {\n return `\n ${priceFormatted}\n `\n }\n}\n\n","class AccountHandlers {\n static init() {\n BindAddresses();\n }\n}\n\nexport default AccountHandlers;\n\nfunction BindAddresses() {\n //funcion temporal para cambiar el contenido de la ventana de direcciones usando el data-name\n $('#addressModal').on('show.bs.modal', function (event) {\n var button = $(event.relatedTarget) // Button that triggered the modal\n var addressName = button.data('name') // Extract info from data-* attributes\n // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).\n // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.\n var modal = $(this);\n modal.find('input[name=\"adname\"]').val(addressName);\n });\n}\n\n","import { analytics } from 'apollo-web'\n\nexport class ApplicationMonitoringService extends analytics.ApplicationMonitoringService {\n constructor() {\n super()\n }\n}\n\n/**\n * \n * @type {Promise}\n * */\nexport const $applicationMonitoringService = new Promise(async (resolve, reject) => {\n try {\n await analytics.clevertapApp.initializeApp()\n await analytics.firebaseApp.initializeApp()\n resolve(new ApplicationMonitoringService())\n } catch (e) {\n console.error(e)\n reject(e)\n }\n})\n","import { TrackerService } from \"./tracker-service\";\r\nimport { trakerList } from \"../helpers/trackerList\";\r\nimport { AnalyticsConstants } from \"../domain/AnalyticsConstants\";\r\n/**\r\n * analytics events service.\r\n * */\r\nexport class ApplicationMonitoringService {\r\n constructor(trackers) {\r\n this._trackService = new TrackerService([...trakerList(), ...trackers || []]);\r\n }\r\n /**\r\n * Track product details\r\n * \r\n * @param value\r\n * @param products\r\n * @param currency\r\n */\r\n trackDetailProduct(value, products, currency, productSource) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.DetailProduct, {\r\n [AnalyticsConstants.Parameters.Value]: value,\r\n [AnalyticsConstants.Parameters.Currency]: currency,\r\n [AnalyticsConstants.Parameters.ProductSource]: productSource,\r\n [AnalyticsConstants.Parameters.Items]: products === null || products === void 0 ? void 0 : products.map(product => {\r\n return {\r\n [AnalyticsConstants.Parameters.ItemId]: product.itemId,\r\n [AnalyticsConstants.Parameters.ItemName]: product.itemName,\r\n [AnalyticsConstants.Parameters.ItemCategory]: product.itemCategory,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: product.itemCategory2,\r\n [AnalyticsConstants.Parameters.department]: product.department,\r\n [AnalyticsConstants.Parameters.classification]: product.classification,\r\n [AnalyticsConstants.Parameters.Price]: product.price,\r\n [AnalyticsConstants.Parameters.Currency]: product.currency,\r\n [AnalyticsConstants.Parameters.Quantity]: product.quantity\r\n };\r\n })\r\n });\r\n }\r\n /**\r\n * Track add to favorite list.\r\n * \r\n * @param currency\r\n * @param value\r\n * @param products\r\n */\r\n trackFavoriteList(currency, value, products) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.FavoriteList, {\r\n [AnalyticsConstants.Parameters.Currency]: currency,\r\n [AnalyticsConstants.Parameters.Value]: value,\r\n [AnalyticsConstants.Parameters.Items]: products === null || products === void 0 ? void 0 : products.map(product => {\r\n return {\r\n [AnalyticsConstants.Parameters.ItemId]: product.itemId,\r\n [AnalyticsConstants.Parameters.ItemName]: product.itemName,\r\n [AnalyticsConstants.Parameters.ItemCategory]: product.itemCategory,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: product.itemCategory2,\r\n [AnalyticsConstants.Parameters.department]: product.department,\r\n [AnalyticsConstants.Parameters.classification]: product.classification,\r\n [AnalyticsConstants.Parameters.Price]: product.price,\r\n [AnalyticsConstants.Parameters.Currency]: product.currency,\r\n [AnalyticsConstants.Parameters.Quantity]: product.quantity\r\n };\r\n })\r\n });\r\n }\r\n /**\r\n * Track add to cart.\r\n * \r\n * @param action\r\n * @param value\r\n * @param products\r\n * @param currency\r\n */\r\n trackCart(action, value, products, currency, productSource) {\r\n let params = {\r\n [AnalyticsConstants.Parameters.Currency]: currency,\r\n [AnalyticsConstants.Parameters.Value]: value,\r\n [AnalyticsConstants.Parameters.EmptyCart]: false,\r\n [AnalyticsConstants.Parameters.ProductSource]: productSource,\r\n [AnalyticsConstants.Parameters.Items]: products === null || products === void 0 ? void 0 : products.map(product => {\r\n return {\r\n [AnalyticsConstants.Parameters.ItemId]: product.itemId,\r\n [AnalyticsConstants.Parameters.ItemName]: product.itemName,\r\n [AnalyticsConstants.Parameters.ItemCategory]: product.itemCategory,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: product.itemCategory2,\r\n [AnalyticsConstants.Parameters.department]: product.department,\r\n [AnalyticsConstants.Parameters.classification]: product.classification,\r\n [AnalyticsConstants.Parameters.Price]: product.price,\r\n [AnalyticsConstants.Parameters.Currency]: product.currency,\r\n [AnalyticsConstants.Parameters.Quantity]: product.quantity\r\n };\r\n })\r\n };\r\n switch (action) {\r\n case 'add':\r\n this._trackService.trackEvent(AnalyticsConstants.Events.AddCart, params);\r\n break;\r\n case 'remove':\r\n this._trackService.trackEvent(AnalyticsConstants.Events.RemoveCart, params);\r\n break;\r\n case 'empty':\r\n params[AnalyticsConstants.Parameters.EmptyCart] = true;\r\n this._trackService.trackEvent(AnalyticsConstants.Events.RemoveCart, params);\r\n break;\r\n case 'view':\r\n this._trackService.trackEvent(AnalyticsConstants.Events.ViewCart, params);\r\n break;\r\n }\r\n }\r\n /**\r\n * Track search.\r\n * \r\n * @param searchTerm\r\n */\r\n trackSearch(searchTerm) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.Search, {\r\n [AnalyticsConstants.Parameters.SearchTerm]: searchTerm\r\n });\r\n }\r\n /**\r\n * Track login\r\n * \r\n * @param method\r\n */\r\n trackLogin(method) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.Login, {\r\n [AnalyticsConstants.Parameters.Method]: method\r\n });\r\n }\r\n /**\r\n * Track sign up\r\n * \r\n * @param method\r\n */\r\n trackSignUp(method) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.SignUp, {\r\n [AnalyticsConstants.Parameters.Method]: method\r\n });\r\n }\r\n /**\r\n * Track checkout\r\n * \r\n * @param value\r\n * @param products\r\n * @param currency\r\n * @param coupon\r\n */\r\n trackCheckout(value, products, currency, coupon) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.Checkout, {\r\n [AnalyticsConstants.Parameters.Coupon]: coupon,\r\n [AnalyticsConstants.Parameters.Currency]: currency,\r\n [AnalyticsConstants.Parameters.Value]: value,\r\n [AnalyticsConstants.Parameters.Items]: products === null || products === void 0 ? void 0 : products.map(product => {\r\n return {\r\n [AnalyticsConstants.Parameters.ItemId]: product.itemId,\r\n [AnalyticsConstants.Parameters.ItemName]: product.itemName,\r\n [AnalyticsConstants.Parameters.ItemCategory]: product.itemCategory,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: product.itemCategory2,\r\n [AnalyticsConstants.Parameters.department]: product.department,\r\n [AnalyticsConstants.Parameters.classification]: product.classification,\r\n [AnalyticsConstants.Parameters.Price]: product.price,\r\n [AnalyticsConstants.Parameters.Currency]: product.currency,\r\n [AnalyticsConstants.Parameters.Quantity]: product.quantity\r\n };\r\n }),\r\n });\r\n }\r\n /**\r\n * Track purchase\r\n * \r\n * @param products\r\n * @param value\r\n * @param transactionId\r\n * @param tax\r\n * @param shipping\r\n * @param coupon\r\n * @param affiliation\r\n * @param currency\r\n */\r\n trackPurcharse({ products, value, transactionId, tax, shipping, coupon, affiliation, currency, paymentType, } = {}) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.Purcharse, {\r\n [AnalyticsConstants.Parameters.Value]: value,\r\n [AnalyticsConstants.Parameters.Currency]: currency,\r\n [AnalyticsConstants.Parameters.TransactionId]: transactionId,\r\n [AnalyticsConstants.Parameters.Tax]: tax,\r\n [AnalyticsConstants.Parameters.Shipping]: shipping,\r\n [AnalyticsConstants.Parameters.Coupon]: coupon,\r\n [AnalyticsConstants.Parameters.Affiliation]: affiliation,\r\n [AnalyticsConstants.Parameters.payment_type]: paymentType,\r\n [AnalyticsConstants.Parameters.Items]: products === null || products === void 0 ? void 0 : products.map(product => {\r\n return {\r\n [AnalyticsConstants.Parameters.ItemId]: product.itemId,\r\n [AnalyticsConstants.Parameters.ItemName]: product.itemName,\r\n [AnalyticsConstants.Parameters.ItemCategory]: product.itemCategory,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: product.itemCategory2,\r\n [AnalyticsConstants.Parameters.department]: product.department,\r\n [AnalyticsConstants.Parameters.classification]: product.classification,\r\n [AnalyticsConstants.Parameters.Price]: product.price,\r\n [AnalyticsConstants.Parameters.Currency]: product.currency,\r\n [AnalyticsConstants.Parameters.Quantity]: product.quantity\r\n };\r\n })\r\n });\r\n }\r\n /**\r\n * Track scroll\r\n * \r\n * @param viewName\r\n * @param viewClass\r\n */\r\n trackScroll(viewName, viewClass, pageNumber, pageCount, pageSize) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.Scroll, {\r\n [AnalyticsConstants.Parameters.ViewClass]: viewClass,\r\n [AnalyticsConstants.Parameters.ViewName]: viewName,\r\n [AnalyticsConstants.Parameters.PageNumber]: pageNumber,\r\n [AnalyticsConstants.Parameters.PageSize]: pageSize,\r\n [AnalyticsConstants.Parameters.PageCount]: pageCount\r\n });\r\n }\r\n /**\r\n * Track zoom in the image\r\n * \r\n * @param productImageName\r\n * @param productImageNumber\r\n */\r\n trackZoomImage(productImageName, productImageNumber) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.ZoomImage, {\r\n product_image_name: productImageName,\r\n product_image_number: productImageNumber\r\n });\r\n }\r\n /**\r\n * Track recover password\r\n * \r\n * @param customerUsername\r\n */\r\n trackRecoverPassword(customerUsername) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.RecoverPassword, {\r\n [AnalyticsConstants.Parameters.CustomerUsername]: customerUsername,\r\n });\r\n }\r\n /**\r\n * Track change password\r\n * \r\n * @param action\r\n */\r\n trackChangePassword(action) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.ChangePassword, {\r\n [AnalyticsConstants.Parameters.Action]: action\r\n });\r\n }\r\n /**\r\n * Track correct password changed\r\n * \r\n * @param action\r\n */\r\n trackPasswordSuccess(action) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.PasswordSuccess, {\r\n [AnalyticsConstants.Parameters.Action]: action\r\n });\r\n }\r\n /**\r\n * Track open chat \"chat_help\"\r\n * \r\n * @param viewName\r\n * @param viewClass\r\n */\r\n trackChatHelp(viewName, viewClass) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.ChatHelp, {\r\n [AnalyticsConstants.Parameters.ViewClass]: viewClass,\r\n [AnalyticsConstants.Parameters.ViewName]: viewName\r\n });\r\n }\r\n /**\r\n * Track create a favorite list\r\n * \r\n * @param action\r\n * @param listName\r\n * @param previousListName\r\n */\r\n trackCreateFavorite(action, listName, previousListName) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.FavoriteList, {\r\n [AnalyticsConstants.Parameters.Action]: action,\r\n [AnalyticsConstants.Parameters.ListName]: listName,\r\n [AnalyticsConstants.Parameters.PreviousListName]: previousListName\r\n });\r\n }\r\n /**\r\n * Track add shipping information\r\n * \r\n * @param value\r\n * @param products\r\n * @param shippingTier\r\n * @param coupon\r\n * @param currency\r\n */\r\n trackAddShippingInfo(value, products, shippingTier, coupon, currency) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.AddShippingInfo, {\r\n [AnalyticsConstants.Parameters.Coupon]: coupon,\r\n [AnalyticsConstants.Parameters.Currency]: currency,\r\n [AnalyticsConstants.Parameters.ShippingTier]: shippingTier,\r\n [AnalyticsConstants.Parameters.Value]: value,\r\n [AnalyticsConstants.Parameters.Items]: products === null || products === void 0 ? void 0 : products.map(product => {\r\n return {\r\n [AnalyticsConstants.Parameters.ItemId]: product.itemId,\r\n [AnalyticsConstants.Parameters.ItemName]: product.itemName,\r\n [AnalyticsConstants.Parameters.ItemCategory]: product.itemCategory,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: product.itemCategory2,\r\n [AnalyticsConstants.Parameters.department]: product.department,\r\n [AnalyticsConstants.Parameters.classification]: product.classification,\r\n [AnalyticsConstants.Parameters.Price]: product.price,\r\n [AnalyticsConstants.Parameters.Currency]: product.currency,\r\n [AnalyticsConstants.Parameters.Quantity]: product.quantity\r\n };\r\n })\r\n });\r\n }\r\n /**\r\n * Track swipes between images of a product\r\n * \r\n * @param productImageName\r\n * @param productImageNumber\r\n * @param productName\r\n * @param productReference\r\n * @param productPrice\r\n * @param productDiscount\r\n * @param productDiscountPrice\r\n * @param productSource\r\n * @param viewName\r\n * @param viewClass\r\n */\r\n trackProductImage(productImageName, productImageNumber, productName, productReference, productPrice, productDiscount, productDiscountPrice, productSource, viewName, viewClass) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.ProductImage, {\r\n [AnalyticsConstants.Parameters.ProductDiscount]: productDiscount,\r\n [AnalyticsConstants.Parameters.ProductDiscountPrice]: productDiscountPrice,\r\n [AnalyticsConstants.Parameters.ProductImageName]: productImageName,\r\n [AnalyticsConstants.Parameters.ProductImageNumber]: productImageNumber,\r\n [AnalyticsConstants.Parameters.ProductName]: productName,\r\n [AnalyticsConstants.Parameters.ProductPrice]: productPrice,\r\n [AnalyticsConstants.Parameters.ProductReference]: productReference,\r\n [AnalyticsConstants.Parameters.ProductSource]: productSource,\r\n [AnalyticsConstants.Parameters.ViewClass]: viewClass,\r\n [AnalyticsConstants.Parameters.ViewName]: viewName\r\n });\r\n }\r\n /**\r\n * Track filter\r\n * \r\n * \r\n * \r\n * @param action\r\n * @param viewName\r\n * @param viewClass\r\n */\r\n trackFilter(action, viewName, viewClass) {\r\n let params = {\r\n [AnalyticsConstants.Parameters.Action]: action,\r\n [AnalyticsConstants.Parameters.ViewClass]: viewClass,\r\n [AnalyticsConstants.Parameters.ViewName]: viewName\r\n };\r\n switch (action) {\r\n case 'activate':\r\n this._trackService.trackEvent(AnalyticsConstants.Events.FilterActivate, params);\r\n break;\r\n case 'clear':\r\n this._trackService.trackEvent(AnalyticsConstants.Events.FilterClear, params);\r\n break;\r\n case 'option':\r\n this._trackService.trackEvent(AnalyticsConstants.Events.FilterOption, params);\r\n break;\r\n }\r\n ;\r\n }\r\n /**\r\n * Track activate account\r\n * \r\n * @param customerUsername\r\n */\r\n trackActivateAccount(customerUsername) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.ActivateAccount, {\r\n [AnalyticsConstants.Parameters.CustomerUsername]: customerUsername\r\n });\r\n }\r\n /**\r\n * Track user without login\r\n */\r\n trackGuestSession() {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.GuestSession);\r\n }\r\n /**\r\n * Set user profile.\r\n * @param userId\r\n * @param params\r\n * @example\r\n * trackUser(\"1123456\", {\r\n * AnalyticsConstants.Parameters.CustomerUsername: \"sebastian.charria\",\r\n * AnalyticsConstants.Parameters.CustomerName: \"Sebastian Charria Muñoz\",\r\n * })\r\n */\r\n trackUser(userId, params) {\r\n this._trackService.setUserId(userId, params);\r\n }\r\n /**\r\n * Track event\r\n * @param eventName\r\n * @param params\r\n */\r\n trackEvent(eventName, params) {\r\n this._trackService.trackEvent(eventName, params);\r\n }\r\n /**\r\n * Track Category viewed\r\n * @param categoryName\r\n */\r\n trackCategory({ categoryName, departmentName }) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.Category, {\r\n [AnalyticsConstants.Parameters.CategoryName]: categoryName,\r\n [AnalyticsConstants.Parameters.department]: departmentName\r\n });\r\n }\r\n trackPromoCode({ action, coupon }) {\r\n let eventId = \"\";\r\n switch (action) {\r\n case 'add':\r\n eventId = AnalyticsConstants.Events.AddPromoCode;\r\n break;\r\n case 'remove':\r\n eventId = AnalyticsConstants.Events.RemovePromoCode;\r\n break;\r\n }\r\n this._trackService.trackEvent(eventId, {\r\n [AnalyticsConstants.Parameters.Coupon]: coupon\r\n });\r\n }\r\n trackAccountVerification({ action, customerEmail, customerPhone }) {\r\n let eventId;\r\n switch (action) {\r\n case 'failed':\r\n eventId = AnalyticsConstants.Events.FailedVerificationAccount;\r\n break;\r\n case 'success':\r\n eventId = AnalyticsConstants.Events.SuccessVerificationAccount;\r\n break;\r\n case 'intent':\r\n eventId = AnalyticsConstants.Events.IntentVerificationAccount;\r\n break;\r\n default:\r\n eventId = AnalyticsConstants.Events.IntentVerificationAccount;\r\n break;\r\n }\r\n this._trackService.trackEvent(eventId, {\r\n [AnalyticsConstants.Parameters.Action]: eventId,\r\n [AnalyticsConstants.Parameters.CustomerEmail]: customerEmail,\r\n [AnalyticsConstants.Parameters.CustomerPhone]: customerPhone\r\n });\r\n }\r\n trackOrder({ action, orderId, CustomerIdentification }) {\r\n var eventId;\r\n switch (action) {\r\n case 'completed':\r\n eventId = AnalyticsConstants.Events.OrderCompleted;\r\n break;\r\n default:\r\n eventId = AnalyticsConstants.Events.OrderCompleted;\r\n break;\r\n }\r\n this._trackService.trackEvent(eventId, {\r\n [AnalyticsConstants.Parameters.Action]: eventId,\r\n [AnalyticsConstants.Parameters.CustomerIdentification]: CustomerIdentification,\r\n [AnalyticsConstants.Parameters.OrderId]: orderId\r\n });\r\n }\r\n /**\r\n *\r\n * @param param0\r\n */\r\n trackMainTabbedClick({ viewName }) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.main_tabbed_click, {\r\n [AnalyticsConstants.Parameters.ViewName]: viewName\r\n });\r\n }\r\n /**\r\n * Track add payment\r\n * @param param0\r\n */\r\n trackPaymentInfo({ currency, paymentType }) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.add_payment_info, {\r\n [AnalyticsConstants.Parameters.Currency]: currency,\r\n [AnalyticsConstants.Parameters.payment_type]: paymentType\r\n });\r\n }\r\n /**\r\n * Track banner events\r\n * @param param0\r\n */\r\n trackBanner({ id, type, viewName, description, product, category, bannerType }) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.banner_click, {\r\n [AnalyticsConstants.Parameters.bannerId]: id,\r\n [AnalyticsConstants.Parameters.type]: type,\r\n [AnalyticsConstants.Parameters.ViewName]: viewName,\r\n [AnalyticsConstants.Parameters.bannerDescription]: description,\r\n [AnalyticsConstants.Parameters.bannerByProduct]: product ? true : false,\r\n [AnalyticsConstants.Parameters.bannerByCategory]: category ? true : false,\r\n [AnalyticsConstants.Parameters.bannerType]: bannerType,\r\n [AnalyticsConstants.Parameters.bannerProduct]: product ? {\r\n [AnalyticsConstants.Parameters.ItemId]: product === null || product === void 0 ? void 0 : product.id,\r\n [AnalyticsConstants.Parameters.ItemName]: product === null || product === void 0 ? void 0 : product.name,\r\n [AnalyticsConstants.Parameters.ItemCategory]: product === null || product === void 0 ? void 0 : product.category,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: product === null || product === void 0 ? void 0 : product.category2,\r\n [AnalyticsConstants.Parameters.department]: product === null || product === void 0 ? void 0 : product.department,\r\n [AnalyticsConstants.Parameters.classification]: product === null || product === void 0 ? void 0 : product.classification,\r\n [AnalyticsConstants.Parameters.Price]: product === null || product === void 0 ? void 0 : product.price,\r\n [AnalyticsConstants.Parameters.manufacture_name]: product === null || product === void 0 ? void 0 : product.manufacturer\r\n } : null,\r\n [AnalyticsConstants.Parameters.bannerCategory]: category ? {\r\n [AnalyticsConstants.Parameters.CategoryName]: category === null || category === void 0 ? void 0 : category.name,\r\n [AnalyticsConstants.Parameters.categoryId]: category === null || category === void 0 ? void 0 : category.id,\r\n [AnalyticsConstants.Parameters.departmentName]: category === null || category === void 0 ? void 0 : category.departmentName,\r\n [AnalyticsConstants.Parameters.departmentId]: category === null || category === void 0 ? void 0 : category.departmentId,\r\n [AnalyticsConstants.Parameters.manufacture_name]: category === null || category === void 0 ? void 0 : category.manufacturer\r\n } : null\r\n });\r\n }\r\n trackRelatedProduct({ products, type }) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.related_product, {\r\n [AnalyticsConstants.Parameters.Items]: products === null || products === void 0 ? void 0 : products.map(product => {\r\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\r\n return {\r\n [AnalyticsConstants.Parameters.ItemId]: product.itemId,\r\n [AnalyticsConstants.Parameters.ItemName]: product.itemName,\r\n [AnalyticsConstants.Parameters.ItemCategory]: product.itemCategory,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: product.itemCategory2,\r\n [AnalyticsConstants.Parameters.department]: product.department,\r\n [AnalyticsConstants.Parameters.classification]: product.classification,\r\n [AnalyticsConstants.Parameters.Price]: product.price,\r\n [AnalyticsConstants.Parameters.Currency]: product.currency,\r\n [AnalyticsConstants.Parameters.Quantity]: product.quantity,\r\n [AnalyticsConstants.Parameters.manufacture_name]: product.manufacturerName,\r\n [AnalyticsConstants.Parameters.related_product_product_source]: {\r\n [AnalyticsConstants.Parameters.ItemId]: (_a = product.productSource) === null || _a === void 0 ? void 0 : _a.itemId,\r\n [AnalyticsConstants.Parameters.ItemName]: (_b = product.productSource) === null || _b === void 0 ? void 0 : _b.itemName,\r\n [AnalyticsConstants.Parameters.ItemCategory]: (_c = product.productSource) === null || _c === void 0 ? void 0 : _c.itemCategory,\r\n [AnalyticsConstants.Parameters.ItemCategory2]: (_d = product.productSource) === null || _d === void 0 ? void 0 : _d.itemCategory2,\r\n [AnalyticsConstants.Parameters.department]: (_e = product.productSource) === null || _e === void 0 ? void 0 : _e.department,\r\n [AnalyticsConstants.Parameters.classification]: (_f = product.productSource) === null || _f === void 0 ? void 0 : _f.classification,\r\n [AnalyticsConstants.Parameters.Price]: (_g = product.productSource) === null || _g === void 0 ? void 0 : _g.price,\r\n [AnalyticsConstants.Parameters.Currency]: (_h = product.productSource) === null || _h === void 0 ? void 0 : _h.currency,\r\n [AnalyticsConstants.Parameters.Quantity]: (_j = product.productSource) === null || _j === void 0 ? void 0 : _j.quantity,\r\n [AnalyticsConstants.Parameters.manufacture_name]: (_k = product.productSource) === null || _k === void 0 ? void 0 : _k.manufacturerName\r\n }\r\n };\r\n }),\r\n [AnalyticsConstants.Parameters.related_product_type]: type\r\n });\r\n }\r\n clearUserId() {\r\n this._trackService.clearUserId();\r\n }\r\n /**\r\n *\r\n */\r\n trackScreenView({ viewName }) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.screen_view, {\r\n [AnalyticsConstants.Parameters.ViewName]: viewName,\r\n [AnalyticsConstants.Parameters.firebase_screen]: viewName\r\n });\r\n }\r\n trackUserProperties(params) {\r\n this._trackService.setUserProperties(params);\r\n }\r\n trackDeepLinkRedirect({ redirectUrl }) {\r\n this._trackService.trackEvent(AnalyticsConstants.Events.deep_link_redirect, {\r\n [AnalyticsConstants.Parameters.redirect_to_url]: redirectUrl\r\n });\r\n }\r\n}\r\n//# sourceMappingURL=application-monitoring-service.js.map","\nexport default class AppHelper {\n static getAge(born, now) {\n var birthday = new Date(now.getFullYear(), born.getMonth(), born.getDate());\n if (now >= birthday)\n return now.getFullYear() - born.getFullYear();\n else\n return now.getFullYear() - born.getFullYear() - 1;\n }\n}","import { $applicationMonitoringService } from \"../application-monitoring\"\nimport { analytics } from \"apollo-web\"\nimport AppHelper from \"../../helpers/app-helper\"\nimport { appConstants } from \"../../enums/site-enum\"\n\nexport class CustomerAnalyticsHelper {\n constructor() {\n }\n\n /**\n * \n * @param {{User: {ReferenceCode: string, Customer: {}, BranchOffice: {}}}} response\n */\n static async trackUserFromAddressAsync(response) {\n await this.trackUser({\n response: response,\n tracklogin: false\n })\n }\n\n /**\n * \n * @param {{response: {}, tracklogin: boolean}} param0\n */\n static async trackUser({response, tracklogin}) {\n\n try {\n const service = await $applicationMonitoringService;\n let user = response.User\n let branchoffice = user.BranchOffice;\n\n service.trackUser(user.Customer.Identification, {\n [analytics.AnalyticsConstants.Parameters.CustomerIdentification]: user.Customer.Identification,\n [analytics.AnalyticsConstants.Parameters.CustomerUsername]: user.Username,\n [analytics.AnalyticsConstants.Parameters.CustomerName]: `${user.Customer.FirstName} ${user.Customer.LastName}`,\n [analytics.AnalyticsConstants.Parameters.CustomerEmail]: user.Customer.Email,\n [analytics.AnalyticsConstants.Parameters.CustomerPhone]: `${appConstants.codePhoneNumber}${user.Customer.PhoneNumber}`,\n [analytics.AnalyticsConstants.Parameters.CustomerBranchOfficeCode]: branchoffice?.Name ?? analytics.AnalyticsConstants.DefaultParameterValue,\n [analytics.AnalyticsConstants.Parameters.CustomerBranchOfficeDescription]: branchoffice?.Description ?? analytics.AnalyticsConstants.DefaultParameterValue,\n [analytics.AnalyticsConstants.Parameters.CustomerCluster]: `${user.Customer.BusinessUnitName}`,\n [analytics.AnalyticsConstants.Parameters.UserType]: `${user.UserType}`,\n [analytics.AnalyticsConstants.Parameters.created_at]: user.Customer.CreatedAt ?? analytics.AnalyticsConstants.DefaultParameterValue,\n [analytics.AnalyticsConstants.Parameters.customer_birthdate]: user.Customer.BirthDate,\n [analytics.AnalyticsConstants.Parameters.customer_age]: user.Customer.BirthDate ? AppHelper.getAge(new Date(user.Customer.BirthDate), new Date()) : null,\n\n [analytics.AnalyticsConstants.Parameters.MSGEmail]: user.Customer.ReceivePromotionalCommunications,\n [analytics.AnalyticsConstants.Parameters.MSGPush]: user.Customer.ReceivePromotionalCommunications,\n [analytics.AnalyticsConstants.Parameters.MSGSms]: user.Customer.ReceivePromotionalCommunications,\n [analytics.AnalyticsConstants.Parameters.MSGWhatsapp]: user.Customer.ReceivePromotionalCommunications,\n\n [analytics.AnalyticsConstants.Parameters.clevertap_dnd_phone]: false,\n [analytics.AnalyticsConstants.Parameters.clevertap_dnd_email]: false\n\n });\n\n if (tracklogin) {\n service.trackLogin();\n }\n\n } catch (e) {\n console.log(e)\n }\n }\n\n /**\n * \n * @param {{[key:string]: any} params\n */\n static async trackUserPropertiesAsync(params) {\n try {\n const service = await $applicationMonitoringService;\n service.trackUserProperties(params);\n } catch (e) {\n console.log(e)\n }\n }\n\n}","import { ServiceBase } from \"../../service/service-base\"\nimport AjaxProxy from \"../../../proxies/ajax-proxy\"\n\nexport class NotificationOrdersService extends ServiceBase {\n\n _endpoints = {\n getNotificationDetail: \"/Store/NotificationOrders?handler=Detail\",\n getUnreadNumber: \"/Store/NotificationOrders?handler=NumberOfUnreadNotification\",\n getNotificationView: \"/Store/NotificationOrders\"\n }\n\n constructor() {\n super();\n }\n\n getNotificationDetail(notificationId) {\n const request = new FormData();\n request.append(\"notificationId\", notificationId);\n return AjaxProxy.postFetch(this._endpoints.getNotificationDetail, { body: request });\n }\n\n getNotificationView() {\n return AjaxProxy.getFetch(this._endpoints.getNotificationView, { });\n }\n\n getUnreadNumber() {\n return AjaxProxy.postFetch(this._endpoints.getUnreadNumber, {});\n }\n}","import { HandlerBase } from \"../../handler/handler-base\"\nimport { NotificationOrdersService } from \"../services/notification-orders-services\"\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service\"\nimport { fromEvent } from \"rxjs\"\n\nexport class NotificationOrdersHandlers extends HandlerBase {\n\n get _detailButton() {\n return $(\".view-notification\");\n }\n\n get _notificationContainter() {\n return $('.notification__container');\n }\n\n get _notificationListContainer() {\n return $(\"#notificationByCustomerList\");\n }\n\n get _notificationTriggerNumber() {\n return $(\".mh__notification-trigger > span\");\n }\n\n constructor() {\n super();\n this._notificationOrdersService = new NotificationOrdersService();\n this._browserCommunicatorService = new BrowserCommunicatorService();\n }\n\n init() {\n fromEvent(this._detailButton, \"click\").subscribe(async e => {\n await this.loadDetail(e);\n })\n\n this.loadUnreadNumberAsync()\n .then(_ => { });\n }\n\n async loadUnreadNumberAsync() {\n try {\n const response = await this._notificationOrdersService.getUnreadNumber();\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (json.Successful) {\n this._notificationTriggerNumber.html(json.Value.NumberOfUnreadNotifications)\n } else {\n this._notificationTriggerNumber.html(\"0\")\n }\n } catch (e) {\n console.log(e);\n }\n }\n\n /**\n * \n * @param {Event} e\n */\n async loadDetail(e) {\n let notificationId = e.currentTarget.id;\n let hasSrcDoc = $('#iFrame_' + notificationId).attr('srcdoc');\n\n try {\n if (!hasSrcDoc) {\n this._loading(true, this._notificationContainter[0])\n\n const response = await this._notificationOrdersService.getNotificationDetail(notificationId);\n\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (json.Successful) {\n var htmlBase = json.Value.Content;\n var quantity = json.Value.Quantity;\n\n this.collapseNotifications(notificationId);\n\n let classNameBase = $('#collapseEnvelope-' + notificationId)[0].className;\n $('#collapseEnvelope-' + notificationId)[0].className = classNameBase.replace('font-weight-bold', '');\n $('#collapseEnvelope-' + notificationId)[0].style.backgroundColor = '';\n $('#collapseHeadings-' + notificationId)[0].style.backgroundColor = '';\n\n $('#iFrame_' + notificationId).attr('srcdoc', htmlBase);\n\n $('.badge.notification-red').each(function (index, element) {\n element.innerHTML = quantity;\n });\n\n } else {\n await this._browserCommunicatorService.displayErrorAlert({ \n description: json.UserMessage, \n html: true \n });\n e.preventDefault()\n }\n } else {\n this.collapseNotifications(notificationId);\n }\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false, this._notificationContainter[0]);\n }\n \n }\n\n collapseNotifications(NotificationId) {\n\n let elements = document.querySelectorAll('[id^=\"collapseNotifications-\"]');\n let notificationId = NotificationId;\n\n var i;\n for (i = 0; i < elements.length; i++) {\n let idItem = elements.item(i).id;\n\n if (idItem.replace('collapseNotifications-', '') == notificationId) {\n $('#' + idItem).collapse('show');\n } else {\n $('#' + idItem).collapse('hide')\n }\n }\n }\n\n async loadNotificationByCustomer() {\n let response = await this._notificationOrdersService.getNotificationView();\n this._notificationContainter.html(await response.text());\n this.init();\n }\n}","import { Subject } from 'rxjs'\n\nexport class LoadViewEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{}} args\n */\n load(args) {\n this._subject.next(args);\n }\n}\n\nconst event = new LoadViewEvent();\nexport default event;","import { analytics } from \"apollo-web\";\nimport { appConstants } from \"../enums/site-enum.js\";\nimport CartHelper from \"../helpers/cart-helper.js\";\nimport { $applicationMonitoringService } from '../shared/application-monitoring'\nimport 'jquery.menuaim'\nimport { BrowserCommunicatorService } from \"../services/browser-communicator-service.js\";\nimport { CustomerAnalyticsHelper } from \"../shared/helper/customer-analytics-helper\"\nimport { NotificationOrdersHandlers } from \"../shared/notification-orders/handlers/notification-orders-handlers.js\";\nimport LoadAddressManagementEvent from \"../shared/address-management/events/load-view-event.js\"\nimport ToggleShoppingCartEvent from \"../shared/shopping-cart/events/toggle-shopping-cart-event\"\nimport { fromEvent } from \"rxjs\"\n\nvar MqL = 1024;\nvar WrapMenu = false;\nvar LeftMenu = false;\nvar LeftMenuAlwaysVisible = false;\nconst notificationOrdersHandler = new NotificationOrdersHandlers();\nconst browserCommunicatorService = new BrowserCommunicatorService();\n\nclass MenuNavHandlers {\n\n constructor() {\n\n }\n\n static init() {\n initControls();\n\n $(\"li.k-menu-item\").removeClass(\"invisible\")\n }\n}\n\nexport default MenuNavHandlers;\n\nfunction initControls() {\n //get menuType to decide which methods to call\n var menuType = $('#headerMenu').data('menuType');\n switch (menuType) {\n case 'MegaMenu':\n moveElementsOnResponsive();\n bindControlsAllTypes();\n bindMegaMenuControls();\n break;\n case 'Hamburger':\n LeftMenu = true;\n moveElementsOnResponsive();\n bindControlsAllTypes();\n bindHamburgerControls();\n break;\n case 'FixedSlide':\n LeftMenu = true;\n LeftMenuAlwaysVisible = true;\n moveElementsOnResponsive();\n bindControlsAllTypes();\n bindFixedSlideControls();\n break;\n case 'Dropdown':\n WrapMenu = true;\n moveElementsOnResponsive();\n wrapMenuonDesktop();\n bindControlsAllTypes();\n bindDropDownControls();\n break;\n default:\n break;\n }\n}\n\nfunction bindControlsAllTypes() {\n $(window).on('resize', function () {\n (!window.requestAnimationFrame) ? setTimeout(moveElementsOnResponsive, 300) : window.requestAnimationFrame(moveElementsOnResponsive);\n });\n\n //open Notifications\n $('.mh__notification-trigger').on('click', async function (event) {\n event.preventDefault();\n toggleNotification();\n toggleAddressManagement('close');\n closeNavNotification();\n\n if ($('.notification__container').hasClass('is-visible')) {\n kendo.ui.progress($('.notification__container'), true);\n await notificationOrdersHandler.loadNotificationByCustomer();\n kendo.ui.progress($('.notification__container'), false);\n }\n\n $applicationMonitoringService\n .then(function (service) {\n service.trackMainTabbedClick({ viewName: 'NotificationByCustomerView' });\n service.trackScreenView({viewName: 'NotificationByCustomerView'})\n })\n .catch(err => console.error(err))\n });\n\n //open cart\n fromEvent(document.querySelector(\".mh__cart-trigger\"), \"click\").subscribe(event => {\n event.preventDefault();\n toggleCart();\n toggleAddressManagement('close');\n closeNav();\n\n $applicationMonitoringService\n .then(function (service) {\n service.trackMainTabbedClick({ viewName: 'ShoppingCartView' });\n service.trackScreenView({ viewName: 'ShoppingCartView' })\n })\n .catch(err => console.error(err))\n\n ToggleShoppingCartEvent.toggle();\n });\n\n $('.usr-addresses-trigger').on('click', async (event) => {\n event.preventDefault();\n toggleAddressManagement();\n closeNav();\n\n LoadAddressManagementEvent.load({})\n });\n\n //close cart when focusing search bar\n $('.main-header__search-bar').off('click');\n $('.main-header__search-bar').on('click', function () {\n closeNav();\n toggleCart('close');\n toggleFilters('close');\n\n toggleAddressManagement('close');\n $('.main__overlay').removeClass('is-visible');\n });\n\n $('.branchoffice-user-selected').off('change');\n $('.branchoffice-user-selected').on('change', branchofficeUserSelected);\n\n $('#stateSelectId').off('change');\n $('#stateSelectId').on('change', getCitiesByState);\n\n $(document).ready(function () {\n getCitiesByState();\n });\n\n $('#selectedCity').off('click');\n $('#selectedCity').on('click', setCityCustomer);\n\n $('#selectedBranchOffice').off('click');\n $('#selectedBranchOffice').on('click', branchofficeWithoutRegistrationSelected);\n\n let searchBtn = document.querySelector(\"button.search-button\")\n searchBtn.addEventListener('click', function (e) {\n\n // dispatch search analytics event.\n let searchinput = document.getElementById(\"ProductNameToSearch\")\n let searchTerm = searchinput.value\n try {\n $applicationMonitoringService\n .then(function (service) {\n service.trackSearch(searchTerm)\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n })\n\n let promoBtn = document.querySelector(\".mh__promo-trigger\")\n if (promoBtn) {\n promoBtn.addEventListener('click', function (ev) {\n $applicationMonitoringService\n .then(function (service) {\n service.trackMainTabbedClick({ viewName: 'ProductCatalogView' });\n service.trackScreenView({viewName: 'ProductCatalogView'})\n })\n .catch(err => console.error(err))\n })\n }\n\n let myAccountBtn = document.querySelector(\".mh__account-trigger\");\n if (myAccountBtn) {\n myAccountBtn.addEventListener(\"click\", function (ev) {\n $applicationMonitoringService\n .then(function (service) {\n service.trackMainTabbedClick({ viewName: 'AccountView' });\n service.trackScreenView({viewName: \"AccountView\"})\n })\n .catch(err => console.error(err))\n })\n }\n}\n\nfunction bindMegaMenuControls() {\n //mobile - open lateral menu clicking on the menu icon\n $('.mh__nav-trigger').on('click', function (event) {\n event.preventDefault();\n openMobileMenu();\n });\n\n //close lateral menu on mobile \n $('.main__overlay').on('swiperight', closeMobileMenu);\n $('.nav-on-left .main__overlay').on('swipeleft', closeMobileMenu);\n $('.main__overlay').on('click', function () {\n closeNav();\n toggleCart('close');\n toggleFilters('close');\n toggleNotification('close');\n\n toggleAddressManagement('close');\n $('.main__overlay').removeClass('is-visible');\n });\n\n //prevent default clicking on direct children of .mh__primary-nav \n $('.mh__primary-nav').children('.has-children').children('a').on('click', function (event) {\n event.preventDefault();\n });\n\n //open submenu\n $('.has-children').children('a').on('click', function (event) {\n if (!checkWindowWidth()) event.preventDefault();\n var selected = $(this);\n if (selected.next('ul').hasClass('is-hidden')) {\n //desktop version only\n selected.addClass('selected').next('ul').removeClass('is-hidden').end().parent('.has-children').parent('ul').addClass('moves-out');\n selected.parent('.has-children').siblings('.has-children').children('ul').addClass('is-hidden').end().children('a').removeClass('selected');\n $('.main__overlay').addClass('is-visible');\n } else {\n selected.removeClass('selected').next('ul').addClass('is-hidden').end().parent('.has-children').parent('ul').removeClass('moves-out');\n $('.main__overlay').removeClass('is-visible');\n }\n\n toggleCart('close');\n toggleNotification('close');\n toggleAddressManagement('close');\n\n });\n\n //submenu items - go back link\n $('.go-back').on('click', function () {\n $(this).parent('ul').addClass('is-hidden').parent('.has-children').parent('ul').removeClass('moves-out');\n });\n}\n\nfunction bindDropDownControls() {\n\n //mobile - open lateral menu clicking on the menu icon\n $('.mh__nav-trigger').on('click', function (event) {\n event.preventDefault();\n openMobileMenu();\n });\n\n //close lateral menu on mobile \n $('.main__overlay').on('swiperight', closeMobileMenu);\n $('.nav-on-left .main__overlay').on('swipeleft', closeMobileMenu);\n $('.main__overlay').on('click', function () {\n closeNav();\n toggleCart('close');\n toggleFilters('close');\n toggleNotification('close');\n\n toggleAddressManagement('close');\n\n $('.main__overlay').removeClass('is-visible');\n });\n\n //prevent default clicking on direct children of .mh__primary-nav \n $('.mh__primary-nav').children('.has-children').children('a').on('click', function (event) {\n event.preventDefault();\n });\n\n ////open submenu \n $('.has-children').children('a').on('click', function (event) {\n if (!checkWindowWidth()) event.preventDefault();\n var selected = $(this);\n if (selected.next('div').length > 0) {\n if (selected.next('div').hasClass('is-hidden')) {\n selected.addClass('selected').next('div').removeClass('is-hidden').end().parent('.has-children').parent('ul').addClass('moves-out');\n selected.parent('.has-children').siblings('.has-children').children('div').addClass('is-hidden').end().children('a').removeClass('selected');\n selected.parent('.has-children').siblings('.has-children').children('ul').addClass('is-hidden').end().children('a').removeClass('selected');\n $('.main__overlay').addClass('is-visible');\n } else {\n selected.removeClass('selected').next('div').addClass('is-hidden').end().parent('.has-children').parent('ul').removeClass('moves-out');\n $('.main__overlay').removeClass('is-visible');\n }\n } else if (selected.next('ul').length > 0) {\n if (selected.next('ul').hasClass('is-hidden')) {\n selected.addClass('selected').next('ul').removeClass('is-hidden').end().parent('.has-children').parent('ul').addClass('moves-out');\n selected.parent('.has-children').siblings('.has-children').children('ul').addClass('is-hidden').end().children('a').removeClass('selected');\n selected.parent('.has-children').siblings('.has-children').children('div').addClass('is-hidden').end().children('a').removeClass('selected');\n $('.main__overlay').addClass('is-visible');\n } else {\n selected.removeClass('selected').next('ul').addClass('is-hidden').end().parent('.has-children').parent('ul').removeClass('moves-out');\n $('.main__overlay').removeClass('is-visible');\n }\n }\n toggleCart('close');\n\n toggleAddressManagement('close');\n });\n\n\n //submenu items - go back link\n $('.go-back').on('click', function () {\n $(this).parent('ul').addClass('is-hidden').parent('.has-children').parent('ul').removeClass('moves-out');\n });\n\n //menu aim\n var submenuDirection = 'right';\n $('.mh__secondary-nav').menuAim({\n activate: function (row) {\n $(row).children().addClass('is-active').removeClass('fade-out');\n if ($('.mh__secondary-nav .fade-in').length == 0) $(row).children('ul').addClass('fade-in');\n updateSubPosition();\n },\n deactivate: function (row) {\n $(row).children().removeClass('is-active');\n if ($('li.has-children:hover').length == 0 || $('li.has-children:hover').is($(row))) {\n $('.mh__secondary-nav').find('.fade-in').removeClass('fade-in');\n $(row).children('ul').addClass('fade-out')\n }\n },\n exitMenu: function () {\n $('.mh__secondary-nav').find('.is-active').removeClass('is-active');\n return true;\n },\n submenuDirection: submenuDirection,\n });\n}\n\nfunction bindHamburgerControls() {\n $('.mh__nav-trigger--hb').on('click', function (event) {\n event.preventDefault();\n openLeftMenu();\n });\n\n //add nave on left to set all mobile navigation elements at left\n $('body').addClass('nav-on-left');\n $('.main__overlay').addClass('hamburger-overlay');\n $('.main__content').addClass('hamburger-content');\n\n //close lateral menu on mobile \n $('.main__overlay').on('swiperight', closeMobileMenu);\n $('.nav-on-left .main__overlay').on('swipeleft', closeMobileMenu);\n $('.main__overlay').on('click', function () {\n closeNav();\n toggleCart('close');\n toggleFilters('close');\n toggleNotification('close');\n\n toggleAddressManagement('close');\n $('.main__overlay').removeClass('is-visible');\n });\n\n //open submenu\n $('.has-children').children('a').on('click', function (event) {\n if (!checkWindowWidth()) event.preventDefault();\n var selected = $(this);\n if (selected.next('ul').hasClass('is-hidden')) {\n selected.addClass('selected').next('ul').removeClass('is-hidden').end().parent('.has-children').parent('ul').addClass('moves-out');\n selected.parent('.has-children').siblings('.has-children').children('ul').addClass('is-hidden').end().children('a').removeClass('selected');\n } else {\n selected.removeClass('selected').next('ul').addClass('is-hidden').end().parent('.has-children').parent('ul').removeClass('moves-out');\n }\n toggleCart('close');\n\n toggleAddressManagement('close');\n });\n\n //submenu items - go back link\n $('.go-back').on('click', function () {\n $(this).parent('ul').addClass('is-hidden').parent('.has-children').parent('ul').removeClass('moves-out');\n });\n}\n\nfunction bindFixedSlideControls() {\n $('.mh__nav-trigger--fs').on('click', function (event) {\n event.preventDefault();\n openLeftMenu();\n });\n //add nave on left to set all mobile navigation elements at left\n $('body').addClass('nav-on-left');\n $('.main__overlay').addClass('hamburger-overlay');\n $('.main__content').addClass('fixed-slide-content');\n\n //close lateral menu on mobile \n $('.main__overlay').on('swiperight', closeMobileMenu);\n $('.nav-on-left .main__overlay').on('swipeleft', closeMobileMenu);\n $('.main__overlay').on('click', function () {\n closeNav();\n toggleCart('close');\n toggleFilters('close');\n toggleNotification('close');\n\n toggleAddressManagement('close');\n\n $('.main__overlay').removeClass('is-visible');\n });\n\n //open submenu\n $('.has-children').children('a').on('click', function (event) {\n if (!checkWindowWidth()) event.preventDefault();\n var selected = $(this);\n if (selected.next('ul').hasClass('is-hidden')) {\n selected.addClass('selected').next('ul').removeClass('is-hidden').end().parent('.has-children').parent('ul').addClass('moves-out');\n selected.parent('.has-children').siblings('.has-children').children('ul').addClass('is-hidden').end().children('a').removeClass('selected');\n $('.main__overlay').removeClass('is-visible');\n } else {\n selected.removeClass('selected').next('ul').addClass('is-hidden').end().parent('.has-children').parent('ul').removeClass('moves-out');\n $('.main__overlay').removeClass('is-visible');\n }\n toggleCart('close');\n\n toggleAddressManagement('close');\n });\n\n //submenu items - go back link\n $('.go-back').on('click', function () {\n $(this).parent('ul').addClass('is-hidden').parent('.has-children').parent('ul').removeClass('moves-out');\n });\n}\n\nfunction toggleFilters(type) {\n if (type == \"close\") {\n //close filters\n $('.filter__wrapper').removeClass('is-visible');\n $('.mh__search-trigger').removeClass('search-is-visible');\n $('.main__overlay').removeClass('search-is-visible');\n } else {\n //toggle filters visibility\n $('.filter__wrapper').toggleClass('is-visible');\n $('.mh__search-trigger').toggleClass('search-is-visible');\n $('.main__overlay').toggleClass('search-is-visible');\n ($('.filter__wrapper').hasClass('is-visible')) ? $('.main__overlay').addClass('is-visible') : $('.main__overlay').removeClass('is-visible');\n }\n}\n\nfunction openMobileMenu() {\n if ($('.main__content').hasClass('nav-is-visible')) {\n closeNav();\n $('.main__overlay').removeClass('is-visible');\n } else {\n $('.mh__nav-trigger').addClass('nav-is-visible');\n $('.mh__primary-nav').addClass('nav-is-visible');\n $('.main-header').addClass('nav-is-visible');\n $('.mh__search-bar-wrapper').addClass('nav-is-visible');\n $('.main__content').addClass('nav-is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {\n $('body').addClass('overflow-hidden');\n });\n toggleCart('close');\n\n toggleAddressManagement('close');\n\n $('.main__overlay').addClass('is-visible');\n }\n}\n\nfunction openLeftMenu() {\n if ($('.main__content').hasClass('nav-is-visible')) {\n closeLeftNav();\n $('.main__overlay').removeClass('is-visible').removeClass('search-is-visible');\n } else {\n $('.mh__nav-trigger--hb').addClass('nav-is-visible');\n $('.mh__nav-trigger--fs').addClass('nav-is-visible');\n $('.footer').addClass('nav-on-left nav-is-visible');\n $('.mh__primary-nav').addClass('nav-is-visible');\n $('.mh__primary-nav-hb').addClass('nav-is-visible');\n $('.mh__primary-nav-fs').addClass('nav-is-visible');\n $('.main-header').addClass('nav-is-visible');\n $('.mh__search-bar-wrapper').addClass('nav-is-visible');\n $('.main__content').addClass('nav-is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {\n $('body').addClass('overflow-hidden');\n });\n toggleCart('close');\n toggleFilters('close');\n\n toggleAddressManagement('close');\n\n $('.main__overlay').addClass('is-visible').removeClass('search-is-visible');\n $('.address-list-container').removeClass('is-visible');\n }\n}\n\nfunction closeMobileMenu() {\n if ($('.mh__primary-nav').hasClass('nav-is-visible')) {\n closeNav();\n $('.main__overlay').removeClass('is-visible');\n }\n}\n\nfunction updateSubPosition() {\n var displaceVal = $('.mh__secondary-nav-wrapper').scrollTop();\n $('.mh__secondary-nav-wrapper').find('ul.is-active').css(\"padding-top\", displaceVal + \"px\");\n}\n\nfunction closeNav() {\n $(\".notification__container\").removeClass('is-visible')\n $('.mh__nav-trigger').removeClass('nav-is-visible');\n $('.main-header').removeClass('nav-is-visible');\n $('.mh__primary-nav').removeClass('nav-is-visible');\n $('.mh__search-bar-wrapper').removeClass('nav-is-visible');\n $('.has-children>div').addClass('is-hidden');\n $('.has-children ul').addClass('is-hidden');\n $('.dropright ul').removeClass('is-hidden');\n $('.has-children a').removeClass('selected');\n $('.moves-out').removeClass('moves-out');\n $('.footer').removeClass('nav-is-visible');\n $('.main__content').removeClass('nav-is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {\n $('body').removeClass('overflow-hidden');\n });\n $('.filter__wrapper').removeClass('is-visble');\n}\n\nfunction closeNavNotification() {\n $('.cart__container').removeClass('is-visible');\n $('.mh__nav-trigger').removeClass('nav-is-visible');\n $('.main-header').removeClass('nav-is-visible');\n $('.mh__primary-nav').removeClass('nav-is-visible');\n $('.mh__search-bar-wrapper').removeClass('nav-is-visible');\n $('.has-children>div').addClass('is-hidden');\n $('.has-children ul').addClass('is-hidden');\n $('.has-children a').removeClass('selected');\n $('.moves-out').removeClass('moves-out');\n $('.footer').removeClass('nav-is-visible');\n $('.main__content').removeClass('nav-is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {\n $('body').removeClass('overflow-hidden');\n });\n $('.filter__wrapper').removeClass('is-visble');\n}\n\nfunction closeLeftNav() {\n $('.mh__nav-trigger--hb').removeClass('nav-is-visible');\n $('.mh__nav-trigger--fs').removeClass('nav-is-visible');\n $('.main-header').removeClass('nav-is-visible');\n $('.footer').removeClass('nav-on-left nav-is-visible');\n $('.mh__primary-nav').removeClass('nav-is-visible');\n $('.mh__search-bar-wrapper').removeClass('nav-is-visible');\n $('.has-children ul').addClass('is-hidden');\n $('.has-children a').removeClass('selected');\n $('.moves-out').removeClass('moves-out');\n $('.main__content').removeClass('nav-is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {\n $('body').removeClass('overflow-hidden');\n });\n $('.filter__wrapper').removeClass('is-visble');\n}\n\nfunction toggleCart(type) {\n if (type == \"close\") {\n //cart serach \n $('.cart__container').removeClass('is-visible');\n $('.mh__search-trigger').removeClass('search-is-visible');\n $('.main__overlay').removeClass('search-is-visible');\n $('.notification__container').removeClass('search-is-visible');\n } else {\n //toggle cart visibility\n $('.cart__container').toggleClass('is-visible');\n $('.mh__search-trigger').toggleClass('search-is-visible');\n $('.main__overlay').toggleClass('search-is-visible');\n $('.notification__container').toggleClass('search-is-visible');\n ($('.cart__container').hasClass('is-visible')) ? $('.main__overlay').addClass('is-visible') : $('.main__overlay').removeClass('is-visible');\n\n // Analytics event: view: \"view_shopping_cart\"\n try {\n let listProductsDTO = CartHelper.getProductFromDataJson().map((productDTO) => {\n return {\n itemId: productDTO.Product.ReferenceCode,\n itemName: productDTO.Product.Name,\n currency: appConstants.currency,\n discount: productDTO.Product.Discount,\n itemCategory: productDTO.Product.ProductCategory,\n itemCategory2: productDTO.Product.ProductGroup,\n classification: productDTO.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: productDTO.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: productDTO.Product.Price,\n quantity: productDTO.Quantity\n }\n })\n let priceValue = CartHelper.getTotalValueFromDataValue();\n if (priceValue >= 0) {\n $applicationMonitoringService\n .then(function (service) {\n service.trackCart(\n 'view', priceValue, listProductsDTO, appConstants.currency, 'Catalog')\n })\n .catch(function (err) {\n console.error(err);\n })\n }\n } catch (e) {\n console.error(e)\n }\n }\n}\n\nfunction toggleAddressManagement(type) {\n if (type == \"close\") {\n //cart serach \n $('.address-list-container').removeClass('is-visible');\n $('.main__overlay').removeClass('search-is-visible');\n } else {\n //toggle cart visibility\n $('.address-list-container').toggleClass('is-visible');\n $('.main__overlay').toggleClass('search-is-visible');\n ($('.address-list-container').hasClass('is-visible')) ? $('.main__overlay').addClass('is-visible') : $('.main__overlay').removeClass('is-visible');\n }\n}\n\nfunction toggleNotification(type) {\n if (type == \"close\") {\n //cart serach \n $('.notification__container').removeClass('is-visible');\n $('.mh__search-trigger').removeClass('search-is-visible');\n $('.main__overlay').removeClass('search-is-visible');\n $('.cart__container').removeClass('search-is-visible');\n } else {\n //toggle cart visibility\n $('.notification__container').toggleClass('is-visible');\n $('.mh__search-trigger').toggleClass('search-is-visible');\n $('.main__overlay').toggleClass('search-is-visible');\n $('.cart__container').toggleClass('search-is-visible');\n ($('.notification__container').hasClass('is-visible')) ? $('.main__overlay').addClass('is-visible') : $('.main__overlay').removeClass('is-visible');\n }\n}\n\nfunction hideCollapseNotifications() {\n\n var i;\n let elements = document.querySelectorAll('[id^=\"collapseNotifications-\"]');\n\n for (i = 0; i < elements.length; i++) {\n let idItem = elements.item(i).id;\n\n $('#' + idItem).collapse('hide')\n }\n}\n\nfunction checkWindowWidth() {\n //check window width (scrollbar included)\n var e = window,\n a = 'inner';\n if (!('innerWidth' in window)) {\n a = 'client';\n e = document.documentElement || document.body;\n }\n if (e[a + 'Width'] >= MqL) {\n return true;\n } else {\n return false;\n }\n}\n\nfunction moveElementsOnResponsive() {\n if (!LeftMenu) {\n moveNavigation();\n } else {\n groupMenuonMobile();\n }\n moveSearchBar();\n if (WrapMenu) {\n wrapMenuonDesktop();\n }\n\n}\n\nfunction wrapMenuonDesktop() {\n var desktop = checkWindowWidth();\n var categoriesList = $('.mh__secondary-nav');\n if (desktop) {\n if (!categoriesList.parent('div.mh__secondary-nav-wrapper').length) {\n categoriesList.wrap('
')\n }\n } else {\n //wrap dropmenu to allow scroll\n if (categoriesList.parent('div.mh__secondary-nav-wrapper').length) {\n categoriesList.unwrap();\n }\n }\n}\n\nfunction groupMenuonMobile() {\n var navigation = $('.main-header__nav');\n var mainMenu = $('.main-categories-menu');\n var desktop = checkWindowWidth();\n navigation.detach();\n if (desktop) {\n if (!$('#headerMenu').has('.main-header__nav').length) {\n mainMenu.detach();\n navigation.insertBefore('.mh__header-buttons');\n }\n if (!$('.main__content').next('.main-header__nav').length) {\n $('.main-categories-wrapper').hide();\n mainMenu.insertAfter('.main__content');\n if (LeftMenuAlwaysVisible) {\n mainMenu.removeClass('mh__secondary-nav').removeClass('is-hidden').addClass('mh__primary-nav-fs');\n } else {\n mainMenu.removeClass('mh__secondary-nav').removeClass('is-hidden').addClass('mh__primary-nav-hb');\n }\n mainMenu.wrap('');\n mainMenu.find('>.go-back').hide();\n }\n } else {\n if (!$('.main__content').next('.main-header__nav').length) {\n navigation.detach();\n navigation.insertAfter('.main__content');\n }\n if (!$('.main-categories-wrapper').children('a').next('.main-categories-menu').length) {\n mainMenu.detach();\n $('.main-categories-wrapper').show();\n mainMenu.insertAfter('.main-categories-wrapper>a');\n if (LeftMenuAlwaysVisible) {\n mainMenu.removeClass('mh__primary-nav-fs').addClass('mh__secondary-nav');\n } else {\n mainMenu.removeClass('mh__primary-nav-hb').addClass('mh__secondary-nav');\n }\n mainMenu.find('>.go-back').show();\n }\n }\n}\n\nfunction moveNavigation() {\n /** Remove address menus in desktop and add in mobile*/\n var navigation = $('.main-header__nav');\n var desktop = checkWindowWidth();\n const addressNav = $(\".mh__primary-nav > li.main-header__nav--include\");\n const addressNavPrimary = $(\".mh__address-bar .mh__primary-nav\");\n addressNav.detach();\n navigation.detach();\n if (desktop) {\n addressNavPrimary.show();\n addressNavPrimary.append(addressNav);\n navigation.insertBefore('.mh__header-buttons');\n } else {\n addressNavPrimary.hide();\n navigation.find(\".mh__primary-nav\").append(addressNav);\n navigation.insertAfter('.main__content');\n }\n}\n\nfunction moveSearchBar() {\n var desktop = checkWindowWidth();\n\n var searchBarTop = $('.search--bar-content-top');\n var searchBarBottom = $('.search--bar-content-bottom');\n if (desktop) {\n searchBarTop.css(\"display\", \"block\");\n searchBarBottom.css(\"display\", \"none\");\n } else {\n searchBarTop.css(\"display\", \"none\");\n searchBarBottom.css(\"display\", \"block\");\n }\n}\n\nasync function branchofficeUserSelected() {\n const confirmResult = await browserCommunicatorService.displayQuestionAlert({\n description: 'Vas a cambiar de sitio, esto recarga la tienda y limpia tu carrito. ¿Deseas continuar?'\n })\n\n if (!confirmResult.isConfirmed) {\n return;\n }\n\n var branchOfficeId = $(\".branchoffice-user-selected option:selected\").val();\n app.storeService.setBranchOfficeSelected(branchOfficeId, async function (response) {\n if (response) {\n await trackUserFromAddressAsync(response)\n window.location.href = '/';\n }\n }, function (response) {\n });\n}\n\nasync function branchofficeWithoutRegistrationSelected() {\n const confirmResult = await browserCommunicatorService.displayQuestionAlert({\n description: 'Vas a cambiar de sitio, esto recarga la tienda y limpia tu carrito. ¿Deseas continuar?'\n })\n\n if (confirmResult.isConfirmed) {\n var branchOfficeId = $(\".branchoffice-selected option:selected\").val();\n app.storeService.setBranchOfficeSelected(branchOfficeId, function (response) {\n if (response) {\n window.location.href = '/';\n }\n }, function (response) {\n });\n }\n}\n\nasync function trackUserFromAddressAsync(response) {\n await CustomerAnalyticsHelper.trackUserFromAddressAsync(response.Value);\n}\n\nfunction getCitiesByState(event) {\n var stateId = $(\"#stateSelectId option:selected\").val();\n if (app.storeService != null && stateId != null) {\n app.storeService.getCitiesByState(stateId, function (response) {\n if (response != null) {\n $(\"#citySelectId\").empty();\n\n $(\"#citySelectId\").append('');\n\n $.each(response, function (i, city) {\n $(\"#citySelectId\").append('');\n });\n\n var cityId = $(\"#UserCityId\").val();\n $(\"#citySelectId option[id=\" + cityId + \"]\").attr(\"selected\", true);\n }\n }, function (response) {\n });\n }\n}\n\nasync function setCityCustomer() {\n var stateId = $(\"#UserStateId\").val();\n var cityId = $(\"#UserCityId\").val();\n\n $('#citySelector').modal('hide');\n\n if (!stateId || !cityId) {\n await browserCommunicatorService.displayErrorAlert({ description: 'Debes seleccionar el Departamento y la Ciudad.' })\n $(\"#citySelector\").modal(\"show\");\n return;\n }\n\n const confirmResult = await browserCommunicatorService.displayQuestionAlert({\n description: 'Vas a cambiar de sitio, esto recarga la tienda y limpia tu carrito. ¿Deseas continuar?'\n })\n\n if (confirmResult.isConfirmed) {\n var cityDataItem = $(\"#UserCityId\").data(\"kendoDropDownList\").dataItem();\n var stateDataItem = $(\"#UserStateId\").data(\"kendoDropDownList\").dataItem();\n var branchOfficeId = cityDataItem.BranchOfficeId;\n\n var state = {\n Id: stateDataItem.Id,\n CountryId: stateDataItem.CountryId,\n Code: stateDataItem.Code,\n Name: stateDataItem.Name,\n };\n\n var city = {\n CityId: cityDataItem.CityId,\n CityName: cityDataItem.CityName,\n BranchOfficeId: cityDataItem.BranchOfficeId,\n BranchOfficeReferenceCode: cityDataItem.BranchOfficeReferenceCode,\n Code: cityDataItem.Code,\n };\n\n app.storeService.setBranchOfficeWithoutRegistrationSelected(branchOfficeId, state, city, function (response) {\n if (response != null && response == true) {\n window.location.href = '/';\n }\n }, function (response) { });\n\n } else {\n $(\"#citySelector\").modal(\"show\");\n }\n}\n\nfunction toggleNav() {\n var navIsVisible = (!$('.cd-dropdown').hasClass('dropdown-is-active')) ? true : false;\n $('.cd-dropdown').toggleClass('dropdown-is-active', navIsVisible);\n $('.cd-dropdown-trigger').toggleClass('dropdown-is-active', navIsVisible);\n if (!navIsVisible) {\n $('.cd-dropdown').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {\n $('.has-children ul').addClass('is-hidden');\n $('.move-out').removeClass('move-out');\n $('.is-active').removeClass('is-active');\n });\n }\n}","import UrlHelper from '../helpers/url-helper.js';\nimport AjaxProxy from '../proxies/ajax-proxy.js';\n\nclass ProductService {\n\n getProductsByName(productName, callback) {\n let url = UrlHelper.getProductsByNameUrl;\n let requestData = { productName: productName };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n /**\n * \n * @param productName {string}\n */\n getProductsByNameAsync(productName) {\n const formData = new FormData()\n formData.append(\"productName\", productName)\n \n return AjaxProxy.postFetch(UrlHelper.getProductsByNameUrl, {\n body: formData\n })\n }\n}\n\nexport default ProductService","\nclass IndexHandlers {\n\n constructor() {\n }\n\n static init() {\n bindIndexControl();\n }\n}\n\nexport default IndexHandlers;\n\nfunction bindIndexControl() {\n \n $('#SortCategoryMain').on('changed.bs.select', changedSortProducts);\n\n}\n\n/**\n * Handle of change of selectpicker.\n * @param {any} e\n * @param {any} clickedIndex\n * @param {boolean} isSelected\n * @param {any} previousValue\n */\nfunction changedSortProducts(e, clickedIndex, isSelected, previousValue) {\n // dispatch \"filter_option\" analytics event.\n try {\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackFilter('option', document.title)\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n}\n","import AjaxProxy from \"../proxies/ajax-proxy\";\nimport { BonusGiftResponse, IsAuthenticatedResponse } from '../domain'\nimport { Observable, of, throwError } from 'rxjs'\nimport { map, catchError } from 'rxjs/operators'\nimport { AjaxError, AjaxResponse } from 'rxjs/ajax'\nimport UrlHelper from \"../helpers/url-helper\";\n\nexport default class BonusService {\n\n /**\n * @returns {Observable}\n * */\n getCustomerBonusAsync() {\n return AjaxProxy.getRxJson({\n url: UrlHelper.bonusByCustomer\n }).pipe(\n map(ajaxResponse => ajaxResponse.response),\n catchError(err => {\n if (err instanceof AjaxError) {\n\n /**@type{AjaxError} */\n let ajaxError = err;\n if (ajaxError.status === 401) {\n /** @type {BonusGiftResponse} */\n let response = {\n AvailableValue: 0,\n Successful: false\n }\n return of(response)\n }\n\n return throwError(err)\n }\n else {\n console.error(err);\n return throwError(err)\n }\n\n })\n );\n }\n\n /**\n * apply bonus in shoppingcart\n * @param {BonusGiftResponse} bonusResponse\n * @returns {Observable<{Successful: true}>}\n */\n postApplyBonusInShoppingCart(bonusResponse) {\n return AjaxProxy.postRxJson({\n url: UrlHelper.applyBonusInShoppingCart,\n body: JSON.stringify(bonusResponse),\n }).pipe(\n map(ajaxResponse => ajaxResponse.response),\n catchError(err => {\n if (err instanceof AjaxError) {\n /**@type{AjaxError} */\n let ajaxError = err;\n if (ajaxError.status === 401) {\n return of({\n Successful: false\n })\n }\n return throwError(err)\n } else {\n console.error(err);\n return throwError(err)\n }\n })\n );\n }\n\n}","import { BehaviorSubject } from 'rxjs'\n\nexport class BonusLoaderHandlers {\n constructor() {\n this._loading = new BehaviorSubject(false);\n this.loading$ = this._loading.asObservable();\n }\n /**\n * \n * @param {boolean} value\n */\n loading(value = true) {\n this._loading.next(value)\n }\n}\n\nwindow.bonusLoaderHandlers = new BonusLoaderHandlers();\nexport default new BonusLoaderHandlers();","import BonusService from \"../services/bonus-service.js\";\nimport { defer, forkJoin, iif, Observable, of, catchError } from 'rxjs';\nimport { finalize, map, scan, switchMap } from 'rxjs/operators';\nimport bonusLoaderHandler from \"./bonus-loader-handler.js\";\nimport { BonusGiftResponse } from \"../domain/index.js\";\n\nexport default class BonusHandlers {\n\n /**\n * @type {BonusService}\n */\n bonusService;\n\n /***\n * @type {Observable}\n * */\n customerBonusGift$;\n\n constructor() {\n this.bonusService = new BonusService();\n }\n\n /**\n * Load customer bonus\n * @returns {Observable}\n * */\n loadCustomerBonusAsync() {\n this.toggleLoading(true);\n\n this.customerBonusGift$ = this.bonusService.getCustomerBonusAsync().pipe(\n switchMap(bonusResponse => forkJoin(\n of(bonusResponse),\n this.bonusService.postApplyBonusInShoppingCart(bonusResponse)\n )),\n map(response => {\n return response[0]\n }),\n finalize(_ => {\n this.toggleLoading(false);\n })\n )\n\n return this.customerBonusGift$;\n }\n\n toggleLoading(load = true) {\n bonusLoaderHandler.loading(load);\n }\n\n}","import UrlHelper from '../helpers/url-helper.js'\nimport AjaxProxy from '../proxies/ajax-proxy.js'\n\nimport ShoppingCartHandlers from '../shared/shopping-cart/handlers/shopping-cart-handlers'\nimport AccountHandlers from '../handlers/account-handlers.js'\nimport MenuNavHandlers from '../handlers/menu-nav-handlers.js'\n\nimport ProductService from './product-service.js'\nimport ShoppingCartService from '../shared/shopping-cart/services/shopping-cart-service'\nimport IndexHandlers from '../handlers/index-handlers.js'\nimport BonusHandlers from '../handlers/bonus-handlers.js'\nimport { map, switchMap } from 'rxjs'\nimport CartHelper from '../helpers/cart-helper.js'\nimport ModalHelper from '../helpers/modal-helper.js'\nimport { BrowserCommunicatorService } from './browser-communicator-service.js'\nimport AddedPredictiveSearchEvent from \"../shared/shopping-cart/events/added-predictive-search-event\"\n\nlet shoppingCartService = new ShoppingCartService();\nlet productService = new ProductService();\n\nlet shoppingCartContainerSelector = '.cart__container';\n\nclass StoreService {\n\n _endpoints = {\n clearFilters: \"?handler=ClearFilter\",\n applyFilter: \"?handler=ApplyFilter\",\n applyOrder: \"?handler=ApplyOrder\",\n loadMore: \"?handler=LoadMore\"\n }\n\n /**\n * @type {BonusHandlers}\n * */\n _bonusHandlers;\n\n constructor(inits = true) {\n this._bonusHandlers = new BonusHandlers();\n this._shoppingCartHandlers = new ShoppingCartHandlers()\n this._browserCommunicatorService = new BrowserCommunicatorService();\n\n if (inits) {\n this._shoppingCartHandlers.init()\n MenuNavHandlers.init();\n AccountHandlers.init();\n IndexHandlers.init();\n }\n }\n\n /**\n * method use only in predictive search - should be replace\n * @param {any} productId\n * @param {any} image\n * @param {any} failCallback\n * @returns\n */\n async addItemToCart(productId, image, failCallback) {\n app.cartHelper.updateCart(image);\n try {\n\n /** @type {Response} */\n const response = await this.shoppingCart.addItemAsync(1, productId, false)\n if (!response.ok) {\n return;\n }\n\n const value = await response.json();\n if (!value.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: value.UserMessage\n })\n return;\n }\n\n const shoppingCartItemChangedResponse = value.Value;\n if (!shoppingCartItemChangedResponse.Successed) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n return;\n }\n else if (shoppingCartItemChangedResponse.Message) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n\n AddedPredictiveSearchEvent.added({\n productId: productId,\n shoppingCartItemChanged: shoppingCartItemChangedResponse\n });\n \n } catch (e) {\n failCallback(e)\n }\n }\n\n /**\n * \n * @param {[]} products\n */\n async addItemsToCart(products) {\n const response = await this.shoppingCart.addItemsAsync(products)\n if (!response.ok) {\n return;\n }\n \n const shoppingCartItemChangedResponse = (await response.json()).Value;\n if (!shoppingCartItemChangedResponse.Successed) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n return;\n }\n else if (shoppingCartItemChangedResponse.Message) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: shoppingCartItemChangedResponse.Message,\n html: true\n })\n }\n\n /** @type {Response} */\n const cartResponse = await this.shoppingCart.getViewAsync(productId)\n if (!cartResponse.ok) {\n return;\n }\n\n $(shoppingCartContainerSelector).html(await cartResponse.text());\n this.bindShoppinCartControlHandlers();\n\n }\n\n getProductsByName(productName, callback) {\n productService.getProductsByName(productName, callback);\n }\n\n /**\n * \n * @param productName {string}\n */\n getProductsByNameAsync(productName){\n return productService.getProductsByNameAsync(productName)\n }\n \n getProductDetailView(productId, callback) {\n let url = UrlHelper.getSelectedProductDetailViewUrl;\n let requestData = { productId: productId };\n let request = {\n url: url,\n dataType: 'html',\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n emptyCart(callback) {\n this.shoppingCart.empty(callback);\n }\n\n bindShoppinCartControlHandlers() {\n this._shoppingCartHandlers.bindShoppinCartControlHandlers();\n }\n\n async loadShoppingCart() {\n await this._shoppingCartHandlers.loadShoppingCart();\n this.bindShoppinCartControlHandlers();\n }\n\n updateShoppingCartTotal(value, valueFormatted) {\n this._shoppingCartHandlers.updateShoppingCartTotal(value, valueFormatted)\n }\n\n updateShoppingCartQuantity() {\n this._shoppingCartHandlers.updateShoppingCartQuantity();\n }\n\n displayEmptyCart() {\n this._shoppingCartHandlers.displayEmptyCart();\n }\n\n get shoppingCart() {\n return shoppingCartService;\n }\n\n pagesTotalsAsync() {\n return AjaxProxy.getFetch(UrlHelper.pagesTotalsUrl, {});\n }\n\n setBranchOfficeSelected(branchOfficeId, successCallback, failCallback) {\n let url = UrlHelper.setBranchOfficeSelected;\n let requestData = { branchOfficeId: branchOfficeId };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n setBranchOfficeWithoutRegistrationSelected(branchOfficeId, stateDataItem, cityDataItem, successCallback, failCallback) {\n let url = UrlHelper.setBranchOfficeWithoutRegistrationSelected;\n let requestData = { branchOfficeId: branchOfficeId, state: stateDataItem, city: cityDataItem };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n getCitiesByState(stateId, successCallback, failCallback) {\n let url = UrlHelper.getCitiesByState;\n let requestData = { stateId: stateId };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n /**\n * \n * @param {Response | XMLHttpRequest} response\n */\n async handleErrorCartResponseAsync(response) {\n if (response.status === 401) {\n await this._browserCommunicatorService.displayErrorAlert({ description: \"No esta autorizado para realizar esta acción\" })\n }\n var spinnerWait = $(this).closest('.product-card').find(\".spinner-border-sm\").eq(0);\n spinnerWait.addClass(\"d-none\");\n }\n\n _loadBonusGift() {\n shoppingCartService.getViewRx().pipe(\n ).subscribe(shoppingCartHtml => {\n document.querySelector('.cart__container').innerHTML = shoppingCartHtml;\n app.storeService.bindShoppinCartControlHandlers();\n })\n }\n\n animateCartForBanner(el) {\n CartHelper.animateCartForBanner()\n }\n\n async clearFiltersAsync(sortSetting, categoryId= null, productNameToSearch = null) {\n const data = new FormData()\n data.append(\"SortSetting\", sortSetting);\n\n if (categoryId) {\n data.append(\"categoryId\", categoryId);\n }\n\n if (productNameToSearch) {\n data.append(\"productNameToSearch\", productNameToSearch)\n }\n\n return AjaxProxy.postFetch(this._endpoints.clearFilters, { body: data })\n }\n\n /**\n * \n * @param {[]} classificationIds\n * @param {[]} manufactureIds\n * @param {[]} productBrandIds\n * @param {string} filterSetting\n * @param {string} sortSetting\n * @returns\n */\n async applyFiltersAsync(classificationIds, manufactureIds, productBrandIds, filterSetting, sortSetting, categoryId = null, productNameToSearch = null) {\n const data = new FormData()\n data.append(\"sortSetting\", sortSetting);\n data.append(\"filterSetting\", filterSetting);\n\n if (categoryId) {\n data.append(\"categoryId\", categoryId);\n }\n\n if (productNameToSearch) {\n data.append(\"productNameToSearch\", productNameToSearch);\n }\n\n if (classificationIds) {\n for (var i = 0; i < classificationIds.length; i++) {\n data.append(`classificationIds[]`, classificationIds[i]);\n }\n }\n\n if (manufactureIds) {\n for (var i = 0; i < manufactureIds.length; i++) {\n data.append(`manufactureIds[]`, manufactureIds[i]);\n }\n }\n\n if (productBrandIds) {\n for (var i = 0; i < productBrandIds.length; i++) {\n data.append(`productBrandIds[]`, productBrandIds[i]);\n }\n }\n\n return AjaxProxy.postFetch(this._endpoints.applyFilter, { body: data })\n }\n\n /**\n * \n * @param {[]} classificationIds\n * @param {[]} manufactureIds\n * @param {[]} productBrandIds\n * @param {string} filterSetting\n * @param {string} sortSetting\n * @returns\n */\n async applyOrderAsync(classificationIds, manufactureIds, productBrandIds, filterSetting, sortSetting, categoryId = null, productNameToSearch = null) {\n const data = new FormData()\n data.append(\"sortSetting\", sortSetting);\n data.append(\"filterSetting\", filterSetting);\n \n if (categoryId) {\n data.append(\"categoryId\", categoryId);\n }\n\n if (productNameToSearch) {\n data.append(\"productNameToSearch\", productNameToSearch);\n }\n\n if (classificationIds) {\n for (var i = 0; i < classificationIds.length; i++) {\n data.append(`classificationIds[]`, classificationIds[i]);\n }\n }\n\n if (manufactureIds) {\n for (var i = 0; i < manufactureIds.length; i++) {\n data.append(`manufactureIds[]`, manufactureIds[i]);\n }\n }\n\n if (productBrandIds) {\n for (var i = 0; i < productBrandIds.length; i++) {\n data.append(`productBrandIds[]`, productBrandIds[i]);\n }\n }\n\n return AjaxProxy.postFetch(this._endpoints.applyOrder, { body: data })\n }\n\n /**\n * \n * @param {[]} classificationIds\n * @param {[]} manufactureIds\n * @param {[]} productBrandIds\n * @param {string} filterSetting\n * @param {string} sortSetting\n * @returns\n */\n async loadMoreAsync(classificationIds, manufactureIds, productBrandIds, filterSetting, sortSetting, categoryId = null, productNameToSearch = null) {\n const data = new FormData()\n data.append(\"sortSetting\", sortSetting);\n data.append(\"filterSetting\", filterSetting);\n\n if (categoryId) {\n data.append(\"categoryId\", categoryId)\n }\n\n if (productNameToSearch) {\n data.append(\"productNameToSearch\", productNameToSearch);\n }\n\n if (classificationIds) {\n for (var i = 0; i < classificationIds.length; i++) {\n data.append(`classificationIds[]`, classificationIds[i]);\n }\n }\n\n if (manufactureIds) {\n for (var i = 0; i < manufactureIds.length; i++) {\n data.append(`manufactureIds[]`, manufactureIds[i]);\n }\n }\n\n if (productBrandIds) {\n for (var i = 0; i < productBrandIds.length; i++) {\n data.append(`productBrandIds[]`, productBrandIds[i]);\n }\n }\n\n return AjaxProxy.postFetch(this._endpoints.loadMore, { body: data })\n }\n \n getCouponListView() {\n return AjaxProxy.postFetch(this._endpoints.couponListView, {})\n }\n}\n\nexport default StoreService;","/*\n\n */\nimport {ServiceBase} from \"../service/service-base\";\n\nexport class CacheServiceBase extends ServiceBase{\n constructor() {\n super()\n }\n\n /**\n * \n * @param key {string}\n * @param value {any}\n * @param ttl {number}\n */\n setWithExpiry(key, value, ttl) {\n const now = new Date()\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n }\n localStorage.setItem(key, JSON.stringify(item))\n }\n\n /**\n * \n * @param key {string}\n * @returns {*|null}\n */\n getWithExpiry(key) {\n const itemStr = localStorage.getItem(key)\n // if the item doesn't exist, return null\n if (!itemStr) {\n return null\n }\n const item = JSON.parse(itemStr)\n const now = new Date()\n // compare the expiry time of the item with the current time\n if (now.getTime() > item.expiry) {\n // If the item is expired, delete the item from storage\n // and return null\n localStorage.removeItem(key)\n return null\n }\n return item.value\n }\n}","import {CacheServiceBase} from \"../../cache\";\nimport AjaxProxy from \"../../../proxies/ajax-proxy\";\nimport UrlHelper from \"../../../helpers/url-helper\";\nimport { CultureSettings } from '../domain'\n\nexport class CultureSettingsCacheService extends CacheServiceBase {\n \n _key = \"culture_setting\"\n _expiration = 5000\n \n constructor() {\n super();\n }\n\n /**\n * \n * @returns {Promise}\n */\n async getAsync(){\n let culture = this.getWithExpiry(this._key)\n if (!culture){\n const response = await AjaxProxy.getFetch(UrlHelper.getCultureSettings, {})\n if (!response.ok)\n return {};\n \n const json = await response.json()\n culture = json.Value\n this.setWithExpiry(this._key, culture, this._expiration)\n }\n return culture\n }\n}","import {ServiceBase} from \"../../service/service-base\";\nimport AjaxProxy from \"../../../proxies/ajax-proxy\";\nimport UrlHelper from \"../../../helpers/url-helper\";\nimport {CultureSettingsCacheService} from \"./culture-settings-cache-service\";\n\nexport class CultureFormatterService extends ServiceBase {\n constructor() {\n super();\n \n this._cultureSettings = new CultureSettingsCacheService()\n }\n\n /**\n *\n * @param value {number}\n * @returns {Promise}\n */\n async formatCurrencyAsync(value) {\n const cultureSettings = await this._cultureSettings.getAsync()\n const valueLocalString = value.toLocaleString(cultureSettings.Name)\n \n const formData = new FormData()\n formData.append(\"value\", valueLocalString)\n const response = await AjaxProxy.postFetch(UrlHelper.postCurrencyFormatter, {\n body: formData\n })\n \n if (!response.ok) {\n return valueLocalString\n }\n \n const json = await response.json()\n return json.Value\n }\n}","export const productTypes = Object.freeze({\n ProductType_KD: \"KD\"\n})","import { HandlerBase } from \"../shared/handler/handler-base\";\nimport 'jquery'\nimport StoreService from '../services/store-service'\nimport { $applicationMonitoringService } from '../shared/application-monitoring'\nimport {CultureFormatterService} from \"../shared/culture\";\nimport { productTypes } from \"../shared/constants/product-constants\";\n\nexport class PredictiveSearchProductHandlers extends HandlerBase {\n\n constructor() {\n super()\n\n this._storeService = new StoreService(false)\n this._cultureFormatterService = new CultureFormatterService()\n }\n\n init() {\n //Create the predictive product search\n $('.main-header__search-bar').autocomplete({\n source: async (request, response) => {\n let productName = $.trim(request.term);\n\n if (productName.length < 3) {\n return;\n }\n\n const responseProducts = await this._storeService.getProductsByNameAsync(productName)\n if (!responseProducts.ok){\n return;\n }\n\n const productFilterResponse = await responseProducts.json();\n const responseList = []\n for (let productCard of productFilterResponse.Items) {\n let product = productCard.ProductStoreInformation\n responseList.push({\n label: product.Name.substring(0, 30) + '...',\n value: product.Name,\n productId: product.ProductBranchOfficeId,\n imgsrc: productCard.ImageFullPath,\n price: await this._cultureFormatterService.formatCurrencyAsync(product.NewPrice == 0 ? product.Price : product.NewPrice),\n secondPrice: product.NewPrice == 0 ? \"\" : await this._cultureFormatterService.formatCurrencyAsync(product.Price),\n rawJSON: JSON.stringify(product),\n showPriceAndButton: productFilterResponse.ShowPriceAndButton,\n soldOut: productCard.HasSoldOutInformation,\n soldOutLabel: productCard.SoldOutInformation?.SoldOutLabel,\n isDynamicKit: product.ProductType === productTypes.ProductType_KD\n })\n }\n\n // resolve\n response(responseList)\n },\n search: function (event, ui) {\n // dispatch search analytics event.\n let searchTerm = event.target.value;\n try {\n $applicationMonitoringService\n .then(function (service) {\n service.trackSearch(searchTerm);\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n },\n create: function (event, ui) {\n $(this).data(\"ui-autocomplete\")._renderItem = function (ul, item) {\n ul.addClass('searched-product');\n\n let priceInfo = (item.showPriceAndButton && !item.isDynamicKit) ? `${item.price} ${item.secondPrice}` : ` `;\n let buttonInfo;\n if (item.isDynamicKit) {\n buttonInfo = (!item.soldOut && item.showPriceAndButton) ? `` : ` `;\n } else {\n buttonInfo = (!item.soldOut && item.showPriceAndButton) ? `` : ` `;\n }\n\n if (item.soldOut) {\n priceInfo = item.soldOutLabel\n }\n\n let showInfoSearch =\n `
\n \n
\n
${item.label}
\n

\n ${priceInfo}\n

\n \n
\n
\n ${buttonInfo}\n
\n
`;\n\n return $(\"
  • \")\n .data(\"item.autocomplete\", item)\n .append(showInfoSearch)\n .appendTo(ul);\n };\n }\n });\n }\n\n /**\n * Obsolete use handler instance\n * */\n static init(app) {\n const predictiveSearchProductHandlers = new PredictiveSearchProductHandlers()\n predictiveSearchProductHandlers.init()\n }\n}\n","import { Subject } from 'rxjs'\n\nexport class AddProductKitSearchEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{productId: string, loadingTarget: HTMLElement}} args\n */\n addProductKitToCart(args) {\n this._subject.next({\n productBranchOfficeId: args.productId,\n loadingTarget: args.loadingTarget\n });\n }\n}\n\nconst event = new AddProductKitSearchEvent();\nexport default event;","import { ServiceBase } from \"../../shared/service/service-base\";\nimport AjaxProxy from \"../../proxies/ajax-proxy\"\n\nexport class ProductDetailService extends ServiceBase {\n\n get _endpoints() {\n return {\n getProduct: `/api/ProductDetail/SelectedProduct`\n }\n }\n\n constructor() {\n super()\n }\n\n getProductDetail(productId) {\n return AjaxProxy.getFetch(`${this._endpoints.getProduct}/${productId}`, {});\n }\n\n}","import { ProductDetailService } from \"../../product-detail/services/product-detail-service\"\nimport { $applicationMonitoringService } from '../../shared/application-monitoring';\nimport { appConstants } from '../../enums/site-enum.js';\nimport { analytics } from 'apollo-web'\n\nexport class ProductAnalyticsHelper {\n constructor() {\n this._productDetailService = new ProductDetailService();\n }\n\n async trackCart(action, productSource, productId) {\n try {\n const response = await this._productDetailService.getProductDetail(productId);\n if (!response.ok) {\n return;\n }\n\n const productDTO = (await response.json()).Value.ProductDetailInformation;\n const applicationMonitoringService = await $applicationMonitoringService;\n\n applicationMonitoringService.trackCart(action, productDTO.Price, [{\n itemId: productDTO.ReferenceCode,\n itemName: productDTO.Name,\n currency: appConstants.currency,\n discount: productDTO.Discount,\n itemCategory: productDTO.ProductCategory,\n itemCategory2: productDTO.ProductGroup,\n classification: productDTO.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: productDTO.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: productDTO.Price,\n quantity: 1\n }], appConstants.currency, productSource);\n\n } catch (e) {\n console.error(e);\n }\n }\n\n /**\n * \n * @param {string} productSource\n * @param {string} productId\n * @returns\n */\n async trackDetail(productSource, productId) {\n try {\n const response = await this._productDetailService.getProductDetail(productId);\n if (!response.ok) {\n return;\n }\n\n const product = (await response.json()).Value.ProductDetailInformation;\n const applicationMonitoringService = await $applicationMonitoringService;\n\n applicationMonitoringService.trackDetailProduct(product.Price, [{\n itemId: product.ReferenceCode,\n itemName: product.Name,\n currency: appConstants.currency,\n discount: product.Discount,\n itemCategory: product.ProductCategory,\n itemCategory2: product.ProductGroup,\n price: product.Price,\n quantity: 1\n }], appConstants.currency, productSource);\n\n } catch (e) {\n console.error(e)\n }\n }\n\n async trackImage(imageName, imageNumber, productId) {\n try {\n const response = await this._productDetailService.getProductDetail(productId);\n if (!response.ok) {\n return;\n }\n\n const product = (await response.json()).Value.ProductDetailInformation;\n const applicationMonitoringService = await $applicationMonitoringService;\n\n applicationMonitoringService.trackProductImage(\n imageName,\n imageNumber,\n product.Name,\n product.ReferenceCode,\n product.Price,\n product.DiscountPercentage,\n product.Discount,\n null);\n } catch (e) {\n console.error(e);\n }\n }\n}","import { appConstants } from '../enums/site-enum.js';\nimport ModalHelper from '../helpers/modal-helper.js';\nimport { $applicationMonitoringService } from '../shared/application-monitoring';\nimport { BrowserCommunicatorService } from '../services/browser-communicator-service'\nimport { analytics } from 'apollo-web'\nimport AddProductKitSearchEvent from \"../shared/dynamic-kits/events/add-product-kit-search-event.js\"\nimport { ProductAnalyticsHelper } from \"../shared/helper/product-analytics-helper\"\n\nvar _browserCommunicatorService = new BrowserCommunicatorService()\nclass AppHandlers {\n\n static _message;\n constructor() {\n }\n\n static init() {\n BindMenu();\n BindSession();\n\n this._setQueryParams();\n if (this._message) {\n _browserCommunicatorService.displayInfoAlert({\n description: this._message,\n html: true\n })\n }\n }\n\n static _setQueryParams() {\n const params = new Proxy(new URLSearchParams(window.location.search), {\n get: (searchParams, prop) => searchParams.get(prop),\n });\n\n // Get the value of \"some_key\" in eg \"https://example.com/?some_key=some_value\"\n this._message = params.message;\n }\n\n static addProductToCartHandler(element, event) {\n\n event.stopPropagation();\n event.preventDefault();\n\n // dispatch \"add to cart\" analytics event.\n let productId = app.productHelper.getProductId(element);\n\n const productAnalyticsHelper = new ProductAnalyticsHelper();\n productAnalyticsHelper.trackCart(\"add\", \"Catalog\", productId);\n\n let image = $(element).closest('.ui-menu-item-wrapper').find('img')\n app.storeService.addItemToCart(productId, image, app.storeService.handleErrorCartResponseAsync);\n }\n\n static async addProductKitToCartHandler(element, event) {\n\n event.stopPropagation();\n event.preventDefault();\n\n let productId = app.productHelper.getProductId(element);\n AddProductKitSearchEvent.addProductKitToCart({ productId: productId, loadingTarget: element.parentNode })\n }\n}\n\nexport default AppHandlers;\n\nfunction BindMenu() {\n //ocultar el menu cuando se seleccione alguna opcion\n var navMain = $(\".navbar-collapse\"); // avoid dependency on #id\n // when you have dropdown inside navbar\n navMain.on(\"click\", \"a:not([data-bs-toggle='dropdown'])\", null, function () {\n navMain.collapse('hide');\n });\n\n //soporte para multinivel del menu\n $('.dropdown-submenu > a').on(\"click\", function (e) {\n var submenu = $(this);\n $('.dropdown-submenu .dropdown-menu').removeClass('show');\n submenu.next('.dropdown-menu').addClass('show');\n e.stopPropagation();\n });\n\n $('.dropdown').on(\"hidden.bs.dropdown\", function () {\n // hide any open menus when parent closes\n $('.dropdown-menu.show').removeClass('show');\n });\n\n // Category viewed Analytics events.\n let itemCategorityEls = document.querySelectorAll(\".menu-item-category\")\n if (itemCategorityEls) {\n for (let itemEl of itemCategorityEls) {\n itemEl.addEventListener('click', async function (e) {\n try {\n let applicationMonitoringService = await $applicationMonitoringService;\n applicationMonitoringService.trackMainTabbedClick({viewName: 'CategoriesView'});\n \n let categorityName = itemEl.title;\n let departmentName = itemEl.getAttribute(\"data-departmentName\");\n applicationMonitoringService.trackCategory({\n categoryName: categorityName,\n departmentName: departmentName\n });\n \n applicationMonitoringService.trackScreenView({viewName: 'CategoriesView'})\n } catch (e) {\n }\n });\n }\n }\n}\n\nfunction BindSession() {\n //config menu elements linked to hide/show config modules and toggle active state\n $('.config-menu').on('click', '.nav-link', function (event) {\n var element = $(this);\n element.addClass('active');\n element.parent().siblings().find('.nav-link').removeClass('active');\n var id = element.data('target');\n if (id != 'logoff') {\n displaySection(id);\n } else {\n //funcion para cerrar sesion\n }\n });\n}\n\nfunction displaySection(id) {\n var element = $('#' + id);\n element.siblings().hide();\n element.show();\n}\n","import \"jquery\"\nimport { fromEvent, Subscription } from \"rxjs\";\n\nexport class WizardForm {\n\n get _radioButtons() {\n return $(\".radio-group .radio\");\n }\n\n get _previousButton() {\n return $(`${this._options.previousButton}`);\n }\n\n get _nextButton() {\n return $(`${this._options.nextButton}`)\n }\n\n /** @type {{ id: string, previousButton: string, nextButton: string, onLeaveStep: (stepNumber: number, operation: \"next\" | \"previous\", button: JQuery) => Promise, scrollTop: boolean }} */\n _options = null;\n\n /** @type { JQuery }*/\n current_fs = null;\n\n /** @type { JQuery }*/\n next_fs = null;\n\n /** @type { JQuery }*/\n previous_fs = null;\n\n /** @type {number} */\n _opacity;\n\n /** @type {Subscription} */\n _nextSub;\n\n /** @type {Subscription} */\n _previousSub;\n\n /**\n * \n * @param {{ id: string, previousButton: string, nextButton: string, onLeaveStep: (stepNumber: number, operation: \"next\" | \"previous\", button: JQuery) => Promise, scrollTop: boolean }} options\n */\n constructor(options) {\n this._options = options \n\n if (this._options.scrollTop === undefined) {\n this._options.scrollTop = true;\n }\n }\n\n init() {\n this.bindWizardNext();\n this.bindWizardPrevious();\n\n this._radioButtons.on(\"click\", function () {\n $(this).parent().find(\".radio\").removeClass(\"selected\");\n $(this).addClass(\"selected\");\n });\n }\n\n bindWizardNext() {\n this._nextSub?.unsubscribe();\n this._nextSub = fromEvent(this._nextButton, \"click\").subscribe(async e => {\n const currentElement = $(e.currentTarget);\n let step = currentElement.data(\"step\");\n\n if (step <= -1) {\n return;\n }\n\n if (step) {\n this.current_fs = this._form.find(`#form-step-${step}`)\n this.next_fs = this._form.find(`#form-step-${step + 1}`)\n }\n else {\n this.current_fs = currentElement.parent();\n this.next_fs = currentElement.parent().next();\n }\n\n let stepNumber = this.current_fs.data(\"step\");\n\n let nexting = await this._options.onLeaveStep(stepNumber, \"next\", currentElement);\n if (nexting) {\n\n //Add Class Active\n this._getNextProgressLi.addClass(\"active\");\n\n //show the next fieldset\n this.next_fs.show();\n //hide the current fieldset with style\n this.current_fs.animate(\n { opacity: 0 },\n {\n step: (now) => {\n // for making fielset appear animation\n this.opacity = 1 - now;\n\n this.current_fs.css({\n display: \"none\",\n position: \"relative\",\n });\n this.next_fs.css({ opacity: this.opacity });\n },\n duration: 600,\n }\n );\n }\n else {\n currentElement.trigger(\"blur\")\n }\n\n if (this._options.scrollTop) {\n $('html, body').animate({ scrollTop: 0 }, 'slow')\n }\n })\n }\n\n bindWizardPrevious() {\n this._previousSub?.unsubscribe();\n this._previousSub = fromEvent(this._previousButton, \"click\").subscribe(async e => {\n const currentElement = $(e.currentTarget);\n let step = currentElement.data(\"step\");\n\n if (step <= -1) {\n return;\n }\n\n if (step) {\n this.current_fs = this._form.find(`#form-step-${step}`)\n this.previous_fs = this._form.find(`#form-step-${step - 1}`)\n }\n else {\n this.current_fs = currentElement.parent();\n this.previous_fs = currentElement.parent().prev();\n }\n\n let stepNumber = this.current_fs.data(\"step\");\n\n let nexting = await this._options.onLeaveStep(stepNumber, \"previous\", currentElement);\n if (nexting) {\n //Remove class active\n this._getCurrentProgressLi.removeClass(\"active\");\n\n //show the previous fieldset\n this.previous_fs.show();\n\n //hide the current fieldset with style\n this.current_fs.animate(\n { opacity: 0 },\n {\n step: (now) => {\n // for making fielset appear animation\n this.opacity = 1 - now;\n\n this.current_fs.css({\n display: \"none\",\n position: \"relative\",\n });\n this.previous_fs.css({ opacity: this.opacity });\n },\n duration: 600,\n }\n );\n }\n else {\n currentElement.trigger(\"blur\")\n }\n if (this._options.scrollTop) {\n $('html, body').animate({ scrollTop: 0 }, 'slow')\n }\n })\n }\n\n get _getNextProgressLi() {\n return $(\"#progressbar li\").eq($(\"fieldset\").index(this.next_fs));\n }\n\n get _getCurrentProgressLi() {\n return $(\"#progressbar li\").eq($(\"fieldset\").index(this.current_fs));\n }\n\n get _form() {\n return $(`${this._options.id}`)\n }\n}","import { map } from 'rxjs';\nimport UrlHelper from '../helpers/url-helper.js';\nimport AjaxProxy from '../proxies/ajax-proxy.js';\nimport { Observable } from 'rxjs';\n\nclass CustomerService {\n\n _endpoints = {\n postCustomerPositiveBalance: \"?handler=PositiveBalance\"\n }\n\n saveCustomer(customer, callback) {\n let url = UrlHelper.saveCustomer;\n let requestData = { customer: customer };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n getAddressView(addressEdit, callback) {\n let url = UrlHelper.getAddressView;\n let requestData = { address: addressEdit };\n let request = {\n url: url,\n dataType: 'html',\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n saveAddress(address, callback) {\n let url = UrlHelper.saveAddress;\n let requestData = { address: address };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n deleteAddress(addressId, callback) {\n let url = UrlHelper.deleteAddress;\n let requestData = { addressId: addressId };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n /// FIXME: Obsolete\n updatePassword(updatePasswordRequest, callback) {\n let url = UrlHelper.updatePassword;\n let requestData = { updatePasswordRequest: updatePasswordRequest };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n signUp(signUpRequest, callback, failCallback, errorCallback) {\n let url = UrlHelper.signUp;\n let requestData = { signUpRequest: signUpRequest };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n getCitiesByState(stateId, successCallback, failCallback) {\n let url = UrlHelper.getCitiesByState;\n let requestData = { id: stateId };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n getNeighborhoodsByCityId(cityId, successCallback, failCallback) {\n let url = UrlHelper.getNeighborhoodsByCityId;\n let requestData = { id: cityId };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n validationCode(code, sendCode, successCallback, failCallback) {\n let url = UrlHelper.validationCode;\n let requestData = { code: code, getSendCode: sendCode };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n reSendValidationCode(sendCode, successCallback, failCallback) {\n let url = UrlHelper.reSendValidationCode;\n let requestData = { getSendCode: sendCode };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n validatePassword(password, successCallback, failCallback) {\n let url = UrlHelper.validatePassword;\n let requestData = { password: password };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n authenticate(email, password, callback, failCallback) {\n let url = UrlHelper.authenticate;\n let requestData = { email: email, password: password };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n rememberPassword(userName, callback, failCallback) {\n let url = UrlHelper.rememberPasswordUrl;\n let requestData = { userName: userName };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n //#region B2C Services\n\n authenticateB2C(user, password, isMobileLogin, callback, failCallback) {\n let url = UrlHelper.authenticate;\n let requestData = { user: user, password: password, isMobileLogin: isMobileLogin };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n validationCodeB2C(sendCode, successCallback, failCallback) {\n let url = UrlHelper.validationCode;\n let requestData = { sendCodeRequest: sendCode };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n reSendValidationCodeB2C(sendCode, successCallback, failCallback) {\n let url = UrlHelper.reSendValidationCode;\n let requestData = { sendCodeRequest: sendCode };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n loginByMobileB2C(phoneNumber, callback, failCallback, errorCallback) {\n let url = UrlHelper.loginByMobileNumber;\n let requestData = { phoneNumber: phoneNumber };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n showConfirmationMessageSending(username, callback, failCallback, errorCallback) {\n let url = UrlHelper.confirmationMessageSending;\n let requestData = { username: username };\n let request = {\n url: url,\n dataType: 'html',\n data: requestData,\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n rememberPasswordWithMethod(username, method, callback, failCallback, errorCallback) {\n let url = UrlHelper.rememberPasswordWithMethod;\n let requestData = { username: username, method: method };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n //#endregion\n\n reloadAddressList(customerId, callback, failCallback, errorCallback) {\n let url = UrlHelper.realodAddressList;\n let requestData = { customerId: customerId };\n let request = {\n url: url,\n dataType: 'html',\n data: requestData,\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n reloadAddressListAsync(customerId) {\n return AjaxProxy.postFetch(UrlHelper.realodAddressList, {})\n }\n\n customerValidate(validationRequest, callback, failCallback, errorCallback) {\n let url = UrlHelper.customerValidate;\n let requestData = validationRequest;\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n //#region Withoutloginb2b\n authenticateWithoutloginb2b(user, password, isMobileLogin, redirectTo, callback, failCallback) {\n let url = UrlHelper.authenticate;\n let requestData = { username: user, password: password, isMobileLogin: isMobileLogin, RedirectTo: redirectTo };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n loginByMobileWithoutloginb2b(phoneNumber, callback, failCallback, errorCallback) {\n let url = UrlHelper.loginByMobileNumber;\n let requestData = { phoneNumber: phoneNumber };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n customerValidateWithoutloginb2bAsync(customerRegistrationFormData) {\n return AjaxProxy.postFetch(UrlHelper.customerValidate, { body: customerRegistrationFormData })\n }\n\n signUpWithoutloginb2bAsync(customerRequestFormData) {\n return AjaxProxy.postFetch(UrlHelper.signUp, {body: customerRequestFormData});\n }\n //#endregion\n\n getCustomer() {\n return AjaxProxy.getFetch(UrlHelper.getCustomer, {})\n }\n\n //#region ChangePassword\n \n sendVerificationCode(verificationCodeFormData) {\n return AjaxProxy.postFetch(UrlHelper.postSendVerificationCode, {\n body: verificationCodeFormData\n })\n }\n\n verifyAccount(accountVerificationFormData) {\n return AjaxProxy.postFetch(UrlHelper.postVerifyAccount, {\n body: accountVerificationFormData\n })\n }\n\n //#endregion\n\n saveInvoicesSelected(invoices, callback) {\n let url = UrlHelper.saveInvoicesSelectedUrl;\n let requestData = { invoices: invoices };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n //#region Pay your bills\n\n\n\n\n goToPayBills(requestData, callback, failCallback, errorCallback) {\n let url = UrlHelper.goToPayBills;\n let request = {\n url: url,\n data: requestData,\n dataType: 'json',\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n reloadPayments(callback, failCallback, errorCallback) {\n let url = UrlHelper.reloadPayments;\n let request = {\n url: url,\n dataType: 'html',\n callback: callback,\n failCallback: failCallback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n codeAccessValidation(codeAccess, callback) {\n let url = UrlHelper.codeAccessValidation;\n let requestData = { codeAccess: codeAccess };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n AjaxProxy.post(request);\n }\n\n //#endregion\n\n\n /**\n * /// FIXME: Obsolete\n * @param {FormData} deleteFormData\n * @returns {Response}\n */\n deleteAccount(deleteFormData) {\n return AjaxProxy.postFetch(UrlHelper.postDeleteAccount, { body: deleteFormData });\n }\n\n validateEmail(email, successCallback, failCallback) {\n let url = UrlHelper.validateEmail;\n let requestData = { email: email };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n validateAgreementCode(agreementCode, successCallback, failCallback) {\n let url = UrlHelper.validateAgreementCode;\n let requestData = { agreementCode: agreementCode };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n recoveryPassword(email, callback, failCallback) {\n let url = UrlHelper.recoveryPassword;\n let requestData = { email: email };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n pdfContentBase64(tipoDoc, nroDocument, customerAccount) {\n const requestFormData = new FormData();\n\n requestFormData.append(\"tipoDoc\", tipoDoc);\n requestFormData.append(\"nroDocument\", nroDocument);\n requestFormData.append(\"customerAccount\", customerAccount);\n\n let request = {\n body: requestFormData\n };\n\n return AjaxProxy.postFetch(UrlHelper.pdfContentBase64, request);\n }\n\n xmlContentBase64(tipoDoc, nroDocument, customerAccount) {\n const requestFormData = new FormData();\n\n requestFormData.append(\"tipoDoc\", tipoDoc);\n requestFormData.append(\"nroDocument\", nroDocument);\n requestFormData.append(\"customerAccount\", customerAccount);\n\n let request = {\n body: requestFormData\n };\n\n return AjaxProxy.postFetch(UrlHelper.xmlContentBase64, request);\n }\n\n\n postCustomerPositiveBalance() {\n return AjaxProxy.postFetch(this._endpoints.postCustomerPositiveBalance, {});\n }\n\n\n}\n\nexport default CustomerService;","import AjaxProxy from \"../../../proxies/ajax-proxy\";\nimport { ServiceBase } from \"../../service/service-base\"\n\nexport class CancelOrdersService extends ServiceBase {\n\n _endpoints = {\n cancelOrder: \"/api/cancelorders/cancelorders\",\n validateProcess: \"/api/cancelorders/validateprocess\"\n }\n\n constructor() {\n super();\n }\n\n /**\n * \n * @param {string} orderId\n * @param {string} process\n */\n cancelOrder(orderId, process) {\n const form = new FormData();\n form.append(\"orderId\", orderId);\n form.append(\"process\", process)\n return AjaxProxy.postFetch(this._endpoints.cancelOrder, { body: form });\n }\n\n validateProcess(orderId, process) {\n const form = new FormData();\n form.append(\"orderId\", orderId);\n form.append(\"process\", process)\n return AjaxProxy.postFetch(this._endpoints.validateProcess, { body: form });\n }\n\n}","\nexport class OrderIdsStorage {\n\n ORDER_ID_KEY = \"order_ids\"\n\n /** @type {[]} */\n #orderIds;\n\n constructor() {\n this.#orderIds = this.getOrderIds();\n }\n\n /**\n * \n * @returns {[]}\n */\n getOrderIds() {\n const str = localStorage.getItem(this.ORDER_ID_KEY);\n const orderIds = str ? JSON.parse(str) : []\n return orderIds\n }\n\n /**\n * \n * @param {string} orderId\n * @returns\n */\n exist(orderId) {\n return this.#orderIds.some(id => id === orderId)\n }\n\n push(orderId) {\n this.#orderIds.push(orderId);\n this.save()\n }\n\n /**\n * \n * @param {any} orderId\n */\n remove(orderId) {\n delete this.#orderIds[this.#orderIds.indexOf(orderId)];\n this.save();\n }\n\n /**\n * \n */\n save() {\n localStorage.setItem(this.ORDER_ID_KEY, JSON.stringify(this.#orderIds));\n }\n \n any() {\n return this.#orderIds.length > 0;\n }\n}","import { HandlerBase } from \"../../handler/handler-base\"\nimport { fromEvent } from \"rxjs\"\nimport { filter } from \"rxjs/operators\"\nimport \"jquery\"\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service\";\nimport { CancelOrdersService } from \"../services/cancel-orders-service\"\nimport { OrderIdsStorage } from \"../shared/order-ids-storage\"\n\nexport class CancelOrdersHandlers extends HandlerBase {\n\n get _cancelOrderButton() {\n return $(\".btn-order-cancel\");\n }\n\n get _testButton() {\n return $(\".btn-order-test\");\n }\n\n constructor() {\n super();\n\n this._orderIdsStorage = new OrderIdsStorage();\n this._cancelOrderService = new CancelOrdersService();\n this._browserCommunicatorService = new BrowserCommunicatorService();\n this._validateProcessWorker = new Worker(new URL(\"../web-worker/validate-process-sw.js\", import.meta.url))\n }\n\n init() {\n this._validateProcessWorker.onmessage = async e => {\n await this._validatedOrderProcces(e.data.orderId, e.data.successful, e.data.userMessage, e.data.orderStatus);\n }\n\n fromEvent(this._cancelOrderButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async e => {\n e.preventDefault();\n const element = $(e.currentTarget);\n const promptMessage = element.data(\"prompt-message\");\n const orderId = element.attr(\"id\")\n const command = element.data(\"command\");\n\n await this._cancelOrderAsync(promptMessage, orderId, command, element.parent().parent()[0]);\n });\n\n if (this._orderIdsStorage.any()) {\n this._processOrderIds()\n }\n }\n\n _processOrderIds() {\n for (var orderId of this._orderIdsStorage.getOrderIds()) {\n if (orderId) {\n this._validateProcessWorker.postMessage({\n orderId: orderId,\n url: this._cancelOrderService._endpoints.validateProcess\n });\n }\n }\n }\n\n /**\n * \n * @param {string} promptMessage\n * @param {string} orderId\n * @param {string} command\n * @param {string} loadingTarget \n * @returns\n */\n async _cancelOrderAsync(promptMessage, orderId, command, loadingTarget) {\n \n if (promptMessage) {\n const result = await this._browserCommunicatorService.displayQuestionAlert({\n description: promptMessage\n })\n\n if (!result.isConfirmed) {\n return;\n }\n }\n \n this._disableButton(orderId)\n this._loading(true, loadingTarget)\n try {\n const response = await this._cancelOrderService.cancelOrder(orderId, command);\n\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n this._enableButton(orderId)\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage,\n })\n return;\n }\n\n if (json.UserMessage) {\n await this._browserCommunicatorService.displaySuccessAlertAsync({\n description: json.UserMessage\n })\n }\n\n this._orderIdsStorage.push(orderId);\n this._validateProcessWorker.postMessage({\n orderId: orderId,\n url: this._cancelOrderService._endpoints.validateProcess\n });\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false, loadingTarget);\n }\n }\n\n /**\n * \n * @param {string} orderId\n * @param {boolean} successful\n * @param {string} userMessage\n * @returns\n */\n async _validatedOrderProcces(orderId, successful, userMessage, orderStatus) {\n this._orderIdsStorage.remove(orderId);\n\n this._enableButton(orderId, false);\n\n if (!successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: userMessage\n });\n return;\n }\n\n if (orderStatus) {\n $(`#order-status-${orderId}`).html(orderStatus);\n }\n\n await this._browserCommunicatorService.displaySuccessAlertAsync({\n description: userMessage,\n })\n }\n\n _getButtonById(orderId) {\n return $(`.btn-order-cancel[id=\"${orderId}\"]`);\n }\n\n _disableButton(orderId) {\n const button = this._getButtonById(orderId)\n const icon = button.find(\"i\");\n const spinner = button.find(\".spinner-border\");\n\n icon.hide();\n button.addClass(\"link-disabled\");\n spinner.removeClass(\"d-none\");\n }\n\n _enableButton(orderId, hideButton) {\n const button = this._getButtonById(orderId)\n const icon = button.find(\"i\");\n const spinner = button.find(\".spinner-border\");\n\n icon.show();\n spinner.addClass(\"d-none\");\n button.removeClass(\"link-disabled\");\n\n if (hideButton) {\n button.hide();\n }\n }\n}","import { Subject } from 'rxjs'\n\nexport class OnCheckedEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{container: HTMLElement}} args\n */\n checked(args) {\n this._subject.next({\n container: args.container,\n });\n }\n}\n\nconst event = new OnCheckedEvent();\nexport default event;","import { HandlerBase } from \"../../handler/handler-base\";\nimport { fromEvent } from \"rxjs\"\nimport OnCheckedEvent from \"../events/on-checked-event\"\n\nexport class StoreCouponHandlers extends HandlerBase {\n\n get _couponsButton() {\n return $(\".mh__my-coupons-trigger\");\n }\n\n get _couponModal() {\n return $(\"#coupon-modal\")\n }\n\n constructor() {\n super();\n }\n init() {\n fromEvent(this._couponsButton, \"click\").subscribe(e => {\n e.preventDefault();\n this._onLoadCoupons(e);\n })\n }\n\n loadCoupons() {\n const modal = this._couponModal;\n // show modal\n modal.modal('show')\n this.bindCouponsEvent();\n }\n\n hide() {\n this._couponModal.modal(\"hide\");\n }\n\n show() {\n this._couponModal.modal(\"show\");\n }\n\n /**\n * \n * @param {Event} e\n */\n _onLoadCoupons(e) {\n e.preventDefault();\n this.loadCoupons();\n }\n\n bindCouponsEvent() {\n $(\".checkout-coupon__card\").off(\"click\")\n const containerButtons = document.querySelectorAll(\".checkout-coupon__card\")\n containerButtons?.forEach((container) => container.addEventListener('click', (e) => {\n e.stopPropagation();\n this.onCheckedCoupon(e.currentTarget);\n }))\n }\n\n /**\n * \n * @param {HTMLElement} container\n */\n onCheckedCoupon(container) {\n OnCheckedEvent.checked({ container: container })\n }\n}","import AjaxProxy from \"../../../proxies/ajax-proxy\";\nimport { ServiceBase } from \"../../service/service-base\";\n\nexport class ExternalOrderService extends ServiceBase {\n\n _endpoints = {\n getView: \"/Security/CustomerPortal/Options/ExternalOrders\",\n filter: \"/Security/CustomerPortal/Options/ExternalOrders?handler=LoadOrderListView\"\n }\n\n constructor() {\n super();\n }\n\n getView() {\n return AjaxProxy.getFetch(`${this._endpoints.getView}`, {});\n }\n\n filter(formData) {\n return AjaxProxy.postFetch(this._endpoints.filter, { body: formData });\n }\n}","import AjaxProxy from '../../../../proxies/ajax-proxy';\nimport { ServiceBase } from '../../../service/service-base'\n\nexport class RatingServiceBase extends ServiceBase {\n\n _basePath = \"/Store/Rating\"\n\n get _pagePath() {\n return `${this._basePath}/${this._options.pageName}`;\n }\n\n get _endpoints() {\n return {\n postRating: `${this._pagePath}?handler=Rating`\n }\n }\n\n /**\n * \n * @param {{pageName: string}} options\n */\n constructor(options) {\n super()\n\n this._options = options;\n }\n\n getRatingViewAsync(queryParams) {\n return AjaxProxy.getFetch(`${this._pagePath}?${queryParams}`, {});\n }\n\n /**\n * \n * @param {FormData} formData\n * @returns\n */\n postRatingAsync(formData) {\n return AjaxProxy.postFetch(`${this._endpoints.postRating}`, {\n body: formData,\n })\n }\n}","import { RatingServiceBase } from '../shared/services/rating-service-base'\n\nexport class RatingTransporterService extends RatingServiceBase {\n constructor() {\n super({\n pageName: \"RatingTransporter\"\n })\n }\n}","export const ratingTypes = Object.freeze({\n seller: \"Seller\",\n transporter: \"Transporter\"\n})","import { HandlerBase } from '../../../handler/handler-base'\nimport 'kendo-ui'\nimport { RatingServiceBase } from '../services/rating-service-base';\nimport { BrowserCommunicatorService } from \"../../../../services/browser-communicator-service\"\nimport \"jquery\"\n\nexport class RatingHandlerBase extends HandlerBase {\n\n\n /** @type{kendo.ui.Validator}*/\n _formValidator;\n\n get _ratingDialog() {\n return $(`#${this._options.dialogId}`).data(\"kendoDialog\");\n }\n\n get _ratingForm() {\n return $(`#${this._options.ratingType}-form`);\n }\n\n get _ratingField() {\n return $(`#${this._getRatingFieldName(\"Score\")}`).data(\"kendoRating\");\n }\n\n get _ratingModalConfirmLabel() {\n return this._ratingDialog.element.find(`#rating-confirm-label`);\n }\n\n get _ratingModalCancelLabel() {\n return this._ratingDialog.element.find(`#rating-cancel-label`);\n }\n \n /**\n * \n * @param {{ formRules: {}, formMessage: {}, dialogId: string, ratingType: string, onRated: () => Promise }} options\n * @param {RatingServiceBase} ratingService\n */\n constructor(ratingService, options) {\n super()\n\n this._options = options;\n this._ratingService = ratingService;\n this._browserCommunicatorService = new BrowserCommunicatorService()\n }\n\n init() {\n\n // prevent default form event\n this._ratingForm.on(\"submit\", e => {\n e.preventDefault();\n })\n\n this._loadFormValidation();\n }\n\n _loadFormValidation() {\n let formCommonRules = {\n ratingRequired: (input) => {\n if (input.is(this._getRatingFieldName(\"Score\"))) {\n return input.val() > 0\n } else {\n return true\n }\n },\n commentsRequired: (input) => {\n if (input.is(this._getRatingFieldName(\"Comment\"))) {\n return input.val()\n } else {\n return true\n }\n }\n }\n let formCommonMessages = {\n ratingRequired: \"Debe indicar la calificación\",\n commentsRequired: \"Debe especificar un comentario\"\n }\n\n this._formValidator = this._ratingForm.kendoValidator({\n rules: {\n ...formCommonRules,\n ...this._options.formRules\n },\n messages: {\n ...formCommonMessages,\n ...this._options.formMessage\n }\n }).data(\"kendoValidator\");\n }\n\n /**\n * \n * @param {string} queryParams\n * @returns\n */\n async onRate(queryParams) {\n try {\n const response = await this._ratingService.getRatingViewAsync(queryParams)\n\n if (!response.ok) {\n return;\n }\n\n const html = await response.text();\n\n //set content\n const modal = this._ratingDialog;\n modal.content(html)\n\n // set options\n modal.setOptions({\n title: false,\n modal: true,\n actions: [\n {\n text: this._ratingModalCancelLabel.html(),\n cssClass: \"button\"\n },\n {\n text: this._ratingModalConfirmLabel.html(),\n action: e => {\n return this.onConfirmRating();\n },\n cssClass: \"button button--primary\"\n }\n ]\n })\n\n // header title\n modal.element.parent().find('.k-window-titlebar,.k-window-actions').addClass(\"modal-dialog-title\")\n\n //validations form\n this._loadFormValidation();\n\n //open\n modal.open()\n\n } catch (e) {\n console.error(e)\n throw e;\n }\n }\n\n /**\n * Override method\n * @returns\n */\n onRated() {\n return this._options.onRated();\n }\n\n onConfirmRating() {\n this._rateAsync()\n .then(_ => { })\n\n return false;\n }\n\n async _rateAsync() {\n this._loading(true)\n\n try {\n const isValid = this._validateRatingForm();\n if (!isValid) {\n return;\n }\n\n const formData = new FormData(this._ratingForm[0])\n\n // set score int value\n formData.set(this._getRatingFieldName(\"Score\"), this._ratingField.value())\n\n const response = await this._ratingService.postRatingAsync(formData);\n if (!response.ok) {\n this._ratingDialog.close();\n return;\n }\n\n const json = await response.json();\n\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage\n })\n this._ratingDialog.open()\n return;\n }\n\n this._ratingDialog.close();\n\n if (json.UserMessage) {\n await this._browserCommunicatorService.displaySuccessAlertAsync({\n description: json.UserMessage,\n autoclosing: true,\n })\n }\n\n await this.onRated();\n\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false)\n }\n }\n\n _validateRatingForm() {\n return this._formValidator.validate();\n }\n\n _loading(loading) {\n super._loading(loading, this._ratingForm[0])\n }\n\n _getRatingFieldName(field) {\n return `${this._options.ratingType}_${field}`;\n }\n \n}","import { RatingTransporterService } from \"../services/rating-transporter-service\";\nimport { ratingTypes } from \"../shared/constants/rating-types\";\nimport { RatingHandlerBase } from \"../shared/handlers/rating-handler-base\";\n\nexport class RatingTransporterHandler extends RatingHandlerBase {\n constructor() {\n super(new RatingTransporterService(), {\n formMessage: { },\n formRules: { },\n dialogId: \"rate-transporter-dialog\",\n ratingType: ratingTypes.transporter,\n onRated: () => { }\n })\n }\n}","import { filter, fromEvent } from \"rxjs\";\nimport { HandlerBase } from \"../../handler/handler-base\";\nimport { ExternalOrderService } from \"../services/external-order-service\";\nimport { RatingTransporterHandler } from \"../../rating/handlers/rating-transporter-handler\"\nimport \"kendo-ui\"\n\nexport class ExternalOrderHandlers extends HandlerBase {\n\n _isBusy = false;\n _validMonths = 6;\n\n /** @type{kendo.ui.Validator} */ \n _formValidation;\n\n get _externalOrdersContainer() {\n return $(\"#external-orders-container\");\n }\n\n get _loadingTarget() {\n return \"#menu-card__content\";\n }\n\n get _externalOrderListContainer() {\n return $(\"#external-order-list-container\");\n }\n \n get _externalOrdersForm() {\n return $(\"#external-orders-form\");\n }\n\n get _rangeDate() {\n return $(\"#external-orders-range\").data(\"kendoDateRangePicker\");\n }\n\n get _externalOrderDetailButton() {\n return $(\".btn-order-detail-external\")\n }\n\n get _externalOrderTrackingButton() {\n return $(\".btn-order-tracking-external\")\n }\n\n get _orderDetailModal() {\n return $(\"#external-order-modal\").data(\"kendoDialog\");\n }\n\n get _orderTrackingModal() {\n return $(\"#external-order-tracking-modal\").data(\"kendoDialog\");\n }\n\n get _rateTransporterButton() {\n return $(\".rate-transporter--trigger\");\n }\n\n constructor() {\n super();\n\n this._externalOrderService = new ExternalOrderService();\n this._ratingTransporterHandler = new RatingTransporterHandler()\n }\n\n init(loadView = false) {\n\n if (loadView) {\n this.loadOrderView().then(_ => {\n this._bindEvents();\n this._bindListEvents();\n })\n }\n }\n\n _bindEvents() {\n fromEvent(this._externalOrdersForm, \"submit\").pipe(\n filter(_ => !this._isBusy)\n ).subscribe(async e => {\n e.preventDefault();\n await this.filterOrders();\n })\n\n this.bindFormValidator();\n }\n\n _bindListEvents() {\n fromEvent(this._externalOrderDetailButton, \"click\").pipe(\n filter(_ => !this._isBusy)\n ).subscribe(e => {\n e.preventDefault();\n this.loadOrderDetail(e);\n })\n\n fromEvent(this._rateTransporterButton, \"click\").pipe(\n filter(_ => !this._isBusy)\n ).subscribe(e => {\n e.preventDefault();\n this.loadRatingTransporter(e);\n })\n\n fromEvent(this._externalOrderTrackingButton, \"click\").pipe(\n filter(_ => !this._isBusy)\n ).subscribe(e => {\n e.preventDefault();\n this.loadOrderTracking(e);\n })\n }\n\n /**\n * \n * @param {Event} e\n */\n loadRatingTransporter(e) {\n const button = $(e.currentTarget);\n const queryParams = new URLSearchParams({\n referenceCode: button.data(\"reference-code\"),\n vehiclePlate: button.data(\"vehicle-plate\"),\n transporterName: button.data(\"transporter-name\")\n });\n this._ratingTransporterHandler.onRate(queryParams.toString());\n }\n\n /**\n * \n * @param {Event} e\n */\n loadOrderDetail(e) {\n this._loading(true);\n\n try {\n const target = $(e.currentTarget);\n const referenceCode = target.data(\"reference-code\");\n const scriptHtml = this._getOrderDetailHtml(referenceCode);\n\n const modal = this._orderDetailModal;\n\n // set content\n modal.content(scriptHtml);\n\n // set options\n modal.setOptions({\n actions: [\n {\n text: \"Cerrar\",\n cssClass: \"button\"\n }\n ]\n });\n\n // header title\n modal.element.parent().find('.k-window-titlebar,.k-window-actions').addClass(\"modal-dialog-title\");\n\n //open\n modal.open();\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false);\n }\n }\n\n /**\n * \n * @param {Event} e\n */\n loadOrderTracking(e) {\n this._loading(true);\n\n try {\n const target = $(e.currentTarget);\n const referenceCode = target.data(\"reference-code\");\n const scriptHtml = this._getOrderTrackingHtml(referenceCode);\n \n const modal = this._orderTrackingModal;\n\n // set content\n modal.content(scriptHtml);\n\n // set options\n modal.setOptions({\n actions: [\n {\n text: \"Cerrar\",\n cssClass: \"button\"\n }\n ]\n });\n\n // header title\n modal.element.parent().find('.k-window-titlebar,.k-window-actions').addClass(\"modal-dialog-title\");\n\n //create timeline\n this._createTimeline(referenceCode);\n\n //open\n modal.open();\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false);\n }\n }\n\n bindFormValidator() {\n const rules = {\n /**\n *\n * @param {JQuery} input\n */\n validRangeDate: (input) => {\n if ((input.is(`[name=\"StartDateExternalOrder\"]`) || input.is(`[name=\"EndDateExternalOrder\"]`))) {\n const dateRanges = this._rangeDate.range();\n const endDateValue = dateRanges.end;\n const startDateValue = dateRanges.start;\n if (endDateValue && !startDateValue) {\n return false;\n } else if (startDateValue && !endDateValue) {\n return false;\n } else if (endDateValue < startDateValue) {\n return false;\n } else {\n /// validate range for 6 months\n let startDateWithValidMonths = new Date(startDateValue);\n startDateWithValidMonths.setMonth(startDateWithValidMonths.getMonth() + this._validMonths);\n if (endDateValue > startDateWithValidMonths) {\n return false;\n }\n else {\n return true;\n }\n //return true;\n }\n }\n else {\n return true;\n }\n },\n };\n\n const message = {\n validRangeDate: `Debe indicar una rango de fecha válido (Solo se permite rangos de fechas inferiores a ${this._validMonths} meses).`\n };\n\n this._formValidation = this._externalOrdersForm.kendoValidator({\n rules: {\n ...rules\n },\n messages: {\n ...message\n },\n validateOnBlur: false,\n }).data(\"kendoValidator\");\n }\n\n async filterOrders() {\n this._loading(true);\n try {\n const valid = this.validateExternalOrdersForm();\n if (!valid) {\n return;\n }\n\n let formData = new FormData(this._externalOrdersForm[0]);\n const response = await this._externalOrderService.filter(formData);\n\n if (!response.ok) {\n return;\n }\n\n const contentHtml = await response.text();\n this._externalOrderListContainer.html(contentHtml)\n this._bindListEvents();\n\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false);\n }\n }\n\n validateExternalOrdersForm() {\n return this._formValidation.validate();\n }\n\n async loadOrderView() {\n this._loading(true);\n try {\n const response = await this._externalOrderService.getView();\n if (!response.ok) {\n return;\n }\n\n let contentHtml = await response.text();\n this._externalOrdersContainer.html(contentHtml);\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false);\n }\n }\n\n /**\n * \n * @param {string} referenceCode\n */\n _createTimeline(referenceCode) {\n const trackingData = this._getOrderTrackingData(referenceCode);\n this._getOrderTrackingElement(referenceCode).kendoTimeline({\n dataSource: new kendo.data.DataSource({\n data: trackingData\n }),\n orientation: \"vertical\",\n collapsibleEvents: true,\n alternatingMode: true\n });\n }\n\n _loading(loading) {\n this._isBusy = loading;\n super._loading(loading, this._loadingTarget);\n }\n\n _getOrderDetailHtml(orderReferenceCode) {\n return $(`#view-details-${orderReferenceCode}`).html();\n }\n\n _getOrderTrackingHtml(orderReferenceCode) {\n return $(`#view-traking-${orderReferenceCode}`).html();\n }\n\n /**\n * \n * @param {any} orderReferenceCode\n * @returns {[]}\n */\n _getOrderTrackingData(orderReferenceCode) {\n const trakingData = $(`#view-traking-${orderReferenceCode}`).data(\"json\")\n return trakingData.map(d => {\n return {\n description: d.StatusDescription,\n date: new Date(d.StatusDate),\n title: d.StatusName,\n }\n });\n }\n\n _getOrderTrackingTimeline(orderReferenceCode) {\n return this._getOrderTrackingElement(orderReferenceCode).data(\"kendoTimeline\");\n }\n\n _getOrderTrackingElement(orderReferenceCode) {\n return $(`#external-orders-traking-${orderReferenceCode}`);\n }\n}","import AjaxProxy from \"../../../proxies/ajax-proxy\";\nimport { ServiceBase } from \"../../service/service-base\";\n\nexport class HistoryPaymentsService extends ServiceBase {\n\n _endpoints = {\n historyMessageView: \"/Security/CustomerPortal/Options/PaymentHistory?handler=HistoryMessage\"\n }\n\n constructor() {\n super()\n }\n\n /** \n * \n * */\n historyMessageView() {\n return AjaxProxy.getFetch(this._endpoints.historyMessageView, {});\n }\n}","import { HandlerBase } from \"../../handler/handler-base\";\nimport { HistoryPaymentsService } from \"../services/history-payments-service\"\nimport { fromEvent } from \"rxjs\"\n\nexport class HistoryPaymentsHandlers extends HandlerBase {\n\n /** @type{kendo.ui.Validator} */\n _formValidation;\n \n get _form() {\n return $(\"#history-payments-form\")\n }\n\n get _rangeDate() {\n return $(\"#history-payments-range\").data(\"kendoDateRangePicker\");\n }\n\n get _loadingTarget() {\n return \"#history-payments-container\"\n }\n\n get _grid() {\n return $(\"#history-payments-grid\").data(\"kendoGrid\")\n }\n\n constructor() {\n super();\n\n this._historyPaymentsService = new HistoryPaymentsService()\n }\n\n init() {\n this.bindFormValidator();\n\n fromEvent(this._form, \"submit\").subscribe(async e => {\n e.preventDefault();\n await this.loadHistoryPaymentsAsync();\n })\n }\n\n bindFormValidator() {\n const rules = {\n /**\n *\n * @param {JQuery} input\n */\n validRangeDate: (input) => {\n if ((input.is(`[name=\"StartDatePayments\"]`) || input.is(`[name=\"EndDatePayments\"]`))) {\n const dateRanges = this._rangeDate.range();\n const endDateValue = dateRanges.end;\n const startDateValue = dateRanges.start;\n if (endDateValue && !startDateValue) {\n return false;\n } else if (startDateValue && !endDateValue) {\n return false;\n } else if (endDateValue < startDateValue) {\n return false;\n } else {\n return true;\n }\n }\n else {\n return true;\n }\n },\n };\n\n const message = {\n validRangeDate: `Debe indicar una rango de fecha válido.`\n };\n\n this._formValidation = this._form.kendoValidator({\n rules: {\n ...rules\n },\n messages: {\n ...message\n },\n validateOnBlur: false,\n }).data(\"kendoValidator\");\n }\n\n _loading(loading) {\n super._loading(loading, this._loadingTarget)\n }\n\n validateForm() {\n return this._formValidation.validate();\n }\n\n async loadHistoryPaymentsAsync() {\n\n try {\n const valid = this.validateForm();\n if (!valid) {\n return;\n }\n\n let formData = new FormData(this._form[0]);\n var initialDate = {\n initialDateHidden: formData.get(\"StartDatePayments\"),\n finalDateHidden: formData.get(\"EndDatePayments\")\n };\n\n await this._grid.dataSource.read(initialDate);\n\n this._loading(true);\n\n /**\n // * @type{Response}*/\n let response = await this._historyPaymentsService.historyMessageView();\n\n if (response.ok) {\n const json = await response.json();\n const html = json.Value.HistoryMessage;\n if (html) {\n $(\"#history-message-card\").show();\n $(\"#history-message-value\").html(html);\n }\n else {\n $(\"#history-message-card\").hide();\n }\n }\n\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false);\n }\n }\n}","import { RatingServiceBase } from '../shared/services/rating-service-base'\n\nexport class RatingSellerService extends RatingServiceBase {\n constructor() {\n super({\n pageName: \"RatingSeller\"\n });\n }\n\n}","import { RatingHandlerBase } from \"../shared/handlers/rating-handler-base\";\nimport { RatingSellerService } from '../services/rating-seller-service'\nimport { ratingTypes } from \"../shared/constants/rating-types\"\n\nexport class RatingSellerHandler extends RatingHandlerBase {\n\n get _salesAdvisorGrid() {\n return $(\"#SalesAdvisorGrid\").data(\"kendoGrid\");\n }\n\n constructor() {\n super(new RatingSellerService(), {\n formRules: { },\n formMessage: { },\n dialogId: \"rate-seller-dialog\",\n ratingType: ratingTypes.seller,\n onRated: async _ => {\n await this._salesAdvisorGrid.dataSource.fetch();\n }\n });\n }\n\n init() {\n super.init()\n }\n}","import { filter, fromEvent } from \"rxjs\";\nimport { HandlerBase } from \"../../handler/handler-base\"\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service\";\nimport ShoppingCartService from \"../../shopping-cart/services/shopping-cart-service\";\nimport OrderReplicatedEvent from \"../events/order-replicated-event\"\n\nexport class ReplicateOrdersHandlers extends HandlerBase {\n\n isBusy = false;\n\n get _replicateOrderButton() {\n return $(\".btn-order-replicate\");\n }\n\n constructor() {\n super();\n\n this._browserCommunicatorService = new BrowserCommunicatorService();\n this._shoppingCartService = new ShoppingCartService();\n }\n\n init() {\n fromEvent(this._replicateOrderButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async e => {\n await this.replicateOrderAsync(e);\n });\n }\n\n /**\n * \n * @param {Event} e\n * @returns\n */\n async replicateOrderAsync(e) {\n const target = $(e.currentTarget);\n const promptMessage = target.data(\"prompt-message\");\n \n if (promptMessage) {\n const result = await this._browserCommunicatorService.displayQuestionAlert({\n description: promptMessage,\n html: true\n })\n\n if (!result.isConfirmed) {\n return;\n }\n }\n\n const loadingTarget = target.parent().parent()[0];\n this._loading(true, loadingTarget)\n try {\n const orderId = target.attr(\"id\");\n const response = await this._shoppingCartService.replicateOrder(orderId);\n\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage,\n html: true\n })\n return;\n }\n\n // dispatch replicate event\n OrderReplicatedEvent.orderReplicated({\n shoppingCartItemChanged: shoppingCartChanged\n })\n\n const shoppingCartChanged = json.Value;\n if (!shoppingCartChanged.Successed) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: shoppingCartChanged.Message,\n html: true\n })\n return;\n }\n\n if (json.UserMessage) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: json.UserMessage,\n html: true\n })\n }\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false, loadingTarget)\n }\n }\n\n _loading(loading, target) {\n this.isBusy = loading;\n super._loading(loading, target)\n }\n}","import '@progress/kendo-ui';\nimport { analytics } from 'apollo-web';\nimport 'jquery';\nimport { RadioButtons } from '../components/radioButtons/radio-buttons.js';\nimport { WizardForm } from \"../components/wizard/wizard-form.js\";\nimport { BrowserCommunicatorService } from '../services/browser-communicator-service';\nimport CustomerService from '../services/customer-service.js';\nimport { CancelOrdersHandlers } from \"../shared/cancel-order/handlers/cancel-orders-handlers.js\";\nimport { StoreCouponHandlers } from \"../shared/coupons/handlers/store-coupon-handlers.js\";\nimport { ExternalOrderHandlers } from '../shared/external-orders/handlers/external-order-handlers.js';\nimport { HandlerBase } from \"../shared/handler/handler-base.js\";\nimport { CustomerAnalyticsHelper } from \"../shared/helper/customer-analytics-helper\";\nimport { HistoryPaymentsHandlers } from \"../shared/history-payments/handlers/history-payments-handlers.js\";\nimport { RatingSellerHandler } from '../shared/rating/handlers/rating-seller-handler.js';\nimport { ReplicateOrdersHandlers } from \"../shared/replicate-order/handlers/replicate-orders-handlers.js\";\nimport ShoppingCartService from \"../shared/shopping-cart/services/shopping-cart-service.js\";\n\n/**\n * @type {CustomerService}\n * */\nconst customerService = new CustomerService();\n\n/**\n * @type {ShoppingCartService}\n * */\nconst shoppingCartService = new ShoppingCartService();\n\nconst browserCommunicatorService = new BrowserCommunicatorService()\n\nconst externalOrdersHandlers = new ExternalOrderHandlers();\n\nconst replicateOrdersHandlers = new ReplicateOrdersHandlers();\n\nconst cancelOrdersHandlers = new CancelOrdersHandlers();\n/** @type {WizardForm} */\nvar _wizard = null;\n\nconst historyPaymentsHandlers = new HistoryPaymentsHandlers();\n\n/**\n * Handlers for customers views\n * */\nexport default class CustomerHandlers extends HandlerBase {\n \n get _businessTypeControl(){\n return $(\"#RegistrationCustomer_RegistrationBusinessUnitByBusinessTypeId\").data(\"kendoDropDownList\");\n }\n\n /**\n * @type CustomerService\n * */\n customerService;\n \n constructor(init = true) {\n super();\n\n this.customerService = new CustomerService();\n this._ratingSellerHandlers = new RatingSellerHandler();\n this._externalOrdersHandlers = externalOrdersHandlers;\n this._replicateOrdersHandlers = replicateOrdersHandlers;\n this._historyPaymentsHandlers = historyPaymentsHandlers\n this._cancelOrdersHandlers = cancelOrdersHandlers;\n\n if (init) {\n this.init();\n }\n }\n\n /** Init the handlers for the customers\n * */\n async init() {\n bindPage();\n bindButtonAccount();\n\n await this.onShowMessageFirstLoad()\n\n this._ratingSellerHandlers.init();\n }\n\n /** Legacy method, use the no static method\n * */\n static initLagacy() {\n bindPage();\n bindButtonAccount();\n }\n \n async onShowMessageFirstLoad() {\n if ($(\"#error-load-checkout\").length > 0) {\n const message = $(\"#error-load-checkout\").text()\n await browserCommunicatorService.displayErrorAlert({\n description: message,\n html: true\n })\n }\n\n if ($(\"#info-load-checkout\").length > 0) {\n const message = $(\"#info-load-checkout\").val()\n await browserCommunicatorService.displayInfoAlert({\n description: message,\n html: true\n })\n }\n }\n\n}\n\nfunction bindPage() {\n //evento para mostrar el componente correspondiente\n $('.config-menu').on('click', function (event) {\n event.stopPropagation();\n\n var selectedOptionId = event.target.id;\n $(event.target).addClass('active');\n\n switch (selectedOptionId) {\n case \"config-item-configuration\":\n $('#config').show();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#bills').hide();\n $('#orders').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-addresses').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-addresses\":\n $('#config').hide();\n $('#addresses').show();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#bills').hide();\n $('#orders').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-configuration').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-mycards\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').show();\n $('#bonus').hide();\n $('#bills').hide();\n $('#orders').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-configuration').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-orders\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#bills').hide();\n $('#orders').show();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-configuration').removeClass('active');\n $('#config-item-addresses').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-bonus\":\n $('#bonus').show();\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bills').hide();\n $('#orders').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-configuration').removeClass('active');\n $('#config-item-addresses').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-bills\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#orders').hide();\n $('#bills').show();\n $('#bonus').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-configuration').removeClass('active');\n $('#config-item-addresses').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-history\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#orders').hide();\n $('#bills').hide();\n $('#history').show();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-addresses').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-configuration').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-certificate\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#orders').hide();\n $('#bills').hide();\n $('#history').hide();\n $('#certificate').show();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-addresses').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-configuration').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-statementaccount\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#orders').hide();\n $('#bills').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').show();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n\n $('#config-item-addresses').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-configuration').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n case \"config-item-viewdocuments\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#orders').hide();\n $('#bills').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#salesadvisor').hide();\n $('#external-orders').hide();\n $('#viewdocuments').show();\n\n $('#config-item-addresses').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-configuration').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n\n case \"config-item-salesadvisor\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#orders').hide();\n $('#bills').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#external-orders').hide();\n $('#salesadvisor').show();\n\n $('#config-item-addresses').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-configuration').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-external-orders').removeClass('active');\n\n break;\n\n case \"config-item-external-orders\":\n $('#config').hide();\n $('#addresses').hide();\n $('#mycards').hide();\n $('#bonus').hide();\n $('#orders').hide();\n $('#bills').hide();\n $('#history').hide();\n $('#certificate').hide();\n $('#statementaccount').hide();\n $('#viewdocuments').hide();\n $('#salesadvisor').hide();\n $('#external-orders').show();\n\n $('#config-item-addresses').removeClass('active');\n $('#config-item-bonus').removeClass('active');\n $('#config-item-orders').removeClass('active');\n $('#config-item-bills').removeClass('active');\n $('#config-item-history').removeClass('active');\n $('#config-item-certificate').removeClass('active');\n $('#config-item-configuration').removeClass('active');\n $('#config-item-statementaccount').removeClass('active');\n $('#config-item-viewdocuments').removeClass('active');\n $('#config-item-mycards').removeClass('active');\n $('#config-item-salesadvisor').removeClass('active');\n\n\n externalOrdersHandlers.init(true);\n break;\n }\n $(\"html, body\").animate({ scrollTop: \"0\" });\n });\n\n //evento para registrar un nuevo usuario\n $('.register-customer-info').on('click', registerCustomer);\n\n $('.login-user').on('click', authenticate);\n $('.send-password').on('click', rememberPassword);\n\n $('#stateSelectId').off('change');\n $('#stateSelectId').on('change', getCitiesByState);\n\n $('#citySelectId').off('change');\n $('#citySelectId').on('change', getNeighborhoodsByCityId);\n\n $('#identificationTypeSelectId').off('change');\n $('#identificationTypeSelectId').on('change', showFieldsIdentificationType);\n\n $('.register-customer-password').on('keyup', validatePassword);\n $('.register-customer-passwordconf').on('keyup', validatePassword);\n\n //#region Login Customer B2C\n\n // handle login for mobile\n $(\".login-with-mobile\").on(\"click\", function () {\n $(\".login-form\").hide(\"fade\", function () {\n $(\".login-phone\").show(\"fade\", {}, 1000);\n\n $(\"#PhoneNumber\").val(\"\");\n $('#Password').val(\"\");\n }, 1000);\n });\n $(\".login-back-user\").on(\"click\", function () {\n $(\".login-phone\").hide(\"fade\", function () {\n $(\".login-form\").show(\"fade\", {}, 1000);\n\n $(\"#PhoneNumber\").val(\"\");\n $(\"#codeMobile\").val(\"\");\n $(\".send-code-phone-number\").show();\n $(\".login-phone-number\").hide();\n }, 1000);\n });\n\n if ($(\"#Email\").length > 0) {\n $(\"#Email\").on(\"keypress\", preventSpaceInput);\n }\n\n if ($(\"#PhoneNumber\").length > 0) {\n $(\"#PhoneNumber\").on(\"keypress\", validateOnlyNumbers);\n }\n\n if ($(\"#Password\").length > 0) {\n $(\"#Password\").on(\"keypress\", preventSpaceInput);\n }\n\n if ($(\"#codeMobile\").length > 0) {\n $(\"#codeMobile\").on(\"keypress\", validateOnlyNumbers);\n }\n\n if ($(\"#codeActivation\").length > 0) {\n $(\"#codeActivation\").on(\"keypress\", validateOnlyNumbers);\n }\n\n //#endregion\n\n}\n\n//#region B2B - B2C\n\n//evento para bindear acciones de los botones en el formulario de Account\nfunction bindButtonAccount() {\n $('.active-code-button').off('click');\n $('.active-code-button').on('click', activeCodeButtonClick);\n\n $('.resend-activation-code-button').off('click');\n $('.resend-activation-code-button').on('click', resendActivationCodeButtonClick);\n}\n\nfunction getCitiesByState(event) {\n var stateId = $(\"#stateSelectId option:selected\").val();\n app.customerService.getCitiesByState(stateId, function (response) {\n if (response != null) {\n $(\"#citySelectId\").empty();\n\n $(\"#citySelectId\").append('');\n\n $.each(response, function (i, city) {\n $(\"#citySelectId\").append('');\n });\n getNeighborhoodsByCityId();\n }\n }, function (response) {\n });\n}\n\nfunction showFieldsIdentificationType(event) {\n var identificationTypeId = $(\"#identificationTypeSelectId option:selected\").val();\n if (identificationTypeId != \"001\") {\n $(\"#no-view-pnombre\").show();\n $(\"#no-view-snombre\").show();\n $(\"#no-view-papellido\").show();\n $(\"#no-view-sapellido\").show();\n $(\"#no-view-razonSocial\").hide();\n $(\"[name='razonSocial']\").val('');\n }\n else {\n $(\"#no-view-pnombre\").hide();\n $(\"#no-view-snombre\").hide();\n $(\"#no-view-papellido\").hide();\n $(\"#no-view-sapellido\").hide();\n $(\"#no-view-razonSocial\").show();\n\n $(\"[name='pnombre']\").val('');\n $(\"[name='snombre']\").val('');\n $(\"[name='papellido']\").val('');\n $(\"[name='sapellido']\").val('');\n }\n}\n\nfunction getNeighborhoodsByCityId(event) {\n var cityId = $(\"#citySelectId option:selected\").val();\n\n app.customerService.getNeighborhoodsByCityId(cityId, function (response) {\n if (response != null) {\n\n $(\"#neighborhoodSelectId\").empty();\n\n $(\"#neighborhoodSelectId\").append('');\n\n $.each(response, function (i, neighborhood) {\n $(\"#neighborhoodSelectId\").append('');\n });\n }\n }, function (response) {\n });\n}\n\nfunction activeCodeButtonClick() {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n var codeInputControl = $('.code-input');\n var code = codeInputControl.val().trim();\n var sendCode = $(\"#SendCode\").val();\n app.customerService.validationCode(code, sendCode, async function (response) {\n if (response.Validation) {\n await browserCommunicatorService.displayInfoAlert({\n description: response.Message,\n html: true\n })\n\n // Analytics Event: \"success_verification_account\"\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackAccountVerification({\n action: 'success',\n customerEmail: response.Email || analytics.AnalyticsConstants.DefaultParameterValue,\n customerPhone: analytics.AnalyticsConstants.DefaultParameterValue,\n });\n })\n .catch(function (err) {\n console.error(err);\n })\n\n // dispatch \"activate_account\" analytics event.\n try {\n let username = response.Email || analytics.AnalyticsConstants.DefaultParameterValue;\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackActivateAccount(username);\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n window.location.href = '/Security/Login/';\n }\n else {\n // Analytics event: \"failed_verification_account\"\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackAccountVerification({\n action: 'failed',\n customerEmail: response.Email || analytics.AnalyticsConstants.DefaultParameterValue,\n customerPhone: analytics.AnalyticsConstants.DefaultParameterValue,\n });\n })\n .catch(function (err) {\n console.error(err);\n })\n await browserCommunicatorService.displayErrorAlert({\n description: response.Message,\n html: true\n })\n }\n spinnerWait.addClass(\"d-none\");\n }, async function (response) {\n await browserCommunicatorService.displayErrorAlert({ description: 'Ocurri\\u00F3 un error. ' + response })\n spinnerWait.addClass(\"d-none\");\n });\n}\n\nfunction resendActivationCodeButtonClick() {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n var sendCode = $(\"#SendCode\").val();\n app.customerService.reSendValidationCode(sendCode, async function (response) {\n await browserCommunicatorService.displayInfoAlert({ description: \"Hemos enviado un nuevo código para activar tu cuenta.\" })\n $(\"#SendCode\").val(response.sendCodeRequest);\n spinnerWait.addClass(\"d-none\");\n }, async function (response) {\n await browserCommunicatorService.displayErrorAlert({ description: 'Ocurri\\u00F3 un error. ' + response })\n spinnerWait.addClass(\"d-none\");\n });\n}\n\nfunction validatePassword(result) {\n var passwordControl = $('.register-customer-password').val();\n app.customerService.validatePassword(passwordControl, function (response) {\n var nivelSeg = $(\"#nivelseguridad\");\n var spanNivelesColores = $(\"#spanNivelesColores\");\n if (passwordControl != \"\") {\n nivelSeg.html(response.StrongPasswordLabel);\n spanNivelesColores.html(response.StrongPasswordLabel);\n spanNivelesColores.prop(\"style\", \"background:\" + response.StrongBarPasswordColor + \"; color:\" + response.StrongBarPasswordColor);\n }\n else {\n nivelSeg.html(\"\");\n spanNivelesColores.html(\"\");\n }\n });\n}\n\nasync function registerCustomer(event) {\n event.stopPropagation();\n\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n $(this).prop('disabled', true);\n var buttonRegister = $(this);\n\n var stateControl = $('.register-customer-state');\n var cityControl = $('.register-customer-city');\n var streeTypeControl = $('.register-customer-streeType');\n var streetNumberControl = $('.register-customer-streetNumber');\n var sideLineControl = $('.register-customer-sideLine');\n var sideLineNumberControl = $('.register-customer-sideLineNumber');\n var complementControl = $('.register-customer-complement');\n var neighborhoodControl = $('.register-customer-neighborhood');\n var neighborhoodNameControl = $('.register-customer-neighborhoodName');\n\n var identificationTypeControl = $('.register-customer-identification-type');\n var identificationControl = $('.register-customer-identification');\n var nameControl = $('.register-customer-name');\n var secondnameControl = $('.register-customer-secondname');\n var surnameControl = $('.register-customer-surname');\n var secondsurnameControl = $('.register-customer-secondsurname');\n var mobileNumberControl = $('.register-customer-mobileNumber');\n var phoneNumberControl = $('.register-customer-phoneNumber');\n var birthControl = $('.register-customer-birth');\n var businessNameControl = $('.register-customer-businessName')\n var businessTypeControl = $('.register-customer-business-type');\n var ciiuCodeControl = $('.register-customer-ciiuCode');\n var tributeControl = $('.register-customer-tribute');\n var fiscalResponsabilityControl = $('.register-customer-fiscalResponsability');\n\n var emailControl = $('.register-customer-email');\n var emailconfControl = $('.register-customer-emailconf');\n var passwordControl = $('.register-customer-password');\n var passwordconfControl = $('.register-customer-passwordconf');\n var agreementcodeControl = $('.register-customer-agreementcode');\n\n var termsControl = $('.register-customer-terms');\n var receivePromotionalCommunicationsControl = $('.register-customer-receivePromotionalCommunications');\n\n var stateId = stateControl[0].selectedOptions[0].value;\n var state = stateControl[0].selectedOptions[0].id;\n var cityId = cityControl[0].selectedOptions[0].value;\n var city = cityControl[0].selectedOptions[0].id;\n var cityName = cityControl[0].selectedOptions[0].text;\n var streeType = streeTypeControl[0].selectedOptions[0].value;\n var streetNumber = streetNumberControl.val().trim();\n var sideLine = sideLineControl.val().trim();\n var sideLineNumber = sideLineNumberControl.val().trim();\n var complement = complementControl.val().trim();\n\n var stree = streeType + \" \" + streetNumber;\n var plate = (sideLine.length != 0 && sideLineNumber.length != 0) ? `#${sideLine}-${sideLineNumber}` : \"\";\n var address = `${stree} ${plate} @${cityName} @${complement}`;\n\n var neighborhood = neighborhoodControl[0].selectedOptions[0].value;\n var neighborhoodName = neighborhoodNameControl.val().trim();\n\n var identificationType = identificationTypeControl[0].selectedOptions[0].value;\n var identification = identificationControl.val().trim();\n var name = nameControl.val().trim();\n var secondname = secondnameControl.val().trim();\n var surname = surnameControl.val();\n var secondsurname = secondsurnameControl.val().trim();\n var mobileNumber = mobileNumberControl.val().trim();\n var phoneNumber = phoneNumberControl.val().trim();\n var birth = birthControl.val().trim();\n var businessName = businessNameControl.length > 0 ? businessNameControl.val().trim() : \"\";\n\n var businessType = businessTypeControl.length > 0 ? businessTypeControl[0].selectedOptions[0].value : \"\";\n var ciiuCode = ciiuCodeControl.length > 0 ? ciiuCodeControl[0].selectedOptions[0].value : \"\";\n var fiscalResponsabilty = fiscalResponsabilityControl.length > 0 ? fiscalResponsabilityControl[0].selectedOptions[0].value : \"\";\n var tribute = tributeControl.length > 0 ? tributeControl[0].selectedOptions[0].value : \"\";\n\n var email = emailControl.val().trim();\n var emailConf = emailconfControl.val() == undefined ? email : emailconfControl.val().trim();\n var password = passwordControl.val();\n var passwordConf = passwordconfControl.val();\n\n var agreementcode = \"\";\n if (agreementcodeControl != undefined) {\n agreementcode = agreementcodeControl.val();\n }\n\n var terms = termsControl[0].checked;\n var receivePromotionalCommunications = receivePromotionalCommunicationsControl[0].checked;\n\n if ((!streeType || streeType.length === 0) ||\n (!streetNumber || streetNumber.length === 0) ||\n (!sideLine || sideLine.length === 0) ||\n (!sideLineNumber || sideLineNumber.length === 0)) {\n await browserCommunicatorService.displayInfoAlert({ description: 'Por favor selecciona tu dirección.' })\n spinnerWait.addClass(\"d-none\");\n $(this).prop('disabled', false);\n return false;\n }\n\n if (identificationType != \"001\") {\n if ((!identificationType || identificationType.length === 0) ||\n (!identification || identification.length === 0) ||\n (!name || name.length === 0) ||\n (!surname || surname.length === 0) ||\n (!mobileNumber || mobileNumber.length === 0)) {\n await browserCommunicatorService.displayInfoAlert({ description: 'La siguiente información es necesaria (tipo de identificación, número de identificación, nombre, apellido, teléfono móvil).' })\n spinnerWait.addClass(\"d-none\");\n $(this).prop('disabled', false);\n return false;\n }\n }\n else {\n if ((!businessName || businessName.length === 0) ||\n (!businessType || businessType.length === 0)) {\n await browserCommunicatorService.displayInfoAlert({ description: 'La siguiente información es necesaria (Razón social y seleccionar tipo de negocio).' })\n spinnerWait.addClass(\"d-none\");\n $(this).prop('disabled', false);\n return false;\n }\n }\n\n if (mobileNumber.length != 10) {\n await browserCommunicatorService.displayInfoAlert({ description: 'El número móvil debe ser de 10 dígitos.' })\n spinnerWait.addClass(\"d-none\");\n $(this).prop('disabled', false);\n return false;\n }\n\n if ((!email || email.length === 0) ||\n (!password || password.length === 0)) {\n await browserCommunicatorService.displayInfoAlert({ description: 'La siguiente información es necesaria (correo electrónico, contraseña y no olvides confirmarla).' })\n spinnerWait.addClass(\"d-none\");\n $(this).prop('disabled', false);\n return false;\n }\n\n if (email != emailConf) {\n await browserCommunicatorService.displayInfoAlert({ description: 'El correo de confirmación no coincide con el correo electrónico.' })\n spinnerWait.addClass(\"d-none\");\n $(this).prop('disabled', false);\n return false;\n }\n\n if (password != passwordConf) {\n await browserCommunicatorService.displayInfoAlert({ description: 'La contraseña de confirmación no coincide con la contraseña.' })\n spinnerWait.addClass(\"d-none\");\n $(this).prop('disabled', false);\n return false;\n }\n\n if (!terms) {\n await browserCommunicatorService.displayInfoAlert({ description: 'No olvides aceptar los términos y condiciones.' })\n spinnerWait.addClass(\"d-none\");\n $(this).prop('disabled', false);\n return false;\n }\n\n // Analytics event: \"intent_verification_account\"\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackAccountVerification({\n action: 'intent',\n customerEmail: email,\n customerPhone: phoneNumber || mobileNumber\n });\n })\n .catch(function (err) {\n console.error(err);\n })\n\n var request = {\n Address: address,\n NeighborhoodName: neighborhoodName,\n Neighborhood: neighborhood,\n City: city,\n CityId: cityId,\n State: state,\n StateId: stateId,\n Password: password,\n PhoneNumber: phoneNumber,\n MobileNumber: mobileNumber,\n SecondSurname: secondsurname,\n Surname: surname,\n SecondName: secondname,\n FirstName: name,\n IdentificationNumber: identification,\n IdentificationType: identificationType,\n Email: email,\n Birthdate: birth,\n BusinessTypeCode: businessType,\n CIIUCode: ciiuCode,\n FiscalResponsabilityCode: fiscalResponsabilty,\n TributeCode: tribute,\n BusinessName: businessName,\n ReceivePromotionalCommunications: receivePromotionalCommunications,\n AgreementCode: agreementcode\n };\n\n app.customerService.signUp(request, async function (response) {\n var email = response.SendCode.Email;\n var mobileNumber = response.SendCode.Phone;\n var userId = response.SendCode.UserId;\n var regId = response.SendCode.RegId;\n var sendCode = `${userId}|${email}|${mobileNumber}|${regId}`;\n\n if (response.SignUpResponse.Successful) {\n // Dispatch sign_up analytics event\n try {\n app.applicationMonitoringService()\n .then(function (service) {\n service.trackSignUp()\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n\n await browserCommunicatorService.displaySuccessAlertAsync({ description: \"Felicitaciones, ¡Completaste tu registro con exito!\" })\n\n $(\"#send-code\").val(sendCode);\n $(\"#form-validate\").submit();\n spinnerWait.addClass(\"d-none\");\n buttonRegister.prop('disabled', false);\n } else {\n if (response.SignUpResponse.Message != \"\" && response.SignUpResponse.Message != 'undefined' &&\n response.SignUpResponse.Message != null) {\n await browserCommunicatorService.displayErrorAlert({\n description: response.SignUpResponse.Message,\n html: true\n })\n if (response.SignUpResponse.ErrorCode == \"USEREXIST\") {\n spinnerWait.addClass(\"d-none\");\n buttonRegister.prop('disabled', false);\n window.location.href = '/Security/Login/';\n }\n // FIXME: REMOVE THIS STRING CONDITION\n else if (response.SignUpResponse.Message == \"Tu usuario esta inactivo, te enviaremos un código de activación.\") {\n spinnerWait.addClass(\"d-none\");\n buttonRegister.prop('disabled', false);\n $(\"#send-code\").val(sendCode);\n $(\"#form-validate\").submit();\n }\n else {\n spinnerWait.addClass(\"d-none\");\n buttonRegister.prop('disabled', false);\n }\n\n }\n else {\n await browserCommunicatorService.displayErrorAlert({ description: 'Ocurri\\u00F3 un error al registrar el usuario, por favor intentalo nuevamente.' })\n spinnerWait.addClass(\"d-none\");\n buttonRegister.prop('disabled', false);\n }\n }\n }, function (response) {\n errorMessaje();\n }, function (response) {\n errorMessaje();\n }\n );\n}\n\nasync function errorMessaje() {\n await browserCommunicatorService.displayErrorAlert({ description: 'Ocurri\\u00F3 un error al registrar el usuario, por favor intentalo nuevamente.' })\n spinnerWait.addClass(\"d-none\");\n buttonRegister.prop('disabled', false);\n}\n\nfunction authenticate(event) {\n event.stopPropagation();\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n\n var email = $('.email-label').val();\n var password = $('.password-label').val();\n\n app.customerService.authenticate(email, password,\n async function (response) {\n if (response.Message != null && !response.User) {\n await browserCommunicatorService.displayErrorAlert({\n description: response.Message,\n html: true\n })\n }\n else {\n\n // track user analytics\n await CustomerAnalyticsHelper.trackUser({\n response: response,\n tracklogin: true\n })\n\n window.location.href = '/';\n spinnerWait.addClass(\"d-none\");\n }\n },\n function (response) {\n spinnerWait.addClass(\"d-none\");\n });\n}\n\nfunction rememberPassword(event) {\n event.stopPropagation();\n\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n\n var userName = $('#UserNameProperty').val();\n\n app.customerService.rememberPassword(userName,\n async function (result) {\n if (result.success) {\n await browserCommunicatorService.displayInfoAlert({\n description: result.processMessage,\n html: true\n })\n // dispatch \"recover_password\" analytics event\n try {\n let usernameEl = document.querySelector(`input[name=\"UserNameProperty\"]`)\n let username = usernameEl.value || analytics.AnalyticsConstants.DefaultParameterValue;\n app.applicationMonitoringService()\n .then(function (service) {\n service.trackRecoverPassword(username)\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n window.location.href = result.pagaToNavigate;\n spinnerWait.addClass(\"d-none\");\n }\n else {\n await browserCommunicatorService.displayErrorAlert({\n description: result.processMessage,\n html: true\n })\n }\n },\n function (response) {\n spinnerWait.addClass(\"d-none\");\n });\n}\n\n//#endregion\n\n//#region SignUp B2C\n\n/**\n * Obsolete, use legacy pages SimpleSignIn, SignIn and SignInComplete \n * @param {any} event\n */\nfunction sendValidationCode(event) {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n\n var sendCodeRequest = {\n UserId: $(\"#SendCode_UserId\").val(),\n Email: $(\"#SendCode_Email\").val(),\n Phone: $(\"#SendCode_PhoneNumber\").val(),\n Method: $(\"input[name='OptionSendSMS']:checked\").val(),\n };\n\n app.customerService.reSendValidationCodeB2C(sendCodeRequest,\n async function (response) {\n if (response.Successful) {\n $(\"#SendCode_RegId\").val(response.RegId);\n\n $('#accountActivation').on('hidden.bs.modal', function () {\n if ($(\"#RefValidation\").val() == \"login\") {\n kendo.ui.progress($(\".login-form\"), false);\n kendo.ui.progress($(\".login-phone\"), false);\n } else {\n kendo.ui.progress($(\"#registerNewUserB2C\"), false);\n }\n });\n\n $(\"#ConfirmationMessageSending\").modal(\"hide\");\n\n let customerEmail = $(\"#SendCode_Email\").val() || analytics.AnalyticsConstants.DefaultParameterValue;\n let customerPhone = $(\"#SendCode_PhoneNumber\").val() || analytics.AnalyticsConstants.DefaultParameterValue;\n\n window.app.applicationMonitoringService()\n .then(function (service) {\n service.trackAccountVerification({ action: 'intent', customerEmail: customerEmail, customerPhone: customerPhone });\n })\n .catch(function (err) {\n console.error(err);\n })\n\n if ($(\"#OnlyActivate\").val() !== \"false\") {\n window.location.href = '/Security/UserAccount/Index';\n return;\n }\n\n $(\"#accountActivation\").modal(\"show\");\n\n $('.resend-activation-code-button-b2c').on(\"click\", reSendValidationCode);\n spinnerWait.addClass(\"d-none\");\n } else {\n await browserCommunicatorService.displayErrorAlert({\n description: response.Message,\n html: true\n })\n spinnerWait.addClass(\"d-none\");\n }\n },\n function (response) {\n spinnerWait.addClass(\"d-none\");\n });\n}\n\n/**\n * Obsolete, use legacy pages SimpleSignIn, SignIn and SignInComplete \n * @param {any} event\n */\nfunction reSendValidationCode(event) {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n\n var sendCodeRequest = {\n UserId: $(\"#SendCode_UserId\").val(),\n Email: $(\"#SendCode_Email\").val(),\n Phone: $(\"#SendCode_PhoneNumber\").val(),\n Method: $(\"input[name='OptionSendSMS']:checked\").val(),\n };\n\n app.customerService.reSendValidationCodeB2C(sendCodeRequest,\n async function (response) {\n if (response.Successful) {\n $(\"#SendCode_RegId\").val(response.RegId);\n spinnerWait.addClass(\"d-none\");\n } else {\n await browserCommunicatorService.displayInfoAlert({\n description: response.Message,\n html: true\n })\n spinnerWait.addClass(\"d-none\");\n }\n },\n function (response) {\n spinnerWait.addClass(\"d-none\");\n });\n}\n\n//#endregion\n\n//#region Input data validation - B2C\n\nfunction validateOnlyNumbers(event) {\n var char = String.fromCharCode(event.keyCode);\n\n if (/[0-9]/.test(char)) {\n return true;\n }\n\n return false;\n}\n\nfunction preventSpaceInput(event) {\n if (event.which === 32)\n return false;\n}\n\n//#endregion\n","class ChatService {\n\n static init() {\n var initESW = function (gslbBaseURL) {\n embedded_svc.settings.displayHelpButton = true; //O falso\n embedded_svc.settings.language = 'es'; //Por ejemplo, introduzca 'en' o 'en-US'\n\n embedded_svc.settings.defaultMinimizedText = '¿Necesitas ayuda?'; //(Toma como valor predeterminado Sesión de chat con un experto)\n embedded_svc.settings.disabledMinimizedText = 'Agente sin conexión...'; //(Toma como valor predeterminado Agente sin conexión)\n embedded_svc.settings.loadingText = 'Cargando'; //(Toma como valor predeterminado Cargando)\n embedded_svc.settings.storageDomain = 'surtiapp.com.co'; //(Establece el dominio para su desarrollo de modo que los visitantes puedan navegar por subdominios durante una sesión de chat)\n\n // Configuración para Chat\n //embedded_svc.settings.directToButtonRouting = function(prechatFormData) {\n // Dynamically changes the button ID based on what the visitor enters in the pre-chat form.\n // Returns a valid button ID.\n //};\n //embedded_svc.settings.prepopulatedPrechatFields = {}; //Establece la cumplimentación automática de los campos del formulario previo al chat\n //embedded_svc.settings.fallbackRouting = []; //Una matriz de identificadores de botones, de usuario o userId_buttonId\n //embedded_svc.settings.offlineSupportMinimizedText = '...'; //(Toma como valor predeterminado la opción Contacto)\n\n embedded_svc.settings.enabledFeatures = ['LiveAgent'];\n embedded_svc.settings.entryFeature = 'LiveAgent';\n\n embedded_svc.init(\n 'https://altipalsas.my.salesforce.com',\n 'https://altipal.force.com',\n gslbBaseURL,\n '00D8c000002g6Rv',\n 'ALT_AgentesChat',\n {\n baseLiveAgentContentURL: 'https://c.la5-c2-ia5.salesforceliveagent.com/content',\n deploymentId: '5728c000000QsVG',\n buttonId: '5738c000000QuSx',\n baseLiveAgentURL: 'https://d.la5-c2-ia5.salesforceliveagent.com/chat',\n eswLiveAgentDevName: 'ALT_AgentesChat',\n isOfflineSupportEnabled: true\n }\n );\n };\n\n if (!window.embedded_svc) {\n var s = document.createElement('script');\n s.setAttribute('src', 'https://altipalsas.my.salesforce.com/embeddedservice/5.0/esw.min.js');\n s.onload = function () {\n initESW(null);\n };\n document.body.appendChild(s);\n } else {\n initESW('https://service.force.com');\n }\n }\n}\n\nexport default ChatService","import UrlHelper from '../helpers/url-helper.js'\nimport AjaxProxy from '../proxies/ajax-proxy.js'\n\nclass CheckoutService {\n\n _endpoints = {\n couponButtonView: \"?handler=CouponButtonView\",\n couponListView: \"?handler=CouponListView\",\n expiredCouponListView: \"?handler=ExpiredCouponListView\",\n removeCoupon: \"?handler=RemovePromotionalCode\",\n increaseProductQuantity: \"?handler=IncreaseProductQuantity\",\n decreaseProductQuantity: \"?handler=DecreaseProductQuantity\",\n removeProductQuantity: \"?handler=RemoveProductQuantity\",\n updateProductQuantity: \"?handler=UpdateProductQuantity\",\n productListView: \"?handler=ProductListView\",\n changeAddress: \"?handler=ChangeAddress\",\n acceptancePoliciesView: \"?handler=AcceptancePoliciesView\",\n getSurticreditoBalanceView: \"?handler=SurtiCreditoBalance\"\n }\n\n constructor() {\n }\n\n saveOrder(order, successCallback, failCallback) {\n let url = UrlHelper.saveOrderUrl;\n let requestData = { parms: JSON.stringify(order) };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n messagesPendingByUserAnswer(successCallback, failCallback) {\n let url = UrlHelper.messagesPendingByUserAnswer;\n let request = {\n url: url,\n dataType: 'json',\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n saveUserAnswerByValidationMessage(answer, successCallback, failCallback) {\n let url = UrlHelper.saveUserAnswerByValidationMessage;\n let requestData = { answer: answer };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: successCallback,\n failCallback: failCallback\n };\n\n AjaxProxy.post(request);\n }\n\n getCouponButtonView() {\n return AjaxProxy.postFetch(this._endpoints.couponButtonView, {})\n }\n\n getCouponListView() {\n return AjaxProxy.postFetch(this._endpoints.couponListView, {})\n }\n\n getExpiredCouponListView() {\n return AjaxProxy.postFetch(this._endpoints.expiredCouponListView, {})\n }\n\n removePromoCode() {\n return AjaxProxy.postFetch(this._endpoints.removeCoupon, {});\n }\n\n /**\n * \n * @param productId {string}\n * @param {boolean} [isKit=false] \n * @param {string} [internalId=null] \n * */\n increaseProductQuantity(productId, internalId = null, isKit = false) {\n const requestData = new FormData()\n requestData.append(\"productId\", productId);\n if (internalId) {\n requestData.append(\"internalId\", internalId);\n }\n requestData.append(\"isKit\", isKit);\n\n return AjaxProxy.postRx({\n url: this._endpoints.increaseProductQuantity,\n body: requestData\n })\n }\n\n decreaseProductQuantity(productId, internalId = null, isKit = false) {\n const requestData = new FormData()\n requestData.append(\"productId\", productId)\n if (internalId) {\n requestData.append(\"internalId\", internalId);\n }\n requestData.append(\"isKit\", isKit);\n \n return AjaxProxy.postRx({\n url: this._endpoints.decreaseProductQuantity,\n body: requestData\n });\n }\n\n removeProductQuantity(productId) {\n const formData = new FormData()\n formData.append(\"productId\", productId);\n return AjaxProxy.postRx({\n url: this._endpoints.removeProductQuantity,\n body: formData\n });\n }\n\n updateProductQuantity(productId, quantity, internalId = null, isKit = false) {\n const requestData = new FormData()\n requestData.append(\"productId\", productId)\n requestData.append(\"quantity\", quantity)\n if (internalId) {\n requestData.append(\"internalId\", internalId);\n }\n requestData.append(\"isKit\", isKit);\n \n return AjaxProxy.postRx({\n url: this._endpoints.updateProductQuantity,\n body: requestData\n });\n }\n\n getProductListView(){\n return AjaxProxy.postRxHtml({ url: this._endpoints.productListView});\n }\n\n changeAddress(addressId){\n const formData = new FormData()\n formData.append('addressId', addressId)\n return AjaxProxy.postRx({ url: this._endpoints.changeAddress, body: formData})\n }\n\n acceptancePoliciesView() {\n return AjaxProxy.postRxHtml({ url: this._endpoints.acceptancePoliciesView })\n }\n\n\n /**\n * \n * @returns\n */\n getSurticreditoBalanceView(paymentAmount) {\n const formData = new FormData()\n formData.append(\"paymentAmount\", paymentAmount);\n let request = {\n body: formData\n }\n return AjaxProxy.postFetch(this._endpoints.getSurticreditoBalanceView, request);\n }\n}\n\nexport default CheckoutService;","const VerificationCodeType = {\n None: {\n VerificationCodeForm: {\n Title: \"Validar código\",\n ImageUrl: \"/img/json/verification-code.json\",\n Message: \"Hemos enviado un código a tu cuenta de correo o celular.\",\n VerificationCodeLabel: \"Escribe tu código aquí:\",\n ValidCodeButtonLabel: \"Validar\",\n ReSendButtonLabel: \"Reenviar código\",\n },\n SendingMethodSelectionForm: {\n Title: \"Validar código\",\n PhoneNumberLabel: \"Envíame el código al número de celular:\",\n EmailLabel: \"Envíame el código al correo:\",\n BugLabel: \"Oops, no podemos encontrar ningún dato para enviarte el código de verificación.\",\n },\n MessageResponse: \"El código ingresaste es correcto.\"\n },\n AccountActivation: {\n VerificationCodeForm: {\n Title: \"Activar cuenta\",\n ImageUrl: \"/img/json/verification-code.json\",\n Message: \"Hemos enviado un código de activación a tu cuenta de correo o celular.\",\n VerificationCodeLabel: \"Escribe tu codigo aqui:\",\n ValidCodeButtonLabel: \"Validar\",\n ReSendButtonLabel: \"Reenviar código\",\n },\n SendingMethodSelectionForm: {\n Title: \"Activar cuenta\",\n PhoneNumberLabel: \"Envíame el código al número de celular:\",\n EmailLabel: \"Envíame el código al correo:\",\n BugLabel: \"Oops, no podemos encontrar ningún dato para enviarte el código para activar tu cuenta.\",\n },\n MessageResponse: \"Su cuenta se ha activado correctamente.\"\n },\n AccountValidation: {\n VerificationCodeForm: {\n Title: \"Verificar cuenta\",\n ImageUrl: \"/img/json/verification-code.json\",\n Message: \"Hemos enviado un código para verificar tu cuenta a tu correo o celular.\",\n VerificationCodeLabel: \"Escribe tu código aquí:\",\n ValidCodeButtonLabel: \"Verificar\",\n ReSendButtonLabel: \"Reenviar código\",\n },\n SendingMethodSelectionForm: {\n Title: \"Verificar cuenta\",\n PhoneNumberLabel: \"Envíame el código al número de celular:\",\n EmailLabel: \"Envíame el código al correo:\",\n BugLabel: \"Oops, no podemos encontrar ningún dato para enviarte el código para verificar tu cuenta.\",\n },\n MessageResponse: \"Su cuenta ha sido verificada con éxito.\"\n },\n CertificateValidation: {\n VerificationCodeForm: {\n Title: \"Validar código\",\n ImageUrl: \"/img/json/verification-code.json\",\n Message: \"Te hemos enviado un código a tu cuenta de correo y/o celular.\",\n VerificationCodeLabel: \"Ingresa aquí tu código :\",\n ValidCodeButtonLabel: \"Validar\",\n ReSendButtonLabel: \"Reenviar código\",\n },\n SendingMethodSelectionForm: {\n Title: \"Validar código\",\n PhoneNumberLabel: \"Recibir código al número de celular:\",\n EmailLabel: \"Recibir código al correo:\",\n BugLabel: \"Oops, no podemos enviarte el código de verificación porque no tienes configurados correo ni celular.\",\n },\n MessageResponse: \"La validación del código es correcta.\"\n },\n}\n\nexport default VerificationCodeType;","import UrlHelper from '../helpers/url-helper.js';\nimport AjaxProxy from '../proxies/ajax-proxy.js';\nimport ModalHelper from '../helpers/modal-helper.js';\nimport VerificationCodeType from '../helpers/verification-code-helper.js';\nimport { BrowserCommunicatorService } from './browser-communicator-service.js';\n\nconst browserCommunicatorService = new BrowserCommunicatorService()\n\nexport default class VerificationCode {\n\n //#region Attributes\n\n #username = \"\";\n #callback = function () { };\n #type = VerificationCodeType.None;\n\n //#endregion\n\n //#region Constructors\n\n constructor() {\n this._browserCommunicatorService = new BrowserCommunicatorService()\n }\n\n //#endregion\n\n //#region Methods\n\n init({ username, callback, verificationCodeType = VerificationCodeType.None }) {\n this.#createContaint();\n\n this.#type = verificationCodeType;\n this.#username = username;\n this.#callback = callback;\n\n $(\"#username\").val(username);\n \n const execModules = async () => {\n await this.#getData();\n }\n\n execModules();\n }\n\n #createContaint(){\n if ($(\"#verification-code\").length === 0) {\n $(\"body\").append(\"
    \");\n }\n\n $(\"#verification-code\").html(\"\");\n\n $(\"#verification-code\").append(\"\");\n $(\"#verification-code\").append(\"\");\n $(\"#verification-code\").append(\"\");\n $(\"#verification-code\").append(\"\");\n $(\"#verification-code\").append(\"\");\n }\n\n async #getData() {\n try {\n var type = this.#type;\n var username = this.#username;\n var callbackMain = this.#callback;\n let verificationCodeService = new VerificationCodeService();\n\n //Load data\n await verificationCodeService.getDataUser(\n this.#username,\n async (response) => {\n if (response.Successful) {\n $(\"#userId\").val(response.UserId);\n $(\"#email\").val(response.Email);\n $(\"#phoneNumber\").val(response.PhoneNumber);\n\n var verificationCodeService = new VerificationCodeService();\n\n\n //start renderSendingMethodSelectionContent\n\n let dataRequest = {\n Title: type.SendingMethodSelectionForm.Title,\n PhoneNumberLabel: type.SendingMethodSelectionForm.PhoneNumberLabel,\n EmailLabel: type.SendingMethodSelectionForm.EmailLabel,\n BugLabel: type.SendingMethodSelectionForm.BugLabel,\n Username: username,\n Email: response.Email,\n PhoneNumber: response.PhoneNumber,\n UserId: response.UserId,\n };\n await verificationCodeService.getRenderSendingMethodSelectionContent(dataRequest, function (response) {\n $(\"#verification-code\").append(response);\n $(\".send-code-verification\").on(\"click\", sendCode);\n $(\"#message-sending-method-window\").modal(\"show\");\n });\n\n\n //start renderVerificationCodeContent\n\n dataRequest = type.VerificationCodeForm;\n await verificationCodeService.getRenderVerificationCodeContent(dataRequest, function (response) {\n $(\"#verification-code\").append(response);\n $(\".resend-code-button\").on(\"click\", sendCode);\n $(\".valid-code-button\").on(\"click\", { callbackMain: callbackMain, message: type.MessageResponse }, validateCode);\n });\n\n return;\n }\n await this._browserCommunicatorService.displayInfoAlert({\n description: response.Message,\n html: true\n })\n },\n async (err) => {\n\n //When you are not authorized [StatusCode==401] or your session expired, in this case a redirection to the login is made.\n //ToDo: remove this redirection when using the old Login.\n\n if (err.status === 401) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: \"No está autorizado para ejecutar esta acción o su sesión ha expirado, por favor inicie nuevamente su sesión\"\n })\n window.location.href = \"/Security/UserAccount/Index\"\n }\n }\n );\n } catch (e) {\n\n }\n }\n\n //#endregion\n\n}\n\n\nclass VerificationCodeService {\n async getDataUser(username, callback, errorCallback) {\n let url = UrlHelper.postDataUser;\n let requestData = { username: username };\n let request = {\n url: url,\n dataType: 'json',\n data: requestData,\n callback: callback,\n errorCallback: errorCallback\n };\n\n AjaxProxy.post(request);\n }\n\n async getRenderVerificationCodeContent(verificationCode, callback) {\n let url = UrlHelper.postRenderVerificationCode;\n let requestData = { verificationCode: verificationCode };\n let request = {\n url: url,\n dataType: 'html',\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n async getRenderSendingMethodSelectionContent(messageSendingMethod, callback) {\n let url = UrlHelper.postRenderSendingMethodSelection;\n let requestData = { messageSendingMethod: messageSendingMethod };\n let request = {\n url: url,\n data: requestData,\n dataType: 'html',\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n sendCode(sendCode, callback) {\n let url = UrlHelper.postSendVerificationCode;\n let requestData = { sendCodeRequest: sendCode };\n let request = {\n url: url,\n data: requestData,\n dataType: 'json',\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n validateCode(sendCode, callback) {\n let url = UrlHelper.postValidateCode;\n let requestData = { sendCodeRequest: sendCode };\n let request = {\n url: url,\n data: requestData,\n dataType: 'json',\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n}\n\n//General Functions\nfunction sendCode() {\n try {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n\n let selectedMethod = $(\"input[name='option-send-sms']:checked\").val();\n let dataRequest = {\n UserId: $(\"#userId\").val(),\n Email: $(\"#email\").val(),\n Phone: $(\"#phoneNumber\").val(),\n Method: selectedMethod\n };\n let verificationCodeService = new VerificationCodeService();\n\n //Send code\n verificationCodeService.sendCode(dataRequest, async (response) => {\n spinnerWait.addClass(\"d-none\");\n\n if (response.Successful) {\n $(\"#regId\").val(response.RegId);\n $(\"#message-sending-method-window\").modal(\"hide\");\n\n if (!$('#verification-code-window').is(':visible')) {\n $(\"#verification-code-window\").modal(\"show\");\n }\n\n return;\n }\n await browserCommunicatorService.displayInfoAlert({\n description: response.Message,\n html: true\n })\n });\n } catch (e) {\n console.error(e)\n }\n}\n\nfunction validateCode(e) {\n try {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n\n let dataRequest = {\n RegId: $(\"#regId\").val(),\n UserId: $(\"#userId\").val(),\n CodeValid: $(\"#number-code\").val(),\n };\n let verificationCodeService = new VerificationCodeService();\n let callbackMain = e.data.callbackMain;\n let message = e.data.message;\n\n //Validate code\n verificationCodeService.validateCode(dataRequest, async function (response) {\n spinnerWait.addClass(\"d-none\");\n\n if (response.Successful) {\n if (response.Validation) {\n await browserCommunicatorService.displaySuccessAlertAsync({\n description: $.trim(message) == \"\" ? response.Message : message,\n autoclosing: true,\n html: true\n })\n callbackMain()\n\n $(\"#verification-code-window\").modal(\"hide\");\n\n return;\n }\n }\n await browserCommunicatorService.displayErrorAlert({\n description: response.Message,\n html: true\n })\n });\n } catch (e) {\n\n }\n}","import Ajax from '../proxies/ajax'\nimport AjaxProxy from '../proxies/ajax-proxy'\nimport UrlHelper from '../helpers/url-helper'\n\nexport class MarkingService {\n\n getMarkingPriceById(markingTypeId, quantity) {\n let formData = new FormData();\n formData.append(\"markingTypeId\", markingTypeId)\n formData.append(\"quantity\", quantity)\n return AjaxProxy.postFetch(UrlHelper.markingByProductModel.postGetMarkingPriceById, {body: formData});\n }\n}","import ShoppingCartService from \"../shared/shopping-cart/services/shopping-cart-service\";\nimport { MarkingService } from \"../services/marking-service\";\nimport { BrowserCommunicatorService } from \"../services/browser-communicator-service\";\n\nexport class MarkingHandlers {\n\n /** @type {ShoppingCartService} **/\n _shoppingCartService;\n\n /**\n * @type {MarkingService}\n * */\n _markingService;\n\n totalQuantity;\n\n imageConfig = {\n\n //Displays the image selected in a file input type.\n loadImage: function (imageFile, imageContainerId, noImageContainerId) {\n const imageContainer = document.getElementById(imageContainerId);\n imageContainer.src = URL.createObjectURL(imageFile);\n imageContainer.style.display = 'inherit';\n\n //Hide image message if necessary\n const imageMessage = document.getElementById(noImageContainerId);\n if (imageMessage) {\n imageMessage.style.display = 'none';\n }\n }\n }\n\n constructor() {\n this._shoppingCartService = new ShoppingCartService();\n this._markingService = new MarkingService();\n this._browserCommunicatorService = new BrowserCommunicatorService()\n this.init();\n }\n\n init() {\n this.bindMarkingControl();\n\n //Init Marking\n }\n\n async markingTypeChange(event) {\n\n let imageEnumImage = $(\"#imageEnumImage\").val();\n let imageEnumLegend = $(\"#imageEnumLegend\").val();\n let imageEnumBoth = $(\"#imageEnumBoth\").val();\n let selected = $(\"#MarkingProduct_MarkingType_Id\").data(\"kendoDropDownList\")?.dataItem().InternalCode;\n let markingTypeId = $(\"#MarkingProduct_MarkingType_Id\").data(\"kendoDropDownList\")?.dataItem().Id;\n\n var response = await this._markingService.getMarkingPriceById(markingTypeId);\n if (response.ok) {\n const responseJson = await response.json()\n if (responseJson.Successful) {\n if (responseJson.Price) {\n let precio = responseJson.Price\n } else {\n await this._browserCommunicatorService.displayInfoAlert({\n description: responseJson.UserMessage,\n html: true\n })\n }\n }\n }\n\n $('#panel-marking-image').hide();\n\n if (selected !== undefined && selected == imageEnumImage) {\n $('#panel-marking-image').show();\n }\n\n var selectedMessage = $(\"#MarkingProduct_MarkingMessage_Id\").data(\"kendoDropDownList\")?.dataItem().Message;\n if (selected == imageEnumLegend) {\n $('.panel-marking-legend').show();\n $('.panel-marking-position').show();\n $('.panel-marking-image').hide();\n\n if (selectedMessage !== undefined && selectedMessage === \"Personalizado\") {\n $('.panel-marking-legend-personalized').show();\n }\n else {\n $('.panel-marking-legend-personalized').hide();\n }\n }\n if (selected == imageEnumImage) {\n\n $('.panel-marking-image').show();\n $('.panel-marking-legend').hide();\n $('.panel-marking-legend-personalized').hide();\n\n }\n if (selected == imageEnumBoth) {\n\n $('.panel-marking-image').show();\n $('.panel-marking-position').show();\n $('.panel-marking-legend').show();\n $('.panel-marking-legend-personalized').show();\n\n }\n }\n\n filterCascadePositionsByMarkingTypeGroup() {\n let BindingPositionsList = \"#MarkingProduct_MarkingType_Id\";\n\n return {\n markingTypeId: $(BindingPositionsList).val(),\n \"__RequestVerificationToken\": $('input[name=__RequestVerificationToken]').val()\n };\n }\n\n bindMarkingControl() {\n $('.btn-marking').on('click', this.marking);\n\n $('.btn-markingByProduct').off('click');\n $('.btn-markingByProduct').on('click', this.markingByProduct);\n\n $('.add-marking').off('click');\n $('.add-marking').on('click', e => { e.preventDefault(); this.createMarkingClick(e) });\n\n $('#markingType').off('change');\n $('#markingType').on('change', this.markingTypeChange);\n\n $('#markingRepeatProduct').off('change');\n $('#markingRepeatProduct').on('change', this.markingRepeatProductChange);\n\n $('.save-marking2').off('click');\n $('.save-marking2').on('click', e => { e.preventDefault(); this.onClickSaveMarking(e) });\n\n $('.delete-from-marking').off('click');\n $('.delete-from-marking').on('click', e => { e.preventDefault(); this.onClickDeleteFromMarking(e) });\n\n\n $('.marking-return-button').off('click');\n $('.marking-return-button').on('click', this.markingReturnClick);\n\n $('.save-image-marking').off('click');\n $('.save-image-marking').on('click', this.onClickImage);\n\n $('#selected-image-marking').off('change');\n $('#selected-image-marking').on('change', this.loadMarkingImage);\n\n $(\"#markingMessageText\").on('input', () => {\n this.updateLabelMarkingMessage();\n });\n }\n\n dataMarkingTypes() {\n var parameter = kendo.antiForgeryTokens();\n parameter.productBranchOfficeId = $(\"#productBranchOfficeId\").val();\n parameter.productId = $(\"#productId\").val();\n\n return parameter;\n }\n\n calculateMaxLength(e) {\n $(\"#MarkingProduct_MarkingCustomMessage\").on('input', (e) => {\n $('.k-counter-container .k-counter-value').html($(e.target).val().length);\n });\n }\n\n onClickImageWeb(e) {\n $('#LoadImageWeb').trigger('click');\n }\n\n marking() {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n var that = this;\n var parent = $(that).parent();\n var productId = app.productHelper.getProductId(parent);\n this.totalQuantity = document.getElementById(\"quantity-\" + productId).previousElementSibling.innerHTML;\n spinnerWait.addClass(\"d-none\");\n window.location.href = \"Marking/\" + productId + \"/\" + this.totalQuantity;\n }\n\n markingByProduct() {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n var that = this;\n var parent = $(that).parent();\n var productId = app.productHelper.getProductId(parent);\n this.totalQuantity = document.getElementById(\"quantity-\" + productId).previousElementSibling.innerHTML;\n spinnerWait.addClass(\"d-none\");\n window.location.href = \"MarkingByProduct/\" + productId + \"/\" + this.totalQuantity;\n }\n\n repeatProductValidation() {\n let quantityProduct = $('#quantityByProductPending').val();\n\n if (quantityProduct !== undefined && quantityProduct == 1) {\n $('.panel-marking-repeatProduct').hide();\n $('.panel-marking-repeat').hide();\n }\n }\n\n async createMarkingClick() {\n let quantityProduct = $('#quantityByProductPending').val();\n if (quantityProduct == 0) {\n await this._browserCommunicatorService.displayErrorAlert({ description: \"Ya tienes el total de productos con marcación.\" })\n return;\n }\n else if (quantityProduct == 1) {\n $('.panel-marking-repeatProduct').hide();\n $('.panel-marking-repeat').hide();\n }\n }\n\n productQuantityChange() {\n\n let quantity = $(\"#MarkingProduct_Quantity\").data(\"kendoNumericTextBox\").value();\n\n $('.panel-marking-cost').text('Valor Unitario : $5.000');\n }\n\n updateLabelMarkingMessage() {\n let lengthMarkingText = $(\"#markingMessageText\").val().length;\n var maxLength = $(\"#markingMessageText\")[0].maxLength;\n let total = maxLength - lengthMarkingText;\n $(\"#markingMessageLength\").text(\"Caracteres restantes \" + total);\n }\n\n markingRepeatProductChange() {\n var markingRepeatProductControl = $('#MarkingProduct_RepeatProduct');\n var markingRepeatProduct = markingRepeatProductControl[0].checked;\n if (!markingRepeatProduct) {\n $('.panel-marking-repeat').show();\n }\n else {\n $('.panel-marking-repeat').hide();\n }\n }\n\n markingMessageChanges() {\n var selected = $(\"#MarkingProduct_MarkingMessage_Id\").data(\"kendoDropDownList\")?.dataItem().Message;\n $('.panel-marking-legend-personalized').hide();\n\n if (selected !== undefined && selected == \"Personalizado\") {\n $('.panel-marking-legend-personalized').show();\n }\n }\n\n markingTypeChanges() {\n let selected = $(\"#MarkingProduct_MarkingType_Id\").data(\"kendoDropDownList\")?.dataItem().InternalCode\n let enumImage = $(\"#imageEnumText\").val();\n\n $('#panel-marking-image').hide();\n\n if (selected !== undefined && selected == enumImage) {\n $('#panel-marking-image').show();\n }\n }\n\n markingSaveClick(e) {\n var image = new FormData();\n var imageName = \"\";\n var imageContent;\n var imageSize;\n var spinnerWait = $(e.target).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n\n const imageSelected = document.getElementById('LoadImageWeb');\n\n if (imageSelected.files && imageSelected.files[0]) {\n image.append('image', imageSelected.files[0]);\n imageName = imageSelected.files[0].name;\n imageSize = imageSelected.files[0].size;\n }\n\n if (imageName != \"\") {\n this._shoppingCartService.markingSaveImage(image, (result) => {\n imageContent = result.ImageContent;\n this.saveMarking(imageName, imageSize, imageContent, spinnerWait);\n });\n }\n else {\n this.saveMarking(imageName, imageSize, imageContent, spinnerWait);\n }\n }\n\n saveMarking(imageName, imageSize, imageContent, spinnerWait) {\n var markingRepeatProductControl = $('#markingRepeatProduct');\n var isRepeat = markingRepeatProductControl[0].checked;\n var markingTypeId = $(\"#ddlMarkingType\").data(\"kendoDropDownList\").value()\n var markingType = $(\"#ddlMarkingType\").data(\"kendoDropDownList\").text()\n var markingPositionId = $(\"#ddlSystemDef\").data(\"kendoDropDownList\").value();\n var markingPosition = $(\"#ddlSystemDef\").data(\"kendoDropDownList\").text()\n var markingMessage = $(\"#MarkingProduct_MarkingMessage\").data(\"kendoDropDownList\").value();\n var markingMessageText = $(\"#MarkingMessageText\").val();\n var quantity = $(\"#quantityProducts\").val();\n var productBranchOfficeId = $(\"#productBranchOfficeId\").val();\n var title = $('#markingModal .marking-modal-title').text();\n var isEdit = $(\"#IsEdit\").val();\n var quantityProduct = $(\"#quantityProducts\").val();\n var totalQuantityProduct = $(\"#totalQuantityProduct\").val();\n\n if (markingMessage != \"Personalizado\") {\n markingMessageText = markingMessage;\n }\n\n var MarkingType = {\n Id: markingTypeId,\n Mark: markingType\n };\n\n var MarkingPosition = {\n Id: markingPositionId,\n Position: markingPosition\n };\n\n var Marking = {\n MarkingPosition: MarkingPosition,\n MarkingType: MarkingType,\n Quantity: quantity,\n Message: markingMessageText,\n ProductBranchOfficeId: productBranchOfficeId,\n Image: imageName != \"\",\n ImageName: imageName,\n ImageSize: imageSize,\n ImageContent: imageContent\n };\n\n let oldMarking = null;\n if (isEdit === 'True') {\n oldMarking = JSON.parse($(\"oldMarking\").val())\n }\n\n this._shoppingCartService.markingSave(Marking, oldMarking, isRepeat, isEdit, quantityProduct, totalQuantityProduct, async (result) => {\n if (result.HasError) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: result.MessageError,\n html: true\n })\n spinnerWait.addClass(\"d-none\");\n }\n else if (result.MessageError != \"Guardado exitoso.\") {\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: result.MessageError,\n html: true\n })\n\n if (confirmResult.isConfirmed) {\n this._shoppingCartService.markingSaveConfirm(result.Marking, oldMarking, isEdit, async (result) => {\n await this._browserCommunicatorService.displayInfoAlert({\n description: result.MessageError,\n html: true\n })\n spinnerWait.addClass(\"d-none\");\n window.location.href = result.RedirectTo;\n });\n } else {\n spinnerWait.addClass(\"d-none\");\n }\n }\n else {\n await this._browserCommunicatorService.displayInfoAlert({\n description: result.MessageError,\n html: true\n })\n spinnerWait.addClass(\"d-none\");\n window.location.href = result.RedirectTo;\n }\n });\n }\n\n /**\n * \n * @param {Event} e\n */\n async onClickDeleteFromMarking(e) {\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: \"Vas a eliminar la marcación, ¿deseas continuar?\"\n })\n\n if (confirmResult.isConfirmed) {\n try {\n this._displayLoading(true)\n\n /** @type {HTMLElement} */\n const element = e.currentTarget;\n const markingId = element.getAttribute(\"data-markingId\")\n const deleteFormData = new FormData()\n deleteFormData.append(\"markingId\", markingId)\n var response = await this._shoppingCartService.markingDelete(deleteFormData);\n if (response.ok) {\n const responseJson = await response.json()\n if (responseJson.Successful) {\n if (responseJson.RedirectTo) {\n window.location.href = responseJson.RedirectTo\n } else {\n await this._browserCommunicatorService.displayInfoAlert({\n description: responseJson.UserMessage,\n html: true\n })\n }\n }\n }\n } catch (e) {\n console.error(e)\n } finally {\n this._displayLoading(false)\n }\n }\n }\n\n markingReturnClick() {\n window.history.back();\n }\n\n onClickImage(e) {\n $('#selected-image-marking').trigger('click');\n }\n\n loadMarkingImage(event) {\n\n const imageSelected = document.getElementById('selected-image-marking');\n\n if (imageSelected.files && imageSelected.files[0]) {\n var imageName = \"\";\n imageName = imageSelected.files[0].name;\n $('#markingModal .selectedImageMarking').text(imageName == \"\" ? 'Imagen: ' : 'Imagen: ' + imageName);\n }\n }\n\n loadBannerImage(event, container, noImageMessage) {\n this.imageConfig.loadImage(event.target.files[0], container, noImageMessage);\n }\n\n onDisplayCustomAlert(title, content) {\n $(\"
    \").kendoAlert({\n title: title,\n content: content\n }).data(\"kendoAlert\").open();\n }\n\n displayLoading(target, value) {\n var element = $(target);\n kendo.ui.progress(element, value);\n }\n\n /**\n * \n * @param boolean show\n * @param {string} target\n */\n _displayLoading(show, target = \".marking__list-container\") {\n kendo.ui.progress($(target), show);\n }\n\n}\n","import ShoppingCartService from \"../shared/shopping-cart/services/shopping-cart-service\";\nimport { MarkingService } from \"../services/marking-service\";\nimport { BrowserCommunicatorService } from \"../services/browser-communicator-service\";\n\nexport class MarkingByProductHandlers {\n\n /** @type {ShoppingCartService} **/\n _shoppingCartService;\n\n /** @type {MarkingService} **/\n _markingService;\n\n totalQuantity;\n imageEnumImage;\n imageEnumLegend;\n imageEnumBoth;\n\n imageConfig = {\n //Displays the image selected in a file input type.\n loadImage: (imageFile, imageContainerId, noImageContainerId) => {\n let size = parseInt(imageFile.size);\n let maximunSize = $(\"#MaximumImageSize\").val();\n\n const imageContainer = document.getElementById(imageContainerId);\n let extensionFile = imageFile.name.split('.').pop();\n\n if (extensionFile.toLowerCase() == \"png\" || extensionFile.toLowerCase() == \"jpg\") {\n if (maximunSize == 0) {\n imageContainer.src = URL.createObjectURL(imageFile);\n } else {\n if (maximunSize > 0) {\n if (size <= maximunSize) {\n imageContainer.src = URL.createObjectURL(imageFile);\n }\n else {\n $(\"#message\").html(\"El tamaño de la imagen seleccionada es mayor al tamaño permitido \" + this.GetMeasureName());\n $('#dialog').data(\"kendoDialog\").open();\n $(\"#LoadImageWeb\").val(\"\");\n imageContainer.src = $(\"#DefaultImage\").val();\n }\n }\n }\n } else {\n $(\"#message\").html(\"Las imágenes para la marcación deben estar en formato jpg ó png.\");\n $('#dialog').data(\"kendoDialog\").open();\n $(\"#LoadImageWeb\").val(\"\");\n imageContainer.src = $(\"#DefaultImage\").val();\n }\n }\n }\n\n constructor() {\n this._shoppingCartService = new ShoppingCartService();\n this._markingService = new MarkingService();\n this._browserCommunicatorService = new BrowserCommunicatorService()\n this.init();\n }\n\n init() {\n this.bindMarkingControl();\n\n $('#panel-marking-image').hide();\n\n $(\"#browserImageWeb\").click((e) => { e.preventDefault(); this.onClickImageWeb(e); })\n\n $(\"#image-container-web\").on(\"load\", function () {\n });\n\n this.repeatProductValidation();\n this.calculateMaxLength();\n\n let isEdit = $(\"#IsEdit\").val();\n if (isEdit === \"True\") {\n\n let imageEnumImage = $(\"#imageEnumImage\").val();\n let imageEnumLegend = $(\"#imageEnumLegend\").val();\n let imageEnumBoth = $(\"#imageEnumBoth\").val();\n\n $(\".panel-marking-legend-personalized\").show();\n $(\".panel-save-marking\").hide();\n $(\".panel-edit-marking\").show();\n\n let markingTypeImage = $(\"#MarkingTypeImage\").val();\n switch (markingTypeImage) {\n case imageEnumImage:\n $('.panel-marking-image').show();\n $('.panel-marking-image-button').show();\n $(\".panel-marking-legend-personalized\").hide();\n $('.panel-marking-legend').hide()\n break;\n case imageEnumLegend:\n $('.panel-marking-image').hide();\n $('.panel-marking-image-button').hide();\n $(\".panel-marking-legend-personalized\").show();\n break;\n default:\n $(\".panel-marking-legend-personalized\").show();\n }\n } else {\n\n $(\".panel-save-marking\").show();\n\n $(\".panel-edit-marking\").hide();\n\n $(\"#image-container\").on(\"load\", function () {\n $(\"#image-container\").removeAttr(\"class\");\n\n });\n\n $('.panel-marking-image').hide();\n\n $('.panel-marking-image-button').hide();\n\n $(\".panel-marking-legend-personalized\").hide();\n }\n }\n\n GetMeasureName() {\n let suffixes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\"];\n let bytes = $(\"#MaximumImageSize\").val();\n let counter = 0;\n let number = bytes;\n\n while (Math.round(number / 1024) >= 1) {\n number = number / 1024;\n counter++;\n }\n\n return `${number} ${suffixes[counter]}`;\n }\n\n async markingTypeChange(event) {\n let imageEnumImage = $(\"#imageEnumImage\").val();\n let imageEnumLegend = $(\"#imageEnumLegend\").val();\n let imageEnumBoth = $(\"#imageEnumBoth\").val();\n\n let selected = $(\"#MarkingProduct_MarkingType_Id\").data(\"kendoDropDownList\")?.dataItem().InternalCode\n\n await this.calculateMarkingPrice();\n\n $('#panel-marking-image').hide();\n\n if (selected !== undefined && selected == imageEnumImage) {\n $('#panel-marking-image').show();\n }\n\n if (selected == imageEnumLegend) {\n $('.panel-marking-legend').show();\n $('.panel-marking-position').show();\n $('.panel-marking-image').hide();\n $('.panel-marking-image-button').hide()\n $('.panel-marking-legend-personalized').show();\n\n }\n if (selected == imageEnumImage) {\n\n $('.panel-marking-image').show();\n $('.panel-marking-image-button').show();\n $('.panel-marking-legend').hide();\n $('.panel-marking-legend-personalized').hide();\n\n }\n if (selected == imageEnumBoth) {\n\n $('.panel-marking-image').show();\n $('.panel-marking-image-button').show();\n $('.panel-marking-position').show();\n $('.panel-marking-legend').show();\n $('.panel-marking-legend-personalized').show();\n\n }\n }\n\n async calculateMarkingPrice() {\n try {\n let markingTypeId = $(\"#MarkingProduct_MarkingType_Id\").data(\"kendoDropDownList\")?.dataItem().Id;\n\n if (markingTypeId) {\n $('.panel-marking-cost').text('Calculando valores...');\n\n let quantityRepeat = parseInt($(\"#quantityByProductPending\").val());\n let manualQuantity = $(\"#MarkingProduct_Quantity\").data(\"kendoNumericTextBox\").value();\n let repeatProduct = $('#MarkingProduct_RepeatProduct')[0].checked\n let quantity = 0;\n\n if (repeatProduct) {\n quantity = quantityRepeat;\n }\n else {\n quantity = manualQuantity;\n }\n\n var response = await this._markingService.getMarkingPriceById(markingTypeId, quantity);\n if (response.ok) {\n const responseJson = await response.json()\n if (responseJson.Successful) {\n if (responseJson.Price) {\n $('.panel-marking-cost').text(responseJson.MarkingCostText);\n } else {\n await this._browserCommunicatorService.displayInfoAlert({\n description: responseJson.UserMessage,\n html: true\n })\n }\n }\n }\n }\n } catch (e) {\n conso.error(e);\n }\n }\n\n filterCascadePositionsByMarkingTypeGroup() {\n let BindingPositionsList = \"#MarkingProduct_MarkingType_Id\";\n\n return {\n markingTypeId: $(BindingPositionsList).val(),\n \"__RequestVerificationToken\": $('input[name=__RequestVerificationToken]').val()\n };\n }\n\n bindMarkingControl() {\n $('.btn-marking').on('click', this.marking);\n\n $('.btn-markingByProduct').off('click');\n $('.btn-markingByProduct').on('click', this.markingByProduct);\n\n $('.add-marking').off('click');\n $('.add-marking').on('click', e => { e.preventDefault(); this.createMarkingClick(e) });\n\n $('#markingType').off('change');\n $('#markingType').on('change', this.markingTypeChange);\n\n $('#MarkingProduct_RepeatProduct').off('change');\n $('#MarkingProduct_RepeatProduct').on('change', e => { this.markingRepeatProductChange(e) });\n\n $('.save-marking2').off('click');\n $('.save-marking2').on('click', e => { e.preventDefault(); this.onClickSaveMarking(e) });\n\n $('.delete-marking').off('click');\n $('.delete-marking').on('click', e => { e.preventDefault(); this.onClickMarkingDelete(e) });\n\n $('.marking-return-button').off('click');\n $('.marking-return-button').on('click', this.markingReturnClick);\n\n $('.save-image-marking').off('click');\n $('.save-image-marking').on('click', this.onClickImage);\n\n $('#selected-image-marking').off('change');\n $('#selected-image-marking').on('change', this.loadMarkingImage);\n\n $(\"#markingMessageText\").on('input', () => {\n this.updateLabelMarkingMessage();\n });\n }\n\n dataMarkingTypes() {\n var parameter = kendo.antiForgeryTokens();\n parameter.productBranchOfficeId = $(\"#productBranchOfficeId\").val();\n parameter.productId = $(\"#productId\").val();\n\n return parameter;\n }\n\n calculateMaxLength(e) {\n $(\"#MarkingProduct_MarkingCustomMessage\").on('input change', (e) => {\n $('.k-counter-container .k-counter-value').html($(e.target).val().length);\n });\n }\n\n onClickImageWeb(e) {\n $('#LoadImageWeb').trigger('click');\n }\n\n marking() {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n var that = this;\n var parent = $(that).parent();\n var productId = app.productHelper.getProductId(parent);\n this.totalQuantity = document.getElementById(\"quantity-\" + productId).previousElementSibling.innerHTML;\n spinnerWait.addClass(\"d-none\");\n window.location.href = \"Marking/\" + productId + \"/\" + this.totalQuantity;\n }\n\n markingByProduct() {\n var spinnerWait = $(this).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n var that = this;\n var parent = $(that).parent();\n var productId = app.productHelper.getProductId(parent);\n this.totalQuantity = document.getElementById(\"quantity-\" + productId).previousElementSibling.innerHTML;\n spinnerWait.addClass(\"d-none\");\n window.location.href = \"MarkingByProduct/\" + productId + \"/\" + this.totalQuantity;\n }\n\n repeatProductValidation() {\n let quantityProduct = $('#quantityByProductPending').val();\n\n if (quantityProduct !== undefined && quantityProduct == 1) {\n $('.panel-marking-repeatProduct').hide();\n $('.panel-marking-repeat').hide();\n }\n }\n\n async createMarkingClick() {\n let quantityProduct = $('.quantityByProductPending').val();\n if (quantityProduct == 0) {\n await this._browserCommunicatorService.displayErrorAlert({ description: \"Ya tienes el total de productos con marcación.\" }) \n return;\n }\n else if (quantityProduct == 1) {\n $('.panel-marking-repeatProduct').hide();\n $('.panel-marking-repeat').hide();\n }\n }\n\n async productQuantityChange(event) {\n await this.calculateMarkingPrice();\n }\n\n updateLabelMarkingMessage() {\n let lengthMarkingText = $(\"#markingMessageText\").val().length;\n var maxLength = $(\"#markingMessageText\")[0].maxLength;\n let total = maxLength - lengthMarkingText;\n $(\"#markingMessageLength\").text(\"Caracteres restantes \" + total);\n }\n\n markingRepeatProductChange(e) {\n var markingRepeatProductControl = $('#MarkingProduct_RepeatProduct');\n var markingRepeatProduct = markingRepeatProductControl[0].checked;\n if (!markingRepeatProduct) {\n\n $('.panel-marking-repeat').show();\n this.calculateMarkingPrice();\n }\n else {\n $('.panel-marking-repeat').hide();\n this.calculateMarkingPrice();\n }\n }\n\n markingMessageChanges() {\n var selected = $(\"#MarkingProduct_MarkingMessage_Message\").data(\"kendoDropDownList\").value();\n\n if (selected) {\n $(\"#MarkingProduct_MarkingCustomMessage\").val(selected);\n $(\"#MarkingProduct_MarkingCustomMessage\").trigger(\"change\");\n }\n }\n\n markingTypeChanges() {\n let selected = $(\"#MarkingProduct_MarkingType_Id\").data(\"kendoDropDownList\")?.dataItem().InternalCode\n let enumImage = $(\"#imageEnumText\").val();\n\n $('#panel-marking-image').hide();\n\n if (selected !== undefined && selected == enumImage) {\n $('#panel-marking-image').show();\n }\n }\n\n markingSaveClick(e) {\n var image = new FormData();\n var imageName = \"\";\n var imageContent;\n var imageSize;\n var spinnerWait = $(e.target).find(\".spinner-border-sm\").eq(0);\n spinnerWait.removeClass(\"d-none\");\n\n const imageSelected = document.getElementById('LoadImageWeb');\n\n if (imageSelected.files && imageSelected.files[0]) {\n image.append('image', imageSelected.files[0]);\n imageName = imageSelected.files[0].name;\n imageSize = imageSelected.files[0].size;\n }\n\n if (imageName != \"\") {\n this._shoppingCartService.markingSaveImage(image, (result) => {\n imageContent = result.ImageContent;\n this.saveMarking(imageName, imageSize, imageContent, spinnerWait);\n });\n }\n else {\n this.saveMarking(imageName, imageSize, imageContent, spinnerWait);\n }\n }\n\n saveMarking(imageName, imageSize, imageContent, spinnerWait) {\n var markingRepeatProductControl = $('#markingRepeatProduct');\n var isRepeat = markingRepeatProductControl[0].checked;\n var markingTypeId = $(\"#ddlMarkingType\").data(\"kendoDropDownList\").value()\n var markingType = $(\"#ddlMarkingType\").data(\"kendoDropDownList\").text()\n var markingPositionId = $(\"#ddlSystemDef\").data(\"kendoDropDownList\").value();\n var markingPosition = $(\"#ddlSystemDef\").data(\"kendoDropDownList\").text()\n var markingMessage = $(\"#MarkingProduct_MarkingMessage\").data(\"kendoDropDownList\").value();\n var markingMessageText = $(\"#MarkingMessageText\").val();\n var quantity = $(\"#quantityProducts\").val();\n var productBranchOfficeId = $(\"#productBranchOfficeId\").val();\n var title = $('#markingModal .marking-modal-title').text();\n var isEdit = $(\"#IsEdit\").val();\n var quantityProduct = $(\"#quantityProducts\").val();\n var totalQuantityProduct = $(\"#totalQuantityProduct\").val();\n\n if (markingMessage != \"Personalizado\") {\n markingMessageText = markingMessage;\n }\n\n var MarkingType = {\n Id: markingTypeId,\n Mark: markingType\n };\n\n var MarkingPosition = {\n Id: markingPositionId,\n Position: markingPosition\n };\n\n var Marking = {\n MarkingPosition: MarkingPosition,\n MarkingType: MarkingType,\n Quantity: quantity,\n Message: markingMessageText,\n ProductBranchOfficeId: productBranchOfficeId,\n Image: imageName != \"\",\n ImageName: imageName,\n ImageSize: imageSize,\n ImageContent: imageContent\n };\n\n let oldMarking = null;\n if (isEdit === 'True') {\n oldMarking = JSON.parse($(\"oldMarking\").val())\n }\n\n this._shoppingCartService.markingSave(Marking, oldMarking, isRepeat, isEdit, quantityProduct, totalQuantityProduct, async (result) => {\n if (result.HasError) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: result.MessageError,\n html: true\n })\n spinnerWait.addClass(\"d-none\");\n }\n else if (result.MessageError != \"Guardado exitoso.\") {\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: result.MessageError,\n html: true\n })\n if (confirmResult.isConfirmed) {\n this._shoppingCartService.markingSaveConfirm(result.Marking, oldMarking, isEdit, async (result) => {\n await this._browserCommunicatorService.displayInfoAlert({\n description: result.MessageError,\n html: true\n })\n spinnerWait.addClass(\"d-none\");\n window.location.href = result.RedirectTo;\n });\n } else {\n spinnerWait.addClass(\"d-none\");\n }\n } else {\n await this._browserCommunicatorService.displayInfoAlert({\n description: result.MessageError,\n html: true\n })\n spinnerWait.addClass(\"d-none\");\n window.location.href = result.RedirectTo;\n }\n });\n }\n\n async onClickMarkingDelete(e) {\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: \"Vas a eliminar la marcación, deseas continuar?\"\n })\n if (confirmResult.isConfirmed) {\n try {\n this._displayLoading(false)\n const markingId = $(\"#MarkingProduct_Id\").val()\n const deleteFormData = new FormData()\n deleteFormData.append(\"markingId\", markingId)\n var response = await this._shoppingCartService.markingDelete(deleteFormData);\n if (response.ok) {\n const responseJson = await response.json()\n if (responseJson.Successful) {\n if (responseJson.RedirectTo) {\n window.location.href = responseJson.RedirectTo\n } else {\n await this._browserCommunicatorService.displayInfoAlert({\n description: responseJson.UserMessage,\n html: true\n })\n }\n }\n }\n } catch (e) {\n console.error(e)\n } finally {\n this._displayLoading(false)\n }\n }\n }\n\n markingReturnClick() {\n window.history.back();\n }\n\n onClickImage(e) {\n $('#selected-image-marking').trigger('click');\n }\n\n loadMarkingImage(event) {\n const imageSelected = document.getElementById('selected-image-marking');\n\n if (imageSelected.files && imageSelected.files[0]) {\n var imageName = \"\";\n imageName = imageSelected.files[0].name;\n $('#markingModal .selectedImageMarking').text(imageName == \"\" ? 'Imagen: ' : 'Imagen: ' + imageName);\n }\n }\n\n loadBannerImage(event, container, noImageMessage) {\n this.imageConfig.loadImage(event.target.files[0], container, noImageMessage);\n }\n\n onDisplayCustomAlert(title, content) {\n $(\"
    \").kendoAlert({\n title: title,\n content: content\n }).data(\"kendoAlert\").open();\n }\n\n displayLoading(target, value) {\n var element = $(target);\n kendo.ui.progress(element, value);\n }\n\n async onClickSaveMarking(e) {\n await this._saveMarking()\n }\n\n async _saveMarking() {\n try {\n this._displayLoading(true);\n //Validate size of defaultImage '/img/general/no-image-marking.png'\n\n if ($('.panel-marking-image').css(\"display\") !== \"none\" && $(\"#image-container-web\").attr(\"src\") == $(\"#DefaultImage\").val()) {\n $(\"#message\").html(\"Por favor seleccione una imagen válida \");\n $('#dialog').data(\"kendoDialog\").open();\n\n return;\n }\n\n const markingFormData = new FormData(document.querySelector(\"#markingByProductForm\"));\n\n // get marking type\n const markingType = $(\"#MarkingProduct_MarkingType_Id\").data(\"kendoDropDownList\").text()\n const markingTypeInternalCode = $(\"#MarkingProduct_MarkingType_Id\").data(\"kendoDropDownList\")?.dataItem().InternalCode\n markingFormData.append(\"MarkingProduct.MarkingType.Mark\", markingType)\n markingFormData.append(\"MarkingProduct.MarkingType.InternalCode\", markingTypeInternalCode)\n\n // get marking position\n const markingPosition = $(\"#MarkingProduct_MarkingPosition_Id\").data(\"kendoDropDownList\").text()\n const markingPositionInternalCode = $(\"#MarkingProduct_MarkingPosition_Id\").data(\"kendoDropDownList\")?.dataItem().InternalCode\n markingFormData.append(\"MarkingProduct.MarkingPosition.Position\", markingPosition)\n markingFormData.append(\"MarkingProduct.MarkingPosition.InternalCode\", markingPositionInternalCode)\n\n // post marking save\n const markingResponse = await this._shoppingCartService.markingSave(markingFormData)\n\n if (markingResponse.ok) {\n // ok response\n const responseJson = await markingResponse.json()\n\n if (responseJson.Successful) {\n if (responseJson.RedirectTo) {\n window.location.href = responseJson.RedirectTo\n }\n }\n else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: responseJson.UserMessage,\n html: true\n })\n }\n }\n\n } catch (e) {\n console.error(e)\n } finally {\n this._displayLoading(false)\n }\n }\n\n /**\n * \n * @param boolean show\n * @param {string} target\n */\n _displayLoading(show, target = \"#markingByProductForm\") {\n kendo.ui.progress($(target), show);\n }\n}\n","import AjaxProxy from '../../proxies/ajax-proxy'\nimport UrlHelper from '../../helpers/url-helper'\n\nexport class TwoFaServiceBase {\n\n constructor() {\n if (this.constructor == TwoFaServiceBase) {\n throw new Error(\" Object of Abstract Class cannot be created\");\n }\n }\n\n /**\n * Send validation code 2FA\n * */\n validationCodeProcess2FAAsync(formData) {\n return AjaxProxy.postFetch(UrlHelper.twoFARequiredPageModelBase.postValidationCodeProcess2FA, {body: formData});\n }\n\n /**\n * Send validation code 2FA\n * */\n reValidationCodeProcess2FAAsync(formData) {\n return AjaxProxy.postFetch(UrlHelper.twoFARequiredPageModelBase.postReValidationCodeProcess2FA, { body: formData});\n }\n\n /**\n * validate code 2FA\n * */\n validateCodeProcess2FAAsync(formData) {\n return AjaxProxy.postFetch(UrlHelper.twoFARequiredPageModelBase.postValidateCodeProcess2FA, {body: formData});\n }\n}","import { TwoFaServiceBase } from \"./abstracts/twofa-servicebase\";\n\nexport class TwoFaChangePasswordService extends TwoFaServiceBase {\n\n}","import ModalHelper from '../../helpers/modal-helper'\nimport { BrowserCommunicatorService } from '../../services/browser-communicator-service'\nimport { WizardForm } from \"../../components/wizard/wizard-form\"\n\nexport class TwoFaHandlersBase {\n\n constructor() {\n if (this.constructor == TwoFaHandlersBase) {\n throw new Error(\" Object of Abstract Class cannot be created\");\n }\n\n this._browserCommunicatorService = new BrowserCommunicatorService();\n this._wizardForm = new WizardForm({\n nextButton: \".two-fa-next\",\n previousButton: \".two-fa-previous\",\n id: \"#twoFAProcess\",\n onLeaveStep: async (stepNumber, direction, button) => {\n return await this._leaveStepAsync(stepNumber, direction);\n },\n })\n }\n\n init() {\n this._setQueryParams();\n this._wizardForm.init();\n $(\"#validate2FACodeForm\").submit((e) => e.preventDefault())\n $(\"#validationCodeProcess2FAForm\").submit((e) => e.preventDefault())\n\n $(\"#reSend2FACode-trigger\").click(async () => {\n try {\n this._showLoading(true)\n await this._reSend2FACodeAsync()\n } catch (e) {\n console.error(e)\n } finally {\n this._showLoading(false)\n }\n })\n $(\"#showmore-sendingOption-trigger\").on(\"click\", function (e) {\n e.preventDefault();\n $(\"li.k-radio-item.d-none\").removeClass(\"d-none\");\n $(this).addClass(\"d-none\");\n });\n }\n\n throwNoImplementError() {\n throw new Error(\"Method not implement\");\n }\n\n _setQueryParams() { }\n\n /**\n * \n * @param {any} e\n * @param {number} stepNumber\n * @param {'next' | 'previous' } direction\n */\n async _leaveStepAsync(stepNumber, direction) {\n this._showLoading(true)\n try {\n if (direction === 'next') {\n if (stepNumber == 1) {\n let isValid = await this._validateFormAsync(`#validationCodeProcess2FAForm`)\n if (isValid) {\n let sendCodeProcess = await this._send2FACodeAsync()\n return sendCodeProcess\n }\n }\n if (stepNumber === 2) {\n let isValid = await this._validateFormAsync(`#validate2FACodeForm`)\n if (isValid) {\n let validateCodeProcess = await this._validate2FACodeAsync();\n return validateCodeProcess\n }\n }\n return false\n }\n return true;\n } catch (e) {\n console.error(e);\n } finally {\n this._showLoading(false);\n }\n }\n\n _showLoading(show = true) {\n kendo.ui.progress($(\"#twoFAProcess\"), show);\n }\n\n /**\n * \n * @param {string} target\n * @returns {Promise}\n */\n _validateFormAsync(target) {\n this.throwNoImplementError();\n }\n\n /**\n * @returns {Promise}\n * */\n async _send2FACodeAsync() {\n this.throwNoImplementError();\n }\n\n /**\n * @returns {Promise}\n * */\n async _reSend2FACodeAsync() {\n this.throwNoImplementError();\n }\n\n /**\n * \n * @param {Response} ajaxResponse\n * @returns {boolean}\n * */\n async _handleSendCode2FAAsync(ajaxResponse) {\n this.throwNoImplementError();\n }\n\n /**\n * \n * @returns {boolean}\n * */\n async _validate2FACodeAsync() {\n this.throwNoImplementError();\n }\n\n /**\n * Redirect\n * @param {string} redirectTo\n */\n redirect(redirectTo) {\n if (redirectTo) {\n window.location.href = redirectTo;\n }\n }\n\n /**\n * Show info alert\n * @param {{userMessage:string, callback: () => {}}} option\n */\n _showAlert(option) {\n this._browserCommunicatorService.displayInfoAlert({\n description: option.userMessage,\n html: true\n }).then(alertResult => option.callback())\n }\n\n /**\n * Return the FormData from SendCode form.\n * @param {string} target\n * @returns {FormData}\n * */\n getSendCodeFormData(target = \"#validationCodeProcess2FAForm\") {\n return new FormData($(target)[0]);\n }\n\n /**\n * Return the FormData from validateCode form\n * @param {string} target\n */\n getValidateFormData(target = \"#validate2FACodeForm\") {\n return new FormData($(target)[0])\n }\n}","import { TwoFaChangePasswordService } from \"../services/twofa-changepassword-service\"\nimport ModalHelper from '../helpers/modal-helper'\nimport { TwoFaHandlersBase } from \"./abstract/twofa-handlerbase\";\n\nexport class TwoFaChangePasswordHandlers extends TwoFaHandlersBase {\n\n /** @type {TwoFaChangePasswordService} **/\n _twoFaService;\n\n /**\n * @type{boolean}\n * */\n _message;\n\n constructor() {\n super()\n this._twoFaService = new TwoFaChangePasswordService();\n this.init()\n }\n\n init() {\n super.init();\n\n if (this._message) {\n this._showAlert({\n userMessage: this._message\n })\n }\n }\n\n _setQueryParams() {\n const params = new Proxy(new URLSearchParams(window.location.search), {\n get: (searchParams, prop) => searchParams.get(prop),\n });\n\n // Get the value of \"some_key\" in eg \"https://example.com/?some_key=some_value\"\n this._message = params.twofamessage;\n }\n\n /**\n * \n * @param {string} target\n */\n async _validateFormAsync(target) {\n let formCommonRules = {\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredCode: function (input) {\n if (input.is(`[name=\"CodeValid\"]`)) {\n if (input.val()) {\n return true;\n } else {\n return false;\n }\n } else {\n return true;\n }\n }\n }\n let formCommonMessages = {\n validEmail: \"Debe ingresar un correo electrónico válido\",\n requiredCode: \"Debe ingresar el código numérico recibido en el correo\"\n }\n\n let validator = $(target).kendoValidator({\n rules: {\n ...formCommonRules\n },\n messages: {\n ...formCommonMessages\n }\n }).data(\"kendoValidator\");\n\n return validator.validate();\n }\n\n /**\n * @returns {Promise}\n * */\n async _send2FACodeAsync() {\n let formData = this.getSendCodeFormData();\n let ajaxResponse = await this._twoFaService.validationCodeProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n return this._handleSendCode2FAAsync(ajaxResponse)\n }\n }\n\n /**\n * @returns {Promise}\n * */\n async _reSend2FACodeAsync() {\n let formData = this.getSendCodeFormData();\n let ajaxResponse = await this._twoFaService.reValidationCodeProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n return this._handleSendCode2FAAsync(ajaxResponse)\n }\n }\n\n getSendCodeFormData() {\n let formData = super.getSendCodeFormData()\n\n /** @type {string} */\n let radioValue = $(\"#SelectedSendingOption\").data(\"kendoRadioGroup\").value()\n\n /** @type {[]} */\n let radioItems = $(\"#SelectedSendingOption\").data(\"kendoRadioGroup\")._items\n let radioItem = radioItems.find(r => r.value === radioValue)\n let attributes = radioItem.attributes;\n\n formData.append(\"SendMethod\", attributes[\"data-sendmethod\"])\n formData.append(\"CustomerAddressId\", attributes[\"data-customeraddressid\"])\n \n return formData;\n }\n\n /**\n * \n * @param {Response} ajaxResponse\n * @returns {boolean}\n * */\n async _handleSendCode2FAAsync(ajaxResponse) {\n try {\n let jsonResponse = await ajaxResponse.json();\n if (!jsonResponse.Successful) {\n let message = jsonResponse.UserMessage ?? jsonResponse.Message\n console.error(message)\n this._showAlert({\n userMessage: message\n });\n return false;\n }\n\n if (jsonResponse.UserMessage) {\n this._showAlert({\n userMessage: jsonResponse.UserMessage\n })\n }\n return true;\n } catch (e) {\n console.error(e)\n return false;\n }\n }\n \n /**\n * \n * @returns {Promise}\n * */\n async _validate2FACodeAsync() {\n\n let formData = this.getValidateFormData();\n let ajaxResponse = await this._twoFaService.validateCodeProcess2FAAsync(formData);\n if (!ajaxResponse.ok) {\n return;\n }\n\n let jsonResponse = await ajaxResponse.json();\n if (!jsonResponse.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: jsonResponse.UserMessage,\n html: true\n });\n return;\n }\n\n this._showLoading(true);\n this.redirect(jsonResponse.Value.RedirectTo);\n }\n\n /**\n * Redirect\n * @param {string} redirectTo\n */\n redirect(redirectTo) {\n if (redirectTo) {\n window.location.href = redirectTo;\n }\n }\n}","import { TwoFaServiceBase } from \"./abstracts/twofa-servicebase\";\n\nexport class TwoFaGenericUserService extends TwoFaServiceBase {\n}","import { TwoFaGenericUserService } from \"../services/twofa-genericuser-service\";\nimport { TwoFaHandlersBase } from \"./abstract/twofa-handlerbase\";\n\nexport class TwoFaGenericUserHandlers extends TwoFaHandlersBase {\n\n /** @type {TwoFaGenericUserService} **/\n _twoFaService;\n\n /**\n * @type{boolean}\n * */\n _showMessage;\n\n constructor() {\n super()\n this._twoFaService = new TwoFaGenericUserService();\n this.init()\n }\n\n init() {\n super.init()\n }\n\n _setQueryParams() {\n const params = new Proxy(new URLSearchParams(window.location.search), {\n get: (searchParams, prop) => searchParams.get(prop),\n });\n\n // Get the value of \"some_key\" in eg \"https://example.com/?some_key=some_value\"\n this._showMessage = params.showMessage;\n }\n\n /**\n * \n * @param {any} e\n * @param {number} stepNumber\n * @param {'next' | 'previous' } direction\n */\n async _leaveStepAsync(stepNumber, direction) {\n this._showLoading(true)\n try {\n if (direction === 'next') {\n if (stepNumber == 1) {\n let isValid = await this._validateFormAsync(`#validationCodeProcess2FAForm`)\n if (isValid) {\n let sendCodeProcess = await this._send2FACodeAsync()\n return sendCodeProcess\n }\n }\n if (stepNumber === 2) {\n let isValid = await this._validateFormAsync(`#validate2FACodeForm`)\n if (isValid) {\n let validateCodeProcess = await this._validate2FACodeAsync();\n return validateCodeProcess\n }\n }\n return false\n }\n return true;\n } catch (e) {\n console.error(e);\n } finally {\n this._showLoading(false);\n }\n }\n\n _showLoading(show = true) {\n kendo.ui.progress($(\"#twoFAProcess\"), show);\n }\n\n /**\n * \n * @param {string} target\n */\n async _validateFormAsync(target) {\n let formCommonRules = {\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n validEmail: function (input) {\n if (input.is(`[name=\"LoginWith2FARequest.Email\"]`)) {\n let re = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n let email = input.val()\n return re.test(email);\n }\n else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredCode: function (input) {\n if (input.is(`[name=\"CodeValid\"]`)) {\n if (input.val()) {\n return true;\n } else {\n return false;\n }\n } else {\n return true;\n }\n }\n }\n let formCommonMessages = {\n validEmail: \"Debe ingresar un correo electrónico válido\",\n requiredCode: \"Debe ingresar el código numérico recibido en el correo\"\n }\n\n let validator = $(target).kendoValidator({\n rules: {\n ...formCommonRules\n },\n messages: {\n ...formCommonMessages\n }\n }).data(\"kendoValidator\");\n\n return validator.validate();\n }\n\n /**\n * @returns {boolean}\n * */\n async _send2FACodeAsync() {\n let formData = new FormData($(\"#validationCodeProcess2FAForm\")[0]);\n let ajaxResponse = await this._twoFaService.validationCodeProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n return this._handleSendCode2FAAsync(ajaxResponse)\n }\n }\n\n /**\n * @returns {boolean}\n * */\n async _reSend2FACodeAsync() {\n let formData = new FormData($(\"#validationCodeProcess2FAForm\")[0]);\n let ajaxResponse = await this._twoFaService.reValidationCodeProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n return this._handleSendCode2FAAsync(ajaxResponse)\n }\n }\n\n /**\n * \n * @param {Response} ajaxResponse\n * @returns {boolean}\n * */\n async _handleSendCode2FAAsync(ajaxResponse) {\n try {\n let jsonResponse = await ajaxResponse.json();\n if (!jsonResponse.Successful) {\n let message = jsonResponse.UserMessage ?? jsonResponse.Message\n console.error(message)\n this._showAlert({\n userMessage: message\n });\n return false;\n }\n\n if (jsonResponse.UserMessage) {\n this._showAlert({\n userMessage: jsonResponse.UserMessage\n })\n }\n return true;\n } catch (e) {\n console.error(e)\n return false;\n }\n }\n\n /**\n * \n * @returns {boolean}\n * */\n async _validate2FACodeAsync() {\n let formData = new FormData($(\"#validate2FACodeForm\")[0]);\n let ajaxResponse = await this._twoFaService.validateCodeProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n\n /** @type {{VerificationCode: {}, RedirectTo: string}} */\n let jsonResponse = await ajaxResponse.json();\n\n /** @type {{Successful: boolean, UserMessage: string, Message: string, Validation: boolean}} */\n let verificationCode = jsonResponse.VerificationCode;\n\n if (!verificationCode.Validation) {\n console.error(verificationCode.Message)\n this._showAlert({\n userMessage: verificationCode.Message\n })\n return false;\n }\n\n this._showLoading(true);\n this.redirect(jsonResponse.RedirectTo);\n }\n }\n\n}","import AjaxProxy from '../proxies/ajax-proxy'\nimport UrlHelper from '../helpers/url-helper'\nimport { TwoFaServiceBase } from \"./abstracts/twofa-servicebase\";\n\nexport class TwoFaAdditionalInformationService extends TwoFaServiceBase {\n\n /**\n * Validate additional information\n * */\n validationAdditionalInformationProcess2FAAsync(formData) {\n return AjaxProxy.postFetch(UrlHelper.twoFARequiredAdditionalInformationPageModelbase.postValidationAdditionalInformationProcess2FA, {body: formData});\n }\n}","import { TwoFaAdditionalInformationService } from \"../services/twofa-additionalinformation-service\";\nimport { TwoFaHandlersBase } from \"./abstract/twofa-handlerbase\";\n\nexport class TwoFaAdditionalInformationHandlers extends TwoFaHandlersBase {\n\n /** @type {TwoFaAdditionalInformationService}*/\n _twoFaService;\n\n constructor() {\n super()\n this._twoFaService = new TwoFaAdditionalInformationService()\n this.init()\n }\n\n init() {\n super.init()\n $(\"#securityQuestion2FAForm\").submit((e) => e.preventDefault())\n $(\"#validationCodeProcess2FAForm\").submit((e) => e.preventDefault())\n }\n\n /**\n * \n * @param {number} stepNumber\n * @param {'next' | 'previous' } direction\n */\n async _leaveStepAsync(stepNumber, direction) {\n this._showLoading(true)\n try {\n if (direction === 'next') {\n if (stepNumber == 1) {\n let isValid = await this._validateSecurityQuestionFormAsync(`#securityQuestion2FAForm`)\n if (isValid) {\n let validProcess = await this._validateSecurityQuestionAsync()\n return validProcess\n }\n }\n\n if (stepNumber === 2) {\n let isValid = await this._validateFormAsync(`#validationCodeProcess2FAForm`)\n if (isValid) {\n let sendCodeProcess = await this._send2FACodeAsync()\n return sendCodeProcess\n }\n }\n\n if (stepNumber === 3) {\n let isValid = await this._validateFormAsync(`#validate2FACodeForm`)\n if (isValid) {\n let validateCodeProcess = await this._validate2FACodeAsync();\n return validateCodeProcess\n }\n }\n return false\n }\n else if (direction === 'previous') {\n if (stepNumber === 2) {\n return false\n }\n }\n return true;\n } catch (e) {\n console.error(e);\n } finally {\n this._showLoading(false);\n }\n }\n\n /**\n * Validate form for security question\n * @param {string} target\n * @returns {Promise}\n */\n _validateSecurityQuestionFormAsync(target) {\n let formCommonRules = {\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredUserAnswer: function (input) {\n if (input.is(`[name=\"UserAnswer\"]`)) {\n if (input.val()) {\n return true;\n } else {\n return false;\n }\n } else {\n return true;\n }\n }\n }\n let formCommonMessages = {\n requiredUserAnswer: \"Debe ingresar una respuesta valida\"\n }\n\n return this._validate(target, formCommonRules, formCommonMessages);\n }\n\n /**\n * Validate security question\n * */\n async _validateSecurityQuestionAsync() {\n let formData = this.getAdditionalInformationFormData();\n let ajaxResponse = await this._twoFaService.validationAdditionalInformationProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n return this._handleAdditionalInformationAsync(ajaxResponse)\n }\n }\n\n /**\n * \n * @param {Response} ajaxResponse\n */\n async _handleAdditionalInformationAsync(ajaxResponse) {\n try {\n let jsonResponse = await ajaxResponse.json();\n if (!jsonResponse.Successful) {\n let message = jsonResponse.UserMessage ?? jsonResponse.Message\n this._showAlert({\n userMessage: message\n });\n return false;\n }\n\n if (jsonResponse.UserMessage) {\n this._showAlert({\n userMessage: jsonResponse.UserMessage\n })\n }\n return true;\n } catch (e) {\n console.error(e)\n return false;\n }\n }\n\n _validate(target, formCommonRules, formCommonMessages) {\n let validator = $(target).kendoValidator({\n rules: {\n ...formCommonRules\n },\n messages: {\n ...formCommonMessages\n }\n }).data(\"kendoValidator\");\n\n return validator.validate();\n }\n\n /**\n * \n * @param {string} target\n */\n async _validateFormAsync(target) {\n let formCommonRules = {\n validSendingValue: function (input) {\n if (input.is(`[name=\"SendingValue\"]`)) {\n let sendingType = $(\"#SendingInformation\").data(\"kendoRadioGroup\")?.value();\n if (sendingType === \"Email\") {\n let re = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n let email = input.val()\n return re.test(email);\n } else if (sendingType === \"Phone\") {\n let re = /^\\+?\\d{2}[- ]?\\d{3}[- ]?\\d{5}$/;\n let phone = input.val()\n return re.test(phone);\n } else {\n return false;\n }\n }\n else {\n return true;\n }\n },\n\n requiredSendingValue: function (input) {\n if (input.is(`[name=\"SendingInformation\"]`)) {\n return input.val()\n } else {\n return true\n }\n\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredCode: function (input) {\n if (input.is(`[name=\"CodeValid\"]`)) {\n if (input.val()) {\n return true;\n } else {\n return false;\n }\n } else {\n return true;\n }\n }\n\n }\n let formCommonMessages = {\n validSendingValue: \"Debe ingresar un medio de envío válido\",\n requiredSendingValue: \"Debe seleccionar un medio para el envío\",\n requiredCode: \"Debe ingresar el código numérico recibido en el correo\"\n }\n\n let validator = $(target).kendoValidator({\n rules: {\n ...formCommonRules\n },\n messages: {\n ...formCommonMessages\n }\n }).data(\"kendoValidator\");\n\n return validator.validate();\n }\n\n /**\n * @returns {boolean}\n * */\n async _send2FACodeAsync() {\n let formData = this.getSendCodeFormData();\n let ajaxResponse = await this._twoFaService.validationCodeProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n return this._handleSendCode2FAAsync(ajaxResponse)\n }\n }\n\n /**\n * @returns {Promise}\n * */\n async _reSend2FACodeAsync() {\n let formData = this.getSendCodeFormData();\n let ajaxResponse = await this._twoFaService.reValidationCodeProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n return this._handleSendCode2FAAsync(ajaxResponse)\n }\n }\n\n /**\n * \n * @returns {Promise}\n * */\n async _validate2FACodeAsync() {\n let formData = this.getValidateFormData();\n let ajaxResponse = await this._twoFaService.validateCodeProcess2FAAsync(formData);\n if (ajaxResponse.ok) {\n\n /** @type {{VerificationCode: {}, RedirectTo: string}} */\n let jsonResponse = await ajaxResponse.json();\n\n /** @type {{Successful: boolean, UserMessage: string, Message: string, Validation: boolean}} */\n let verificationCode = jsonResponse.VerificationCode;\n\n if (!verificationCode.Validation) {\n console.error(verificationCode.Message)\n this._showAlert({\n userMessage: verificationCode.Message\n })\n return false;\n }\n\n this._showLoading(true);\n this.redirect(jsonResponse.RedirectTo);\n }\n }\n\n /**\n * \n * @param {Response} ajaxResponse\n * @returns {boolean}\n * */\n async _handleSendCode2FAAsync(ajaxResponse) {\n try {\n let jsonResponse = await ajaxResponse.json();\n if (!jsonResponse.Successful) {\n let message = jsonResponse.UserMessage ?? jsonResponse.Message\n console.error(message)\n this._showAlert({\n userMessage: message\n });\n return false;\n }\n\n if (jsonResponse.UserMessage) {\n this._showAlert({\n userMessage: jsonResponse.UserMessage\n })\n }\n return true;\n } catch (e) {\n console.error(e)\n return false;\n }\n }\n\n /**\n * \n * @param {string} target\n */\n getAdditionalInformationFormData(target = `#securityQuestion2FAForm`) {\n return new FormData($(target)[0]);\n }\n\n}","export class ForgeryTokenHelper {\n\n constructor() { }\n\n // Write your Javascript code.\n static forgeryToken() {\n return kendo.antiForgeryTokens();\n }\n\n static forgeryTokenString() {\n const tokenObject = ForgeryTokenHelper.forgeryToken();\n return tokenObject.__RequestVerificationToken;\n }\n}","import { ForgeryTokenHelper } from \"../../shared/helper/forgeryTokenHelper\";\n\nexport class CreditCardService {\n\n constructor() { }\n\n /**\n * \n * @param {FormData} formData\n * @returns {Promise}\n * */\n postSave(formData) {\n return fetch(\"/api/CreditCard/Save\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n },\n body: formData\n });\n }\n\n /**\n * \n * @param {FormData} formData\n * @returns {Promise}\n * */\n postDelete(formData) {\n return fetch(\"/api/CreditCard/Delete\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n },\n body: formData\n });\n }\n\n /**\n * \n * @returns {Promise}\n * */\n postGetAcceptanceInfo() {\n return fetch(\"/api/CreditCard/GetAcceptanceInfo\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n }\n });\n }\n\n /**\n * \n * @param {FormData} formData\n * @returns {Promise}\n * */\n postLoadItem(formData) {\n return fetch(\"/Security/MyAccount/Options/MyCards?handler=LoadCreditCardItem\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n },\n body: formData\n });\n }\n\n\n /**\n * \n * @returns {Promise}\n * */\n postLoadItemsForCheckout() {\n return fetch(\"?handler=LoadCreditCardItems\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n }\n });\n }\n\n\n}","function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}\n\nexport { _objectWithoutPropertiesLoose as _ };\n","/**\n * Applies mask on element.\n * @constructor\n * @param {HTMLInputElement|HTMLTextAreaElement|MaskElement} el - Element to apply mask\n * @param {Object} opts - Custom mask options\n * @return {InputMask}\n */\nfunction IMask(el) {\n let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n // currently available only for input-like elements\n return new IMask.InputMask(el, opts);\n}\n\nexport { IMask as default };\n","import IMask from './holder.js';\n\n/**\n Provides details of changing model value\n @param {Object} [details]\n @param {string} [details.inserted] - Inserted symbols\n @param {boolean} [details.skip] - Can skip chars\n @param {number} [details.removeCount] - Removed symbols count\n @param {number} [details.tailShift] - Additional offset if any changes occurred before tail\n*/\nclass ChangeDetails {\n /** Inserted symbols */\n\n /** Can skip chars */\n\n /** Additional offset if any changes occurred before tail */\n\n /** Raw inserted is used by dynamic mask */\n\n constructor(details) {\n Object.assign(this, {\n inserted: '',\n rawInserted: '',\n skip: false,\n tailShift: 0\n }, details);\n }\n\n /**\n Aggregate changes\n @returns {ChangeDetails} `this`\n */\n aggregate(details) {\n this.rawInserted += details.rawInserted;\n this.skip = this.skip || details.skip;\n this.inserted += details.inserted;\n this.tailShift += details.tailShift;\n return this;\n }\n\n /** Total offset considering all changes */\n get offset() {\n return this.tailShift + this.inserted.length;\n }\n}\nIMask.ChangeDetails = ChangeDetails;\n\nexport { ChangeDetails as default };\n","import ChangeDetails from './change-details.js';\nimport './holder.js';\n\n/** Checks if value is string */\nfunction isString(str) {\n return typeof str === 'string' || str instanceof String;\n}\n\n/**\n Direction\n @prop {string} NONE\n @prop {string} LEFT\n @prop {string} FORCE_LEFT\n @prop {string} RIGHT\n @prop {string} FORCE_RIGHT\n*/\nconst DIRECTION = {\n NONE: 'NONE',\n LEFT: 'LEFT',\n FORCE_LEFT: 'FORCE_LEFT',\n RIGHT: 'RIGHT',\n FORCE_RIGHT: 'FORCE_RIGHT'\n};\n/**\n Direction\n @enum {string}\n*/\n\n/** Returns next char index in direction */\nfunction indexInDirection(pos, direction) {\n if (direction === DIRECTION.LEFT) --pos;\n return pos;\n}\n\n/** Returns next char position in direction */\nfunction posInDirection(pos, direction) {\n switch (direction) {\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n return --pos;\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n return ++pos;\n default:\n return pos;\n }\n}\n\n/** */\nfunction forceDirection(direction) {\n switch (direction) {\n case DIRECTION.LEFT:\n return DIRECTION.FORCE_LEFT;\n case DIRECTION.RIGHT:\n return DIRECTION.FORCE_RIGHT;\n default:\n return direction;\n }\n}\n\n/** Escapes regular expression control chars */\nfunction escapeRegExp(str) {\n return str.replace(/([.*+?^=!:${}()|[\\]\\/\\\\])/g, '\\\\$1');\n}\nfunction normalizePrepare(prep) {\n return Array.isArray(prep) ? prep : [prep, new ChangeDetails()];\n}\n\n// cloned from https://github.com/epoberezkin/fast-deep-equal with small changes\nfunction objectIncludes(b, a) {\n if (a === b) return true;\n var arrA = Array.isArray(a),\n arrB = Array.isArray(b),\n i;\n if (arrA && arrB) {\n if (a.length != b.length) return false;\n for (i = 0; i < a.length; i++) if (!objectIncludes(a[i], b[i])) return false;\n return true;\n }\n if (arrA != arrB) return false;\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n var dateA = a instanceof Date,\n dateB = b instanceof Date;\n if (dateA && dateB) return a.getTime() == b.getTime();\n if (dateA != dateB) return false;\n var regexpA = a instanceof RegExp,\n regexpB = b instanceof RegExp;\n if (regexpA && regexpB) return a.toString() == b.toString();\n if (regexpA != regexpB) return false;\n var keys = Object.keys(a);\n // if (keys.length !== Object.keys(b).length) return false;\n\n for (i = 0; i < keys.length; i++)\n // $FlowFixMe ... ???\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n for (i = 0; i < keys.length; i++) if (!objectIncludes(b[keys[i]], a[keys[i]])) return false;\n return true;\n } else if (a && b && typeof a === 'function' && typeof b === 'function') {\n return a.toString() === b.toString();\n }\n return false;\n}\n\n/** Selection range */\n\nexport { DIRECTION, escapeRegExp, forceDirection, indexInDirection, isString, normalizePrepare, objectIncludes, posInDirection };\n","import { DIRECTION } from './utils.js';\nimport './change-details.js';\nimport './holder.js';\n\n/** Provides details of changing input */\nclass ActionDetails {\n /** Current input value */\n\n /** Current cursor position */\n\n /** Old input value */\n\n /** Old selection */\n\n constructor(value, cursorPos, oldValue, oldSelection) {\n this.value = value;\n this.cursorPos = cursorPos;\n this.oldValue = oldValue;\n this.oldSelection = oldSelection;\n\n // double check if left part was changed (autofilling, other non-standard input triggers)\n while (this.value.slice(0, this.startChangePos) !== this.oldValue.slice(0, this.startChangePos)) {\n --this.oldSelection.start;\n }\n }\n\n /**\n Start changing position\n @readonly\n */\n get startChangePos() {\n return Math.min(this.cursorPos, this.oldSelection.start);\n }\n\n /**\n Inserted symbols count\n @readonly\n */\n get insertedCount() {\n return this.cursorPos - this.startChangePos;\n }\n\n /**\n Inserted symbols\n @readonly\n */\n get inserted() {\n return this.value.substr(this.startChangePos, this.insertedCount);\n }\n\n /**\n Removed symbols count\n @readonly\n */\n get removedCount() {\n // Math.max for opposite operation\n return Math.max(this.oldSelection.end - this.startChangePos ||\n // for Delete\n this.oldValue.length - this.value.length, 0);\n }\n\n /**\n Removed symbols\n @readonly\n */\n get removed() {\n return this.oldValue.substr(this.startChangePos, this.removedCount);\n }\n\n /**\n Unchanged head symbols\n @readonly\n */\n get head() {\n return this.value.substring(0, this.startChangePos);\n }\n\n /**\n Unchanged tail symbols\n @readonly\n */\n get tail() {\n return this.value.substring(this.startChangePos + this.insertedCount);\n }\n\n /**\n Remove direction\n @readonly\n */\n get removeDirection() {\n if (!this.removedCount || this.insertedCount) return DIRECTION.NONE;\n\n // align right if delete at right\n return (this.oldSelection.end === this.cursorPos || this.oldSelection.start === this.cursorPos) &&\n // if not range removed (event with backspace)\n this.oldSelection.end === this.oldSelection.start ? DIRECTION.RIGHT : DIRECTION.LEFT;\n }\n}\n\nexport { ActionDetails as default };\n","/** Provides details of continuous extracted tail */\nclass ContinuousTailDetails {\n /** Tail value as string */\n\n /** Tail start position */\n\n /** Start position */\n\n constructor() {\n let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n let stop = arguments.length > 2 ? arguments[2] : undefined;\n this.value = value;\n this.from = from;\n this.stop = stop;\n }\n toString() {\n return this.value;\n }\n extend(tail) {\n this.value += String(tail);\n }\n appendTo(masked) {\n return masked.append(this.toString(), {\n tail: true\n }).aggregate(masked._appendPlaceholder());\n }\n get state() {\n return {\n value: this.value,\n from: this.from,\n stop: this.stop\n };\n }\n set state(state) {\n Object.assign(this, state);\n }\n unshift(beforePos) {\n if (!this.value.length || beforePos != null && this.from >= beforePos) return '';\n const shiftChar = this.value[0];\n this.value = this.value.slice(1);\n return shiftChar;\n }\n shift() {\n if (!this.value.length) return '';\n const shiftChar = this.value[this.value.length - 1];\n this.value = this.value.slice(0, -1);\n return shiftChar;\n }\n}\n\nexport { ContinuousTailDetails as default };\n","import ChangeDetails from '../core/change-details.js';\nimport ContinuousTailDetails from '../core/continuous-tail-details.js';\nimport { isString, normalizePrepare, DIRECTION, forceDirection } from '../core/utils.js';\nimport IMask from '../core/holder.js';\n\n/** Supported mask type */\n\n/** Append flags */\n\n/** Extract flags */\n\n/** Provides common masking stuff */\nclass Masked {\n // $Shape; TODO after fix https://github.com/facebook/flow/issues/4773\n\n /** @type {Mask} */\n\n /** */ // $FlowFixMe no ideas\n /** Transforms value before mask processing */\n /** Validates if value is acceptable */\n /** Does additional processing in the end of editing */\n /** Format typed value to string */\n /** Parse strgin to get typed value */\n /** Enable characters overwriting */\n /** */\n /** */\n /** */\n constructor(opts) {\n this._value = '';\n this._update(Object.assign({}, Masked.DEFAULTS, opts));\n this.isInitialized = true;\n }\n\n /** Sets and applies new options */\n updateOptions(opts) {\n if (!Object.keys(opts).length) return;\n // $FlowFixMe\n this.withValueRefresh(this._update.bind(this, opts));\n }\n\n /**\n Sets new options\n @protected\n */\n _update(opts) {\n Object.assign(this, opts);\n }\n\n /** Mask state */\n get state() {\n return {\n _value: this.value\n };\n }\n set state(state) {\n this._value = state._value;\n }\n\n /** Resets value */\n reset() {\n this._value = '';\n }\n\n /** */\n get value() {\n return this._value;\n }\n set value(value) {\n this.resolve(value);\n }\n\n /** Resolve new value */\n resolve(value) {\n this.reset();\n this.append(value, {\n input: true\n }, '');\n this.doCommit();\n return this.value;\n }\n\n /** */\n get unmaskedValue() {\n return this.value;\n }\n set unmaskedValue(value) {\n this.reset();\n this.append(value, {}, '');\n this.doCommit();\n }\n\n /** */\n get typedValue() {\n return this.doParse(this.value);\n }\n set typedValue(value) {\n this.value = this.doFormat(value);\n }\n\n /** Value that includes raw user input */\n get rawInputValue() {\n return this.extractInput(0, this.value.length, {\n raw: true\n });\n }\n set rawInputValue(value) {\n this.reset();\n this.append(value, {\n raw: true\n }, '');\n this.doCommit();\n }\n get displayValue() {\n return this.value;\n }\n\n /** */\n get isComplete() {\n return true;\n }\n\n /** */\n get isFilled() {\n return this.isComplete;\n }\n\n /** Finds nearest input position in direction */\n nearestInputPos(cursorPos, direction) {\n return cursorPos;\n }\n totalInputPositions() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n return Math.min(this.value.length, toPos - fromPos);\n }\n\n /** Extracts value in range considering flags */\n extractInput() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n return this.value.slice(fromPos, toPos);\n }\n\n /** Extracts tail in range */\n extractTail() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n return new ContinuousTailDetails(this.extractInput(fromPos, toPos), fromPos);\n }\n\n /** Appends tail */\n // $FlowFixMe no ideas\n appendTail(tail) {\n if (isString(tail)) tail = new ContinuousTailDetails(String(tail));\n return tail.appendTo(this);\n }\n\n /** Appends char */\n _appendCharRaw(ch) {\n if (!ch) return new ChangeDetails();\n this._value += ch;\n return new ChangeDetails({\n inserted: ch,\n rawInserted: ch\n });\n }\n\n /** Appends char */\n _appendChar(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let checkTail = arguments.length > 2 ? arguments[2] : undefined;\n const consistentState = this.state;\n let details;\n [ch, details] = normalizePrepare(this.doPrepare(ch, flags));\n details = details.aggregate(this._appendCharRaw(ch, flags));\n if (details.inserted) {\n let consistentTail;\n let appended = this.doValidate(flags) !== false;\n if (appended && checkTail != null) {\n // validation ok, check tail\n const beforeTailState = this.state;\n if (this.overwrite === true) {\n consistentTail = checkTail.state;\n checkTail.unshift(this.value.length - details.tailShift);\n }\n let tailDetails = this.appendTail(checkTail);\n appended = tailDetails.rawInserted === checkTail.toString();\n\n // not ok, try shift\n if (!(appended && tailDetails.inserted) && this.overwrite === 'shift') {\n this.state = beforeTailState;\n consistentTail = checkTail.state;\n checkTail.shift();\n tailDetails = this.appendTail(checkTail);\n appended = tailDetails.rawInserted === checkTail.toString();\n }\n\n // if ok, rollback state after tail\n if (appended && tailDetails.inserted) this.state = beforeTailState;\n }\n\n // revert all if something went wrong\n if (!appended) {\n details = new ChangeDetails();\n this.state = consistentState;\n if (checkTail && consistentTail) checkTail.state = consistentTail;\n }\n }\n return details;\n }\n\n /** Appends optional placeholder at end */\n _appendPlaceholder() {\n return new ChangeDetails();\n }\n\n /** Appends optional eager placeholder at end */\n _appendEager() {\n return new ChangeDetails();\n }\n\n /** Appends symbols considering flags */\n // $FlowFixMe no ideas\n append(str, flags, tail) {\n if (!isString(str)) throw new Error('value should be string');\n const details = new ChangeDetails();\n const checkTail = isString(tail) ? new ContinuousTailDetails(String(tail)) : tail;\n if (flags !== null && flags !== void 0 && flags.tail) flags._beforeTailState = this.state;\n for (let ci = 0; ci < str.length; ++ci) {\n const d = this._appendChar(str[ci], flags, checkTail);\n if (!d.rawInserted && !this.doSkipInvalid(str[ci], flags, checkTail)) break;\n details.aggregate(d);\n }\n\n // append tail but aggregate only tailShift\n if (checkTail != null) {\n details.tailShift += this.appendTail(checkTail).tailShift;\n // TODO it's a good idea to clear state after appending ends\n // but it causes bugs when one append calls another (when dynamic dispatch set rawInputValue)\n // this._resetBeforeTailState();\n }\n\n if ((this.eager === true || this.eager === 'append') && flags !== null && flags !== void 0 && flags.input && str) {\n details.aggregate(this._appendEager());\n }\n return details;\n }\n\n /** */\n remove() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n this._value = this.value.slice(0, fromPos) + this.value.slice(toPos);\n return new ChangeDetails();\n }\n\n /** Calls function and reapplies current value */\n withValueRefresh(fn) {\n if (this._refreshing || !this.isInitialized) return fn();\n this._refreshing = true;\n const rawInput = this.rawInputValue;\n const value = this.value;\n const ret = fn();\n this.rawInputValue = rawInput;\n // append lost trailing chars at end\n if (this.value && this.value !== value && value.indexOf(this.value) === 0) {\n this.append(value.slice(this.value.length), {}, '');\n }\n delete this._refreshing;\n return ret;\n }\n\n /** */\n runIsolated(fn) {\n if (this._isolated || !this.isInitialized) return fn(this);\n this._isolated = true;\n const state = this.state;\n const ret = fn(this);\n this.state = state;\n delete this._isolated;\n return ret;\n }\n\n /** */\n doSkipInvalid(ch) {\n return this.skipInvalid;\n }\n\n /**\n Prepares string before mask processing\n @protected\n */\n doPrepare(str) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return this.prepare ? this.prepare(str, this, flags) : str;\n }\n\n /**\n Validates if value is acceptable\n @protected\n */\n doValidate(flags) {\n return (!this.validate || this.validate(this.value, this, flags)) && (!this.parent || this.parent.doValidate(flags));\n }\n\n /**\n Does additional processing in the end of editing\n @protected\n */\n doCommit() {\n if (this.commit) this.commit(this.value, this);\n }\n\n /** */\n doFormat(value) {\n return this.format ? this.format(value, this) : value;\n }\n\n /** */\n doParse(str) {\n return this.parse ? this.parse(str, this) : str;\n }\n\n /** */\n splice(start, deleteCount, inserted, removeDirection) {\n let flags = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {\n input: true\n };\n const tailPos = start + deleteCount;\n const tail = this.extractTail(tailPos);\n const eagerRemove = this.eager === true || this.eager === 'remove';\n let oldRawValue;\n if (eagerRemove) {\n removeDirection = forceDirection(removeDirection);\n oldRawValue = this.extractInput(0, tailPos, {\n raw: true\n });\n }\n let startChangePos = start;\n const details = new ChangeDetails();\n\n // if it is just deletion without insertion\n if (removeDirection !== DIRECTION.NONE) {\n startChangePos = this.nearestInputPos(start, deleteCount > 1 && start !== 0 && !eagerRemove ? DIRECTION.NONE : removeDirection);\n\n // adjust tailShift if start was aligned\n details.tailShift = startChangePos - start;\n }\n details.aggregate(this.remove(startChangePos));\n if (eagerRemove && removeDirection !== DIRECTION.NONE && oldRawValue === this.rawInputValue) {\n if (removeDirection === DIRECTION.FORCE_LEFT) {\n let valLength;\n while (oldRawValue === this.rawInputValue && (valLength = this.value.length)) {\n details.aggregate(new ChangeDetails({\n tailShift: -1\n })).aggregate(this.remove(valLength - 1));\n }\n } else if (removeDirection === DIRECTION.FORCE_RIGHT) {\n tail.unshift();\n }\n }\n return details.aggregate(this.append(inserted, flags, tail));\n }\n maskEquals(mask) {\n return this.mask === mask;\n }\n typedValueEquals(value) {\n const tval = this.typedValue;\n return value === tval || Masked.EMPTY_VALUES.includes(value) && Masked.EMPTY_VALUES.includes(tval) || this.doFormat(value) === this.doFormat(this.typedValue);\n }\n}\nMasked.DEFAULTS = {\n format: String,\n parse: v => v,\n skipInvalid: true\n};\nMasked.EMPTY_VALUES = [undefined, null, ''];\nIMask.Masked = Masked;\n\nexport { Masked as default };\n","import { isString } from '../core/utils.js';\nimport IMask from '../core/holder.js';\nimport '../core/change-details.js';\n\n/** Get Masked class by mask type */\nfunction maskedClass(mask) {\n if (mask == null) {\n throw new Error('mask property should be defined');\n }\n\n // $FlowFixMe\n if (mask instanceof RegExp) return IMask.MaskedRegExp;\n // $FlowFixMe\n if (isString(mask)) return IMask.MaskedPattern;\n // $FlowFixMe\n if (mask instanceof Date || mask === Date) return IMask.MaskedDate;\n // $FlowFixMe\n if (mask instanceof Number || typeof mask === 'number' || mask === Number) return IMask.MaskedNumber;\n // $FlowFixMe\n if (Array.isArray(mask) || mask === Array) return IMask.MaskedDynamic;\n // $FlowFixMe\n if (IMask.Masked && mask.prototype instanceof IMask.Masked) return mask;\n // $FlowFixMe\n if (mask instanceof IMask.Masked) return mask.constructor;\n // $FlowFixMe\n if (mask instanceof Function) return IMask.MaskedFunction;\n console.warn('Mask not found for mask', mask); // eslint-disable-line no-console\n // $FlowFixMe\n return IMask.Masked;\n}\n\n/** Creates new {@link Masked} depending on mask type */\nfunction createMask(opts) {\n // $FlowFixMe\n if (IMask.Masked && opts instanceof IMask.Masked) return opts;\n opts = Object.assign({}, opts);\n const mask = opts.mask;\n\n // $FlowFixMe\n if (IMask.Masked && mask instanceof IMask.Masked) return mask;\n const MaskedClass = maskedClass(mask);\n if (!MaskedClass) throw new Error('Masked class is not found for provided mask, appropriate module needs to be import manually before creating mask.');\n return new MaskedClass(opts);\n}\nIMask.createMask = createMask;\n\nexport { createMask as default, maskedClass };\n","import { _ as _objectWithoutPropertiesLoose } from '../../_rollupPluginBabelHelpers-6b3bd404.js';\nimport createMask from '../factory.js';\nimport ChangeDetails from '../../core/change-details.js';\nimport { DIRECTION } from '../../core/utils.js';\nimport '../../core/holder.js';\n\nconst _excluded = [\"parent\", \"isOptional\", \"placeholderChar\", \"displayChar\", \"lazy\", \"eager\"];\n\n/** */\n\nconst DEFAULT_INPUT_DEFINITIONS = {\n '0': /\\d/,\n 'a': /[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]/,\n // http://stackoverflow.com/a/22075070\n '*': /./\n};\n\n/** */\nclass PatternInputDefinition {\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n const {\n parent,\n isOptional,\n placeholderChar,\n displayChar,\n lazy,\n eager\n } = opts,\n maskOpts = _objectWithoutPropertiesLoose(opts, _excluded);\n this.masked = createMask(maskOpts);\n Object.assign(this, {\n parent,\n isOptional,\n placeholderChar,\n displayChar,\n lazy,\n eager\n });\n }\n reset() {\n this.isFilled = false;\n this.masked.reset();\n }\n remove() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n if (fromPos === 0 && toPos >= 1) {\n this.isFilled = false;\n return this.masked.remove(fromPos, toPos);\n }\n return new ChangeDetails();\n }\n get value() {\n return this.masked.value || (this.isFilled && !this.isOptional ? this.placeholderChar : '');\n }\n get unmaskedValue() {\n return this.masked.unmaskedValue;\n }\n get displayValue() {\n return this.masked.value && this.displayChar || this.value;\n }\n get isComplete() {\n return Boolean(this.masked.value) || this.isOptional;\n }\n _appendChar(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (this.isFilled) return new ChangeDetails();\n const state = this.masked.state;\n // simulate input\n const details = this.masked._appendChar(ch, flags);\n if (details.inserted && this.doValidate(flags) === false) {\n details.inserted = details.rawInserted = '';\n this.masked.state = state;\n }\n if (!details.inserted && !this.isOptional && !this.lazy && !flags.input) {\n details.inserted = this.placeholderChar;\n }\n details.skip = !details.inserted && !this.isOptional;\n this.isFilled = Boolean(details.inserted);\n return details;\n }\n append() {\n // TODO probably should be done via _appendChar\n return this.masked.append(...arguments);\n }\n _appendPlaceholder() {\n const details = new ChangeDetails();\n if (this.isFilled || this.isOptional) return details;\n this.isFilled = true;\n details.inserted = this.placeholderChar;\n return details;\n }\n _appendEager() {\n return new ChangeDetails();\n }\n extractTail() {\n return this.masked.extractTail(...arguments);\n }\n appendTail() {\n return this.masked.appendTail(...arguments);\n }\n extractInput() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n let flags = arguments.length > 2 ? arguments[2] : undefined;\n return this.masked.extractInput(fromPos, toPos, flags);\n }\n nearestInputPos(cursorPos) {\n let direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DIRECTION.NONE;\n const minPos = 0;\n const maxPos = this.value.length;\n const boundPos = Math.min(Math.max(cursorPos, minPos), maxPos);\n switch (direction) {\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n return this.isComplete ? boundPos : minPos;\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n return this.isComplete ? boundPos : maxPos;\n case DIRECTION.NONE:\n default:\n return boundPos;\n }\n }\n totalInputPositions() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n return this.value.slice(fromPos, toPos).length;\n }\n doValidate() {\n return this.masked.doValidate(...arguments) && (!this.parent || this.parent.doValidate(...arguments));\n }\n doCommit() {\n this.masked.doCommit();\n }\n get state() {\n return {\n masked: this.masked.state,\n isFilled: this.isFilled\n };\n }\n set state(state) {\n this.masked.state = state.masked;\n this.isFilled = state.isFilled;\n }\n}\n\nexport { DEFAULT_INPUT_DEFINITIONS, PatternInputDefinition as default };\n","import ChangeDetails from '../../core/change-details.js';\nimport { DIRECTION, isString } from '../../core/utils.js';\nimport ContinuousTailDetails from '../../core/continuous-tail-details.js';\nimport '../../core/holder.js';\n\n/** */\n\nclass PatternFixedDefinition {\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n /** */\n\n constructor(opts) {\n Object.assign(this, opts);\n this._value = '';\n this.isFixed = true;\n }\n get value() {\n return this._value;\n }\n get unmaskedValue() {\n return this.isUnmasking ? this.value : '';\n }\n get displayValue() {\n return this.value;\n }\n reset() {\n this._isRawInput = false;\n this._value = '';\n }\n remove() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._value.length;\n this._value = this._value.slice(0, fromPos) + this._value.slice(toPos);\n if (!this._value) this._isRawInput = false;\n return new ChangeDetails();\n }\n nearestInputPos(cursorPos) {\n let direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DIRECTION.NONE;\n const minPos = 0;\n const maxPos = this._value.length;\n switch (direction) {\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n return minPos;\n case DIRECTION.NONE:\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n default:\n return maxPos;\n }\n }\n totalInputPositions() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._value.length;\n return this._isRawInput ? toPos - fromPos : 0;\n }\n extractInput() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._value.length;\n let flags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return flags.raw && this._isRawInput && this._value.slice(fromPos, toPos) || '';\n }\n get isComplete() {\n return true;\n }\n get isFilled() {\n return Boolean(this._value);\n }\n _appendChar(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n const details = new ChangeDetails();\n if (this.isFilled) return details;\n const appendEager = this.eager === true || this.eager === 'append';\n const appended = this.char === ch;\n const isResolved = appended && (this.isUnmasking || flags.input || flags.raw) && (!flags.raw || !appendEager) && !flags.tail;\n if (isResolved) details.rawInserted = this.char;\n this._value = details.inserted = this.char;\n this._isRawInput = isResolved && (flags.raw || flags.input);\n return details;\n }\n _appendEager() {\n return this._appendChar(this.char, {\n tail: true\n });\n }\n _appendPlaceholder() {\n const details = new ChangeDetails();\n if (this.isFilled) return details;\n this._value = details.inserted = this.char;\n return details;\n }\n extractTail() {\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n return new ContinuousTailDetails('');\n }\n\n // $FlowFixMe no ideas\n appendTail(tail) {\n if (isString(tail)) tail = new ContinuousTailDetails(String(tail));\n return tail.appendTo(this);\n }\n append(str, flags, tail) {\n const details = this._appendChar(str[0], flags);\n if (tail != null) {\n details.tailShift += this.appendTail(tail).tailShift;\n }\n return details;\n }\n doCommit() {}\n get state() {\n return {\n _value: this._value,\n _isRawInput: this._isRawInput\n };\n }\n set state(state) {\n Object.assign(this, state);\n }\n}\n\nexport { PatternFixedDefinition as default };\n","import { _ as _objectWithoutPropertiesLoose } from '../../_rollupPluginBabelHelpers-6b3bd404.js';\nimport ChangeDetails from '../../core/change-details.js';\nimport { isString } from '../../core/utils.js';\nimport ContinuousTailDetails from '../../core/continuous-tail-details.js';\nimport IMask from '../../core/holder.js';\n\nconst _excluded = [\"chunks\"];\nclass ChunksTailDetails {\n /** */\n\n constructor() {\n let chunks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n this.chunks = chunks;\n this.from = from;\n }\n toString() {\n return this.chunks.map(String).join('');\n }\n\n // $FlowFixMe no ideas\n extend(tailChunk) {\n if (!String(tailChunk)) return;\n if (isString(tailChunk)) tailChunk = new ContinuousTailDetails(String(tailChunk));\n const lastChunk = this.chunks[this.chunks.length - 1];\n const extendLast = lastChunk && (\n // if stops are same or tail has no stop\n lastChunk.stop === tailChunk.stop || tailChunk.stop == null) &&\n // if tail chunk goes just after last chunk\n tailChunk.from === lastChunk.from + lastChunk.toString().length;\n if (tailChunk instanceof ContinuousTailDetails) {\n // check the ability to extend previous chunk\n if (extendLast) {\n // extend previous chunk\n lastChunk.extend(tailChunk.toString());\n } else {\n // append new chunk\n this.chunks.push(tailChunk);\n }\n } else if (tailChunk instanceof ChunksTailDetails) {\n if (tailChunk.stop == null) {\n // unwrap floating chunks to parent, keeping `from` pos\n let firstTailChunk;\n while (tailChunk.chunks.length && tailChunk.chunks[0].stop == null) {\n firstTailChunk = tailChunk.chunks.shift();\n firstTailChunk.from += tailChunk.from;\n this.extend(firstTailChunk);\n }\n }\n\n // if tail chunk still has value\n if (tailChunk.toString()) {\n // if chunks contains stops, then popup stop to container\n tailChunk.stop = tailChunk.blockIndex;\n this.chunks.push(tailChunk);\n }\n }\n }\n appendTo(masked) {\n // $FlowFixMe\n if (!(masked instanceof IMask.MaskedPattern)) {\n const tail = new ContinuousTailDetails(this.toString());\n return tail.appendTo(masked);\n }\n const details = new ChangeDetails();\n for (let ci = 0; ci < this.chunks.length && !details.skip; ++ci) {\n const chunk = this.chunks[ci];\n const lastBlockIter = masked._mapPosToBlock(masked.value.length);\n const stop = chunk.stop;\n let chunkBlock;\n if (stop != null && (\n // if block not found or stop is behind lastBlock\n !lastBlockIter || lastBlockIter.index <= stop)) {\n if (chunk instanceof ChunksTailDetails ||\n // for continuous block also check if stop is exist\n masked._stops.indexOf(stop) >= 0) {\n const phDetails = masked._appendPlaceholder(stop);\n details.aggregate(phDetails);\n }\n chunkBlock = chunk instanceof ChunksTailDetails && masked._blocks[stop];\n }\n if (chunkBlock) {\n const tailDetails = chunkBlock.appendTail(chunk);\n tailDetails.skip = false; // always ignore skip, it will be set on last\n details.aggregate(tailDetails);\n masked._value += tailDetails.inserted;\n\n // get not inserted chars\n const remainChars = chunk.toString().slice(tailDetails.rawInserted.length);\n if (remainChars) details.aggregate(masked.append(remainChars, {\n tail: true\n }));\n } else {\n details.aggregate(masked.append(chunk.toString(), {\n tail: true\n }));\n }\n }\n return details;\n }\n get state() {\n return {\n chunks: this.chunks.map(c => c.state),\n from: this.from,\n stop: this.stop,\n blockIndex: this.blockIndex\n };\n }\n set state(state) {\n const {\n chunks\n } = state,\n props = _objectWithoutPropertiesLoose(state, _excluded);\n Object.assign(this, props);\n this.chunks = chunks.map(cstate => {\n const chunk = \"chunks\" in cstate ? new ChunksTailDetails() : new ContinuousTailDetails();\n // $FlowFixMe already checked above\n chunk.state = cstate;\n return chunk;\n });\n }\n unshift(beforePos) {\n if (!this.chunks.length || beforePos != null && this.from >= beforePos) return '';\n const chunkShiftPos = beforePos != null ? beforePos - this.from : beforePos;\n let ci = 0;\n while (ci < this.chunks.length) {\n const chunk = this.chunks[ci];\n const shiftChar = chunk.unshift(chunkShiftPos);\n if (chunk.toString()) {\n // chunk still contains value\n // but not shifted - means no more available chars to shift\n if (!shiftChar) break;\n ++ci;\n } else {\n // clean if chunk has no value\n this.chunks.splice(ci, 1);\n }\n if (shiftChar) return shiftChar;\n }\n return '';\n }\n shift() {\n if (!this.chunks.length) return '';\n let ci = this.chunks.length - 1;\n while (0 <= ci) {\n const chunk = this.chunks[ci];\n const shiftChar = chunk.shift();\n if (chunk.toString()) {\n // chunk still contains value\n // but not shifted - means no more available chars to shift\n if (!shiftChar) break;\n --ci;\n } else {\n // clean if chunk has no value\n this.chunks.splice(ci, 1);\n }\n if (shiftChar) return shiftChar;\n }\n return '';\n }\n}\n\nexport { ChunksTailDetails as default };\n","import { DIRECTION } from '../../core/utils.js';\nimport '../../core/change-details.js';\nimport '../../core/holder.js';\n\nclass PatternCursor {\n constructor(masked, pos) {\n this.masked = masked;\n this._log = [];\n const {\n offset,\n index\n } = masked._mapPosToBlock(pos) || (pos < 0 ?\n // first\n {\n index: 0,\n offset: 0\n } :\n // last\n {\n index: this.masked._blocks.length,\n offset: 0\n });\n this.offset = offset;\n this.index = index;\n this.ok = false;\n }\n get block() {\n return this.masked._blocks[this.index];\n }\n get pos() {\n return this.masked._blockStartPos(this.index) + this.offset;\n }\n get state() {\n return {\n index: this.index,\n offset: this.offset,\n ok: this.ok\n };\n }\n set state(s) {\n Object.assign(this, s);\n }\n pushState() {\n this._log.push(this.state);\n }\n popState() {\n const s = this._log.pop();\n this.state = s;\n return s;\n }\n bindBlock() {\n if (this.block) return;\n if (this.index < 0) {\n this.index = 0;\n this.offset = 0;\n }\n if (this.index >= this.masked._blocks.length) {\n this.index = this.masked._blocks.length - 1;\n this.offset = this.block.value.length;\n }\n }\n _pushLeft(fn) {\n this.pushState();\n for (this.bindBlock(); 0 <= this.index; --this.index, this.offset = ((_this$block = this.block) === null || _this$block === void 0 ? void 0 : _this$block.value.length) || 0) {\n var _this$block;\n if (fn()) return this.ok = true;\n }\n return this.ok = false;\n }\n _pushRight(fn) {\n this.pushState();\n for (this.bindBlock(); this.index < this.masked._blocks.length; ++this.index, this.offset = 0) {\n if (fn()) return this.ok = true;\n }\n return this.ok = false;\n }\n pushLeftBeforeFilled() {\n return this._pushLeft(() => {\n if (this.block.isFixed || !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.FORCE_LEFT);\n if (this.offset !== 0) return true;\n });\n }\n pushLeftBeforeInput() {\n // cases:\n // filled input: 00|\n // optional empty input: 00[]|\n // nested block: XX<[]>|\n return this._pushLeft(() => {\n if (this.block.isFixed) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.LEFT);\n return true;\n });\n }\n pushLeftBeforeRequired() {\n return this._pushLeft(() => {\n if (this.block.isFixed || this.block.isOptional && !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.LEFT);\n return true;\n });\n }\n pushRightBeforeFilled() {\n return this._pushRight(() => {\n if (this.block.isFixed || !this.block.value) return;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.FORCE_RIGHT);\n if (this.offset !== this.block.value.length) return true;\n });\n }\n pushRightBeforeInput() {\n return this._pushRight(() => {\n if (this.block.isFixed) return;\n\n // const o = this.offset;\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.NONE);\n // HACK cases like (STILL DOES NOT WORK FOR NESTED)\n // aa|X\n // aaX_ - this will not work\n // if (o && o === this.offset && this.block instanceof PatternInputDefinition) continue;\n return true;\n });\n }\n pushRightBeforeRequired() {\n return this._pushRight(() => {\n if (this.block.isFixed || this.block.isOptional && !this.block.value) return;\n\n // TODO check |[*]XX_\n this.offset = this.block.nearestInputPos(this.offset, DIRECTION.NONE);\n return true;\n });\n }\n}\n\nexport { PatternCursor as default };\n","import Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/change-details.js';\nimport '../core/continuous-tail-details.js';\nimport '../core/utils.js';\n\n/** Masking by RegExp */\nclass MaskedRegExp extends Masked {\n /**\n @override\n @param {Object} opts\n */\n _update(opts) {\n if (opts.mask) opts.validate = value => value.search(opts.mask) >= 0;\n super._update(opts);\n }\n}\nIMask.MaskedRegExp = MaskedRegExp;\n\nexport { MaskedRegExp as default };\n","import { _ as _objectWithoutPropertiesLoose } from '../_rollupPluginBabelHelpers-6b3bd404.js';\nimport { DIRECTION } from '../core/utils.js';\nimport ChangeDetails from '../core/change-details.js';\nimport Masked from './base.js';\nimport PatternInputDefinition, { DEFAULT_INPUT_DEFINITIONS } from './pattern/input-definition.js';\nimport PatternFixedDefinition from './pattern/fixed-definition.js';\nimport ChunksTailDetails from './pattern/chunk-tail-details.js';\nimport PatternCursor from './pattern/cursor.js';\nimport createMask from './factory.js';\nimport IMask from '../core/holder.js';\nimport './regexp.js';\nimport '../core/continuous-tail-details.js';\n\nconst _excluded = [\"_blocks\"];\n\n/**\n Pattern mask\n @param {Object} opts\n @param {Object} opts.blocks\n @param {Object} opts.definitions\n @param {string} opts.placeholderChar\n @param {string} opts.displayChar\n @param {boolean} opts.lazy\n*/\nclass MaskedPattern extends Masked {\n /** */\n\n /** */\n\n /** Single char for empty input */\n\n /** Single char for filled input */\n\n /** Show placeholder only when needed */\n\n constructor() {\n let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n // TODO type $Shape={} does not work\n opts.definitions = Object.assign({}, DEFAULT_INPUT_DEFINITIONS, opts.definitions);\n super(Object.assign({}, MaskedPattern.DEFAULTS, opts));\n }\n\n /**\n @override\n @param {Object} opts\n */\n _update() {\n let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n opts.definitions = Object.assign({}, this.definitions, opts.definitions);\n super._update(opts);\n this._rebuildMask();\n }\n\n /** */\n _rebuildMask() {\n const defs = this.definitions;\n this._blocks = [];\n this._stops = [];\n this._maskedBlocks = {};\n let pattern = this.mask;\n if (!pattern || !defs) return;\n let unmaskingBlock = false;\n let optionalBlock = false;\n for (let i = 0; i < pattern.length; ++i) {\n var _defs$char, _defs$char2;\n if (this.blocks) {\n const p = pattern.slice(i);\n const bNames = Object.keys(this.blocks).filter(bName => p.indexOf(bName) === 0);\n // order by key length\n bNames.sort((a, b) => b.length - a.length);\n // use block name with max length\n const bName = bNames[0];\n if (bName) {\n // $FlowFixMe no ideas\n const maskedBlock = createMask(Object.assign({\n parent: this,\n lazy: this.lazy,\n eager: this.eager,\n placeholderChar: this.placeholderChar,\n displayChar: this.displayChar,\n overwrite: this.overwrite\n }, this.blocks[bName]));\n if (maskedBlock) {\n this._blocks.push(maskedBlock);\n\n // store block index\n if (!this._maskedBlocks[bName]) this._maskedBlocks[bName] = [];\n this._maskedBlocks[bName].push(this._blocks.length - 1);\n }\n i += bName.length - 1;\n continue;\n }\n }\n let char = pattern[i];\n let isInput = (char in defs);\n if (char === MaskedPattern.STOP_CHAR) {\n this._stops.push(this._blocks.length);\n continue;\n }\n if (char === '{' || char === '}') {\n unmaskingBlock = !unmaskingBlock;\n continue;\n }\n if (char === '[' || char === ']') {\n optionalBlock = !optionalBlock;\n continue;\n }\n if (char === MaskedPattern.ESCAPE_CHAR) {\n ++i;\n char = pattern[i];\n if (!char) break;\n isInput = false;\n }\n const maskOpts = (_defs$char = defs[char]) !== null && _defs$char !== void 0 && _defs$char.mask && !(((_defs$char2 = defs[char]) === null || _defs$char2 === void 0 ? void 0 : _defs$char2.mask.prototype) instanceof IMask.Masked) ? defs[char] : {\n mask: defs[char]\n };\n const def = isInput ? new PatternInputDefinition(Object.assign({\n parent: this,\n isOptional: optionalBlock,\n lazy: this.lazy,\n eager: this.eager,\n placeholderChar: this.placeholderChar,\n displayChar: this.displayChar\n }, maskOpts)) : new PatternFixedDefinition({\n char,\n eager: this.eager,\n isUnmasking: unmaskingBlock\n });\n this._blocks.push(def);\n }\n }\n\n /**\n @override\n */\n get state() {\n return Object.assign({}, super.state, {\n _blocks: this._blocks.map(b => b.state)\n });\n }\n set state(state) {\n const {\n _blocks\n } = state,\n maskedState = _objectWithoutPropertiesLoose(state, _excluded);\n this._blocks.forEach((b, bi) => b.state = _blocks[bi]);\n super.state = maskedState;\n }\n\n /**\n @override\n */\n reset() {\n super.reset();\n this._blocks.forEach(b => b.reset());\n }\n\n /**\n @override\n */\n get isComplete() {\n return this._blocks.every(b => b.isComplete);\n }\n\n /**\n @override\n */\n get isFilled() {\n return this._blocks.every(b => b.isFilled);\n }\n get isFixed() {\n return this._blocks.every(b => b.isFixed);\n }\n get isOptional() {\n return this._blocks.every(b => b.isOptional);\n }\n\n /**\n @override\n */\n doCommit() {\n this._blocks.forEach(b => b.doCommit());\n super.doCommit();\n }\n\n /**\n @override\n */\n get unmaskedValue() {\n return this._blocks.reduce((str, b) => str += b.unmaskedValue, '');\n }\n set unmaskedValue(unmaskedValue) {\n super.unmaskedValue = unmaskedValue;\n }\n\n /**\n @override\n */\n get value() {\n // TODO return _value when not in change?\n return this._blocks.reduce((str, b) => str += b.value, '');\n }\n set value(value) {\n super.value = value;\n }\n get displayValue() {\n return this._blocks.reduce((str, b) => str += b.displayValue, '');\n }\n\n /**\n @override\n */\n appendTail(tail) {\n return super.appendTail(tail).aggregate(this._appendPlaceholder());\n }\n\n /**\n @override\n */\n _appendEager() {\n var _this$_mapPosToBlock;\n const details = new ChangeDetails();\n let startBlockIndex = (_this$_mapPosToBlock = this._mapPosToBlock(this.value.length)) === null || _this$_mapPosToBlock === void 0 ? void 0 : _this$_mapPosToBlock.index;\n if (startBlockIndex == null) return details;\n\n // TODO test if it works for nested pattern masks\n if (this._blocks[startBlockIndex].isFilled) ++startBlockIndex;\n for (let bi = startBlockIndex; bi < this._blocks.length; ++bi) {\n const d = this._blocks[bi]._appendEager();\n if (!d.inserted) break;\n details.aggregate(d);\n }\n return details;\n }\n\n /**\n @override\n */\n _appendCharRaw(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n const blockIter = this._mapPosToBlock(this.value.length);\n const details = new ChangeDetails();\n if (!blockIter) return details;\n for (let bi = blockIter.index;; ++bi) {\n var _flags$_beforeTailSta, _flags$_beforeTailSta2;\n const block = this._blocks[bi];\n if (!block) break;\n const blockDetails = block._appendChar(ch, Object.assign({}, flags, {\n _beforeTailState: (_flags$_beforeTailSta = flags._beforeTailState) === null || _flags$_beforeTailSta === void 0 ? void 0 : (_flags$_beforeTailSta2 = _flags$_beforeTailSta._blocks) === null || _flags$_beforeTailSta2 === void 0 ? void 0 : _flags$_beforeTailSta2[bi]\n }));\n const skip = blockDetails.skip;\n details.aggregate(blockDetails);\n if (skip || blockDetails.rawInserted) break; // go next char\n }\n\n return details;\n }\n\n /**\n @override\n */\n extractTail() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n const chunkTail = new ChunksTailDetails();\n if (fromPos === toPos) return chunkTail;\n this._forEachBlocksInRange(fromPos, toPos, (b, bi, bFromPos, bToPos) => {\n const blockChunk = b.extractTail(bFromPos, bToPos);\n blockChunk.stop = this._findStopBefore(bi);\n blockChunk.from = this._blockStartPos(bi);\n if (blockChunk instanceof ChunksTailDetails) blockChunk.blockIndex = bi;\n chunkTail.extend(blockChunk);\n });\n return chunkTail;\n }\n\n /**\n @override\n */\n extractInput() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n let flags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (fromPos === toPos) return '';\n let input = '';\n this._forEachBlocksInRange(fromPos, toPos, (b, _, fromPos, toPos) => {\n input += b.extractInput(fromPos, toPos, flags);\n });\n return input;\n }\n _findStopBefore(blockIndex) {\n let stopBefore;\n for (let si = 0; si < this._stops.length; ++si) {\n const stop = this._stops[si];\n if (stop <= blockIndex) stopBefore = stop;else break;\n }\n return stopBefore;\n }\n\n /** Appends placeholder depending on laziness */\n _appendPlaceholder(toBlockIndex) {\n const details = new ChangeDetails();\n if (this.lazy && toBlockIndex == null) return details;\n const startBlockIter = this._mapPosToBlock(this.value.length);\n if (!startBlockIter) return details;\n const startBlockIndex = startBlockIter.index;\n const endBlockIndex = toBlockIndex != null ? toBlockIndex : this._blocks.length;\n this._blocks.slice(startBlockIndex, endBlockIndex).forEach(b => {\n if (!b.lazy || toBlockIndex != null) {\n // $FlowFixMe `_blocks` may not be present\n const args = b._blocks != null ? [b._blocks.length] : [];\n const bDetails = b._appendPlaceholder(...args);\n this._value += bDetails.inserted;\n details.aggregate(bDetails);\n }\n });\n return details;\n }\n\n /** Finds block in pos */\n _mapPosToBlock(pos) {\n let accVal = '';\n for (let bi = 0; bi < this._blocks.length; ++bi) {\n const block = this._blocks[bi];\n const blockStartPos = accVal.length;\n accVal += block.value;\n if (pos <= accVal.length) {\n return {\n index: bi,\n offset: pos - blockStartPos\n };\n }\n }\n }\n\n /** */\n _blockStartPos(blockIndex) {\n return this._blocks.slice(0, blockIndex).reduce((pos, b) => pos += b.value.length, 0);\n }\n\n /** */\n _forEachBlocksInRange(fromPos) {\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n let fn = arguments.length > 2 ? arguments[2] : undefined;\n const fromBlockIter = this._mapPosToBlock(fromPos);\n if (fromBlockIter) {\n const toBlockIter = this._mapPosToBlock(toPos);\n // process first block\n const isSameBlock = toBlockIter && fromBlockIter.index === toBlockIter.index;\n const fromBlockStartPos = fromBlockIter.offset;\n const fromBlockEndPos = toBlockIter && isSameBlock ? toBlockIter.offset : this._blocks[fromBlockIter.index].value.length;\n fn(this._blocks[fromBlockIter.index], fromBlockIter.index, fromBlockStartPos, fromBlockEndPos);\n if (toBlockIter && !isSameBlock) {\n // process intermediate blocks\n for (let bi = fromBlockIter.index + 1; bi < toBlockIter.index; ++bi) {\n fn(this._blocks[bi], bi, 0, this._blocks[bi].value.length);\n }\n\n // process last block\n fn(this._blocks[toBlockIter.index], toBlockIter.index, 0, toBlockIter.offset);\n }\n }\n }\n\n /**\n @override\n */\n remove() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n const removeDetails = super.remove(fromPos, toPos);\n this._forEachBlocksInRange(fromPos, toPos, (b, _, bFromPos, bToPos) => {\n removeDetails.aggregate(b.remove(bFromPos, bToPos));\n });\n return removeDetails;\n }\n\n /**\n @override\n */\n nearestInputPos(cursorPos) {\n let direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DIRECTION.NONE;\n if (!this._blocks.length) return 0;\n const cursor = new PatternCursor(this, cursorPos);\n if (direction === DIRECTION.NONE) {\n // -------------------------------------------------\n // NONE should only go out from fixed to the right!\n // -------------------------------------------------\n if (cursor.pushRightBeforeInput()) return cursor.pos;\n cursor.popState();\n if (cursor.pushLeftBeforeInput()) return cursor.pos;\n return this.value.length;\n }\n\n // FORCE is only about a|* otherwise is 0\n if (direction === DIRECTION.LEFT || direction === DIRECTION.FORCE_LEFT) {\n // try to break fast when *|a\n if (direction === DIRECTION.LEFT) {\n cursor.pushRightBeforeFilled();\n if (cursor.ok && cursor.pos === cursorPos) return cursorPos;\n cursor.popState();\n }\n\n // forward flow\n cursor.pushLeftBeforeInput();\n cursor.pushLeftBeforeRequired();\n cursor.pushLeftBeforeFilled();\n\n // backward flow\n if (direction === DIRECTION.LEFT) {\n cursor.pushRightBeforeInput();\n cursor.pushRightBeforeRequired();\n if (cursor.ok && cursor.pos <= cursorPos) return cursor.pos;\n cursor.popState();\n if (cursor.ok && cursor.pos <= cursorPos) return cursor.pos;\n cursor.popState();\n }\n if (cursor.ok) return cursor.pos;\n if (direction === DIRECTION.FORCE_LEFT) return 0;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n\n // cursor.popState();\n // if (\n // cursor.pushRightBeforeInput() &&\n // // TODO HACK for lazy if has aligned left inside fixed and has came to the start - use start position\n // (!this.lazy || this.extractInput())\n // ) return cursor.pos;\n\n return 0;\n }\n if (direction === DIRECTION.RIGHT || direction === DIRECTION.FORCE_RIGHT) {\n // forward flow\n cursor.pushRightBeforeInput();\n cursor.pushRightBeforeRequired();\n if (cursor.pushRightBeforeFilled()) return cursor.pos;\n if (direction === DIRECTION.FORCE_RIGHT) return this.value.length;\n\n // backward flow\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n cursor.popState();\n if (cursor.ok) return cursor.pos;\n return this.nearestInputPos(cursorPos, DIRECTION.LEFT);\n }\n return cursorPos;\n }\n\n /**\n @override\n */\n totalInputPositions() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n let total = 0;\n this._forEachBlocksInRange(fromPos, toPos, (b, _, bFromPos, bToPos) => {\n total += b.totalInputPositions(bFromPos, bToPos);\n });\n return total;\n }\n\n /** Get block by name */\n maskedBlock(name) {\n return this.maskedBlocks(name)[0];\n }\n\n /** Get all blocks by name */\n maskedBlocks(name) {\n const indices = this._maskedBlocks[name];\n if (!indices) return [];\n return indices.map(gi => this._blocks[gi]);\n }\n}\nMaskedPattern.DEFAULTS = {\n lazy: true,\n placeholderChar: '_'\n};\nMaskedPattern.STOP_CHAR = '`';\nMaskedPattern.ESCAPE_CHAR = '\\\\';\nMaskedPattern.InputDefinition = PatternInputDefinition;\nMaskedPattern.FixedDefinition = PatternFixedDefinition;\nIMask.MaskedPattern = MaskedPattern;\n\nexport { MaskedPattern as default };\n","import MaskedPattern from './pattern.js';\nimport '../core/change-details.js';\nimport { normalizePrepare } from '../core/utils.js';\nimport IMask from '../core/holder.js';\nimport '../_rollupPluginBabelHelpers-6b3bd404.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './pattern/input-definition.js';\nimport './factory.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './regexp.js';\n\n/** Pattern which accepts ranges */\nclass MaskedRange extends MaskedPattern {\n /**\n Optionally sets max length of pattern.\n Used when pattern length is longer then `to` param length. Pads zeros at start in this case.\n */\n\n /** Min bound */\n\n /** Max bound */\n\n /** */\n\n get _matchFrom() {\n return this.maxLength - String(this.from).length;\n }\n\n /**\n @override\n */\n _update(opts) {\n // TODO type\n opts = Object.assign({\n to: this.to || 0,\n from: this.from || 0,\n maxLength: this.maxLength || 0\n }, opts);\n let maxLength = String(opts.to).length;\n if (opts.maxLength != null) maxLength = Math.max(maxLength, opts.maxLength);\n opts.maxLength = maxLength;\n const fromStr = String(opts.from).padStart(maxLength, '0');\n const toStr = String(opts.to).padStart(maxLength, '0');\n let sameCharsCount = 0;\n while (sameCharsCount < toStr.length && toStr[sameCharsCount] === fromStr[sameCharsCount]) ++sameCharsCount;\n opts.mask = toStr.slice(0, sameCharsCount).replace(/0/g, '\\\\0') + '0'.repeat(maxLength - sameCharsCount);\n super._update(opts);\n }\n\n /**\n @override\n */\n get isComplete() {\n return super.isComplete && Boolean(this.value);\n }\n boundaries(str) {\n let minstr = '';\n let maxstr = '';\n const [, placeholder, num] = str.match(/^(\\D*)(\\d*)(\\D*)/) || [];\n if (num) {\n minstr = '0'.repeat(placeholder.length) + num;\n maxstr = '9'.repeat(placeholder.length) + num;\n }\n minstr = minstr.padEnd(this.maxLength, '0');\n maxstr = maxstr.padEnd(this.maxLength, '9');\n return [minstr, maxstr];\n }\n\n // TODO str is a single char everytime\n /**\n @override\n */\n doPrepare(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let details;\n [ch, details] = normalizePrepare(super.doPrepare(ch.replace(/\\D/g, ''), flags));\n if (!this.autofix || !ch) return ch;\n const fromStr = String(this.from).padStart(this.maxLength, '0');\n const toStr = String(this.to).padStart(this.maxLength, '0');\n let nextVal = this.value + ch;\n if (nextVal.length > this.maxLength) return '';\n const [minstr, maxstr] = this.boundaries(nextVal);\n if (Number(maxstr) < this.from) return fromStr[nextVal.length - 1];\n if (Number(minstr) > this.to) {\n if (this.autofix === 'pad' && nextVal.length < this.maxLength) {\n return ['', details.aggregate(this.append(fromStr[nextVal.length - 1] + ch, flags))];\n }\n return toStr[nextVal.length - 1];\n }\n return ch;\n }\n\n /**\n @override\n */\n doValidate() {\n const str = this.value;\n const firstNonZero = str.search(/[^0]/);\n if (firstNonZero === -1 && str.length <= this._matchFrom) return true;\n const [minstr, maxstr] = this.boundaries(str);\n return this.from <= Number(maxstr) && Number(minstr) <= this.to && super.doValidate(...arguments);\n }\n}\nIMask.MaskedRange = MaskedRange;\n\nexport { MaskedRange as default };\n","import MaskedPattern from './pattern.js';\nimport MaskedRange from './range.js';\nimport IMask from '../core/holder.js';\nimport '../_rollupPluginBabelHelpers-6b3bd404.js';\nimport '../core/utils.js';\nimport '../core/change-details.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './pattern/input-definition.js';\nimport './factory.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './regexp.js';\n\n/** Date mask */\nclass MaskedDate extends MaskedPattern {\n /** Pattern mask for date according to {@link MaskedDate#format} */\n\n /** Start date */\n\n /** End date */\n\n /** */\n\n /**\n @param {Object} opts\n */\n constructor(opts) {\n super(Object.assign({}, MaskedDate.DEFAULTS, opts));\n }\n\n /**\n @override\n */\n _update(opts) {\n if (opts.mask === Date) delete opts.mask;\n if (opts.pattern) opts.mask = opts.pattern;\n const blocks = opts.blocks;\n opts.blocks = Object.assign({}, MaskedDate.GET_DEFAULT_BLOCKS());\n // adjust year block\n if (opts.min) opts.blocks.Y.from = opts.min.getFullYear();\n if (opts.max) opts.blocks.Y.to = opts.max.getFullYear();\n if (opts.min && opts.max && opts.blocks.Y.from === opts.blocks.Y.to) {\n opts.blocks.m.from = opts.min.getMonth() + 1;\n opts.blocks.m.to = opts.max.getMonth() + 1;\n if (opts.blocks.m.from === opts.blocks.m.to) {\n opts.blocks.d.from = opts.min.getDate();\n opts.blocks.d.to = opts.max.getDate();\n }\n }\n Object.assign(opts.blocks, this.blocks, blocks);\n\n // add autofix\n Object.keys(opts.blocks).forEach(bk => {\n const b = opts.blocks[bk];\n if (!('autofix' in b) && 'autofix' in opts) b.autofix = opts.autofix;\n });\n super._update(opts);\n }\n\n /**\n @override\n */\n doValidate() {\n const date = this.date;\n return super.doValidate(...arguments) && (!this.isComplete || this.isDateExist(this.value) && date != null && (this.min == null || this.min <= date) && (this.max == null || date <= this.max));\n }\n\n /** Checks if date is exists */\n isDateExist(str) {\n return this.format(this.parse(str, this), this).indexOf(str) >= 0;\n }\n\n /** Parsed Date */\n get date() {\n return this.typedValue;\n }\n set date(date) {\n this.typedValue = date;\n }\n\n /**\n @override\n */\n get typedValue() {\n return this.isComplete ? super.typedValue : null;\n }\n set typedValue(value) {\n super.typedValue = value;\n }\n\n /**\n @override\n */\n maskEquals(mask) {\n return mask === Date || super.maskEquals(mask);\n }\n}\nMaskedDate.DEFAULTS = {\n pattern: 'd{.}`m{.}`Y',\n format: date => {\n if (!date) return '';\n const day = String(date.getDate()).padStart(2, '0');\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const year = date.getFullYear();\n return [day, month, year].join('.');\n },\n parse: str => {\n const [day, month, year] = str.split('.');\n return new Date(year, month - 1, day);\n }\n};\nMaskedDate.GET_DEFAULT_BLOCKS = () => ({\n d: {\n mask: MaskedRange,\n from: 1,\n to: 31,\n maxLength: 2\n },\n m: {\n mask: MaskedRange,\n from: 1,\n to: 12,\n maxLength: 2\n },\n Y: {\n mask: MaskedRange,\n from: 1900,\n to: 9999\n }\n});\nIMask.MaskedDate = MaskedDate;\n\nexport { MaskedDate as default };\n","import IMask from '../core/holder.js';\n\n/**\n Generic element API to use with mask\n @interface\n*/\nclass MaskElement {\n /** */\n\n /** */\n\n /** */\n\n /** Safely returns selection start */\n get selectionStart() {\n let start;\n try {\n start = this._unsafeSelectionStart;\n } catch (e) {}\n return start != null ? start : this.value.length;\n }\n\n /** Safely returns selection end */\n get selectionEnd() {\n let end;\n try {\n end = this._unsafeSelectionEnd;\n } catch (e) {}\n return end != null ? end : this.value.length;\n }\n\n /** Safely sets element selection */\n select(start, end) {\n if (start == null || end == null || start === this.selectionStart && end === this.selectionEnd) return;\n try {\n this._unsafeSelect(start, end);\n } catch (e) {}\n }\n\n /** Should be overriden in subclasses */\n _unsafeSelect(start, end) {}\n /** Should be overriden in subclasses */\n get isActive() {\n return false;\n }\n /** Should be overriden in subclasses */\n bindEvents(handlers) {}\n /** Should be overriden in subclasses */\n unbindEvents() {}\n}\nIMask.MaskElement = MaskElement;\n\nexport { MaskElement as default };\n","import MaskElement from './mask-element.js';\nimport IMask from '../core/holder.js';\n\n/** Bridge between HTMLElement and {@link Masked} */\nclass HTMLMaskElement extends MaskElement {\n /** Mapping between HTMLElement events and mask internal events */\n\n /** HTMLElement to use mask on */\n\n /**\n @param {HTMLInputElement|HTMLTextAreaElement} input\n */\n constructor(input) {\n super();\n this.input = input;\n this._handlers = {};\n }\n\n /** */\n // $FlowFixMe https://github.com/facebook/flow/issues/2839\n get rootElement() {\n var _this$input$getRootNo, _this$input$getRootNo2, _this$input;\n return (_this$input$getRootNo = (_this$input$getRootNo2 = (_this$input = this.input).getRootNode) === null || _this$input$getRootNo2 === void 0 ? void 0 : _this$input$getRootNo2.call(_this$input)) !== null && _this$input$getRootNo !== void 0 ? _this$input$getRootNo : document;\n }\n\n /**\n Is element in focus\n @readonly\n */\n get isActive() {\n //$FlowFixMe\n return this.input === this.rootElement.activeElement;\n }\n\n /**\n Returns HTMLElement selection start\n @override\n */\n get _unsafeSelectionStart() {\n return this.input.selectionStart;\n }\n\n /**\n Returns HTMLElement selection end\n @override\n */\n get _unsafeSelectionEnd() {\n return this.input.selectionEnd;\n }\n\n /**\n Sets HTMLElement selection\n @override\n */\n _unsafeSelect(start, end) {\n this.input.setSelectionRange(start, end);\n }\n\n /**\n HTMLElement value\n @override\n */\n get value() {\n return this.input.value;\n }\n set value(value) {\n this.input.value = value;\n }\n\n /**\n Binds HTMLElement events to mask internal events\n @override\n */\n bindEvents(handlers) {\n Object.keys(handlers).forEach(event => this._toggleEventHandler(HTMLMaskElement.EVENTS_MAP[event], handlers[event]));\n }\n\n /**\n Unbinds HTMLElement events to mask internal events\n @override\n */\n unbindEvents() {\n Object.keys(this._handlers).forEach(event => this._toggleEventHandler(event));\n }\n\n /** */\n _toggleEventHandler(event, handler) {\n if (this._handlers[event]) {\n this.input.removeEventListener(event, this._handlers[event]);\n delete this._handlers[event];\n }\n if (handler) {\n this.input.addEventListener(event, handler);\n this._handlers[event] = handler;\n }\n }\n}\nHTMLMaskElement.EVENTS_MAP = {\n selectionChange: 'keydown',\n input: 'input',\n drop: 'drop',\n click: 'click',\n focus: 'focus',\n commit: 'blur'\n};\nIMask.HTMLMaskElement = HTMLMaskElement;\n\nexport { HTMLMaskElement as default };\n","import HTMLMaskElement from './html-mask-element.js';\nimport IMask from '../core/holder.js';\nimport './mask-element.js';\n\nclass HTMLContenteditableMaskElement extends HTMLMaskElement {\n /**\n Returns HTMLElement selection start\n @override\n */\n get _unsafeSelectionStart() {\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n const anchorOffset = selection && selection.anchorOffset;\n const focusOffset = selection && selection.focusOffset;\n if (focusOffset == null || anchorOffset == null || anchorOffset < focusOffset) {\n return anchorOffset;\n }\n return focusOffset;\n }\n\n /**\n Returns HTMLElement selection end\n @override\n */\n get _unsafeSelectionEnd() {\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n const anchorOffset = selection && selection.anchorOffset;\n const focusOffset = selection && selection.focusOffset;\n if (focusOffset == null || anchorOffset == null || anchorOffset > focusOffset) {\n return anchorOffset;\n }\n return focusOffset;\n }\n\n /**\n Sets HTMLElement selection\n @override\n */\n _unsafeSelect(start, end) {\n if (!this.rootElement.createRange) return;\n const range = this.rootElement.createRange();\n range.setStart(this.input.firstChild || this.input, start);\n range.setEnd(this.input.lastChild || this.input, end);\n const root = this.rootElement;\n const selection = root.getSelection && root.getSelection();\n if (selection) {\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }\n\n /**\n HTMLElement value\n @override\n */\n get value() {\n // $FlowFixMe\n return this.input.textContent;\n }\n set value(value) {\n this.input.textContent = value;\n }\n}\nIMask.HTMLContenteditableMaskElement = HTMLContenteditableMaskElement;\n\nexport { HTMLContenteditableMaskElement as default };\n","import { _ as _objectWithoutPropertiesLoose } from '../_rollupPluginBabelHelpers-6b3bd404.js';\nimport { objectIncludes, DIRECTION } from '../core/utils.js';\nimport ActionDetails from '../core/action-details.js';\nimport '../masked/date.js';\nimport createMask, { maskedClass } from '../masked/factory.js';\nimport MaskElement from './mask-element.js';\nimport HTMLMaskElement from './html-mask-element.js';\nimport HTMLContenteditableMaskElement from './html-contenteditable-mask-element.js';\nimport IMask from '../core/holder.js';\nimport '../core/change-details.js';\nimport '../masked/pattern.js';\nimport '../masked/base.js';\nimport '../core/continuous-tail-details.js';\nimport '../masked/pattern/input-definition.js';\nimport '../masked/pattern/fixed-definition.js';\nimport '../masked/pattern/chunk-tail-details.js';\nimport '../masked/pattern/cursor.js';\nimport '../masked/regexp.js';\nimport '../masked/range.js';\n\nconst _excluded = [\"mask\"];\n\n/** Listens to element events and controls changes between element and {@link Masked} */\nclass InputMask {\n /**\n View element\n @readonly\n */\n\n /**\n Internal {@link Masked} model\n @readonly\n */\n\n /**\n @param {MaskElement|HTMLInputElement|HTMLTextAreaElement} el\n @param {Object} opts\n */\n constructor(el, opts) {\n this.el = el instanceof MaskElement ? el : el.isContentEditable && el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' ? new HTMLContenteditableMaskElement(el) : new HTMLMaskElement(el);\n this.masked = createMask(opts);\n this._listeners = {};\n this._value = '';\n this._unmaskedValue = '';\n this._saveSelection = this._saveSelection.bind(this);\n this._onInput = this._onInput.bind(this);\n this._onChange = this._onChange.bind(this);\n this._onDrop = this._onDrop.bind(this);\n this._onFocus = this._onFocus.bind(this);\n this._onClick = this._onClick.bind(this);\n this.alignCursor = this.alignCursor.bind(this);\n this.alignCursorFriendly = this.alignCursorFriendly.bind(this);\n this._bindEvents();\n\n // refresh\n this.updateValue();\n this._onChange();\n }\n\n /** Read or update mask */\n get mask() {\n return this.masked.mask;\n }\n maskEquals(mask) {\n var _this$masked;\n return mask == null || ((_this$masked = this.masked) === null || _this$masked === void 0 ? void 0 : _this$masked.maskEquals(mask));\n }\n set mask(mask) {\n if (this.maskEquals(mask)) return;\n\n // $FlowFixMe No ideas ... after update\n if (!(mask instanceof IMask.Masked) && this.masked.constructor === maskedClass(mask)) {\n this.masked.updateOptions({\n mask\n });\n return;\n }\n const masked = createMask({\n mask\n });\n masked.unmaskedValue = this.masked.unmaskedValue;\n this.masked = masked;\n }\n\n /** Raw value */\n get value() {\n return this._value;\n }\n set value(str) {\n if (this.value === str) return;\n this.masked.value = str;\n this.updateControl();\n this.alignCursor();\n }\n\n /** Unmasked value */\n get unmaskedValue() {\n return this._unmaskedValue;\n }\n set unmaskedValue(str) {\n if (this.unmaskedValue === str) return;\n this.masked.unmaskedValue = str;\n this.updateControl();\n this.alignCursor();\n }\n\n /** Typed unmasked value */\n get typedValue() {\n return this.masked.typedValue;\n }\n set typedValue(val) {\n if (this.masked.typedValueEquals(val)) return;\n this.masked.typedValue = val;\n this.updateControl();\n this.alignCursor();\n }\n\n /** Display value */\n get displayValue() {\n return this.masked.displayValue;\n }\n\n /**\n Starts listening to element events\n @protected\n */\n _bindEvents() {\n this.el.bindEvents({\n selectionChange: this._saveSelection,\n input: this._onInput,\n drop: this._onDrop,\n click: this._onClick,\n focus: this._onFocus,\n commit: this._onChange\n });\n }\n\n /**\n Stops listening to element events\n @protected\n */\n _unbindEvents() {\n if (this.el) this.el.unbindEvents();\n }\n\n /**\n Fires custom event\n @protected\n */\n _fireEvent(ev) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n const listeners = this._listeners[ev];\n if (!listeners) return;\n listeners.forEach(l => l(...args));\n }\n\n /**\n Current selection start\n @readonly\n */\n get selectionStart() {\n return this._cursorChanging ? this._changingCursorPos : this.el.selectionStart;\n }\n\n /** Current cursor position */\n get cursorPos() {\n return this._cursorChanging ? this._changingCursorPos : this.el.selectionEnd;\n }\n set cursorPos(pos) {\n if (!this.el || !this.el.isActive) return;\n this.el.select(pos, pos);\n this._saveSelection();\n }\n\n /**\n Stores current selection\n @protected\n */\n _saveSelection( /* ev */\n ) {\n if (this.displayValue !== this.el.value) {\n console.warn('Element value was changed outside of mask. Syncronize mask using `mask.updateValue()` to work properly.'); // eslint-disable-line no-console\n }\n\n this._selection = {\n start: this.selectionStart,\n end: this.cursorPos\n };\n }\n\n /** Syncronizes model value from view */\n updateValue() {\n this.masked.value = this.el.value;\n this._value = this.masked.value;\n }\n\n /** Syncronizes view from model value, fires change events */\n updateControl() {\n const newUnmaskedValue = this.masked.unmaskedValue;\n const newValue = this.masked.value;\n const newDisplayValue = this.displayValue;\n const isChanged = this.unmaskedValue !== newUnmaskedValue || this.value !== newValue;\n this._unmaskedValue = newUnmaskedValue;\n this._value = newValue;\n if (this.el.value !== newDisplayValue) this.el.value = newDisplayValue;\n if (isChanged) this._fireChangeEvents();\n }\n\n /** Updates options with deep equal check, recreates @{link Masked} model if mask type changes */\n updateOptions(opts) {\n const {\n mask\n } = opts,\n restOpts = _objectWithoutPropertiesLoose(opts, _excluded);\n const updateMask = !this.maskEquals(mask);\n const updateOpts = !objectIncludes(this.masked, restOpts);\n if (updateMask) this.mask = mask;\n if (updateOpts) this.masked.updateOptions(restOpts);\n if (updateMask || updateOpts) this.updateControl();\n }\n\n /** Updates cursor */\n updateCursor(cursorPos) {\n if (cursorPos == null) return;\n this.cursorPos = cursorPos;\n\n // also queue change cursor for mobile browsers\n this._delayUpdateCursor(cursorPos);\n }\n\n /**\n Delays cursor update to support mobile browsers\n @private\n */\n _delayUpdateCursor(cursorPos) {\n this._abortUpdateCursor();\n this._changingCursorPos = cursorPos;\n this._cursorChanging = setTimeout(() => {\n if (!this.el) return; // if was destroyed\n this.cursorPos = this._changingCursorPos;\n this._abortUpdateCursor();\n }, 10);\n }\n\n /**\n Fires custom events\n @protected\n */\n _fireChangeEvents() {\n this._fireEvent('accept', this._inputEvent);\n if (this.masked.isComplete) this._fireEvent('complete', this._inputEvent);\n }\n\n /**\n Aborts delayed cursor update\n @private\n */\n _abortUpdateCursor() {\n if (this._cursorChanging) {\n clearTimeout(this._cursorChanging);\n delete this._cursorChanging;\n }\n }\n\n /** Aligns cursor to nearest available position */\n alignCursor() {\n this.cursorPos = this.masked.nearestInputPos(this.masked.nearestInputPos(this.cursorPos, DIRECTION.LEFT));\n }\n\n /** Aligns cursor only if selection is empty */\n alignCursorFriendly() {\n if (this.selectionStart !== this.cursorPos) return; // skip if range is selected\n this.alignCursor();\n }\n\n /** Adds listener on custom event */\n on(ev, handler) {\n if (!this._listeners[ev]) this._listeners[ev] = [];\n this._listeners[ev].push(handler);\n return this;\n }\n\n /** Removes custom event listener */\n off(ev, handler) {\n if (!this._listeners[ev]) return this;\n if (!handler) {\n delete this._listeners[ev];\n return this;\n }\n const hIndex = this._listeners[ev].indexOf(handler);\n if (hIndex >= 0) this._listeners[ev].splice(hIndex, 1);\n return this;\n }\n\n /** Handles view input event */\n _onInput(e) {\n this._inputEvent = e;\n this._abortUpdateCursor();\n\n // fix strange IE behavior\n if (!this._selection) return this.updateValue();\n const details = new ActionDetails(\n // new state\n this.el.value, this.cursorPos,\n // old state\n this.displayValue, this._selection);\n const oldRawValue = this.masked.rawInputValue;\n const offset = this.masked.splice(details.startChangePos, details.removed.length, details.inserted, details.removeDirection, {\n input: true,\n raw: true\n }).offset;\n\n // force align in remove direction only if no input chars were removed\n // otherwise we still need to align with NONE (to get out from fixed symbols for instance)\n const removeDirection = oldRawValue === this.masked.rawInputValue ? details.removeDirection : DIRECTION.NONE;\n let cursorPos = this.masked.nearestInputPos(details.startChangePos + offset, removeDirection);\n if (removeDirection !== DIRECTION.NONE) cursorPos = this.masked.nearestInputPos(cursorPos, DIRECTION.NONE);\n this.updateControl();\n this.updateCursor(cursorPos);\n delete this._inputEvent;\n }\n\n /** Handles view change event and commits model value */\n _onChange() {\n if (this.displayValue !== this.el.value) {\n this.updateValue();\n }\n this.masked.doCommit();\n this.updateControl();\n this._saveSelection();\n }\n\n /** Handles view drop event, prevents by default */\n _onDrop(ev) {\n ev.preventDefault();\n ev.stopPropagation();\n }\n\n /** Restore last selection on focus */\n _onFocus(ev) {\n this.alignCursorFriendly();\n }\n\n /** Restore last selection on focus */\n _onClick(ev) {\n this.alignCursorFriendly();\n }\n\n /** Unbind view events and removes element reference */\n destroy() {\n this._unbindEvents();\n // $FlowFixMe why not do so?\n this._listeners.length = 0;\n // $FlowFixMe\n delete this.el;\n }\n}\nIMask.InputMask = InputMask;\n\nexport { InputMask as default };\n","import MaskedPattern from './pattern.js';\nimport IMask from '../core/holder.js';\nimport '../_rollupPluginBabelHelpers-6b3bd404.js';\nimport '../core/utils.js';\nimport '../core/change-details.js';\nimport './base.js';\nimport '../core/continuous-tail-details.js';\nimport './pattern/input-definition.js';\nimport './factory.js';\nimport './pattern/fixed-definition.js';\nimport './pattern/chunk-tail-details.js';\nimport './pattern/cursor.js';\nimport './regexp.js';\n\n/** Pattern which validates enum values */\nclass MaskedEnum extends MaskedPattern {\n /**\n @override\n @param {Object} opts\n */\n _update(opts) {\n // TODO type\n if (opts.enum) opts.mask = '*'.repeat(opts.enum[0].length);\n super._update(opts);\n }\n\n /**\n @override\n */\n doValidate() {\n return this.enum.some(e => e.indexOf(this.unmaskedValue) >= 0) && super.doValidate(...arguments);\n }\n}\nIMask.MaskedEnum = MaskedEnum;\n\nexport { MaskedEnum as default };\n","import { escapeRegExp, normalizePrepare, DIRECTION } from '../core/utils.js';\nimport ChangeDetails from '../core/change-details.js';\nimport Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/continuous-tail-details.js';\n\n/**\n Number mask\n @param {Object} opts\n @param {string} opts.radix - Single char\n @param {string} opts.thousandsSeparator - Single char\n @param {Array} opts.mapToRadix - Array of single chars\n @param {number} opts.min\n @param {number} opts.max\n @param {number} opts.scale - Digits after point\n @param {boolean} opts.signed - Allow negative\n @param {boolean} opts.normalizeZeros - Flag to remove leading and trailing zeros in the end of editing\n @param {boolean} opts.padFractionalZeros - Flag to pad trailing zeros after point in the end of editing\n*/\nclass MaskedNumber extends Masked {\n /** Single char */\n\n /** Single char */\n\n /** Array of single chars */\n\n /** */\n\n /** */\n\n /** Digits after point */\n\n /** */\n\n /** Flag to remove leading and trailing zeros in the end of editing */\n\n /** Flag to pad trailing zeros after point in the end of editing */\n\n constructor(opts) {\n super(Object.assign({}, MaskedNumber.DEFAULTS, opts));\n }\n\n /**\n @override\n */\n _update(opts) {\n super._update(opts);\n this._updateRegExps();\n }\n\n /** */\n _updateRegExps() {\n let start = '^' + (this.allowNegative ? '[+|\\\\-]?' : '');\n let mid = '\\\\d*';\n let end = (this.scale ? \"(\".concat(escapeRegExp(this.radix), \"\\\\d{0,\").concat(this.scale, \"})?\") : '') + '$';\n this._numberRegExp = new RegExp(start + mid + end);\n this._mapToRadixRegExp = new RegExp(\"[\".concat(this.mapToRadix.map(escapeRegExp).join(''), \"]\"), 'g');\n this._thousandsSeparatorRegExp = new RegExp(escapeRegExp(this.thousandsSeparator), 'g');\n }\n\n /** */\n _removeThousandsSeparators(value) {\n return value.replace(this._thousandsSeparatorRegExp, '');\n }\n\n /** */\n _insertThousandsSeparators(value) {\n // https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript\n const parts = value.split(this.radix);\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, this.thousandsSeparator);\n return parts.join(this.radix);\n }\n\n /**\n @override\n */\n doPrepare(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n ch = this._removeThousandsSeparators(this.scale && this.mapToRadix.length && (\n /*\n radix should be mapped when\n 1) input is done from keyboard = flags.input && flags.raw\n 2) unmasked value is set = !flags.input && !flags.raw\n and should not be mapped when\n 1) value is set = flags.input && !flags.raw\n 2) raw value is set = !flags.input && flags.raw\n */\n flags.input && flags.raw || !flags.input && !flags.raw) ? ch.replace(this._mapToRadixRegExp, this.radix) : ch);\n const [prepCh, details] = normalizePrepare(super.doPrepare(ch, flags));\n if (ch && !prepCh) details.skip = true;\n return [prepCh, details];\n }\n\n /** */\n _separatorsCount(to) {\n let extendOnSeparators = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n let count = 0;\n for (let pos = 0; pos < to; ++pos) {\n if (this._value.indexOf(this.thousandsSeparator, pos) === pos) {\n ++count;\n if (extendOnSeparators) to += this.thousandsSeparator.length;\n }\n }\n return count;\n }\n\n /** */\n _separatorsCountFromSlice() {\n let slice = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._value;\n return this._separatorsCount(this._removeThousandsSeparators(slice).length, true);\n }\n\n /**\n @override\n */\n extractInput() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n let flags = arguments.length > 2 ? arguments[2] : undefined;\n [fromPos, toPos] = this._adjustRangeWithSeparators(fromPos, toPos);\n return this._removeThousandsSeparators(super.extractInput(fromPos, toPos, flags));\n }\n\n /**\n @override\n */\n _appendCharRaw(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (!this.thousandsSeparator) return super._appendCharRaw(ch, flags);\n const prevBeforeTailValue = flags.tail && flags._beforeTailState ? flags._beforeTailState._value : this._value;\n const prevBeforeTailSeparatorsCount = this._separatorsCountFromSlice(prevBeforeTailValue);\n this._value = this._removeThousandsSeparators(this.value);\n const appendDetails = super._appendCharRaw(ch, flags);\n this._value = this._insertThousandsSeparators(this._value);\n const beforeTailValue = flags.tail && flags._beforeTailState ? flags._beforeTailState._value : this._value;\n const beforeTailSeparatorsCount = this._separatorsCountFromSlice(beforeTailValue);\n appendDetails.tailShift += (beforeTailSeparatorsCount - prevBeforeTailSeparatorsCount) * this.thousandsSeparator.length;\n appendDetails.skip = !appendDetails.rawInserted && ch === this.thousandsSeparator;\n return appendDetails;\n }\n\n /** */\n _findSeparatorAround(pos) {\n if (this.thousandsSeparator) {\n const searchFrom = pos - this.thousandsSeparator.length + 1;\n const separatorPos = this.value.indexOf(this.thousandsSeparator, searchFrom);\n if (separatorPos <= pos) return separatorPos;\n }\n return -1;\n }\n _adjustRangeWithSeparators(from, to) {\n const separatorAroundFromPos = this._findSeparatorAround(from);\n if (separatorAroundFromPos >= 0) from = separatorAroundFromPos;\n const separatorAroundToPos = this._findSeparatorAround(to);\n if (separatorAroundToPos >= 0) to = separatorAroundToPos + this.thousandsSeparator.length;\n return [from, to];\n }\n\n /**\n @override\n */\n remove() {\n let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length;\n [fromPos, toPos] = this._adjustRangeWithSeparators(fromPos, toPos);\n const valueBeforePos = this.value.slice(0, fromPos);\n const valueAfterPos = this.value.slice(toPos);\n const prevBeforeTailSeparatorsCount = this._separatorsCount(valueBeforePos.length);\n this._value = this._insertThousandsSeparators(this._removeThousandsSeparators(valueBeforePos + valueAfterPos));\n const beforeTailSeparatorsCount = this._separatorsCountFromSlice(valueBeforePos);\n return new ChangeDetails({\n tailShift: (beforeTailSeparatorsCount - prevBeforeTailSeparatorsCount) * this.thousandsSeparator.length\n });\n }\n\n /**\n @override\n */\n nearestInputPos(cursorPos, direction) {\n if (!this.thousandsSeparator) return cursorPos;\n switch (direction) {\n case DIRECTION.NONE:\n case DIRECTION.LEFT:\n case DIRECTION.FORCE_LEFT:\n {\n const separatorAtLeftPos = this._findSeparatorAround(cursorPos - 1);\n if (separatorAtLeftPos >= 0) {\n const separatorAtLeftEndPos = separatorAtLeftPos + this.thousandsSeparator.length;\n if (cursorPos < separatorAtLeftEndPos || this.value.length <= separatorAtLeftEndPos || direction === DIRECTION.FORCE_LEFT) {\n return separatorAtLeftPos;\n }\n }\n break;\n }\n case DIRECTION.RIGHT:\n case DIRECTION.FORCE_RIGHT:\n {\n const separatorAtRightPos = this._findSeparatorAround(cursorPos);\n if (separatorAtRightPos >= 0) {\n return separatorAtRightPos + this.thousandsSeparator.length;\n }\n }\n }\n return cursorPos;\n }\n\n /**\n @override\n */\n doValidate(flags) {\n // validate as string\n let valid = Boolean(this._removeThousandsSeparators(this.value).match(this._numberRegExp));\n if (valid) {\n // validate as number\n const number = this.number;\n valid = valid && !isNaN(number) && (\n // check min bound for negative values\n this.min == null || this.min >= 0 || this.min <= this.number) && (\n // check max bound for positive values\n this.max == null || this.max <= 0 || this.number <= this.max);\n }\n return valid && super.doValidate(flags);\n }\n\n /**\n @override\n */\n doCommit() {\n if (this.value) {\n const number = this.number;\n let validnum = number;\n\n // check bounds\n if (this.min != null) validnum = Math.max(validnum, this.min);\n if (this.max != null) validnum = Math.min(validnum, this.max);\n if (validnum !== number) this.unmaskedValue = this.doFormat(validnum);\n let formatted = this.value;\n if (this.normalizeZeros) formatted = this._normalizeZeros(formatted);\n if (this.padFractionalZeros && this.scale > 0) formatted = this._padFractionalZeros(formatted);\n this._value = formatted;\n }\n super.doCommit();\n }\n\n /** */\n _normalizeZeros(value) {\n const parts = this._removeThousandsSeparators(value).split(this.radix);\n\n // remove leading zeros\n parts[0] = parts[0].replace(/^(\\D*)(0*)(\\d*)/, (match, sign, zeros, num) => sign + num);\n // add leading zero\n if (value.length && !/\\d$/.test(parts[0])) parts[0] = parts[0] + '0';\n if (parts.length > 1) {\n parts[1] = parts[1].replace(/0*$/, ''); // remove trailing zeros\n if (!parts[1].length) parts.length = 1; // remove fractional\n }\n\n return this._insertThousandsSeparators(parts.join(this.radix));\n }\n\n /** */\n _padFractionalZeros(value) {\n if (!value) return value;\n const parts = value.split(this.radix);\n if (parts.length < 2) parts.push('');\n parts[1] = parts[1].padEnd(this.scale, '0');\n return parts.join(this.radix);\n }\n\n /** */\n doSkipInvalid(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let checkTail = arguments.length > 2 ? arguments[2] : undefined;\n const dropFractional = this.scale === 0 && ch !== this.thousandsSeparator && (ch === this.radix || ch === MaskedNumber.UNMASKED_RADIX || this.mapToRadix.includes(ch));\n return super.doSkipInvalid(ch, flags, checkTail) && !dropFractional;\n }\n\n /**\n @override\n */\n get unmaskedValue() {\n return this._removeThousandsSeparators(this._normalizeZeros(this.value)).replace(this.radix, MaskedNumber.UNMASKED_RADIX);\n }\n set unmaskedValue(unmaskedValue) {\n super.unmaskedValue = unmaskedValue;\n }\n\n /**\n @override\n */\n get typedValue() {\n return this.doParse(this.unmaskedValue);\n }\n set typedValue(n) {\n this.rawInputValue = this.doFormat(n).replace(MaskedNumber.UNMASKED_RADIX, this.radix);\n }\n\n /** Parsed Number */\n get number() {\n return this.typedValue;\n }\n set number(number) {\n this.typedValue = number;\n }\n\n /**\n Is negative allowed\n @readonly\n */\n get allowNegative() {\n return this.signed || this.min != null && this.min < 0 || this.max != null && this.max < 0;\n }\n\n /**\n @override\n */\n typedValueEquals(value) {\n // handle 0 -> '' case (typed = 0 even if value = '')\n // for details see https://github.com/uNmAnNeR/imaskjs/issues/134\n return (super.typedValueEquals(value) || MaskedNumber.EMPTY_VALUES.includes(value) && MaskedNumber.EMPTY_VALUES.includes(this.typedValue)) && !(value === 0 && this.value === '');\n }\n}\nMaskedNumber.UNMASKED_RADIX = '.';\nMaskedNumber.DEFAULTS = {\n radix: ',',\n thousandsSeparator: '',\n mapToRadix: [MaskedNumber.UNMASKED_RADIX],\n scale: 2,\n signed: false,\n normalizeZeros: true,\n padFractionalZeros: false,\n parse: Number,\n format: n => n.toLocaleString('en-US', {\n useGrouping: false,\n maximumFractionDigits: 20\n })\n};\nMaskedNumber.EMPTY_VALUES = [...Masked.EMPTY_VALUES, 0];\nIMask.MaskedNumber = MaskedNumber;\n\nexport { MaskedNumber as default };\n","import Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/change-details.js';\nimport '../core/continuous-tail-details.js';\nimport '../core/utils.js';\n\n/** Masking by custom Function */\nclass MaskedFunction extends Masked {\n /**\n @override\n @param {Object} opts\n */\n _update(opts) {\n if (opts.mask) opts.validate = opts.mask;\n super._update(opts);\n }\n}\nIMask.MaskedFunction = MaskedFunction;\n\nexport { MaskedFunction as default };\n","import { _ as _objectWithoutPropertiesLoose } from '../_rollupPluginBabelHelpers-6b3bd404.js';\nimport { DIRECTION, normalizePrepare, objectIncludes } from '../core/utils.js';\nimport ChangeDetails from '../core/change-details.js';\nimport createMask from './factory.js';\nimport Masked from './base.js';\nimport IMask from '../core/holder.js';\nimport '../core/continuous-tail-details.js';\n\nconst _excluded = [\"compiledMasks\", \"currentMaskRef\", \"currentMask\"],\n _excluded2 = [\"mask\"];\n/** Dynamic mask for choosing apropriate mask in run-time */\nclass MaskedDynamic extends Masked {\n /** Currently chosen mask */\n\n /** Compliled {@link Masked} options */\n\n /** Chooses {@link Masked} depending on input value */\n\n /**\n @param {Object} opts\n */\n constructor(opts) {\n super(Object.assign({}, MaskedDynamic.DEFAULTS, opts));\n this.currentMask = null;\n }\n\n /**\n @override\n */\n _update(opts) {\n super._update(opts);\n if ('mask' in opts) {\n // mask could be totally dynamic with only `dispatch` option\n this.compiledMasks = Array.isArray(opts.mask) ? opts.mask.map(m => createMask(m)) : [];\n\n // this.currentMask = this.doDispatch(''); // probably not needed but lets see\n }\n }\n\n /**\n @override\n */\n _appendCharRaw(ch) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n const details = this._applyDispatch(ch, flags);\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendChar(ch, this.currentMaskFlags(flags)));\n }\n return details;\n }\n _applyDispatch() {\n let appended = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let tail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';\n const prevValueBeforeTail = flags.tail && flags._beforeTailState != null ? flags._beforeTailState._value : this.value;\n const inputValue = this.rawInputValue;\n const insertValue = flags.tail && flags._beforeTailState != null ?\n // $FlowFixMe - tired to fight with type system\n flags._beforeTailState._rawInputValue : inputValue;\n const tailValue = inputValue.slice(insertValue.length);\n const prevMask = this.currentMask;\n const details = new ChangeDetails();\n const prevMaskState = prevMask === null || prevMask === void 0 ? void 0 : prevMask.state;\n\n // clone flags to prevent overwriting `_beforeTailState`\n this.currentMask = this.doDispatch(appended, Object.assign({}, flags), tail);\n\n // restore state after dispatch\n if (this.currentMask) {\n if (this.currentMask !== prevMask) {\n // if mask changed reapply input\n this.currentMask.reset();\n if (insertValue) {\n // $FlowFixMe - it's ok, we don't change current mask above\n const d = this.currentMask.append(insertValue, {\n raw: true\n });\n details.tailShift = d.inserted.length - prevValueBeforeTail.length;\n }\n if (tailValue) {\n // $FlowFixMe - it's ok, we don't change current mask above\n details.tailShift += this.currentMask.append(tailValue, {\n raw: true,\n tail: true\n }).tailShift;\n }\n } else {\n // Dispatch can do something bad with state, so\n // restore prev mask state\n this.currentMask.state = prevMaskState;\n }\n }\n return details;\n }\n _appendPlaceholder() {\n const details = this._applyDispatch(...arguments);\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendPlaceholder());\n }\n return details;\n }\n\n /**\n @override\n */\n _appendEager() {\n const details = this._applyDispatch(...arguments);\n if (this.currentMask) {\n details.aggregate(this.currentMask._appendEager());\n }\n return details;\n }\n appendTail(tail) {\n const details = new ChangeDetails();\n if (tail) details.aggregate(this._applyDispatch('', {}, tail));\n return details.aggregate(this.currentMask ? this.currentMask.appendTail(tail) : super.appendTail(tail));\n }\n currentMaskFlags(flags) {\n var _flags$_beforeTailSta, _flags$_beforeTailSta2;\n return Object.assign({}, flags, {\n _beforeTailState: ((_flags$_beforeTailSta = flags._beforeTailState) === null || _flags$_beforeTailSta === void 0 ? void 0 : _flags$_beforeTailSta.currentMaskRef) === this.currentMask && ((_flags$_beforeTailSta2 = flags._beforeTailState) === null || _flags$_beforeTailSta2 === void 0 ? void 0 : _flags$_beforeTailSta2.currentMask) || flags._beforeTailState\n });\n }\n\n /**\n @override\n */\n doDispatch(appended) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let tail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';\n return this.dispatch(appended, this, flags, tail);\n }\n\n /**\n @override\n */\n doValidate(flags) {\n return super.doValidate(flags) && (!this.currentMask || this.currentMask.doValidate(this.currentMaskFlags(flags)));\n }\n\n /**\n @override\n */\n doPrepare(str) {\n let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let [s, details] = normalizePrepare(super.doPrepare(str, flags));\n if (this.currentMask) {\n let currentDetails;\n [s, currentDetails] = normalizePrepare(super.doPrepare(s, this.currentMaskFlags(flags)));\n details = details.aggregate(currentDetails);\n }\n return [s, details];\n }\n\n /**\n @override\n */\n reset() {\n var _this$currentMask;\n (_this$currentMask = this.currentMask) === null || _this$currentMask === void 0 ? void 0 : _this$currentMask.reset();\n this.compiledMasks.forEach(m => m.reset());\n }\n\n /**\n @override\n */\n get value() {\n return this.currentMask ? this.currentMask.value : '';\n }\n set value(value) {\n super.value = value;\n }\n\n /**\n @override\n */\n get unmaskedValue() {\n return this.currentMask ? this.currentMask.unmaskedValue : '';\n }\n set unmaskedValue(unmaskedValue) {\n super.unmaskedValue = unmaskedValue;\n }\n\n /**\n @override\n */\n get typedValue() {\n return this.currentMask ? this.currentMask.typedValue : '';\n }\n\n // probably typedValue should not be used with dynamic\n set typedValue(value) {\n let unmaskedValue = String(value);\n\n // double check it\n if (this.currentMask) {\n this.currentMask.typedValue = value;\n unmaskedValue = this.currentMask.unmaskedValue;\n }\n this.unmaskedValue = unmaskedValue;\n }\n get displayValue() {\n return this.currentMask ? this.currentMask.displayValue : '';\n }\n\n /**\n @override\n */\n get isComplete() {\n var _this$currentMask2;\n return Boolean((_this$currentMask2 = this.currentMask) === null || _this$currentMask2 === void 0 ? void 0 : _this$currentMask2.isComplete);\n }\n\n /**\n @override\n */\n get isFilled() {\n var _this$currentMask3;\n return Boolean((_this$currentMask3 = this.currentMask) === null || _this$currentMask3 === void 0 ? void 0 : _this$currentMask3.isFilled);\n }\n\n /**\n @override\n */\n remove() {\n const details = new ChangeDetails();\n if (this.currentMask) {\n details.aggregate(this.currentMask.remove(...arguments))\n // update with dispatch\n .aggregate(this._applyDispatch());\n }\n return details;\n }\n\n /**\n @override\n */\n get state() {\n var _this$currentMask4;\n return Object.assign({}, super.state, {\n _rawInputValue: this.rawInputValue,\n compiledMasks: this.compiledMasks.map(m => m.state),\n currentMaskRef: this.currentMask,\n currentMask: (_this$currentMask4 = this.currentMask) === null || _this$currentMask4 === void 0 ? void 0 : _this$currentMask4.state\n });\n }\n set state(state) {\n const {\n compiledMasks,\n currentMaskRef,\n currentMask\n } = state,\n maskedState = _objectWithoutPropertiesLoose(state, _excluded);\n this.compiledMasks.forEach((m, mi) => m.state = compiledMasks[mi]);\n if (currentMaskRef != null) {\n this.currentMask = currentMaskRef;\n this.currentMask.state = currentMask;\n }\n super.state = maskedState;\n }\n\n /**\n @override\n */\n extractInput() {\n return this.currentMask ? this.currentMask.extractInput(...arguments) : '';\n }\n\n /**\n @override\n */\n extractTail() {\n return this.currentMask ? this.currentMask.extractTail(...arguments) : super.extractTail(...arguments);\n }\n\n /**\n @override\n */\n doCommit() {\n if (this.currentMask) this.currentMask.doCommit();\n super.doCommit();\n }\n\n /**\n @override\n */\n nearestInputPos() {\n return this.currentMask ? this.currentMask.nearestInputPos(...arguments) : super.nearestInputPos(...arguments);\n }\n get overwrite() {\n return this.currentMask ? this.currentMask.overwrite : super.overwrite;\n }\n set overwrite(overwrite) {\n console.warn('\"overwrite\" option is not available in dynamic mask, use this option in siblings');\n }\n get eager() {\n return this.currentMask ? this.currentMask.eager : super.eager;\n }\n set eager(eager) {\n console.warn('\"eager\" option is not available in dynamic mask, use this option in siblings');\n }\n get skipInvalid() {\n return this.currentMask ? this.currentMask.skipInvalid : super.skipInvalid;\n }\n set skipInvalid(skipInvalid) {\n if (this.isInitialized || skipInvalid !== Masked.DEFAULTS.skipInvalid) {\n console.warn('\"skipInvalid\" option is not available in dynamic mask, use this option in siblings');\n }\n }\n\n /**\n @override\n */\n maskEquals(mask) {\n return Array.isArray(mask) && this.compiledMasks.every((m, mi) => {\n if (!mask[mi]) return;\n const _mask$mi = mask[mi],\n {\n mask: oldMask\n } = _mask$mi,\n restOpts = _objectWithoutPropertiesLoose(_mask$mi, _excluded2);\n return objectIncludes(m, restOpts) && m.maskEquals(oldMask);\n });\n }\n\n /**\n @override\n */\n typedValueEquals(value) {\n var _this$currentMask5;\n return Boolean((_this$currentMask5 = this.currentMask) === null || _this$currentMask5 === void 0 ? void 0 : _this$currentMask5.typedValueEquals(value));\n }\n}\nMaskedDynamic.DEFAULTS = {\n dispatch: (appended, masked, flags, tail) => {\n if (!masked.compiledMasks.length) return;\n const inputValue = masked.rawInputValue;\n\n // simulate input\n const inputs = masked.compiledMasks.map((m, index) => {\n const isCurrent = masked.currentMask === m;\n const startInputPos = isCurrent ? m.value.length : m.nearestInputPos(m.value.length, DIRECTION.FORCE_LEFT);\n if (m.rawInputValue !== inputValue) {\n m.reset();\n m.append(inputValue, {\n raw: true\n });\n } else if (!isCurrent) {\n m.remove(startInputPos);\n }\n m.append(appended, masked.currentMaskFlags(flags));\n m.appendTail(tail);\n return {\n index,\n weight: m.rawInputValue.length,\n totalInputPositions: m.totalInputPositions(0, Math.max(startInputPos, m.nearestInputPos(m.value.length, DIRECTION.FORCE_LEFT)))\n };\n });\n\n // pop masks with longer values first\n inputs.sort((i1, i2) => i2.weight - i1.weight || i2.totalInputPositions - i1.totalInputPositions);\n return masked.compiledMasks[inputs[0].index];\n }\n};\nIMask.MaskedDynamic = MaskedDynamic;\n\nexport { MaskedDynamic as default };\n","import createMask from './factory.js';\nimport IMask from '../core/holder.js';\nimport '../core/utils.js';\nimport '../core/change-details.js';\n\n/** Mask pipe source and destination types */\nconst PIPE_TYPE = {\n MASKED: 'value',\n UNMASKED: 'unmaskedValue',\n TYPED: 'typedValue'\n};\n\n/** Creates new pipe function depending on mask type, source and destination options */\nfunction createPipe(mask) {\n let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : PIPE_TYPE.MASKED;\n let to = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : PIPE_TYPE.MASKED;\n const masked = createMask(mask);\n return value => masked.runIsolated(m => {\n m[from] = value;\n return m[to];\n });\n}\n\n/** Pipes value through mask depending on mask type, source and destination options */\nfunction pipe(value) {\n for (var _len = arguments.length, pipeArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n pipeArgs[_key - 1] = arguments[_key];\n }\n return createPipe(...pipeArgs)(value);\n}\nIMask.PIPE_TYPE = PIPE_TYPE;\nIMask.createPipe = createPipe;\nIMask.pipe = pipe;\n\nexport { PIPE_TYPE, createPipe, pipe };\n","export { default as InputMask } from './controls/input.js';\nimport IMask from './core/holder.js';\nexport { default } from './core/holder.js';\nexport { default as Masked } from './masked/base.js';\nexport { default as MaskedPattern } from './masked/pattern.js';\nexport { default as MaskedEnum } from './masked/enum.js';\nexport { default as MaskedRange } from './masked/range.js';\nexport { default as MaskedNumber } from './masked/number.js';\nexport { default as MaskedDate } from './masked/date.js';\nexport { default as MaskedRegExp } from './masked/regexp.js';\nexport { default as MaskedFunction } from './masked/function.js';\nexport { default as MaskedDynamic } from './masked/dynamic.js';\nexport { default as createMask } from './masked/factory.js';\nexport { default as MaskElement } from './controls/mask-element.js';\nexport { default as HTMLMaskElement } from './controls/html-mask-element.js';\nexport { default as HTMLContenteditableMaskElement } from './controls/html-contenteditable-mask-element.js';\nexport { PIPE_TYPE, createPipe, pipe } from './masked/pipe.js';\nexport { default as ChangeDetails } from './core/change-details.js';\nimport './_rollupPluginBabelHelpers-6b3bd404.js';\nimport './core/utils.js';\nimport './core/action-details.js';\nimport './core/continuous-tail-details.js';\nimport './masked/pattern/input-definition.js';\nimport './masked/pattern/fixed-definition.js';\nimport './masked/pattern/chunk-tail-details.js';\nimport './masked/pattern/cursor.js';\n\ntry {\n globalThis.IMask = IMask;\n} catch (e) {}\n","import { HandlerBase } from \"../../../shared/handler/handler-base\";\nimport { CreditCardService } from \"../../services/credit-card-service\";\nimport { BrowserCommunicatorService } from '../../../services/browser-communicator-service';\nimport IMask from 'imask';\n\nexport class CreditCardHandlerBase extends HandlerBase {\n\n constructor() {\n super();\n }\n\n init() {\n this._creditCardService = new CreditCardService();\n this._browserCommunicatorService = new BrowserCommunicatorService();\n\n this.cardNumber_mask = null;\n this.expirationDate_mask = null;\n this.securityCode_mask = null;\n\n this._renderDataForm();\n }\n\n async _renderDataForm() {\n //#region Click event to flipped\n $(\".credit-card-inner\").off(\"click\");\n $(\".credit-card-inner\").on(\"click\", function (e) {\n if ($(\".credit-card-inner\").hasClass(\"flipped\")) {\n $(\".credit-card-inner\").removeClass(\"flipped\");\n } else {\n $(\".credit-card-inner\").addClass(\"flipped\");\n }\n });\n //#endregion\n\n //#region Render controls\n if ($(\"#HolderName\").length > 0) {\n this._renderHolderNameField();\n }\n\n if ($(\"#CardNumber\").length > 0) {\n this._renderCardNumberField();\n }\n\n if ($(\"#ExpirationDate\").length > 0) {\n this._renderExpirationDate();\n }\n\n if ($(\"#SecurityCode\").length > 0) {\n this._renderSecurityCode();\n }\n //#endregion\n\n //#region Save Button\n $(\".save-credit-card\").off(\"click\");\n $(\".save-credit-card\").on(\"click\", { creditCardHandler: this }, this.onSubmitForm);\n //#endregion\n\n if ($(\"#credit-card-form\").length > 0) {\n $(\"#credit-card-form\").off(\"hidden.bs.modal\");\n $(\"#credit-card-form\").on(\"hidden.bs.modal\", { creditCardHandler: this }, function (e) {\n //#region Reset Form\n $(\"#CreditCardIcon\").html(\"\");\n $(\"#CreditCardIcon-back\").html(\"\");\n $(\"#card-texture\").attr(\"src\", `/img/card-textures/card-background-18.png`);\n $(\".card-no\").html(\"

    ####

    ####

    ####

    ####

    \");\n $(\"#holder-name\").html('********');\n $(\"#holder-name-signature\").html('');\n $(\".security-code\").html(\"000\");\n $(\".credit-card-inner\").removeClass(\"flipped\");\n $(\".valid-to\").html('00/00');\n CreditCardHandlerBase._swapColor(\"unknown\");\n\n $(\"#HolderName\").val(\"\");\n $(\"#HolderName\").trigger(\"change\");\n\n $(\"#CardNumber\").val(\"\");\n $(\"#CardNumber\").trigger(\"change\");\n\n $(\"#ExpirationDate\").val(\"\");\n $(\"#ExpirationDate\").trigger(\"change\");\n\n $(\"#SecurityCode\").val(\"\");\n $(\"#SecurityCode\").trigger(\"change\");\n\n $(\"#AcceptanceToken\").data(\"kendoSwitch\").value(false);\n $(\"#AcceptanceToken\").trigger(\"change\");\n\n $(\".terms-conditions-label>a\").attr(\"href\", \"#\");\n //#endregion\n\n const creditCardHandler = e.data.creditCardHandler;\n creditCardHandler.cardNumber_mask.updateValue();\n creditCardHandler.expirationDate_mask.updateValue();\n creditCardHandler.securityCode_mask.updateValue();\n });\n\n $(\"#credit-card-form\").off(\"show.bs.modal\");\n $(\"#credit-card-form\").on(\"show.bs.modal\", { creditCardHandler: this }, function (e) {\n const creditCardHandler = e.data.creditCardHandler;\n creditCardHandler.onGetAcceptanceInfo();\n });\n }\n }\n\n _renderHolderNameField() {\n const holderName = document.getElementById(\"HolderName\");\n\n holderName.addEventListener('input', function () {\n if ($(\"#HolderName\").val().length === 0) {\n $(\"#holder-name\").html('********');\n $(\"#holder-name-signature\").html('');\n } else {\n $(\"#holder-name\").html(this.value);\n $(\"#holder-name-signature\").html(this.value);\n }\n });\n\n holderName.addEventListener('focus', function () {\n $(\".credit-card-inner\").removeClass(\"flipped\");\n });\n }\n\n _renderCardNumberField() {\n const cardNumber = document.getElementById(\"CardNumber\");\n\n //#region Credit Card Number Mask\n const cardNumber_mask = new IMask(cardNumber, {\n mask: [\n {\n mask: '0000 000000 00000',\n regex: '^3[47]\\\\d{0,13}',\n cardType: 'amex',\n cardIcon: `Slice 1Created with Sketch.`,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 0000 0000 0000',\n regex: '^(?:6011|65\\\\d{0,2}|64[4-9]\\\\d?)\\\\d{0,12}',\n cardType: 'discover',\n cardIcon: `discoverCreated with Sketch.`,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 000000 0000',\n regex: '^3(?:0([0-5]|9)|[689]\\\\d?)\\\\d{0,11}',\n cardType: 'diners',\n cardIcon: `dinersCreated with Sketch.`,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 0000 0000 0000',\n regex: '^(5[1-5]\\\\d{0,2}|22[2-9]\\\\d{0,1}|2[3-7]\\\\d{0,2})\\\\d{0,12}',\n cardType: 'mastercard',\n cardIcon: ` mastercard `,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 000000 00000',\n regex: '^(?:2131|1800)\\\\d{0,11}',\n cardType: 'jcb15',\n cardIcon: `Slice 1Created with Sketch.`,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 0000 0000 0000',\n regex: '^(?:35\\\\d{0,2})\\\\d{0,12}',\n cardType: 'jcb',\n cardIcon: `Slice 1Created with Sketch.`,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 0000 0000 0000',\n regex: '^(?:5[0678]\\\\d{0,2}|6304|67\\\\d{0,2})\\\\d{0,12}',\n cardType: 'maestro',\n cardIcon: ` maestro `,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 0000 0000 0000',\n regex: '^4\\\\d{0,15}',\n cardType: 'visa',\n cardIcon: `Slice 1Created with Sketch.`,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 0000 0000 0000',\n regex: '^62\\\\d{0,14}',\n cardType: 'unionpay',\n cardIcon: ` `,\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n },\n {\n mask: '0000 0000 0000 0000',\n cardType: 'unknown',\n cardIcon: '',\n cardTexture: `card-background-${CreditCardHandlerBase._indexTexture(1, 19)}.png`\n }\n ],\n dispatch: function (appended, dynamicMasked) {\n var number = (dynamicMasked.value + appended).replace(/\\D/g, '');\n\n for (var i = 0; i < dynamicMasked.compiledMasks.length; i++) {\n let re = new RegExp(dynamicMasked.compiledMasks[i].regex);\n if (number.match(re) != null) {\n return dynamicMasked.compiledMasks[i];\n }\n }\n }\n });\n\n cardNumber_mask.off(\"accept\");\n cardNumber_mask.on('accept', function (e) {\n if (cardNumber_mask.value.length == 0) {\n $(\".card-no\").html(\"

    ####

    ####

    ####

    ####

    \")\n } else {\n let response = \"\";\n let section = 0;\n\n cardNumber_mask.value.split(\" \").forEach(function (item) {\n response += `

    ${item.padEnd(4, '#')}

    `;\n section++;\n });\n\n for (let index = section; index < 4; index++) {\n response += `

    ####

    `;\n }\n\n $(\".card-no\").html(response)\n }\n });\n\n cardNumber_mask.on(\"accept\", function (e) {\n const creditCardIcon = document.getElementById(\"CreditCardIcon\");\n const creditCardIconBack = document.getElementById(\"CreditCardIcon-back\");\n\n CreditCardHandlerBase._swapColor(cardNumber_mask.masked.currentMask.cardType);\n\n creditCardIcon.innerHTML = cardNumber_mask.masked.currentMask.cardIcon;\n creditCardIconBack.innerHTML = cardNumber_mask.masked.currentMask.cardIcon;\n $(\"#card-texture\").attr(\"src\", `/img/card-textures/${cardNumber_mask.masked.currentMask.cardTexture}`)\n });\n\n cardNumber.addEventListener('focus', function () {\n $(\".credit-card-inner\").removeClass(\"flipped\");\n });\n //#endregion\n\n this.cardNumber_mask = cardNumber_mask;\n }\n\n _renderExpirationDate() {\n const expirationDate = document.getElementById(\"ExpirationDate\");\n\n //#region Credit Card Expiration Date Mask\n const expirationDate_mask = new IMask(expirationDate, {\n mask: 'MM{/}YY',\n lazy: true,\n blocks: {\n YY: {\n mask: IMask.MaskedRange,\n from: 0,\n to: 99\n },\n MM: {\n mask: IMask.MaskedRange,\n from: 1,\n to: 12\n }\n }\n });\n\n expirationDate_mask.off(\"accept\");\n expirationDate_mask.on('accept', function (e) {\n if (expirationDate_mask.value.length == 0) {\n $(\".valid-to\").html('00/00')\n } else {\n $(\".valid-to\").html(expirationDate_mask.value)\n }\n });\n\n expirationDate.addEventListener('focus', function () {\n $(\".credit-card-inner\").removeClass(\"flipped\");\n });\n //#endregion\n\n this.expirationDate_mask = expirationDate_mask;\n }\n\n _renderSecurityCode() {\n const securityCode = document.getElementById(\"SecurityCode\");\n\n //#region Credit Card Security Code Mask\n const securityCode_mask = new IMask(securityCode, {\n mask: '0000',\n });\n\n securityCode_mask.off('accept');\n securityCode_mask.on('accept', function (e) {\n if (securityCode_mask.value.length == 0) {\n $(\".security-code\").html(\"000\");\n } else {\n $(\".security-code\").html(securityCode_mask.value);\n }\n });\n\n securityCode.addEventListener('focus', function () {\n $(\".credit-card-inner\").addClass(\"flipped\");\n });\n //#endregion\n\n this.securityCode_mask = securityCode_mask;\n }\n\n /**\n * \n * @param {string} target Selector\n * @param {boolean} value (Show/Hide)\n */\n _displayLoading(target, value) {\n const element = $(target);\n kendo.ui.progress(element, value);\n }\n\n /**\n * \n * @param {String} errorPre error description\n * */\n _showError(errorPre) {\n let errorstr =\n `\n

    Ocurrio un error no controlado al guardar el cup�n

    \n
    ${errorPre}
    \n `;\n this._browserCommunicatorService.displayErrorAlert({\n description: errorstr,\n html: true\n });\n }\n\n /**\n * Gets a random number within the min and max range\n * @param {Number} min\n * @param {Number} max\n * @returns {Number}\n * */\n static _indexTexture(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1) + min);\n }\n\n /**\n * Change color according to the base sent (CSS Class)\n * @param {String} basecolor class color\n * */\n static _swapColor(basecolor) {\n document.querySelectorAll('.front')\n .forEach(function (input) {\n input.setAttribute('class', '');\n input.setAttribute('class', 'front ' + basecolor);\n });\n document.querySelectorAll('.back')\n .forEach(function (input) {\n input.setAttribute('class', '');\n input.setAttribute('class', 'back ' + basecolor);\n });\n }\n\n /**\n * Load all items list\n * */\n async onLoadItems() {\n //here your code\n }\n\n /**\n * Load the item in a list\n * @param {String} token\n * */\n async onLoadItem(token = \"\") {\n\n }\n\n /**\n * \n * @param {Event} e\n * */\n async onSubmitForm(e) {\n e.preventDefault();\n\n const creditCardHandler = e.data.creditCardHandler;\n creditCardHandler._displayLoading(\"#credit-card-view\", true);\n\n const isValid = await creditCardHandler.validateForm();\n\n if (!isValid) {\n creditCardHandler._displayLoading(\"#credit-card-view\", false);\n return;\n }\n\n if ($(\"#AcceptanceToken\").data(\"kendoSwitch\").value() === false) {\n creditCardHandler._displayLoading(\"#credit-card-view\", false);\n creditCardHandler._browserCommunicatorService.displayWarningAlert({\n title: 'Agregar tarjeta',\n description: \"Para continuar debes aceptar los términos y condiciones\"\n })\n return;\n }\n\n\n let formData = new FormData();\n\n formData.append('creditCardModel.HolderName', $(\"#HolderName\").data(\"kendoTextBox\").value())\n formData.append('creditCardModel.CardNumber', $(\"#CardNumber\").data(\"kendoTextBox\").value())\n formData.append('creditCardModel.ExpirationDate', $(\"#ExpirationDate\").data(\"kendoTextBox\").value())\n formData.append('creditCardModel.SecurityCode', $(\"#SecurityCode\").data(\"kendoTextBox\").value())\n formData.append('creditCardModel.AcceptanceToken', $(\"#AcceptanceToken\").data(\"kendoSwitch\").value())\n formData.append('creditCardModel.AcceptanceTokenId', $(\"#AcceptanceTokenId\").val())\n\n const response = await creditCardHandler._creditCardService.postSave(formData);\n const responseJson = await response.json();\n\n if (responseJson.Successful) {\n await creditCardHandler.onLoadItem(responseJson.TokenId);\n await creditCardHandler._browserCommunicatorService.displaySuccessAlertAsync({\n title: 'Agregar tarjeta',\n description: responseJson.UserMessage,\n html: true\n });\n } else {\n await creditCardHandler._browserCommunicatorService.displayErrorAlert({\n title: 'Agregar tarjeta',\n description: responseJson.UserMessage,\n html: true\n });\n }\n\n creditCardHandler._displayLoading(\"#credit-card-view\", false);\n\n $('#credit-card-form').modal('hide');\n }\n\n /**\n * \n * @param {Event} e\n * */\n async onDeleteItem(e) {\n e.preventDefault();\n }\n\n /**\n * \n */\n async onGetAcceptanceInfo() {\n const response = await this._creditCardService.postGetAcceptanceInfo();\n const responseJson = await response.json();\n\n $(\".terms-conditions-label>a\").attr(\"href\", responseJson.AcceptanceInfo.Url);\n\n if (responseJson.Successful) {\n $(\"#AcceptanceTokenId\").val(responseJson.AcceptanceInfo.AcceptanceToken);\n }\n }\n\n /**\n * \n * @param {String} target Selector form\n * @returns {boolean} Validate\n * */\n async validateForm(target = \"#credit-card-root-data\") {\n const validator = $(target).kendoValidator().data(\"kendoValidator\");\n return validator.validate();\n }\n}\n\n","import { CreditCardHandlerBase } from \"../../shared/handler/credit-card-handler-base\";\n\nexport class CreditCardMyAccountHandler extends CreditCardHandlerBase {\n\n constructor() {\n super();\n }\n\n /**\n * @override\n */\n init() {\n super.init();\n }\n\n /**\n * @override\n */\n _renderDataForm() {\n super._renderDataForm();\n\n //#region Delete Button\n $(\".remove-credit-card\").off(\"click\");\n $(\".remove-credit-card\").on(\"click\", { creditCardHandler: this }, this.onDeleteItem);\n //#endregion\n }\n\n /**\n * @param {String} token\n * @override\n */\n async onLoadItem(token = \"\") {\n let formData = new FormData();\n formData.append('tokenId', token);\n\n const response = await this._creditCardService.postLoadItem(formData);\n const responseJson = await response.text();\n\n $(\".credit-card-list\").append(responseJson);\n\n $(\".remove-credit-card\").off(\"click\");\n $(\".remove-credit-card\").on(\"click\", { creditCardHandler: this }, this.onDeleteItem);\n\n super.onLoadItem(token);\n }\n\n /**\n * @override\n */\n async onDeleteItem(e) {\n e.preventDefault();\n\n const creditCardHandler = e.data.creditCardHandler;\n const titleMessage = $(this).attr(\"data-message-title\");\n const cardNumber = $(this).attr(\"data-card-number\");\n\n const confirmResult = await creditCardHandler._browserCommunicatorService.displayQuestionAlert({\n title: titleMessage,\n description: `¿Quieres eliminar tu tarjeta terminada en ${cardNumber}?`,\n html: true\n });\n\n if (confirmResult.isConfirmed) {\n creditCardHandler._displayLoading(\"body\", true);\n const token = $(this).attr(\"data-token-id\");\n\n let formData = new FormData();\n formData.append('token', token);\n\n const response = await creditCardHandler._creditCardService.postDelete(formData);\n const responseJson = await response.json();\n\n if (responseJson.Successful) {\n $(`div[data-token='${token}']`).remove();\n await creditCardHandler._browserCommunicatorService.displaySuccessAlertAsync({\n title: titleMessage,\n description: responseJson.UserMessage,\n html: true\n });\n } else {\n await creditCardHandler._browserCommunicatorService.displayErrorAlert({\n title: titleMessage,\n description: responseJson.UserMessage,\n html: true\n });\n }\n\n creditCardHandler._displayLoading(\"body\", false);\n }\n }\n}\n\n","import { CreditCardHandlerBase } from \"../../shared/handler/credit-card-handler-base\";\nimport '@progress/kendo-ui'\n\nexport class CreditCardCheckoutHandler extends CreditCardHandlerBase {\n\n constructor() {\n super();\n }\n\n /**\n * @override\n */\n init() {\n super.init();\n }\n\n /**\n * @override\n */\n _renderDataForm() {\n super._renderDataForm();\n\n //#region Load Credit Card Items\n if ($(\"#checkout-credit-card-list\").length > 0) {\n\n $(\"#checkout-credit-card-list\").off(\"show.bs.modal\");\n $(\"#checkout-credit-card-list\").on(\"show.bs.modal\", { creditCardHandler: this }, function (e) {\n const creditCardHandler = e.data.creditCardHandler;\n creditCardHandler.onLoadItems();\n });\n\n $(\"#checkout-credit-card-list\").off(\"hidden.bs.modal\");\n $(\"#checkout-credit-card-list\").on(\"hidden.bs.modal\", function () {\n $(\".credit-card-list-section\").html(\"\");\n\n if ($(\".credit-card-selected\").length === 0) {\n $(\"input[name='paymentMethod']:checked\").parent().removeClass('checked');\n $(\"input[name='paymentMethod']:checked\").prop('checked', false);\n }\n });\n }\n\n $(\".apply-selection-credit-card\").off(\"click\");\n $(\".apply-selection-credit-card\").on(\"click\", { creditCardHandler: this }, function (e) {\n if ($(\"input[name='CreditCardItem']:checked\").val() !== undefined) {\n let quota = $(\"ul.credit-card-list-section > li.checked\").children(\"div.container-radioButton__content\").children(\"div.credit-card-installments\").find(\"select\").find(\":selected\").val();\n let card = $(\"input[name='CreditCardItem']:checked\").attr(\"data-card-name\");\n let number = $(\"input[name='CreditCardItem']:checked\").attr(\"data-card-number\");\n let type = $(\"input[name='CreditCardItem']:checked\").attr(\"data-card-type\");\n let token = $(\"input[name='CreditCardItem']:checked\").val();\n\n $(\".credit-card-selected\").remove();\n $(\"ul.checkout__payment-list > li.checked\").append(`
    [ ${card} / # Cuotas ${quota} ]
    `);\n $(\"#checkout-credit-card-list\").modal(\"hide\");\n } else {\n const creditCardHandler = e.data.creditCardHandler;\n creditCardHandler._browserCommunicatorService.displayWarningAlert({ description: \"Debe seleccionar una tarjeta para continuar\" });\n }\n });\n\n $(\"input[name='paymentMethod']\").on(\"change\", function () {\n if ($(\".credit-card-selected\").length > 0) {\n const internalcode = $(this).attr(\"internalcode\");\n const creditCardInternalCode = \"TCR\";\n\n if (internalcode !== creditCardInternalCode) {\n $(\".credit-card-selected\").remove();\n }\n }\n });\n\n $(\"ul.checkout__payment-list > li\").on(\"click\", function () {\n if ($(\".credit-card-selected\").length > 0) {\n const internalcode = $(this).children(\"input[name='paymentMethod']\").attr(\"internalcode\");\n const creditCardInternalCode = \"TCR\";\n\n if (internalcode !== creditCardInternalCode) {\n $(\".credit-card-selected\").remove();\n }\n }\n });\n //#endregion\n }\n\n /**\n * @override\n */\n async onLoadItem(token = \"\") {\n let formData = new FormData();\n formData.append('tokenId', token);\n\n const response = await this._creditCardService.postLoadItem(formData);\n const responseJson = await response.text();\n\n $(\".credit-card-list-section\").append(responseJson);\n\n $(\"ul.credit-card-list-section > li\").off(\"click\");\n $(\"ul.credit-card-list-section > li\").on(\"click\", function (e) {\n $(\"ul.credit-card-list-section>li\").removeClass(\"checked\");\n $(this).addClass(\"checked\");\n $(this).children(\"input[name='CreditCardItem']\").prop('checked', true);\n });\n \n super.onLoadItem(token);\n }\n\n /**\n * @override\n */\n async onLoadItems() {\n this._displayLoading(\"credit-card-list-section\", true);\n\n super.onLoadItems();\n\n const response = await this._creditCardService.postLoadItemsForCheckout();\n const responseJson = await response.text();\n\n $(\".credit-card-list-section\").append(responseJson);\n\n $(\"ul.credit-card-list-section > li\").off(\"click\");\n $(\"ul.credit-card-list-section > li\").on(\"click\", function (e) {\n $(\"ul.credit-card-list-section>li\").removeClass(\"checked\");\n $(this).addClass(\"checked\");\n $(this).children(\"input[name='CreditCardItem']\").prop('checked', true);\n });\n\n this._displayLoading(\"credit-card-list-section\", false);\n }\n}\n\n","import { HandlerBase } from \"../../../shared/handler/handler-base\";\n\nexport class SecurityHandlerBase extends HandlerBase {\n constructor() {\n super()\n }\n\n init() {\n\n }\n\n /**\n * \n * @param event {JQuery.Event}\n * */\n _preventSpaceInput(event) {\n if (event.which === 32)\n return false;\n }\n\n /**\n * \n * @param event {JQuery.Event}\n * */\n _validateOnlyNumbers(event) {\n var char = String.fromCharCode(event.keyCode);\n\n if (/[0-9]/.test(char)) {\n return true;\n }\n\n return false;\n }\n\n}","import { ForgeryTokenHelper } from \"../../../shared/helper/forgeryTokenHelper\";\n\nexport class AccountActivationService {\n\n constructor() { }\n\n /**\n * \n * @param formData {FormData}\n * @returns {Promise}\n * */\n postAuthenticate(formData) {\n return fetch(\"?handler=Authenticate\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n },\n body: formData\n });\n }\n\n /**\n * \n * @param formData {FormData}\n * @returns {Promise}\n * */\n postMessageSendingMethodActivation(formData) {\n return fetch(\"?handler=MessageSendingMethodActivation\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n },\n body: formData\n });\n }\n\n /**\n * \n * @param formData {FormData}\n * @returns {Promise}\n * */\n postSendActivationCode(formData) {\n return fetch(\"?handler=SendActivationCode\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n },\n body: formData\n });\n }\n\n /**\n * \n * @param formData {FormData}\n * @returns {Promise}\n * */\n postValidateActivationCode(formData) {\n return fetch(\"?handler=ValidateActivationCode\", {\n method: \"POST\",\n headers: {\n \"RequestVerificationToken\": ForgeryTokenHelper.forgeryTokenString()\n },\n body: formData\n });\n }\n}","import { BrowserCommunicatorService } from '../../../services/browser-communicator-service'\nimport 'jquery'\nimport { SecurityHandlerBase } from '../../shared/handler/security-handler-base';\nimport { $applicationMonitoringService } from '../../../shared/application-monitoring'\nimport { analytics } from 'apollo-web'\nimport { CacheServiceBase } from \"../../../shared/cache/cache-service-base\";\nimport { AccountActivationService } from \"../services/account-activation-service\"\nimport { CustomerAnalyticsHelper } from '../../../shared/helper/customer-analytics-helper';\n\nexport class AccountActivationHandlers extends SecurityHandlerBase {\n constructor() {\n super()\n\n this._browserCommunicatorservice = new BrowserCommunicatorService()\n this._accountActivationService = new AccountActivationService()\n this._cacheServiceBase = new CacheServiceBase()\n\n this.cacheKey = \"account_activate_settings\"\n this.expire = 60000000\n }\n\n init() {\n super.init()\n window.app.applicationMonitoringService = () => $applicationMonitoringService\n\n if ($(\"#codeActivation\").length > 0) {\n $(\"#codeActivation\").on(\"keypress\", e => this._validateOnlyNumbers(e));\n }\n\n if ($(\".activate-account-button-b2c\").length > 0) {\n $(\".activate-account-button-b2c\").on(\"click\", e => this._showConfirmationMessageSending())\n }\n\n $(\".active-code-button-b2c\").on(\"click\", e => this._activeAccount(e));\n }\n\n /**\n * \n * @param {object} activateAccount\n */\n _saveActivateAccountData(activateAccount = null) {\n this._cacheServiceBase.setWithExpiry(this.cacheKey, activateAccount, this.expire)\n }\n\n async _showConfirmationMessageSending() {\n this._loading(true, \"body\")\n\n const formData = new FormData()\n\n if ($(\"#RefValidation\").val() == \"login\") {\n var accountActivationData = this._cacheServiceBase.getWithExpiry(this.cacheKey)\n\n if (accountActivationData === undefined || accountActivationData === \"\" || accountActivationData === null) {\n await this._browserCommunicatorservice.displayErrorAlert({ description: `Ocurri\\u00F3 un error al intentar iniciar el proceso de activaci�n.` })\n this._loading(false, \"body\")\n\n return\n }\n\n formData.append('accountActivation.EmailMasked', accountActivationData.EmailMasked)\n formData.append('accountActivation.PhoneNumberMasked', accountActivationData.PhoneNumberMasked)\n formData.append('accountActivation.Username', accountActivationData.Username)\n } else {\n\n if ($(\"#SignUpB2C_Email\").length === 0 || $(\"#SignUpB2C_Password\").length === 0) {\n await this._browserCommunicatorservice.displayErrorAlert({ description: `Ocurri\\u00F3 un error al intentar iniciar el proceso de activaci�n.` })\n this._loading(false, \"body\")\n\n return\n }\n\n var accountActivationData = {\n PhoneNumber: $(\"#SignUpB2C_MobileNumber\").val().trim(),\n Email: $(\"#SignUpB2C_Email\").val().trim(),\n Username: $(\"#SignUpB2C_Email\").val().trim()\n }\n\n\n this._saveActivateAccountData(accountActivationData);\n\n formData.append('accountActivation.PhoneNumber', accountActivationData.PhoneNumber)\n formData.append('accountActivation.Email', accountActivationData.Email)\n formData.append('accountActivation.Username', accountActivationData.Username)\n }\n\n const response = await this._accountActivationService.postMessageSendingMethodActivation(formData)\n\n if (!response.ok) {\n await this._browserCommunicatorservice.displayErrorAlert({ description: `Ocurri\\u00F3 un error. ${response.statusText}` })\n this._loading(false, \"body\")\n\n return\n }\n\n const responseJson = await response.text()\n\n\n\n $(\"#title-verification-code\").html(\"Enviar código de activación\");\n $(\"#ConfirmationMessageSending > div.modal-dialog > div.modal-content > div.modal-body\").html(responseJson)\n $(\"#ConfirmationMessageSending\").modal(\"show\");\n\n $(\".send-code-information\").on(\"click\", e => this._sendValidationCode(e))\n\n this._loading(false, \"body\")\n }\n\n async _sendValidationCode(e) {\n this._loading(true, \"#ConfirmationMessageSending\")\n\n var accountActivationData = this._cacheServiceBase.getWithExpiry(this.cacheKey)\n\n const formData = new FormData()\n formData.append('accountActivation.SendMethod', $(\"input[name='OptionSendSMS']:checked\").val())\n formData.append('accountActivation.Username', accountActivationData.Username)\n\n const response = await this._accountActivationService.postSendActivationCode(formData)\n\n if (!response.ok) {\n await this._browserCommunicatorservice.displayErrorAlert({ description: `Ocurri\\u00F3 un error. ${response.statusText}` })\n this._loading(false, \"#ConfirmationMessageSending\")\n\n return\n }\n\n const responseJson = await response.json()\n\n if (responseJson.Successful) {\n this._loading(false, \"#ConfirmationMessageSending\")\n $(\"#ConfirmationMessageSending\").modal(\"hide\")\n\n let customerEmail = accountActivationData.Email || analytics.AnalyticsConstants.DefaultParameterValue;\n let customerPhone = accountActivationData.PhoneNumber || analytics.AnalyticsConstants.DefaultParameterValue;\n\n $applicationMonitoringService\n .then(function (service) {\n service.trackAccountVerification({ action: 'intent', customerEmail: customerEmail, customerPhone: customerPhone });\n })\n .catch(function (err) {\n console.error(err);\n })\n\n $(\"#accountActivation\").modal(\"show\")\n\n $('.resend-activation-code-button-b2c').on(\"click\", e => this._reSendValidationCode(e))\n } else {\n await this._browserCommunicatorservice.displayErrorAlert({\n description: responseJson.Message,\n html: true\n })\n return;\n }\n }\n\n async _reSendValidationCode(e) {\n this._loading(true, \"#accountActivation\")\n\n var accountActivationData = this._cacheServiceBase.getWithExpiry(this.cacheKey);\n\n const formData = new FormData()\n\n formData.append('accountActivation.SendMethod', $(\"input[name='OptionSendSMS']:checked\").val())\n formData.append('accountActivation.Username', accountActivationData.Username)\n\n const response = await this._accountActivationService.postSendActivationCode(formData)\n\n if (!response.ok) {\n await this._browserCommunicatorservice.displayErrorAlert({ description: `Ocurri\\u00F3 un error. ${response.statusText}` })\n this._loading(false, \"#accountActivation\")\n\n return\n }\n\n const responseJson = await response.json()\n\n if (!responseJson.Successful) {\n await this._browserCommunicatorservice.displayWarningAlert({\n description: responseJson.Message,\n html: true\n })\n }\n\n this._loading(false, \"#accountActivation\")\n }\n\n async _activeAccount(e) {\n this._loading(true, \"#accountActivation\")\n\n var accountActivationData = this._cacheServiceBase.getWithExpiry(this.cacheKey);\n\n const formData = new FormData()\n\n formData.append('accountActivation.Code', $('#codeActivation').val().trim())\n formData.append('accountActivation.Username', accountActivationData.Username)\n\n const response = await this._accountActivationService.postValidateActivationCode(formData)\n\n if (!response.ok) {\n await this._browserCommunicatorservice.displayErrorAlert({ description: `Ocurri\\u00F3 un error. ${response.statusText}` })\n this._loading(false, \"#accountActivation\")\n\n return\n }\n\n const responseJson = await response.json()\n\n if (responseJson.Successful) {\n await this._browserCommunicatorservice.displayInfoAlert({\n description: responseJson.Message,\n html: true\n })\n\n // dispatch \"activate_account\" analytics event.\n try {\n let username = accountActivationData.Email || analytics.AnalyticsConstants.DefaultParameterValue;\n $applicationMonitoringService\n .then(function (service) {\n service.trackActivateAccount(username);\n })\n .catch(function (err) {\n console.error(err)\n })\n } catch (e) {\n console.error(e)\n }\n\n let customerEmail = accountActivationData.Email || analytics.AnalyticsConstants.DefaultParameterValue;;\n let customerPhone = accountActivationData.PhoneNumber || analytics.AnalyticsConstants.DefaultParameterValue;;\n\n $applicationMonitoringService\n .then(function (service) {\n service.trackAccountVerification({ action: 'success', customerEmail: customerEmail, customerPhone: customerPhone })\n })\n .catch(function (err) {\n console.error(err)\n })\n\n if ($(\"#OnlyActivate\").val() !== \"false\") {\n window.location.href = '/Security/UserAccount/Index'\n return\n }\n\n $('.code-input').val('')\n\n\n if ($(\"#RefValidation\").val() == \"login\") {\n $(\"#AuthenticationParameter_Username\").data(\"kendoTextBox\").value(\"\")\n $(\"#AuthenticationParameter_Username\").data(\"kendoTextBox\").trigger(\"change\")\n $(\"#AuthenticationParameter_Password\").data(\"kendoTextBox\").value(\"\")\n $(\"#AuthenticationParameter_Password\").data(\"kendoTextBox\").trigger(\"change\")\n $(\"#AuthenticationParameter_PhoneNumber\").data(\"kendoTextBox\").value(\"\")\n $(\"#AuthenticationParameter_PhoneNumber\").data(\"kendoTextBox\").trigger(\"change\")\n $(\"#AuthenticationParameter_PasswordCode\").val(\"\")\n $(\"#AuthenticationParameter_PasswordCode\").trigger(\"change\")\n\n $(\".send-code-phone-number\").show()\n $(\".login-phone\").hide()\n $(\".login-phone-number\").hide()\n $(\".login-form\").show()\n } else {\n\n if ($(\"#SignUpB2C_Email\").length > 0 && $(\"#SignUpB2C_Password\").length > 0) {\n\n var user = $(\"#SignUpB2C_Email\").val();\n var password = $(\"#SignUpB2C_Password\").val();\n\n const formData = new FormData()\n\n formData.append('AuthenticationParameter.Username', user)\n formData.append('AuthenticationParameter.Password', password)\n formData.append('AuthenticationParameter.IsMobileLogin', false)\n\n const responseAuth = await this._accountActivationService.postAuthenticate(formData)\n\n if (!responseAuth.ok) {\n await this._browserCommunicatorservice.displayErrorAlert({ description: `Ocurri\\u00F3 un error. ${responseAuth.statusText}` })\n this._loading(false, \"#accountActivation\")\n $(\"#accountActivation\").modal(\"hide\")\n\n return\n }\n\n const responseAuthJson = await responseAuth.json()\n\n if (responseAuthJson.Successful) {\n // track user analytics\n await CustomerAnalyticsHelper.trackUser({\n response: responseAuthJson,\n tracklogin: true\n })\n\n window.location.href = responseAuthJson.GoToPage !== \"\" && responseAuthJson.GoToPage !== undefined && responseAuthJson.GoToPage !== \"/Security/UserAccount/Index\" ? responseAuthJson.GoToPage : '/';\n return;\n }\n }\n\n }\n\n\n //window.location.reload()\n $(\"#accountActivation\").modal(\"hide\")\n } else {\n await this._browserCommunicatorservice.displayWarningAlert({\n description: responseJson.Message,\n html: true\n })\n\n let customerEmail = accountActivationData.Email || analytics.AnalyticsConstants.DefaultParameterValue\n let customerPhone = accountActivationData.PhoneNumber || analytics.AnalyticsConstants.DefaultParameterValue\n\n $applicationMonitoringService\n .then(function (service) {\n service.trackAccountVerification({ action: 'failed', customerEmail: customerEmail, customerPhone: customerPhone })\n })\n .catch(function (err) {\n console.error(err)\n })\n }\n\n this._loading(false, \"#accountActivation\")\n }\n}","import { ServiceBase } from \"../../service/service-base\"\nimport AjaxProxy from \"../../../proxies/ajax-proxy\"\n\nexport class DynamicKitService extends ServiceBase {\n\n _endpoints = {\n getView: \"/Store/ProductKit/ProductKitEdit\",\n getConfirmationView: \"/Store/ProductKit/ProductKitEdit?handler=ConfirmationView\",\n validateKit: \"/api/productkit/validatekit\",\n validations: \"/api/productkit/validations\",\n increase: \"/api/productkit/increase\",\n decrease: \"/api/productkit/decrease\",\n addToCart: \"/api/productkit/addtocart\",\n updateToCart: \"/api/productkit/updateToCart\",\n setQuantity: \"/api/productkit/setquantity\",\n increaseKit: \"/api/productkit/increasekit\",\n decreaseKit: \"/api/productkit/decreasekit\",\n setKitQuantity: \"/api/productkit/setkitquantity\"\n }\n\n constructor() {\n super();\n }\n\n getView(productBranchOfficeId, preventCache = false, internalId = null) {\n return AjaxProxy.getFetch(`${this._endpoints.getView}/${productBranchOfficeId}?preventCache=${preventCache}&internalId=${internalId}`, {});\n }\n\n getConfirmationView(internalId) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n return AjaxProxy.postFetch(`${this._endpoints.getConfirmationView}`, { body: form });\n }\n\n validateKit(productBranchOfficeId) {\n const form = new FormData();\n form.append(\"productBranchOfficeId\", productBranchOfficeId);\n return AjaxProxy.postFetch(this._endpoints.validateKit, { body: form});\n }\n\n validations(productBranchOfficeId, internalId) {\n const form = new FormData();\n form.append(\"productBranchOfficeId\", productBranchOfficeId);\n form.append(\"internalId\", internalId);\n return AjaxProxy.postFetch(this._endpoints.validations, { body: form });\n }\n\n increase(productInternalId, internalId) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n form.append(\"productInternalId\", productInternalId);\n return AjaxProxy.postFetch(this._endpoints.increase, { body: form });\n }\n\n decrease(productInternalId, internalId) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n form.append(\"productInternalId\", productInternalId);\n return AjaxProxy.postFetch(this._endpoints.decrease, { body: form });\n }\n\n setQuantity(productInternalId, internalId, quantity) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n form.append(\"productInternalId\", productInternalId);\n form.append(\"quantity\", quantity);\n return AjaxProxy.postFetch(this._endpoints.setQuantity, { body: form });\n }\n\n /**\n * \n * @param {string} productBranchOfficeId\n * @param {string} internalId\n * @returns\n */\n addToCart(productBranchOfficeId, internalId, quantity) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n form.append(\"productBranchOfficeId\", productBranchOfficeId);\n form.append(\"quantity\", quantity);\n return AjaxProxy.postFetch(this._endpoints.addToCart, { body: form });\n }\n\n /**\n * \n * @param {string} internalId\n * @returns\n */\n updateToCart(productBranchOfficeId, internalId, quantity) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n form.append(\"productBranchOfficeId\", productBranchOfficeId);\n form.append(\"quantity\", quantity)\n return AjaxProxy.postFetch(this._endpoints.updateToCart, { body: form });\n }\n\n increaseKit(internalId) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n return AjaxProxy.postFetch(this._endpoints.increaseKit, { body: form });\n }\n\n decreaseKit(internalId) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n return AjaxProxy.postFetch(this._endpoints.decreaseKit, { body: form });\n }\n\n setKitQuantity(internalId, quantity) {\n const form = new FormData();\n form.append(\"internalId\", internalId);\n form.append(\"quantity\", quantity);\n return AjaxProxy.postFetch(this._endpoints.setKitQuantity, { body: form });\n }\n}","import { Subject } from 'rxjs'\n\nexport class AddProductKitBannerEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{productId: string, loadingTarget: HTMLElement}} args\n */\n addProductKitToCart(args) {\n this._subject.next({\n productBranchOfficeId: args.productId,\n loadingTarget: args.loadingTarget\n });\n }\n}\n\nconst event = new AddProductKitBannerEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class LoadCheckoutEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n */\n loaded() {\n this._subject.next();\n }\n}\n\nconst event = new LoadCheckoutEvent();\nexport default event;","import { Subject } from 'rxjs'\n\nexport class LoadProductKitViewEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{loadingTarget: HTMLElement | JQuery, productBranchOfficeId: string, internalId: string, validateKit: boolean}} args\n */\n load(args) {\n this._subject.next({\n loadingTarget: args.loadingTarget,\n productBranchOfficeId: args.productBranchOfficeId,\n internalId: args.internalId,\n validateKit: args.validateKit\n });\n }\n}\n\nconst event = new LoadProductKitViewEvent();\nexport default event;","import { HandlerBase } from \"../../handler/handler-base\"\nimport ShoppingCartHandlers from \"../../shopping-cart/handlers/shopping-cart-handlers\";\nimport LoadProductKitViewEvent from \"../events/load-product-kit-view-event\"\nimport ProductHelper from \"../../../helpers/product-helper\";\nimport { fromEvent } from \"rxjs\"\nimport { filter } from \"rxjs/operators\"\n\nexport class ProductKitShoppingCartHandlers extends HandlerBase {\n\n isBusy = false;\n\n get _viewContentShoppingCartButton() {\n return $(\".product__kit-content\");\n }\n\n constructor() {\n super();\n\n this._shoppingCartHandlers = new ShoppingCartHandlers();\n }\n\n init() {\n this._shoppingCartHandlers._loadedEvent$.subscribe(async _ => {\n this._bindShoppingCartControls();\n })\n }\n\n _bindShoppingCartControls() {\n fromEvent(this._viewContentShoppingCartButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async (e) => {\n\n const parent = $(e.currentTarget).parent();\n const shoppingCartContainer = this._shoppingCartHandlers._shoppingCartContainer[0];\n const productBranchOfficeId = ProductHelper.getProductId(parent);\n const internalId = ProductHelper.getInternalId(parent);\n\n LoadProductKitViewEvent.load({\n internalId: internalId,\n loadingTarget: shoppingCartContainer, \n productBranchOfficeId: productBranchOfficeId,\n validateKit: false\n })\n });\n }\n}","import \"jquery\"\n\nexport class ProductKitHelpers {\n static get _dynamicKitModal() {\n return $(\"#product-dynamic-kit-modal\").data(\"kendoDialog\");\n }\n\n static get _dynamicKitCollapse() {\n return $('#product-kit__content');\n }\n\n /**\n * \n * @param {JQuery.EventBase} e\n * @returns\n */\n static getKitItem(e) {\n return $(e.currentTarget).closest('.product-kit__content-item')\n }\n\n static get _loadingTarget() {\n return \"div.k-widget.k-window.k-dialog\";\n }\n\n static get _form(){\n return $(\"#product-kit-form\");\n }\n\n static get _productInternalId() {\n return this._dynamicKitModal.element.find(`[name=\"ProductKit.ProductInformation.InternalId\"]`).val();\n }\n\n static get _productBranchOfficeId() {\n return this._dynamicKitModal.element.find(`[name=\"ProductBranchOfficeId\"]`).val();\n }\n\n static get _totalAmount() {\n return this._dynamicKitModal.element.find(`.product-kit__totals > span`)\n }\n\n /**\n * \n * @param {JQuery} kitItemElement \n */\n static _getKitInternalId(kitItemElement) {\n return kitItemElement.find(`[name=\"KitComponent[][KitInternalId]\"]`).val()\n }\n\n static get _productQuantity() {\n return $(\"#ProductKit_Quantity\")\n }\n \n}","import { Subject } from 'rxjs'\n\nexport class ProductKitSetupQuantityEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{kitItemElement: JQuery, productKitResponse: {} }} args\n */\n setup(args) {\n this._subject.next({\n kitItemElement: args.kitItemElement,\n productKitResponse: args.productKitResponse\n });\n }\n}\n\nconst event = new ProductKitSetupQuantityEvent();\nexport default event;","import { HandlerBase } from \"../../handler/handler-base\"\nimport { ProductKitHelpers } from \"../helpers/product-kit-helpers\"\nimport ProductKitSetupQuantityEvent from \"../events/product-kit-setup-quantity-event\"\nimport { DynamicKitService } from \"../services/dynamic-kit-service\";\nimport { fromEvent } from \"rxjs\"\nimport { filter } from \"rxjs/operators\"\n\nexport class ProductKitComponentsHandlers extends HandlerBase {\n\n get _dynamicKitModal() {\n return ProductKitHelpers._dynamicKitModal;\n }\n\n get _loadingTarget() {\n return ProductKitHelpers._loadingTarget;\n }\n\n get _moreButton() {\n return this._dynamicKitModal.element.find(`.controls__more`);\n }\n\n get _lessButton() {\n return this._dynamicKitModal.element.find(`.controls__less`);\n }\n\n get _controlNumber() {\n return this._dynamicKitModal.element.find(`.kit-controls__number`);\n }\n\n get _totalAmount() {\n return ProductKitHelpers._totalAmount;\n }\n\n get _productInternalId() {\n return ProductKitHelpers._productInternalId;\n }\n \n constructor() {\n super();\n\n this._dynamicKitService = new DynamicKitService();\n }\n\n init() {\n\n //more button\n fromEvent(this._moreButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async e => {\n const kitItemElement = this._getKitItem(e);\n this._loading(true, this._loadingTarget);\n try {\n await this._setupQuantity(\"increase\", kitItemElement)\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false, this._loadingTarget);\n }\n })\n\n //less button\n fromEvent(this._lessButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async e => {\n const kitItemElement = this._getKitItem(e);\n\n this._loading(true, this._loadingTarget);\n try {\n await this._setupQuantity(\"decrease\", kitItemElement)\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false, this._loadingTarget);\n }\n })\n\n this._controlNumber.off('click');\n this._controlNumber.on('click', this.switchToInput.bind(this));\n\n ProductKitHelpers._dynamicKitCollapse.on(\"shown.bs.collapse\", _ => {\n this._dynamicKitModal.center();\n })\n\n ProductKitHelpers._dynamicKitCollapse.on(\"hidden.bs.collapse\", _ => {\n this._dynamicKitModal.center();\n })\n }\n\n /**\n * \n * @param {JQuery.EventBase} event\n */\n switchToInput(event) {\n var $input = $(\"\", {\n val: $(event.currentTarget).text(),\n type: \"number\",\n min: 1\n });\n $input.addClass(\"cart-number-input\");\n const kitItemElement = this._getKitItem(event);\n $(event.currentTarget).replaceWith($input);\n $input.on(\"blur\", { kitItemElement: kitItemElement }, this.switchToSpan.bind(this));\n $input.select();\n }\n\n /**\n * \n * @param {JQuery.EventBase} event\n */\n switchToSpan(event) {\n let quantityElement = $(event.currentTarget);\n let productQuantityElement = quantityElement.val();\n\n var $span = $(\"\", {\n text: productQuantityElement\n });\n\n $span.addClass(\"kit-controls__number\");\n $(event.currentTarget).replaceWith($span);\n $span.on(\"click\", this.switchToInput.bind(this));\n\n this._setQuantity(event.data.kitItemElement, productQuantityElement).then(_ => { })\n }\n\n /**\n * \n * @param {JQuery} kitItemElement\n * @param {number} quantity\n */\n async _setQuantity(kitItemElement, quantity) {\n this._loading(true, this._loadingTarget);\n try {\n await this._setupQuantity(\"setQuantity\", kitItemElement, quantity)\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false, this._loadingTarget);\n }\n }\n\n /**\n * \n * @param {\"decrease\" | \"increase\" | \"setQuantity\"} operation\n * @param {JQuery} kitItemElement\n * @param {number} [quantity=0] \n * @returns\n */\n async _setupQuantity(operation, kitItemElement, quantity = 0) {\n const productInternalId = this._productInternalId;\n const kitInternalId = this._getKitInternalId(kitItemElement);\n\n /**@type {Response}*/\n let response = null;\n switch (operation) {\n case \"decrease\":\n response = await this._dynamicKitService.decrease(productInternalId, kitInternalId);\n break;\n case \"increase\":\n response = await this._dynamicKitService.increase(productInternalId, kitInternalId)\n break;\n case \"setQuantity\":\n response = await this._dynamicKitService.setQuantity(productInternalId, kitInternalId, quantity)\n break;\n }\n\n if (!response.ok) {\n return;\n }\n\n const productKitResponse = await response.json();\n\n if (productKitResponse.Successful) {\n this.updateKitComponentQuantity(kitItemElement, productKitResponse.KitQuantity);\n this.updateTotalAmount(productKitResponse.TotalAmountFormatted);\n\n ProductKitSetupQuantityEvent.setup({\n kitItemElement: kitItemElement,\n productKitResponse: productKitResponse\n })\n }\n else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage,\n html: true\n })\n }\n }\n\n /**\n * \n * @param {number} totalAmount\n */\n updateTotalAmount(totalAmount) {\n this._totalAmount.text(totalAmount);\n }\n\n /**\n * \n * @param {JQuery} kitItemElement\n * @param {number} quantity\n */\n updateKitComponentQuantity(kitItemElement, quantity) {\n kitItemElement.find(`[name=\"KitComponent[][Quantity]\"]`).val(quantity);\n kitItemElement.find(`.kit-controls__number`).text(quantity);\n }\n\n /**\n * \n * @param {Event} e\n * @returns\n */\n _getKitItem(e) {\n return ProductKitHelpers.getKitItem(e);\n }\n\n /**\n * \n * @param {JQuery} kitItemElement \n */\n _getKitInternalId(kitItemElement) {\n return ProductKitHelpers._getKitInternalId(kitItemElement);\n }\n\n}","import { HandlerBase } from \"../../handler/handler-base\"\nimport { ProductKitHelpers } from \"../helpers/product-kit-helpers\"\nimport { DynamicKitService } from \"../services/dynamic-kit-service\";\nimport { fromEvent } from \"rxjs\"\nimport { filter } from \"rxjs/operators\"\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service\"\n\nexport class ProductKitConfirmationHandlers extends HandlerBase {\n\n get _increaseKitQuantityButton() {\n return $(\".quantity--increase\");\n }\n\n get _decreaseKitQuantityButton() {\n return $(\".quantity--decrease\")\n }\n\n get _quantityElement() {\n return $(\".quantity--display\")\n }\n\n get _quantityInput() {\n return ProductKitHelpers._productQuantity\n }\n \n get _form() {\n return ProductKitHelpers._form;\n }\n\n get _productInternalId() {\n return ProductKitHelpers._productInternalId;\n }\n\n get _confirmationContainer() {\n return $(\"#product-kit__confirmation-wrapper\");\n }\n\n get _loadingTarget() {\n return ProductKitHelpers._loadingTarget;\n }\n\n get _totalAmount() {\n return $(\".product-kit-detail__price > span\");\n }\n \n constructor() {\n super();\n\n this._dynamicKitService = new DynamicKitService();\n this._browserCommunicatorService = new BrowserCommunicatorService();\n }\n\n init() {\n this._loadConfirmationView().then(_ => {\n this._bindControls();\n })\n }\n\n _bindControls() {\n // increase kit quantity\n fromEvent(this._increaseKitQuantityButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async e => {\n const internaId = this._productInternalId;\n await this._setupQuantity(\"increase\", internaId);\n })\n\n // decrease kit quantity\n fromEvent(this._decreaseKitQuantityButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async e => {\n const internaId = this._productInternalId;\n await this._setupQuantity(\"decrease\", internaId);\n })\n\n // set quantity\n this._quantityElement.off('click');\n this._quantityElement.on('click', this.switchToInput.bind(this));\n }\n\n /**\n * \n * @param {JQuery.EventBase} event\n */\n switchToInput(event) {\n var $input = $(\"\", {\n val: $(event.currentTarget).text(),\n type: \"number\",\n min: 1\n });\n $input.addClass(\"quantity_display-input\");\n $(event.currentTarget).replaceWith($input);\n $input.on(\"blur\", this.switchToSpan.bind(this));\n $input.trigger(\"select\");\n }\n\n /**\n * \n * @param {JQuery.EventBase} event\n */\n switchToSpan(event) {\n let quantityElement = $(event.currentTarget);\n let productQuantityElement = quantityElement.val();\n\n var $span = $(\"\", {\n text: productQuantityElement\n });\n\n $span.addClass(\"button button--secondary-reverse quantity--display\");\n $(event.currentTarget).replaceWith($span);\n $span.on(\"click\", this.switchToInput.bind(this));\n\n this._setupQuantity(\"setQuantity\", this._productInternalId, productQuantityElement)\n }\n\n /**\n * \n * @param {\"increase\" | \"decrease\" | \"setQuantity\"} operation\n * @param {string} internalId \n * @param {number} [quantity=0] \n */\n async _setupQuantity(operation, internalId, quantity = 0) {\n this._loading(true, this._loadingTarget);\n try {\n let response;\n switch (operation) {\n case \"setQuantity\":\n response = await this._dynamicKitService.setKitQuantity(internalId, quantity);\n break;\n case \"decrease\":\n response = await this._dynamicKitService.decreaseKit(internalId);\n break;\n case \"increase\":\n response = await this._dynamicKitService.increaseKit(internalId);\n break;\n default:\n throw new Error(\"Operation no avaliable !!\")\n }\n\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage\n })\n return;\n }\n\n this._quantityElement.html(json.KitQuantity);\n this._quantityInput.val(json.KitQuantity);\n this._totalAmount.text(json.TotalAmountFormatted)\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false, this._loadingTarget);\n }\n }\n\n async _loadConfirmationView() {\n this._loading(true, this._loadingTarget);\n try {\n const internalId = this._productInternalId;\n const response = await this._dynamicKitService.getConfirmationView(internalId);\n if (!response.ok) {\n return;\n }\n\n const html = await response.text();\n this._confirmationContainer.html(html);\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false, this._loadingTarget);\n }\n }\n\n}","import { HandlerBase } from \"../../handler/handler-base\"\nimport { fromEvent } from \"rxjs\"\nimport { filter } from \"rxjs/operators\"\nimport { DynamicKitService } from \"../services/dynamic-kit-service\";\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service\"\nimport AddProductKitSearchEvent from \"../events/add-product-kit-search-event\"\nimport AddProductKitBannerEvent from \"../events/add-product-kit-banner-event\"\nimport ProductHelper from \"../../../helpers/product-helper\";\nimport LoadedCheckoutEvent from \"../../../checkout/events/load-checkout-event\"\nimport AddedProductKitEvent from \"../events/added-product-kit-event\"\nimport LoadProductKitViewEvent from \"../events/load-product-kit-view-event\"\nimport { ProductKitShoppingCartHandlers } from \"./product-kit-shopping-cart-handlers\"\nimport { ProductKitComponentsHandlers } from \"./product-kit-components-handlers\"\nimport { ProductKitConfirmationHandlers } from \"./product-kit-confirmation-handlers\"\nimport { ProductKitHelpers } from \"../helpers/product-kit-helpers\"\nimport ProductKitSetupQuantityEvent from \"../events/product-kit-setup-quantity-event\"\nimport { WizardForm } from \"../../../components/wizard/wizard-form\";\nimport \"kendo-ui\"\n\nexport class DynamicKitHandlers extends HandlerBase {\n\n get _addDynamicKitButton() {\n return $(\".add-dynamic-kit\");\n }\n\n get _addDynamicKitDetailButton() {\n return $(\".add-dynamic-kit-detail\");\n }\n\n get _addDynamicKitDetailLink() {\n return $(\".product-card__body--kit-add\");\n }\n\n get _dynamicKitModal() {\n return ProductKitHelpers._dynamicKitModal\n }\n\n get _dynamicKitModalTitle() {\n return this._dynamicKitModal.element.find(`#product-kit-title`);\n }\n\n get _dynamicKitModalConfirmLabel() {\n return this._dynamicKitModal.element.find(`#product-kit-confirm-label`);\n }\n\n get _dynamicKitModalCancelLabel() {\n return this._dynamicKitModal.element.find(`#product-kit-cancel-label`);\n }\n\n get _dynamicKitModalContinuelLabel() {\n return this._dynamicKitModal.element.find(`#product-kit-continue-label`);\n }\n\n get _dynamicKitModalBacklLabel() {\n return this._dynamicKitModal.element.find(`#product-kit-back-label`);\n }\n \n get _productBranchOfficeId() {\n return ProductKitHelpers._productBranchOfficeId;\n }\n\n get _productInternalId() {\n return ProductKitHelpers._productInternalId;\n }\n \n get _viewContentOrderButton() {\n return $(\".product__kit-content-order\");\n }\n\n get _isEdit() {\n const val = this._dynamicKitModal.element.find(`#IsEdit`).val();\n if (val === \"True\") {\n return true;\n } else if (val === \"False\") {\n return false;\n } else {\n return false;\n }\n }\n\n get _addDynamicKitFromSearchEvent() {\n return AddProductKitSearchEvent.event$;\n }\n\n get _addDynamicKitFromBannerEvent() {\n return AddProductKitBannerEvent.event$;\n }\n\n get _loadedCheckoutEvent() {\n return LoadedCheckoutEvent.event$;\n }\n\n get _loadProductKitViewEvent() {\n return LoadProductKitViewEvent.event$;\n }\n\n get _setupQuantityEvent() {\n return ProductKitSetupQuantityEvent.event$;\n }\n\n get _form() {\n return ProductKitHelpers._form;\n }\n\n get _productQuantityValue() {\n return ProductKitHelpers._productQuantity.val();\n }\n \n _loadingTarget = \"div.k-widget.k-window.k-dialog\"\n \n constructor() {\n super();\n\n this._dynamicKitService = new DynamicKitService();\n this._browserCommunicatorService = new BrowserCommunicatorService();\n this._productKitShoppingCartHandlers = new ProductKitShoppingCartHandlers();\n this._productKitComponentsHandlers = new ProductKitComponentsHandlers();\n this._productKitConfirmationHandlers = new ProductKitConfirmationHandlers();\n this._wizard = new WizardForm({\n nextButton: \".product-kit-next\",\n previousButton: \".product-kit-previous\",\n id: \"#product-kit-form\",\n scrollTop: false,\n onLeaveStep: async (stepNumber, direction, button) => {\n return await this._leaveStep(stepNumber, direction, button);\n },\n });\n }\n\n init() {\n\n this._productKitShoppingCartHandlers.init();\n\n fromEvent(this._addDynamicKitButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async (e) => {\n const productCard = this.getProductCard(e);\n const productBranchOfficeId = this.getProductBranchOfficeId(e);\n await this._loadDynamicKitView(productCard, productBranchOfficeId)\n\n this._updateQuantitySelected()\n });\n\n fromEvent(this._addDynamicKitDetailButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async e => {\n const productCard = this.getProductCardDetail(e);\n const productBranchOfficeId = this.getProductBranchOfficeIdDetail(e);\n await this._loadDynamicKitView(productCard, productBranchOfficeId);\n\n this._updateQuantitySelected()\n })\n\n fromEvent(this._addDynamicKitDetailLink, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async e => {\n e.preventDefault()\n const productCard = this.getProductCard(e);\n const productBranchOfficeId = this.getProductBranchOfficeId(e);\n await this._loadDynamicKitView(productCard, productBranchOfficeId);\n this._updateQuantitySelected()\n })\n\n this._addDynamicKitFromSearchEvent.subscribe(async e => {\n await this._loadDynamicKitView(e.loadingTarget, e.productBranchOfficeId);\n\n this._updateQuantitySelected()\n })\n\n this._addDynamicKitFromBannerEvent.subscribe(async e => {\n await this._loadDynamicKitView(e.loadingTarget, e.productBranchOfficeId);\n this._updateQuantitySelected()\n })\n\n this._loadedCheckoutEvent.subscribe(_ => {\n this.bindOrderControls();\n })\n\n this._loadProductKitViewEvent.subscribe(async args => {\n this._loading(true, this._loadingTarget);\n try {\n await this._loadDynamicKitView(args.loadingTarget, args.productBranchOfficeId, args.internalId, args.validateKit);\n this._updateQuantitySelected()\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false, this._loadingTarget);\n }\n })\n\n this._setupQuantityEvent.subscribe(_ => {\n this._updateQuantitySelected()\n })\n\n const destokMediaQuery = matchMedia(\"(max-width: 1024px)\");\n this.resizeModalWidth(destokMediaQuery.matches);\n\n destokMediaQuery.addEventListener(\"change\", e => {\n this.resizeModalWidth(e.matches);\n });\n }\n\n resizeModalWidth(matches) {\n if (matches) {\n this._dynamicKitModal?.setOptions({\n title: false,\n width: \"100%\",\n height: \"100%\"\n });\n }\n else {\n this._dynamicKitModal?.setOptions({\n title: false,\n width: 800,\n height: undefined,\n minHeight: 0,\n maxHeight: \"100%\"\n });\n\n }\n }\n\n _bindWizardForm() {\n this._wizard.init();\n }\n\n bindOrderControls() {\n fromEvent(this._viewContentOrderButton, \"click\").pipe(\n filter(_ => !this.isBusy)\n ).subscribe(async (e) => {\n const parent = $(e.currentTarget).parent();\n const productBranchOfficeId = ProductHelper.getProductId(parent);\n const internalId = ProductHelper.getInternalId(parent);\n\n await this._loadDynamicKitView(parent, productBranchOfficeId, internalId, false);\n\n this._updateQuantitySelected()\n });\n }\n\n async _leaveStep(stepNumber, direction, button) {\n \n if (direction == \"next\") {\n if (stepNumber == 1) {\n const isValid = await this._validateProductKit();\n if (!isValid) {\n return false;\n }\n \n // load kit confirmationview\n this._productKitConfirmationHandlers.init();\n }\n\n if (stepNumber == 2) {\n const confirm = await this.confirmKit()\n if (!confirm) {\n return false;\n }\n }\n }\n\n this._updateButtonDataStep(stepNumber, direction);\n\n return true;\n }\n\n /**\n * \n * @param {JQuery} modal\n * @param {any} stepNumber\n * @param {any} direction\n */\n _updateButtonDataStep(stepNumber, direction) {\n\n const previousButton = this._dynamicKitModal.element.parent().find(\".product-kit-previous\");\n const nextButton = this._dynamicKitModal.element.parent().find(\".product-kit-next\");\n\n if (stepNumber == 1 && direction == \"next\") {\n previousButton.removeClass(\"d-none\")\n previousButton.data(\"step\", stepNumber + 1)\n previousButton.text(this._dynamicKitModalBacklLabel.html())\n\n nextButton.data(\"step\", stepNumber + 1)\n nextButton.text(this._dynamicKitModalConfirmLabel.html())\n }\n\n if (stepNumber == 2 && direction == \"previous\") {\n nextButton.text(this._dynamicKitModalContinuelLabel.html())\n nextButton.data(\"step\", stepNumber - 1);\n\n previousButton.data(\"step\", -1)\n previousButton.text(this._dynamicKitModalCancelLabel.html())\n previousButton.addClass(\"d-none\")\n }\n }\n\n /**\n * Validate kit\n * @returns {boolean}\n */\n async _validateProductKit() {\n\n this._loading(true, this._loadingTarget)\n try {\n const internalId = this._productInternalId;\n const productBranchOfficeId = this._productBranchOfficeId;\n\n const response = await this._dynamicKitService.validations(productBranchOfficeId, internalId);\n\n if (!response.ok) {\n return false;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage,\n html: true\n })\n return false;\n }\n \n if (json.UserMessage) {\n await this._browserCommunicatorService.displaySuccessAlertAsync({\n description: json.UserMessage,\n html: true\n })\n }\n\n return true;\n } catch (e) {\n console.error(e);\n return false;\n } finally {\n this._loading(false, this._loadingTarget);\n }\n }\n \n /**\n * \n * @param {HTMLElement | JQuery} loadingTarget\n * @param {string} productBranchOfficeId\n * @param {string} internalId\n * @param {boolean} validateKit\n * @returns\n */\n async _loadDynamicKitView(loadingTarget, productBranchOfficeId, internalId = null, validateKit = true) {\n try {\n this._loading(true, loadingTarget);\n\n let validkit = true;\n if (validateKit) {\n const validKitResponse = await this.validateKit(productBranchOfficeId);\n\n if (!validKitResponse.successful) {\n validkit = false\n }\n\n if (validKitResponse.shownConfirm & !validKitResponse.isConfirmed) {\n validkit = false\n }\n }\n\n if (!validkit) {\n return;\n }\n\n const response = await this._dynamicKitService.getView(productBranchOfficeId, true, internalId);\n if (!response.ok) {\n return;\n }\n\n const modal = this._dynamicKitModal;\n\n //content\n const contentHtml = await response.text();\n modal.content(contentHtml)\n\n //title\n const title = this._dynamicKitModalTitle.text();\n modal.title(title)\n\n // set options\n modal.setOptions({\n title: false,\n open: _ => {\n // load components handlers\n this._productKitComponentsHandlers.init();\n\n this._dynamicKitModal.element.css(\"max-height\", \"100%\")\n this._dynamicKitModal.element.parent().css(\"max-height\", \"100%\")\n this._dynamicKitModal.element.scrollTop(0)\n this._dynamicKitModal.center();\n },\n actions: [\n {\n text: this._dynamicKitModalCancelLabel.html(),\n cssClass: \"button product-kit-previous d-none\",\n action: e => {\n return false;\n },\n },\n {\n text: this._dynamicKitModalContinuelLabel.html(),\n action: e => {\n return false;\n },\n cssClass: \"button button--primary product-kit-next action-button\"\n }\n ]\n })\n\n // header title\n modal.element.parent().find('.k-window-titlebar,.k-window-actions').addClass(\"modal-dialog-title\")\n\n // add data steps\n modal.element.parent().find(\".product-kit-next\").data(\"step\", 1);\n modal.element.parent().find(\".product-kit-previous\").data(\"step\", -1);\n\n //wizard events\n this._bindWizardForm();\n\n //open\n modal.open()\n\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false, loadingTarget);\n }\n }\n\n /**\n * \n * @returns {boolean}\n */\n async confirmKit() {\n this._loading(true, this._loadingTarget);\n try {\n\n const internalId = this._productInternalId;\n const productBranchOfficeId = this._productBranchOfficeId;\n const isEdit = this._isEdit;\n const quantity = this._productQuantityValue;\n\n /** @type {Response}*/\n let response;\n if (isEdit) {\n response = await this._dynamicKitService.updateToCart(productBranchOfficeId, internalId, quantity)\n } else {\n response = await this._dynamicKitService.addToCart(productBranchOfficeId, internalId, quantity);\n }\n\n if (!response.ok) {\n return false;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage,\n html: true\n })\n return false;\n }\n\n if (json.UserMessage) {\n await this._browserCommunicatorService.displaySuccessAlertAsync({\n description: json.UserMessage,\n html: true\n })\n }\n\n this._dynamicKitModal.close();\n\n AddedProductKitEvent.added({\n productId: productBranchOfficeId,\n internalId: internalId,\n shoppingCartItemChanged: json.ShoppingCartItemChanged,\n productKit: json.Entity\n })\n\n return true;\n\n } catch (e) {\n console.error(e);\n return false;\n } finally {\n this._loading(false, this._loadingTarget);\n }\n }\n\n _updateQuantitySelected() {\n let gifts = 0\n let regular = 0\n\n $(\".product-kit__content-item\").each(function (index, item) {\n const isRegular = $(item).children(`[name=\"KitComponent[][IsRegular]\"]`).val()\n const isGift = $(item).children(`[name=\"KitComponent[][IsGift]\"]`).val()\n let qty = Number.parseInt($(item).children(`[name=\"KitComponent[][Quantity]\"]`).val())\n\n if (isGift === \"True\") {\n gifts += qty\n }\n\n if(isRegular === \"True\"){\n regular += qty\n }\n })\n\n $(\"#quantity-gift\").html(gifts)\n $(\"#quantity-regular\").html(regular)\n }\n \n async validateKit(productBranchOfficeId) {\n const response = await this._dynamicKitService.validateKit(productBranchOfficeId);\n if (!response.ok) {\n return {\n successful: false\n }\n }\n\n const json = await response.json();\n if (!json.Successful) {\n\n const result = await this._browserCommunicatorService.displayQuestionAlert({\n description: json.UserMessage,\n html: true\n });\n\n return {\n shownConfirm: true,\n isConfirmed: result.isConfirmed,\n successful: true\n }\n }\n else {\n return {\n shownConfirm: false,\n isConfirmed: false,\n successful: true\n }\n }\n }\n\n /**\n * \n * @param {Event} e\n * @returns\n */\n getProductCard(e) {\n return $(e.currentTarget).closest('.product-card')\n }\n\n /**\n * \n * @param {Event} e\n * @returns\n */\n getProductCardDetail(e) {\n return $(e.currentTarget).closest('.product-card-detail')\n }\n \n /**\n * \n * @param {Event} e\n */\n getProductBranchOfficeId(e) {\n return $(e.currentTarget).closest('.product-card').data(\"product\")\n }\n\n /**\n * \n * @param {Event} e\n */\n getProductBranchOfficeIdDetail(e) {\n return $(e.currentTarget).closest('.product-id-contaniner').data(\"product\")\n }\n\n /**\n * \n * @param {Event} e\n */\n getProductBranchOfficeIdSearch(e) {\n return $(e.currentTarget).data(\"product\")\n }\n \n}","export class StreetTypesHelper {\n /**\n * \n * @param options {{ stretTypeSelector: string, nomenclatureSelector: string, triggerNomenclature: boolean, nomenclatureFieldSelectors: string[]}}\n */\n static bindStreetTypeSelection(options) {\n\n async function enableNomenclatureFileds(enable) {\n await Promise.all(options.nomenclatureFieldSelectors.map(selector => {\n return new Promise((resolve, reject) => {\n $(selector).data(\"kendoTextBox\").enable(enable);\n resolve();\n });\n }));\n }\n\n async function onChange(e) {\n const nomenclatureTextBox = $(options.nomenclatureSelector).data(\"kendoTextBox\")\n const streetTypeDTO = e.sender.dataItem();\n if (!streetTypeDTO.Extra1) {\n nomenclatureTextBox.enable(false);\n } else {\n nomenclatureTextBox.enable(true)\n }\n\n if (streetTypeDTO && streetTypeDTO.RequiresNomenclature) {\n await enableNomenclatureFileds(true) \n } else {\n await enableNomenclatureFileds(false);\n } \n }\n\n const neighborHood = $(options.stretTypeSelector).data(\"kendoDropDownList\")\n neighborHood?.unbind(\"change\", onChange)\n neighborHood?.bind(\"change\", onChange)\n\n }\n\n /**\n * Validate the street inputs (Street, StreetIntersection and StreetNumber)\n * @param options {{input: JQuery, streetTypeTarget: string}}\n * @returns {boolean}\n */\n static validateStreetInput(options) {\n let streetType = $(options.streetTypeTarget).data(\"kendoDropDownList\").dataItem()\n let input = options.input\n if (streetType && streetType.RequiresNomenclature && !input.val()) {\n return false;\n } else {\n return true;\n }\n }\n}","import 'jquery'\nimport '@progress/kendo-ui'\n\nexport class NeighborhoodHelper {\n constructor() {\n\n }\n\n /**\n * \n * @param options {{ neighborhoodSelector: string, neighborhoodNameSelector: string, triggerNeighborhoodName: boolean}}\n */\n static bindNeighborhoodSelection(options) {\n \n let action = e => {\n const neighborhoodNameTextBox = $(options.neighborhoodNameSelector).data(\"kendoTextBox\")\n const neighborhoodDTO = e.sender.dataItem();\n\n if (neighborhoodDTO && neighborhoodDTO.RequiresUserDefinition) {\n neighborhoodNameTextBox.enable();\n } else {\n neighborhoodNameTextBox.enable(false);\n neighborhoodNameTextBox.value(\"\");\n if (options.triggerNeighborhoodName) {\n neighborhoodNameTextBox.trigger(\"change\");\n }\n }\n }\n\n const neighborHood = $(options.neighborhoodSelector).data(\"kendoDropDownList\")\n neighborHood?.unbind(\"change\", action)\n neighborHood?.bind(\"change\", action)\n }\n}","export class EmailValidationHelper {\n constructor() { }\n\n /**\n * \n * @param {string} email\n * @returns {boolean}\n */\n static validate(email) {\n let re = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n return re.test(email);\n }\n}","import { ServiceBase } from \"../../service/service-base\"\nimport AjaxProxy from \"../../../proxies/ajax-proxy\"\n\nexport class AddressManagementService extends ServiceBase {\n\n _endpoints = {\n getView: \"/Security/AddressManagement\",\n deleteAddressB2C: \"/Security/AddressManagement?handler=deleteb2c\",\n deleteAddressB2B: \"/Security/AddressManagement?handler=deleteb2b\",\n setCustomerAddressB2C: \"/Security/AddressManagement?handler=setcustomeraddressb2c\",\n setCustomerAddressB2B: \"/Security/AddressManagement?handler=setcustomeraddressb2b\",\n resetCustomerAddressB2C: \"/Security/AddressManagement?handler=resetcustomeraddressb2c\",\n saveCustomerAddressB2C: \"/Security/AddressManagement?handler=savecustomeraddressb2c\",\n saveBillingAddressB2C: \"/Security/AddressManagement?handler=savebillingaddressb2c\"\n }\n\n constructor() {\n super();\n }\n\n getView() {\n return AjaxProxy.getFetch(this._endpoints.getView, {});\n }\n\n deleteAddressB2C(addressId) {\n const data = new FormData();\n data.append(\"addressId\", addressId);\n return AjaxProxy.postFetch(this._endpoints.deleteAddressB2C, { body: data });\n }\n\n deleteAddressB2B(addressId, addressReferenceCode) {\n const data = new FormData();\n data.append(\"addressId\", addressId);\n data.append(\"addressReferenceCode\", addressReferenceCode);\n return AjaxProxy.postFetch(this._endpoints.deleteAddressB2B, { body: data });\n }\n\n setCustomerAddressB2CAsync(addressId, clearShoppingCart) {\n const data = new FormData();\n data.append(\"addressId\", addressId)\n data.append(\"clearShoppingCart\", clearShoppingCart)\n return AjaxProxy.postFetch(this._endpoints.setCustomerAddressB2C, { body: data });\n }\n\n setCustomerAddressB2BAsync(addressId, clearShoppingCart) {\n const data = new FormData();\n data.append(\"addressId\", addressId)\n data.append(\"clearShoppingCart\", clearShoppingCart)\n return AjaxProxy.postFetch(this._endpoints.setCustomerAddressB2B, { body: data });\n }\n\n resetCustomerAddressB2CAsync(clearShoppingCart) {\n const data = new FormData();\n data.append(\"clearShoppingCart\", clearShoppingCart)\n return AjaxProxy.postFetch(this._endpoints.resetCustomerAddressB2C, { body: data });\n }\n\n saveAddressB2CAsync(addressRequest) {\n const form_data = new FormData();\n for (var key in addressRequest) {\n if (addressRequest[key]) {\n form_data.append(`address.${key}`, addressRequest[key]);\n }\n }\n return AjaxProxy.postFetch(this._endpoints.saveCustomerAddressB2C, { body: form_data });\n }\n\n saveBillingAddressB2CAsync(signUpAddressB2C) {\n const form_data = new FormData();\n for (var key in signUpAddressB2C) {\n if (signUpAddressB2C[key]) {\n form_data.append(`billingAddress.${key}`, signUpAddressB2C[key]);\n }\n }\n return AjaxProxy.postFetch(this._endpoints.saveBillingAddressB2C, { body: form_data });\n }\n}","import ModalHelper from '../../../helpers/modal-helper';\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service\";\nimport CustomerService from '../../../services/customer-service';\nimport { $applicationMonitoringService } from \"../../application-monitoring\";\nimport { HandlerBase } from \"../../handler/handler-base\";\n\nexport class LegacyAddressHandlers extends HandlerBase {\n constructor() {\n super();\n\n this._customerService = new CustomerService();\n this._browserCommunicatorService = new BrowserCommunicatorService();\n }\n\n init() {\n this.bindAddressesView();\n }\n\n bindAddressesView() {\n $('#addressModal').on('show.bs.modal', (event) => {\n let button = $(event.relatedTarget); // Button that triggered the modal\n let isEdit = button.data('addressIsEdit');\n let address = {\n CustomerAddress: {},\n Identification: $('.customer-d-id').val(),\n IsEdit: isEdit\n };\n\n $('#addressModal .address-modal-title').text('Crear direcci\\u00F3n');\n\n if (isEdit === true) {\n $('#addressModal .address-modal-title').text('Editar direcci\\u00F3n');\n address.CustomerAddress.Neighborhood = { Id: button.data('addressNeighborhoodId') };\n address.CustomerAddress.City = { Id: button.data('addressCityId') };\n address.CustomerAddress.State = { Id: button.data('addressStateId') };\n address.CustomerAddress.IsLocked = button.data('addressIsLocked');\n address.CustomerAddress.PostalCode = button.data('addressPostalcode');\n address.CustomerAddress.Longitude = button.data('addressLongitude');\n address.CustomerAddress.Latitude = button.data(\"addressLatitude\");\n address.CustomerAddress.PaymTerm = button.data(\"addressPaymTerm\");\n address.CustomerAddress.Email = button.data(\"addressEmail\");\n address.CustomerAddress.MobileNumber = button.data(\"addressMobileNumber\");\n address.CustomerAddress.PhoneNumber = button.data(\"addressPhoneNumber\");\n address.CustomerAddress.Address = button.data(\"addressAddress\")\n address.CustomerAddress.ReferenceCode = button.data(\"addressReferenceCode\");\n address.CustomerAddress.CustomerId = button.data(\"addressCustomerId\");\n address.CustomerAddress.Id = button.data(\"addressId\");\n address.CustomerAddress.PositiveBalance = button.data(\"addressPositiveBalance\");\n }\n\n let modal = $('#addressModal');\n\n ModalHelper.clearBody(modal);\n var loadingContent = '
    Loading...
    ';\n ModalHelper.setHtmlBody(modal, loadingContent);\n this._customerService.getAddressView(address, (response) => {\n ModalHelper.clearBody(modal);\n ModalHelper.setHtmlBody(modal, response);\n\n this.bindAddressForm();\n });\n });\n }\n\n getCitiesByStateAddress(event) {\n var stateId = $(\"#stateId option:selected\").val();\n\n this._customerService.getCitiesByState(stateId, (response) => {\n if (response != null) {\n $(\"#cityId\").empty();\n $(\"#cityId\").append('');\n\n $.each(response, function (i, city) {\n $(\"#cityId\").append('');\n });\n\n this.getNeighborhoodsByCityAddress();\n }\n }, function (response) {\n });\n }\n\n getNeighborhoodsByCityAddress(event) {\n var cityId = $(\"#cityId option:selected\").val();\n\n this._customerService.getNeighborhoodsByCityId(cityId, (response) => {\n if (response != null) {\n\n $(\"#neighborhoodId\").empty();\n\n $(\"#neighborhoodId\").append('');\n\n $.each(response, function (i, neighborhood) {\n $(\"#neighborhoodId\").append('');\n });\n }\n }, function (response) {\n });\n }\n\n setAddress() {\n var address = '';\n var streetType = $('.account-customer-streeType').val();\n var streetNumber = $('.account-customer-streetNumber').val();\n var sideLine = $('.account-customer-sideLine').val();\n var sideLineNumber = $('.account-customer-sideLineNumber').val();\n\n address = address + streetType + ' ' + streetNumber;\n\n\n if ($.trim(sideLine) === '' && $.trim(sideLineNumber) !== '') {\n address = address + ' ' + $.trim(sideLineNumber);\n }\n else if ($.trim(sideLine) !== '' && $.trim(sideLineNumber) === '') {\n address = address + ' ' + $.trim(streetNumber);\n }\n else if ($.trim(sideLine) !== '' && $.trim(sideLineNumber) !== '') {\n address = address + ' #' + $.trim(sideLine) + '-' + $.trim(sideLineNumber);\n }\n\n $('#addressModal .account-customer-current-address').html($.trim(address));\n }\n\n bindAddressForm() {\n $('#stateId').off('change');\n $('#stateId').on('change', this.getCitiesByStateAddress.bind(this));\n\n $('#cityId').off('change');\n $('#cityId').on('change', this.getNeighborhoodsByCityAddress.bind(this));\n\n $('.account-customer-streeType').off('change');\n $('.account-customer-streeType').on('change', this.setAddress.bind(this));\n\n $('.account-customer-streetNumber').off('change');\n $('.account-customer-streetNumber').on('change', this.setAddress.bind(this));\n\n $('.account-customer-sideLine').off('change');\n $('.account-customer-sideLine').on('change', this.setAddress.bind(this));\n\n $('.account-customer-sideLineNumber').off('change');\n $('.account-customer-sideLineNumber').on('change', this.setAddress.bind(this));\n\n //evento para eliminar una dirección del usuario\n $('.delete-customer-address').on('click', async (event) => {\n event.stopPropagation();\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({ description: '¿Desea elimiar esta direcci\\u00F3n?' })\n if (confirmResult.isConfirmed) {\n $('.save-customer-address .spinner-border').removeClass(\"d-none\");\n $('.save-customer-address').prop('disabled', true);\n\n $('.delete-customer-address .spinner-border').removeClass(\"d-none\");\n $('.delete-customer-address').prop('disabled', true);\n\n var addressId = $('.account-customer-address-id').val();\n\n this._customerService.deleteAddress(addressId, async (response) => {\n if (response.Successful) {\n\n $('.addresses-wrapper ul').find('#' + addressId).fadeOutAndRemove();\n $('#addressModal').modal('hide');\n\n await this._browserCommunicatorService.displaySuccessAlertAsync({ description: 'La direcci\\u00F3n se ha eliminado correctamente.' })\n\n } else {\n await this._browserCommunicatorService.displayErrorAlert({ description: 'Ocurri\\u00F3 un error al borrar la direcci\\u00F3n, por favor intentalo nuevamente.' })\n }\n\n $('.save-customer-address .spinner-border').addClass(\"d-none\");\n $('.save-customer-address').prop('disabled', false);\n\n $('.delete-customer-address .spinner-border').addClass(\"d-none\");\n $('.delete-customer-address').prop('disabled', false);\n });\n }\n });\n\n //evento para guardar una dirección del usuario\n $('.save-customer-address').on('click', async (event) => {\n event.stopPropagation();\n\n // dispatch \"add_shipping_info\" analytics event\n try {\n $applicationMonitoringService\n .then(function (service) {\n service.trackAddShippingInfo(\n analytics.AnalyticsConstants.DefaultParameterValue,\n [],\n analytics.AnalyticsConstants.DefaultParameterValue,\n analytics.AnalyticsConstants.DefaultParameterValue,\n appConstants.currency)\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n\n var state = $(\".account-customer-state\");\n var city = $(\".account-customer-city\");\n var neighborhood = $(\".account-customer-neighborhood\");\n var neighborhoodName = $(\".account-customer-neighborhoodName\");\n var mobileNumber = $(\".account-customer-mobileNumber\");\n var currentAddress = $(\".account-customer-current-address\").html();\n\n if ($.trim(state.val()) == '' || $.trim(city.val()) == '') {\n await this._browserCommunicatorService.displayInfoAlert({ description: 'Debes seleccionar el Departamento y la Ciudad.' })\n return;\n }\n\n if ($.trim(neighborhood.val()) == '' && $.trim(neighborhoodName.val()) == '') {\n await this._browserCommunicatorService.displayInfoAlert({ description: 'Debes seleccionar o escribir tu barrio.' })\n return;\n }\n\n if ($.trim(currentAddress) == '' || $.trim(mobileNumber.val()) == '') {\n await this._browserCommunicatorService.displayInfoAlert({ description: 'Escribe tu dirección y el número de teléfono.' })\n return;\n }\n\n $('.save-customer-address .spinner-border').removeClass(\"d-none\");\n $('.save-customer-address').prop('disabled', true);\n\n var complement = $('.account-customer-complement');\n var phoneNumber = $('.account-customer-phoneNumber');\n var email = $('.account-customer-email');\n var addressId = $('.account-customer-address-id');\n var latitude = $('.account-customer-latitude');\n var longitude = $('.account-customer-longitude');\n var postalCode = $('.account-customer-postal-code');\n var customerId = $('.account-customer-id');\n var customerDId = $('.account-customer-d-id');\n\n var referenceCode = $('.account-customer-reference-code');\n var identification = customerDId.val();\n\n if ($.trim(currentAddress) !== '' && $.trim(currentAddress).indexOf('- ') !== -1) {\n var address = $.trim(currentAddress).substring(0, $.trim(currentAddress).indexOf('- '));\n\n currentAddress = $.trim(address);\n\n if ($.trim(complement) === '') {\n complement = $.trim($.trim(currentAddress).substring($.trim(currentAddress).indexOf('- ') + 2, $.trim(currentAddress).length));\n }\n }\n\n var addressSave = {\n Neighborhood: $(\".account-customer-neighborhood option:selected\").attr(\"id\"),\n NeighborhoodId: neighborhood.val(),\n City: $(\".account-customer-city option:selected\").attr(\"id\"),\n CityId: city.val(),\n State: $(\".account-customer-state option:selected\").attr(\"id\"),\n StateId: state.val(),\n PostalCode: postalCode.val(),\n Longitude: longitude.val(),\n NeighborhoodName: neighborhoodName.val(),\n Latitude: latitude.val(),\n Email: email.val(),\n PhoneNumber: phoneNumber.val(),\n MobileNumber: mobileNumber.val(),\n Address: currentAddress + \"@\" + $.trim($(\".account-customer-city option:selected\").text()) + \"@\" + $.trim(complement.val()), //string\n CustomerAccount: referenceCode.val(),\n IdentificationNumber: customerDId.val(),\n CustomerId: $('.customer-id').val(),\n };\n\n this._customerService.saveAddress(addressSave, async (response) => {\n if (!response.Successful) {\n $('.save-customer-address .spinner-border').addClass(\"d-none\");\n $('.save-customer-address').prop('disabled', false);\n await this._browserCommunicatorService.displayErrorAlert({ description: 'Ocurrrio un error al guardar la direcci\\u00F3n, por favor intenta nuevamente.' })\n return;\n }\n\n $(\".my-addresses .addresses__item\").remove();\n\n const numberFormat = new Intl.NumberFormat('es-CO', { style: 'currency', currency: 'COP' });\n\n if (response.addresses.length > 0) {\n $.each(response.addresses, function (i, item) {\n $('#addresses ul')\n .find(' > li:nth-last-child(1)')\n .before($(\"
  • \")\n .append(\"
    \" +\n \"\" + item.Name + \"\" +\n \"
    \" + item.Address + \"
    \" +\n \"
    Saldo a Favor: \" + numberFormat.format(item.PositiveBalance) + \"
    \" +\n \"\" + item.Description + \"\" +\n \"
    \")\n .append(\"\" +\n \"\" +\n \"\"));\n });\n }\n\n $('#addressModal').modal('hide');\n await this._browserCommunicatorService.displaySuccessAlertAsync({ description: 'La direcci\\u00F3n se ha guardado correctamente.' })\n $('.save-customer-address .spinner-border').addClass(\"d-none\");\n $('.save-customer-address').prop('disabled', false);\n });\n });\n }\n}","import { StreetTypesHelper } from '../../../helpers/streettypes-helper'\nimport { NeighborhoodHelper } from '../../../helpers/neighborhood-helper'\nimport { EmailValidationHelper } from \"../../../shared/helper/email-validation-helper.js\";\nimport { CustomerAnalyticsHelper } from \"../../../shared/helper/customer-analytics-helper\"\nimport { HandlerBase } from \"../../handler/handler-base\"\nimport { AddressManagementService } from \"../services/address-management-service\"\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service\"\nimport { fromEvent } from \"rxjs\"\nimport { $applicationMonitoringService } from '../../application-monitoring';\nimport { analytics } from 'apollo-web'\nimport { appConstants } from \"../../../enums/site-enum.js\";\nimport CustomerService from '../../../services/customer-service';\nimport LoadViewEvent from \"../events/load-view-event\"\nimport ModalHelper from '../../../helpers/modal-helper';\nimport { LegacyAddressHandlers } from \"./legacy-address-handlers\"\n\nexport class AddressManagementHandler extends HandlerBase {\n\n get _addressListContainer() {\n return $(\".address-list-container\");\n }\n\n get _addressListContainerMyAccount() {\n return $(\".addresses__list-container\");\n }\n\n get _addressContainerIsVisible() {\n return this._addressListContainer.hasClass(\"is-visible\")\n }\n\n get _deleteAddressb2cButton() {\n return $('.delete-customer-address-b2c');\n }\n\n get _deleteAddressb2bButton() {\n return $('.delete-customer-address-b2b');\n }\n\n get _seletedAddressb2cButton() {\n return $('.selected-customer-address-b2c');\n }\n\n get _saveAddressb2cButton() {\n return $('.save-customer-address-b2c');\n }\n\n get _billingAddressModal() {\n return $('#billingAddress');\n }\n\n get _saveBillingAddressButton() {\n return $(\"#saveBillingAddress\");\n }\n\n get $loadEvent() {\n return LoadViewEvent.event$\n }\n\n get _seletedAddressb2bButton() {\n return $('#principalAddress');\n }\n \n _addressValidationKey = \"ErrorAddressValidation\";\n\n /** @type {[]}*/\n _addressViewB2CSubs = [];\n\n /** @type {[]}*/\n _addressViewB2BSubs = [];\n \n constructor() {\n super()\n\n this._addressManagementService = new AddressManagementService();\n this._browserCommunicatorService = new BrowserCommunicatorService();\n this._customerService = new CustomerService();\n this._legacyAddressHandlers = new LegacyAddressHandlers();\n }\n\n init() {\n this.bindAddressesViewB2C({ insertIcons: true });\n this.bindBillingAddressView();\n this._legacyAddressHandlers.init()\n\n this.$loadEvent.subscribe(async _ => {\n await this.loadViewAsync(false);\n })\n }\n\n setBillingAddressValidation() {\n if ($(\"[data-name=address-root-data]\").length > 0) {\n $.data(document.body, this._addressValidationKey, false);\n const streetTypeTarget = `[name=\"BillingAddress_StreetType\"]`\n $(\"[data-name=address-root-data]\").kendoValidator({\n rules: {\n\n fieldFirstName: (input) => {\n if (input.is(\"#BillingAddress_FirstName\")) {\n if ($.trim($(\"#BillingAddress_FirstName\").val()) === '') {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true;\n },\n\n fieldSurname: (input) => {\n if (input.is(\"#BillingAddress_Surname\")) {\n if ($.trim($(\"#BillingAddress_Surname\").val()) === '') {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true;\n },\n\n fieldState: (input) => {\n if (input.is(\"#BillingAddress_StateId\")) {\n if ($.trim($(\"#BillingAddress_StateId\").val()) === '') {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true;\n },\n\n fieldCity: (input) => {\n if (input.is(\"#BillingAddress_CityId\")) {\n if ($.trim($(\"#BillingAddress_CityId\").val()) === '') {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true;\n },\n\n fieldStreetNeighborhood: function (input) {\n if (input.is(`#BillingAddress_NeighborhoodName`)) {\n let neighborhoodName = input.val()\n let neighborhoodId = $(`#BillingAddress_NeighborhoodId`)?.val()\n\n if ((!neighborhoodId || neighborhoodId === '00000000-0000-0000-0000-000000000000') && !neighborhoodName) {\n return false;\n }\n else {\n return true;\n }\n } else {\n return true;\n }\n },\n\n fieldSaveAddressAs: (input) => {\n if (input.is(\"#BillingAddress_SaveAddressAs\")) {\n if ($.trim($(\"#BillingAddress_SaveAddressAs\").val()) === '') {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true;\n },\n\n fieldReceiveAcceptTerms: (input) => {\n if (input.is(\"#BillingAddress_AcceptTerms\")) {\n if (!$(\"#BillingAddress_AcceptTerms\").is(\":checked\")) {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true\n },\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n fieldStreetType: function (input) {\n if (input.is(`[name=\"BillingAddress_StreetType\"]`)) {\n if (!input.val()) {\n return false;\n } else {\n return true;\n }\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredStreetComplement: function (input) {\n if (input.is(`[name=\"BillingAddress_Complement\"]`)) {\n let complement = input.val()\n let streetType = $(`[name=\"BillingAddress_StreetType\"]`).data(\"kendoDropDownList\").dataItem()\n if ((streetType && !streetType.RequiresNomenclature) && !complement) {\n return false;\n } else {\n return true;\n }\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredStreet: function (input) {\n if (input.is(`[name=\"BillingAddress_Street\"]`)) {\n return StreetTypesHelper.validateStreetInput({\n input: input,\n streetTypeTarget: streetTypeTarget\n })\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredStreetIntersection: function (input) {\n if (input.is(`[name=\"BillingAddress_StreetIntersection\"]`)) {\n return StreetTypesHelper.validateStreetInput({\n input: input,\n streetTypeTarget: streetTypeTarget\n })\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredStreetNumber: function (input) {\n if (input.is(`[name=\"BillingAddress.StreetNumber\"]`)) {\n let streetType = $(`[name=\"BillingAddress.StreetType\"]`).data(\"kendoDropDownList\").dataItem()\n if (streetType.RequiresNomenclature && !input.val()) {\n console.log(false)\n return false;\n } else {\n return true;\n }\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery {\n\n $(\"#BillingAddress_StreetIntersection\").siblings(\"span\").remove();\n $(\"#BillingAddress_StreetNumber\").siblings(\"span\").remove();\n\n $(\"#BillingAddress_StreetIntersection\").parent().prepend('');\n $(\"#BillingAddress_StreetNumber\").parent().prepend('');\n\n NeighborhoodHelper.bindNeighborhoodSelection({\n neighborhoodSelector: '#BillingAddress_NeighborhoodId',\n neighborhoodNameSelector: '#BillingAddress_NeighborhoodName',\n triggerNeighborhoodName: true\n })\n\n StreetTypesHelper.bindStreetTypeSelection({\n stretTypeSelector: '#BillingAddress_StreetType',\n nomenclatureSelector: '#BillingAddress_Complement',\n nomenclatureFieldSelectors: ['#BillingAddress_Street', '#BillingAddress_StreetIntersection', '#BillingAddress_StreetNumber'],\n triggerNomenclature: true\n })\n\n this.setBillingAddressValidation();\n\n });\n \n this.setBillingAddressValidation();\n\n // save button\n fromEvent(this._saveBillingAddressButton, \"click\").subscribe(async e => {\n e.preventDefault();\n const spinnerWait = $(e.currentTarget).find(\".spinner-border-sm\").eq(0);\n await this._saveAddressBilling(spinnerWait);\n })\n }\n\n /**\n * \n * @param {JQuery} spinnerWait\n * @returns\n */\n async _saveAddressBilling(spinnerWait) {\n const formTargetEl = \"[data-name=address-root-data]\"\n const formValidator = $(formTargetEl).data(\"kendoValidator\");\n formValidator.reset()\n\n var addressValidation = formValidator.validate();\n\n if (addressValidation == false || $.trim($(\"#BillingAddress_SaveAddressAs\").val()) == \"\") {\n await this._browserCommunicatorService.displayInfoAlert({\n description: \"Debes ingresar los datos marcados con \\\"*\\\".\"\n })\n return;\n }\n\n try {\n this._loadingBillingForm(true);\n spinnerWait.removeClass(\"d-none\");\n\n var stateSelected = $(\"#BillingAddress_StateId\").data(\"kendoDropDownList\").dataItem();\n var citySelected = $(\"#BillingAddress_CityId\").data(\"kendoDropDownList\").dataItem();\n var cityName = citySelected.CityName;\n var branchOfficeId = citySelected.BranchOfficeId;\n var branchOfficeReferenceCode = citySelected.BranchOfficeReferenceCode;\n var neighborhoodSelected = $(\"#BillingAddress_NeighborhoodId\").data(\"kendoDropDownList\").dataItem();\n\n var complement = $.trim($(\"#BillingAddress_Complement\").val());\n var intersection = $(\"#BillingAddress_StreetIntersection\").val();\n var streetNumber = $(\"#BillingAddress_StreetNumber\").val();\n\n var stree = $(\"#BillingAddress_StreetType\").val() + \" \" + $(\"#BillingAddress_Street\").val();\n var plate = (intersection.length != 0 && streetNumber.length != 0) ? `#${intersection}-${streetNumber}` : \"\";\n let address = `${plate} @${cityName} @${complement}`;\n\n let streetType = $(`#BillingAddress_StreetType`).data(\"kendoDropDownList\").dataItem()\n if (streetType.RequiresNomenclature) {\n address = `${stree} ${address}`\n }\n\n var firstName = $(\"#BillingAddress_FirstName\").data(\"kendoTextBox\").value();\n var secondName = $(\"#BillingAddress_SecondName\").data(\"kendoTextBox\").value();\n var surname = $(\"#BillingAddress_Surname\").data(\"kendoTextBox\").value();\n var secondSurname = $(\"#BillingAddress_SecondSurname\").data(\"kendoTextBox\").value();\n var neighborhoodName = $(\"#BillingAddress_NeighborhoodName\").data(\"kendoTextBox\").value();\n\n const signUpAddressB2C = {\n FirstName: firstName.toUpperCase(),\n SecondName: secondName.toUpperCase(),\n Surname: surname.toUpperCase(),\n SecondSurname: secondSurname.toUpperCase(),\n StateId: stateSelected !== undefined ? stateSelected.Id : null,\n State: stateSelected !== undefined ? stateSelected.Code : null,\n CityId: citySelected !== undefined ? citySelected.CityId : null,\n City: citySelected !== undefined ? citySelected.Code : null,\n StreetType: $(\"#BillingAddress_StreetType\").data(\"kendoDropDownList\").value(),\n Street: $(\"#BillingAddress_Street\").data(\"kendoTextBox\").value(),\n StreetIntersection: $(\"#BillingAddress_StreetIntersection\").data(\"kendoTextBox\").value(),\n StreetNumber: $(\"#BillingAddress_StreetNumber\").data(\"kendoTextBox\").value(),\n Complement: $(\"#BillingAddress_Complement\").data(\"kendoTextBox\").value(),\n NeighborhoodId: $(\"#BillingAddress_NeighborhoodId\").data(\"kendoDropDownList\").value(),\n Neighborhood: neighborhoodSelected !== undefined ? neighborhoodSelected.Code : null,\n NeighborhoodName: neighborhoodName.toUpperCase(),\n SaveAddressAs: $(\"#BillingAddress_SaveAddressAs\").data(\"kendoTextBox\").value(),\n MobileNumber: $(\"#BillingAddress_MobileNumber\").data(\"kendoTextBox\").value(),\n Email: $(\"#BillingAddress_Email\").data(\"kendoTextBox\").value(),\n Address: address,\n PostalCode: '',\n Longitude: 0,\n Latitude: 0,\n BranchOfficeId: branchOfficeId,\n BranchOfficeReferenceCode: branchOfficeReferenceCode,\n ReceivePromotionalCommunications: $(\"#ReceivePromotionalCommunications\").is(\":checked\"),\n AcceptTerms: $(\"#BillingAddress_AcceptTerms\").is(\":checked\"),\n };\n\n const response = await this._addressManagementService.saveBillingAddressB2CAsync(signUpAddressB2C);\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (json.Successful) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: \"Tu información se registró correctamente\"\n })\n\n if ($(location).attr(\"pathname\").split('/').slice(-1)[0] === \"MyAccount\" || $(location).attr(\"pathname\").split('/').slice(-1)[0] === \"MyAccount#addresses\") {\n this._reloadAddressList();\n } else {\n window.location.href = json.GoToPage !== \"\" ? json.GoToPage : '/';\n }\n }\n else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.Message ?? \"Ocurrió un error al intentar guardar tu dirección, inténtalo de nuevo\",\n html: true\n })\n }\n\n this._billingAddressModal.modal(\"hide\");\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loadingBillingForm(false);\n spinnerWait.addClass(\"d-none\");\n }\n }\n\n /**\n * Reload address list in MyAccount Page\n */\n _reloadAddressList() {\n var customerId = $(\".customer-id\").val();\n kendo.ui.progress($(\"#addresses\"), true);\n\n this._customerService.reloadAddressList(customerId,\n (response) => {\n $(\".address-list\").html(response);\n this.bindAddressesViewB2C({ insertIcons: false });\n kendo.ui.progress($(\"#addresses\"), false);\n },\n async (response) => {\n await this._browserCommunicatorService.displayErrorAlert({\n description: 'Ocurri\\u00F3 un error al cargar tu lista de direcciones.'\n })\n kendo.ui.progress($(\"#addresses\"), false);\n },\n function (response) {\n kendo.ui.progress($(\"#addresses\"), false);\n });\n }\n\n async loadViewAsync(ignoreIsVisible = false) {\n\n if (!ignoreIsVisible && !this._addressContainerIsVisible) {\n return;\n }\n\n try {\n this._loading(true);\n const response = await this._addressManagementService.getView();\n if (!response.ok) {\n return;\n }\n\n const html = await response.text()\n this._addressListContainer.html(html);\n\n this.bindAddressesViewB2C({ insertIcons: false })\n\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false);\n }\n }\n \n setAddressAccountValidation() {\n if ($(\"[data-name=address-account-root-data]\").length > 0) {\n $.data(document.body, this._addressValidationKey, false);\n\n const streetTypeTarget = `[name=\"Address_StreetType\"]`\n $(\"[data-name=address-account-root-data]\").kendoValidator({\n rules: {\n fieldState: (input) => {\n if (input.is(\"#Address_StateId\")) {\n if ($.trim($(\"#Address_StateId\").val()) === '') {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true;\n },\n\n fieldCity: (input) => {\n if (input.is(\"#Address_CityId\")) {\n if ($.trim($(\"#Address_CityId\").val()) === '') {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true;\n },\n\n fieldStreetNeighborhood: function (input) {\n if (input.is(`#Address_NeighborhoodName`)) {\n let neighborhoodName = input.val()\n let neighborhoodId = $(`#Address_NeighborhoodId`)?.val()\n\n if ((!neighborhoodId || neighborhoodId === '00000000-0000-0000-0000-000000000000') && !neighborhoodName) {\n return false;\n }\n else {\n return true;\n }\n } else {\n return true;\n }\n\n },\n\n fieldSaveAddressAs: (input) => {\n if (input.is(\"#Address_SaveAddressAs\")) {\n if ($.trim($(\"#Address_SaveAddressAs\").val()) === '') {\n $.data(document.body, this._addressValidationKey, true);\n return false;\n }\n }\n\n return true;\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n fieldStreetType: function (input) {\n if (input.is(`[name=\"Address_StreetType\"]`)) {\n if (!input.val()) {\n return false;\n } else {\n return true;\n }\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredStreetComplement: function (input) {\n if (input.is(`[name=\"Address_Complement\"]`)) {\n let complement = input.val()\n let streetType = $(`[name=\"Address_StreetType\"]`).data(\"kendoDropDownList\").dataItem()\n if ((streetType && !streetType.RequiresNomenclature) && !complement) {\n return false;\n } else {\n return true;\n }\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredStreet: function (input) {\n if (input.is(`[name=\"Address_Street\"]`)) {\n return StreetTypesHelper.validateStreetInput({\n input: input,\n streetTypeTarget: streetTypeTarget\n })\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredStreetIntersection: function (input) {\n if (input.is(`[name=\"Address_StreetIntersection\"]`)) {\n return StreetTypesHelper.validateStreetInput({\n input: input,\n streetTypeTarget: streetTypeTarget\n })\n } else {\n return true;\n }\n },\n\n /**\n * \n * @param {JQuery} input\n * @returns {boolean}\n */\n requiredStreetNumber: function (input) {\n if (input.is(`[name=\"Address_StreetNumber\"]`)) {\n return StreetTypesHelper.validateStreetInput({\n input: input,\n streetTypeTarget: streetTypeTarget\n })\n } else {\n return true;\n }\n },\n\n validEmail: function (input) {\n if (input.is(`[name=\"Address_Email\"]`)) {\n let email = input.val();\n if (!input.attr(\"required\") && !input.val()) {\n return true;\n }\n else {\n return EmailValidationHelper.validate(email)\n }\n } else {\n return true;\n }\n }\n },\n messages: {\n fieldFirstName: \"Ingresa tu nombre\",\n fieldSurname: \"Ingresa tu apellido\",\n fieldState: \"Selecciona tu departamento\",\n fieldCity: \"Selecciona tu ciudad\",\n fieldStreetNeighborhood: \"Selecciona tu barrio\",\n fieldSaveAddressAs: \"Escribe el nombre de tu dirección (Ej. Casa u Oficina)\",\n fieldRequires: \"Este dato es requerido\",\n fieldStreetType: 'El tipo de dirección es requerido',\n requiredStreetComplement: \"Debes ingresar el complemento si no especificas un tipo de vía\",\n requiredStreet: 'La calle es requerido',\n requiredStreetIntersection: 'El número de dirección es requerido',\n validEmail: $(\"#Address_Email\").attr(\"validationMessage\")\n }\n });\n\n $(\"#Address_StateId\").attr(\"data-val-required\", \"Selecciona tu departamento\");\n $(\"#Address_CityId\").attr(\"data-val-required\", \"Selecciona tu ciudad\");\n }\n }\n\n setAddressFieldView() {\n let streetType = $(`[name=\"Address_StreetType\"]`).data(\"kendoDropDownList\").dataItem()\n\n var address = '';\n if (streetType.RequiresNomenclature) {\n var intersection = $(\"#Address_StreetIntersection\").val();\n var streetNumber = $(\"#Address_StreetNumber\").val();\n\n var stree = $(\"#Address_StreetType\").val() + \" \" + $(\"#Address_Street\").val();\n var plate = (intersection.length != 0 && streetNumber.length != 0) ? `#${intersection}-${streetNumber}` : \"\";\n\n address = `${stree} ${plate}`;\n }\n $(\"#Address_Address\").val(address)\n }\n\n async actionBranchOffice(objectId, stateId, cityId) {\n if (objectId === stateId && $.data(document.body, \"revertStateSelection\") === true) {\n $.data(document.body, \"revertStateSelection\", false);\n return false;\n }\n\n if (objectId === cityId && $.data(document.body, \"revertCitySelection\") === true) {\n $.data(document.body, \"revertCitySelection\", false);\n return false;\n }\n\n var stateSelected = $(\"#UserStateId\").val();\n var citySelected = $(\"#UserCityId\").val();\n\n if ($.trim(citySelected) !== \"\" || $.trim(stateSelected) !== \"\") {\n var newStateSelected = $(\"#\" + stateId).val();\n var newCitySelected = $(\"#\" + cityId).val();\n\n if ($.trim(citySelected) !== $.trim(newCitySelected) ||\n $.trim(stateSelected) !== $.trim(newStateSelected)) {\n\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: 'Vas a cambiar ciudad esto recarga la tienda y limpia tu carrito, ¿Desea continuar?'\n })\n\n if (confirmResult.isConfirmed) {\n $.data(document.body, \"revertStateSelection\", true);\n\n $(\"#\" + stateId).data(\"kendoDropDownList\").value(stateSelected);\n\n $(\"#\" + cityId).data(\"kendoDropDownList\").bind(\"dataBound\", function () {\n $.data(document.body, \"revertCitySelection\", true);\n $(\"#\" + cityId).data(\"kendoDropDownList\").value(citySelected);\n $(\"#\" + cityId).trigger(\"change\");\n });\n\n $(\"#\" + stateId).trigger(\"change\");\n $(\"#\" + cityId).data(\"kendoDropDownList\").dataSource.read();\n } else {\n $(\"#UserStateId\").val(newStateSelected);\n $(\"#UserCityId\").val(newCitySelected);\n $.data(document.body, \"reloadStore\", true);\n }\n }\n }\n }\n\n async resetCustomerAddressB2C() {\n try {\n await this._addressManagementService.resetCustomerAddressB2CAsync(false);\n } catch (e) {\n console.error(e)\n }\n }\n\n /**\n * \n * @param {any} addressId\n * @param {any} clearShoppingCart\n * @returns {boolean}\n */\n async _setCustomerAddressb2c(addressId, clearShoppingCart) {\n try {\n const response = await this._addressManagementService.setCustomerAddressB2CAsync(addressId, clearShoppingCart);\n if (!response.ok) {\n return false;\n }\n const json = await response.json();\n return json.Successful\n } catch (e) {\n console.error(e);\n }\n }\n\n /**\n * \n * @param {{insertIcons: boolean}} options\n */\n bindAddressesViewB2C(options) {\n\n if (options.insertIcons) {\n $(\"#Address_StreetIntersection\").parent().prepend('');\n $(\"#Address_StreetNumber\").parent().prepend('');\n }\n\n $(\".edit-address\").off(\"click\");\n $(\".edit-address\").on(\"click\", event => {\n\n $('#addressForm').modal(\"show\");\n\n $(\"#Address_StateId, #Address_CityId\").off(\"change\");\n\n $('#addressForm .address-modal-title').html(' Editar direcci\\u00F3n');\n\n const data = $(event.currentTarget);\n const json = data.data(\"json\");\n\n $(\"#Address_Id\").val(json.Id);\n $(\"#Address_ReferenceCode\").val(json.ReferenceCode);\n $(\"#Address_Latitude\").val(json.Latitude);\n $(\"#Address_Longitude\").val(json.Longitude);\n $(\"#Address_PostalCode\").val(json.PostalCode);\n $(\"#Address_LocationIdentifier\").val(json.LocationIdentifier);\n $(\"#Address_PositiveBalance\").val(json.PositiveBalance);\n\n $(\"#Address_MobileNumber\").data(\"kendoTextBox\").value($.trim(json.MobileNumber));\n $(\"#Address_MobileNumber\").trigger(\"change\");\n\n $(\"#Address_PhoneNumber\").data(\"kendoTextBox\").value($.trim(json.PhoneNumber));\n $(\"#Address_PhoneNumber\").trigger(\"change\");\n\n $(\"#Address_Email\").data(\"kendoTextBox\").value($.trim(json.Email));\n $(\"#Address_Email\").trigger(\"change\");\n\n if (json.State) {\n $(\"#Address_StateId\").data(\"kendoDropDownList\").value($.trim(json.State.Id));\n } else {\n $(\"#Address_StateId\").data(\"kendoDropDownList\").select(-1);\n }\n\n $(\"#Address_StateId\").trigger(\"change\");\n\n if (json.City) {\n $(\"#Address_CityId\").data(\"kendoDropDownList\").value($.trim(json.City.Id));\n } else {\n $(\"#Address_CityId\").data(\"kendoDropDownList\").select(-1);\n }\n\n $(\"#Address_CityId\").trigger(\"change\");\n\n NeighborhoodHelper.bindNeighborhoodSelection({\n neighborhoodSelector: '#Address_NeighborhoodId',\n neighborhoodNameSelector: '#Address_NeighborhoodName',\n triggerNeighborhoodName: true\n })\n\n if (json.Neighborhood) {\n $(\"#Address_NeighborhoodId\").data(\"kendoDropDownList\").value($.trim(json.Neighborhood.Id));\n } else {\n $(\"#Address_NeighborhoodId\").data(\"kendoDropDownList\").select(-1);\n }\n\n $(\"#Address_NeighborhoodId\").trigger(\"change\");\n\n StreetTypesHelper.bindStreetTypeSelection({\n stretTypeSelector: '#Address_StreetType',\n nomenclatureSelector: '#Address_Complement',\n nomenclatureFieldSelectors: ['#Address_Street', '#Address_StreetIntersection', '#Address_StreetNumber'],\n triggerNomenclature: true\n })\n\n $(\"#Address_StreetType\").off(\"change\");\n $(\"#Address_StreetType\").data(\"kendoDropDownList\").select(-1);\n $(\"#Address_StreetType\").on(\"change\", e => this.setAddressFieldView());\n\n $(\"#Address_Street\").off(\"change\");\n $(\"#Address_Street\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_Street\").on(\"change\", e => this.setAddressFieldView());\n\n $(\"#Address_StreetIntersection\").off(\"change\");\n $(\"#Address_StreetIntersection\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_StreetIntersection\").on(\"change\", e => this.setAddressFieldView());\n\n $(\"#Address_StreetNumber\").off(\"change\");\n $(\"#Address_StreetNumber\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_StreetNumber\").on(\"change\", e => this.setAddressFieldView());\n\n\n $(\"#Address_NeighborhoodName\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_NeighborhoodName\").trigger(\"change\");\n\n $(\"#Address_Complement\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_Complement\").trigger(\"change\");\n\n $(\"#Address_Address\").data(\"kendoTextBox\").value(json.Address);\n $(\"#Address_Address\").trigger(\"change\");\n\n if ($(\"#Address_SaveAddressAs\").data(\"kendoTextBox\") != undefined) {\n $(\"#Address_SaveAddressAs\").data(\"kendoTextBox\").value(json.Name);\n $(\"#Address_SaveAddressAs\").trigger(\"change\");\n } else {\n $(\"#Address_SaveAddressAs\").val(\"SN\");\n }\n\n $(\"#Address_Main\").data(\"kendoSwitch\")?.check(($.trim(json.IsMain) === \"True\"));\n\n if (data.attr(\"data-address-selected\") === \"true\" || data.attr(\"data-address-selected\") === \"True\") {\n $(\"#Address_StateId, #Address_CityId\").on(\"change\", (e) => {\n this.actionBranchOffice($(e.currentTarget).attr(\"id\"), \"Address_StateId\", \"Address_CityId\");\n });\n }\n\n $.data(document.body, \"revertStateSelection\", false);\n $.data(document.body, \"revertCitySelection\", false);\n $.data(document.body, \"reloadStore\", false);\n })\n\n $('#addressForm').off('show.bs.modal');\n $('#addressForm').on('show.bs.modal', (event) => {\n\n this.setAddressAccountValidation();\n \n if ($(event.relatedTarget).attr(\"class\") == \"add-address\") {\n $(\"#Address_StateId, #Address_CityId\").off(\"change\");\n\n $('#addressForm .address-modal-title').html(' Nueva direcci\\u00F3n');\n\n if ($(\"#UserStateId\").length > 0) {\n $(\"#Address_StateId\").data(\"kendoDropDownList\").value($(\"#UserStateId\").val());\n } else {\n $(\"#Address_StateId\").data(\"kendoDropDownList\").select(-1);\n }\n\n $(\"#Address_StateId\").trigger(\"change\");\n\n\n if ($(\"#UserCityId\").length > 0) {\n $(\"#Address_CityId\").data(\"kendoDropDownList\").value($(\"#UserCityId\").val());\n } else {\n $(\"#Address_CityId\").data(\"kendoDropDownList\").select(-1);\n }\n\n $(\"#Address_CityId\").trigger(\"change\");\n\n $(\"#Address_StreetType\").off(\"change\");\n $(\"#Address_StreetType\").data(\"kendoDropDownList\").select(-1);\n $(\"#Address_StreetType\").on(\"change\", e => this.setAddressFieldView());\n\n $(\"#Address_Street\").off(\"change\");\n $(\"#Address_Street\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_Street\").on(\"change\", e => this.setAddressFieldView());\n\n $(\"#Address_StreetIntersection\").off(\"change\");\n $(\"#Address_StreetIntersection\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_StreetIntersection\").on(\"change\", e => this.setAddressFieldView());\n\n $(\"#Address_StreetNumber\").off(\"change\");\n $(\"#Address_StreetNumber\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_StreetNumber\").on(\"change\", e => this.setAddressFieldView());\n\n $(\"#Address_Address\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_Complement\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_NeighborhoodId\").data(\"kendoDropDownList\").select(-1);\n\n NeighborhoodHelper.bindNeighborhoodSelection({\n neighborhoodSelector: '#Address_NeighborhoodId',\n neighborhoodNameSelector: '#Address_NeighborhoodName',\n triggerNeighborhoodName: true\n })\n\n StreetTypesHelper.bindStreetTypeSelection({\n stretTypeSelector: '#Address_StreetType',\n nomenclatureSelector: '#Address_Complement',\n nomenclatureFieldSelectors: ['#Address_Street', '#Address_StreetIntersection', '#Address_StreetNumber'],\n triggerNomenclature: true\n })\n\n $(\"#Address_NeighborhoodName\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_Main\").data(\"kendoSwitch\")?.check(false);\n\n if ($(\"#Address_SaveAddressAs\").data(\"kendoTextBox\") != undefined) {\n $(\"#Address_SaveAddressAs\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_SaveAddressAs\").trigger(\"change\");\n } else {\n $(\"#Address_SaveAddressAs\").val(\"SN\");\n }\n\n $(\"#Address_MobileNumber\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_MobileNumber\").trigger(\"change\");\n\n $(\"#Address_PhoneNumber\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_PhoneNumber\").trigger(\"change\");\n\n $(\"#Address_Email\").data(\"kendoTextBox\").value(\"\");\n $(\"#Address_Email\").trigger(\"change\");\n\n $(\"#Address_ReferenceCode\").val(\"\");\n $(\"#Address_Latitude\").val(\"\");\n $(\"#Address_Longitude\").val(\"\");\n $(\"#Address_PostalCode\").val(\"\");\n $(\"#Address_LocationIdentifier\").val(\"\");\n $(\"#Address_PositiveBalance\").val(\"\");\n $(\"#Address_Id\").val(\"\");\n\n $(\"#Address_StateId, #Address_CityId\").off(\"change\");\n }\n });\n\n this.unBindEvents();\n this._addressViewB2CSubs.push(\n //delete customer address\n fromEvent(this._deleteAddressb2cButton, \"click\").subscribe(async e => {\n e.stopPropagation();\n const customerAddressId = $(e.currentTarget).attr(\"data-address-id\");\n this._deleteCustomerAddressb2c(customerAddressId);\n }),\n \n //select customer address\n fromEvent(this._seletedAddressb2cButton, \"click\").subscribe(async e => {\n e.stopPropagation();\n let customerAddressId = $(e.currentTarget).attr(\"data-address-id\");\n let applyChangeStore = $(e.currentTarget).attr(\"data-apply-change-store\");\n await this._selectedCustomerAddressb2c(customerAddressId, applyChangeStore);\n }),\n\n //save customer address\n fromEvent(this._saveAddressb2cButton, \"click\").subscribe(async e => {\n e.stopPropagation();\n const formTargetEl = \"[data-name=address-account-root-data]\"\n const spinnerWait = $(e.currentTarget).find(\".spinner-border-sm\").eq(0);\n await this._saveCustomerAddressb2c(formTargetEl, spinnerWait)\n })\n );\n\n this._addressViewB2BSubs.push(\n\n // delete customer address b2b\n fromEvent(this._deleteAddressb2bButton, \"click\").subscribe(async e => {\n e.stopPropagation();\n const data = $(e.currentTarget).data(\"json\")\n const customerAddressId = data.Id;\n const customerAddressReferenceCode = data.ReferenceCode;\n this._deleteCustomerAddressb2b(customerAddressId, customerAddressReferenceCode);\n }),\n\n //select customer address\n fromEvent(this._seletedAddressb2bButton, \"change\").subscribe(async e => {\n e.stopPropagation();\n let customerAddressId = $(e.currentTarget).val();\n let applyChangeStore = $(e.currentTarget).attr(\"data-apply-change-store\");\n await this._selectedCustomerAddressb2b(customerAddressId, applyChangeStore === \"true\");\n }),\n )\n }\n\n unBindEvents() {\n this._addressViewB2CSubs.forEach(sub => {\n sub?.unsubscribe()\n })\n this._addressViewB2CSubs = [];\n\n this._addressViewB2BSubs.forEach(sub => {\n sub?.unsubscribe()\n })\n this._addressViewB2BSubs = [];\n }\n\n /**\n * \n * @param {string} formTargetEl\n * @param {JQuery} spinnerWait\n * @returns\n */\n async _saveCustomerAddressb2c(formTargetEl, spinnerWait) {\n const formValidator = $(formTargetEl).data(\"kendoValidator\");\n formValidator.reset()\n\n var addressValidation = formValidator.validate();\n\n if (addressValidation == false || $.trim($(\"#Address_SaveAddressAs\").val()) == \"\") {\n await this._browserCommunicatorService.displayWarningAlert({ description: \"Debes ingresar los datos marcados con \\\"*\\\".\" })\n return;\n }\n\n // dispatch \"add_shipping_info\" analytics event\n $applicationMonitoringService\n .then(function (service) {\n service.trackAddShippingInfo(\n analytics.AnalyticsConstants.DefaultParameterValue,\n [],\n analytics.AnalyticsConstants.DefaultParameterValue,\n analytics.AnalyticsConstants.DefaultParameterValue,\n appConstants.currency)\n })\n .catch(function (err) {\n console.error(err);\n })\n\n this._loadingForm(true);\n spinnerWait.removeClass(\"d-none\");\n\n try {\n\n var stateSelected = $(\"#Address_StateId\").data(\"kendoDropDownList\").dataItem();\n var citySelected = $(\"#Address_CityId\").data(\"kendoDropDownList\").dataItem();\n var cityName = citySelected.CityName;\n var branchOfficeReferenceCode = citySelected.BranchOfficeReferenceCode;\n var neighborhoodSelected = $(\"#Address_NeighborhoodId\").data(\"kendoDropDownList\").dataItem();\n\n var complement = $.trim($(\"#Address_Complement\").val());\n var stree = $(\"#Address_Address\").val();\n\n if ($.trim(stree) !== '' && $.trim(stree).indexOf('- ') !== -1) {\n var currentAddress = $.trim($.trim(stree).substring(0, $.trim(stree).indexOf('- ')));\n\n if ($.trim(complement) === '') {\n complement = $.trim($.trim(stree).substring($.trim(stree).indexOf('- ') + 2, $.trim(stree).length));\n }\n } else {\n var currentAddress = $.trim(stree);\n }\n\n var address = `${currentAddress}@${cityName}@${complement}`;\n\n var editAddress = {\n Id: $(\"#Address_Id\").val(),\n CustomerId: $(\".customer-id\").val(),\n IdentificationType: $(\".customer-identificationtype\").val(),\n ReferenceCode: $(\"#Address_ReferenceCode\").val(),\n IdentificationNumber: $(\".customer-identification\").val(),\n CustomerAccount: $(\"#Address_ReferenceCode\").val(),\n Address: address,\n MobileNumber: $(\"#Address_MobileNumber\").data(\"kendoTextBox\").value(),\n PhoneNumber: $(\"#Address_PhoneNumber\").val(),\n Email: $(\"#Address_Email\").data(\"kendoTextBox\").value(),\n BranchOfficeReferenceCode: branchOfficeReferenceCode,\n Latitude: $(\"#Address_Latitude\").val(),\n Longitude: $(\"#Address_Longitude\").val(),\n PostalCode: $(\"#Address_PostalCode\").val(),\n StateId: stateSelected !== undefined ? stateSelected.Id : null,\n State: stateSelected !== undefined ? stateSelected.Code : null,\n CityId: $(\"#Address_CityId\").data(\"kendoDropDownList\").value(),\n City: citySelected !== undefined ? citySelected.Code : null,\n NeighborhoodId: neighborhoodSelected !== undefined ? neighborhoodSelected.Id : null,\n Neighborhood: neighborhoodSelected !== undefined ? neighborhoodSelected.Code : null,\n NeighborhoodName: $(\"#Address_NeighborhoodName\").val().toUpperCase(),\n PositiveBalance: $(\"#Address_PositiveBalance\").val(),\n IsMain: $(\"#Address_Main\").data(\"kendoSwitch\")?.check(),\n LocationIdentifier: $(\"#Address_LocationIdentifier\").val(),\n AddressName: $(\"#Address_SaveAddressAs\").val(),\n };\n\n const response = await this._addressManagementService.saveAddressB2CAsync(editAddress);\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.Message ?? \"Ocurrió un error al intentar guardar tu dirección, inténtalo de nuevo\"\n });\n return;\n }\n\n await this._browserCommunicatorService.displaySuccessAlertAsync({\n description: \"Tu dirección se guardo con éxito\",\n autoclosing: true\n })\n\n if ($.data(document.body, \"reloadStore\")) {\n const customerAddressId = $(\".customer-id\").val();\n const valid = this._setCustomerAddressb2c(customerAddressId, true);\n\n if (!valid) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: 'Ocurrió un error al seleccionar la dirección, por favor intentalo nuevamente.'\n })\n return;\n }\n\n window.location.href = '/';\n return;\n }\n\n $('#addressForm').modal('hide');\n await this.loadViewAsync(true);\n this._reloadAddressList();\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loadingForm(false);\n spinnerWait.addClass(\"d-none\");\n }\n }\n\n /**\n * \n * @param {string} customerAddressId\n * @returns\n */\n async _deleteCustomerAddressb2c(customerAddressId) {\n\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: '¿Desea eliminar esta dirección?', confirmButtonText: \"Aceptar\", denyButtonText: \"Cancelar\"\n })\n\n if (!confirmResult.isConfirmed) {\n return;\n }\n\n try {\n this._loading(true);\n const response = await this._addressManagementService.deleteAddressB2C(customerAddressId)\n\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: 'Ocurri\\u00F3 un error al borrar la dirección, por favor intentalo nuevamente.'\n })\n }\n\n await this._browserCommunicatorService.displaySuccessAlertAsync({\n description: 'La dirección se ha eliminado correctamente.', autoclosing: true\n })\n\n const value = json.Value;\n if (value.ReloadStore) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: 'Vas a cambiar de sitio, esto recarga la tienda y limpia tu carrito.'\n })\n\n await this.resetCustomerAddressB2C();\n window.location.href = \"/\";\n }\n else {\n await this.loadViewAsync(true)\n }\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false)\n }\n }\n\n /**\n * \n * @param {string} customerAddressId\n * @returns\n */\n async _deleteCustomerAddressb2b(customerAddressId, customerAddressReferenceCode) {\n\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: \"Vamos a eliminar tu dirección, ¿deseas continuar?\",\n confirmButtonText: \"Aceptar\",\n denyButtonText: \"Cancelar\"\n })\n\n if (!confirmResult.isConfirmed) {\n return;\n }\n\n try {\n this._loadingAddressMyAccount(true);\n const response = await this._addressManagementService.deleteAddressB2B(customerAddressId, customerAddressReferenceCode)\n\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage\n })\n return;\n }\n\n await this._browserCommunicatorService.displaySuccessAlertAsync({\n description: 'Dirección eliminada correctamente'\n })\n\n $(`.addresses__item#${customerAddressId}`).fadeOut();\n\n const value = json.Value;\n if (value.ReloadStore) {\n await this._browserCommunicatorService.displayInfoAlert({\n description: 'Vas a cambiar de sitio, esto recarga la tienda y limpia tu carrito.'\n })\n\n await this.resetCustomerAddressB2C();\n window.location.reload();\n return;\n }\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loadingAddressMyAccount(false)\n this._reloadAddressList();\n }\n\n }\n\n /**\n * \n * @param {string} customerAddressId\n * @param {string} applyChangeStore\n * @returns\n */\n async _selectedCustomerAddressb2c(customerAddressId, applyChangeStore) {\n try {\n this._loading(true);\n \n if (applyChangeStore === 'true') {\n\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: 'Vas a cambiar de sitio, esto recarga la tienda y limpia tu carrito. ¿Deseas continuar?',\n denyButtonText: 'Cancelar',\n confirmButtonText: 'Aceptar'\n })\n\n if (!confirmResult.isConfirmed) {\n return;\n }\n\n const response = await this._addressManagementService.setCustomerAddressB2CAsync(customerAddressId, true);\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (json.Successful) {\n await CustomerAnalyticsHelper.trackUserFromAddressAsync(json.Value)\n window.location.href = '/';\n } else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: 'Ocurri\\u00F3 un error al seleccionar la direcci\\u00F3n, por favor intentalo nuevamente.'\n })\n }\n\n }\n else {\n\n const response = await this._addressManagementService.setCustomerAddressB2CAsync(customerAddressId, false);\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (json.Successful) {\n window.location.href = '/';\n }\n else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: 'Ocurri\\u00F3 un error al seleccionar la direcci\\u00F3n, por favor intentalo nuevamente.'\n })\n }\n }\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false);\n }\n }\n\n /**\n * \n * @param {string} customerAddressId\n * @param {boolean} applyChangeStore\n * @returns\n */\n async _selectedCustomerAddressb2b(customerAddressId, applyChangeStore) {\n try {\n this._loading(true);\n\n if (applyChangeStore) {\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: 'Vas a cambiar de sitio, esto recarga la tienda y limpia tu carrito. ¿Deseas continuar?',\n denyButtonText: 'Cancelar',\n confirmButtonText: 'Aceptar'\n })\n\n if (!confirmResult.isConfirmed) {\n return;\n }\n }\n\n const response = await this._addressManagementService.setCustomerAddressB2BAsync(customerAddressId, applyChangeStore);\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (json.Successful) {\n await CustomerAnalyticsHelper.trackUserFromAddressAsync(json.Value)\n window.location.href = '/';\n } else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: 'Ocurrió un error al seleccionar la dirección, por favor intentalo nuevamente.'\n })\n }\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false);\n }\n }\n\n /**\n * \n * @param {string} customerAddressId\n * @param {boolean} applyChangeStore\n * @returns\n */\n async _selectedCustomerAddressb2b(customerAddressId, applyChangeStore) {\n try {\n this._loading(true);\n\n if (applyChangeStore) {\n const confirmResult = await this._browserCommunicatorService.displayQuestionAlert({\n description: 'Vas a cambiar de sitio, esto recarga la tienda y limpia tu carrito. ¿Deseas continuar?',\n denyButtonText: 'Cancelar',\n confirmButtonText: 'Aceptar'\n })\n\n if (!confirmResult.isConfirmed) {\n return;\n }\n }\n\n const response = await this._addressManagementService.setCustomerAddressB2BAsync(customerAddressId, applyChangeStore);\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (json.Successful) {\n await CustomerAnalyticsHelper.trackUserFromAddressAsync(json.Value)\n window.location.href = '/';\n } else {\n await this._browserCommunicatorService.displayErrorAlert({\n description: 'Ocurrió un error al seleccionar la dirección, por favor intentalo nuevamente.'\n })\n }\n } catch (e) {\n console.error(e)\n } finally {\n this._loading(false);\n }\n }\n\n _loadingForm(loading) {\n super._loading(loading, \"#addressForm\");\n }\n\n _loadingBillingForm(loading) {\n super._loading(loading, this._billingAddressModal[0]);\n }\n\n _loading(value) {\n super._loading(value, this._addressListContainer[0]);\n }\n\n _loadingAddressMyAccount(value) {\n super._loading(value, this._addressListContainerMyAccount[0]);\n }\n}","import { Observable } from \"rxjs\";\nimport { AjaxResponse } from \"rxjs/ajax\";\nimport UrlHelper from \"../helpers/url-helper\";\nimport AjaxProxy from \"../proxies/ajax-proxy\";\n\nexport default class CheckoutSummaryService {\n\n /**\n * @returns {Observable>}\n * */\n getView() {\n let request = {\n url: UrlHelper.getCheckoutSummaryView\n }\n return AjaxProxy.postRxHtml(request);\n }\n}","import { Observable } from \"rxjs\";\nimport { AjaxResponse } from \"rxjs/ajax\";\nimport UrlHelper from \"../helpers/url-helper\";\nimport AjaxProxy from \"../proxies/ajax-proxy\";\n\nexport class CheckoutPaymentListService {\n\n /**\n * @returns {Observable>}\n * */\n getView() {\n let request = {\n url: UrlHelper.getCheckoutPaymentListView\n }\n return AjaxProxy.postRxHtml(request);\n }\n}","export default class CheckoutHelper {\n static getTotalPriceFromDataTotal(target = \".total-order-price\") {\n let totalPriceOrderEl = document.querySelector(target)\n if (!totalPriceOrderEl) {\n return -1;\n }\n return parseFloat(totalPriceOrderEl.getAttribute(\"data-total\"));\n }\n}","export class RadioButtons {\n\n /**\n * \n * */\n _constants = Object.freeze({\n changeEventName: \"radiobuttons:change\",\n containerRadioButtonsSelector: \".container-radioButton\",\n radioButtonInputSelector: '.container-radioButton__input-radioButton',\n radioButtonContentSelector: '.container-radioButton__content',\n radioButtonContentTextSelector: `.container-radioButton__content p` \n })\n\n /**\n * @type {{el: string, onChange: (e: Event) => {}}}\n * */\n _options;\n\n /**\n * @type {HTMLElement}\n * */\n TargetElement\n\n /**\n * \n * @param {{el: string, onChange: (e: Event) => {}}} options\n */\n constructor(options) {\n this._options = options;\n this.init()\n }\n\n init() {\n const el = document.querySelector(this._options.el)\n this.TargetElement = el;\n const containerRadioButtons = el.querySelectorAll(this._constants.containerRadioButtonsSelector)\n containerRadioButtons?.forEach((container) => container.addEventListener('click', (e) => { this._onChecked(e.currentTarget) }))\n\n const inputs = el.querySelectorAll(`${this._constants.radioButtonInputSelector}:checked`)\n inputs?.forEach((input) => input.parentElement.classList.add('checked'));\n\n if (this._options.onChange) {\n this.TargetElement.addEventListener(this._constants.changeEventName, this._options.onChange.bind(this))\n }\n }\n\n /**\n * \n * */\n _removeCheckedClass() {\n const containerRdioButtons = this.TargetElement.querySelectorAll(this._constants.containerRadioButtonsSelector)\n containerRdioButtons.forEach((container) => container.classList.remove('checked'))\n }\n\n /**\n * \n * @param {Event} e\n * @param {HTMLElement} container\n */\n _onChecked(container) {\n this._removeCheckedClass()\n\n /** @type {HTMLInputElement} */\n const inputCheckbox = container.firstElementChild\n inputCheckbox.checked = true\n\n // update checked class\n container.classList.add('checked')\n\n // get text content element\n const textContent = container.querySelector(this._constants.radioButtonContentTextSelector)\n\n // dispatch change event\n let event = new CustomEvent(this._constants.changeEventName, {\n detail: {\n checkedTarget: inputCheckbox,\n text: textContent.textContent,\n checked: inputCheckbox.checked,\n value: inputCheckbox.value,\n container: container\n }\n })\n this.TargetElement.dispatchEvent(event)\n }\n}\n","import { Observable } from \"rxjs\";\nimport { AjaxResponse } from \"rxjs/ajax\";\nimport UrlHelper from \"../helpers/url-helper\";\nimport AjaxProxy from \"../proxies/ajax-proxy\";\nimport { ServiceBase } from \"../shared/service/service-base\"\n\nexport class CheckoutSubTotalsService extends ServiceBase {\n\n _endpoints = {\n computeSubTotals: \"?handler=ComputeSubTotals\",\n getMinimunOrderAmount: \"?handler=MinimunorderAmount\"\n }\n\n computeSubTotals() {\n let request = {\n url: this._endpoints.computeSubTotals\n }\n return AjaxProxy.postRxJson(request);\n }\n\n getMinimunOrderAmount() {\n let request = {\n };\n return AjaxProxy.postFetch(this._endpoints.getMinimunOrderAmount, request);\n }\n}","import { ServiceBase } from \"../../service/service-base\"\nimport AjaxProxy from \"../../../proxies/ajax-proxy\"\n\nexport class FiltersService extends ServiceBase {\n\n _endpoints = {\n getClassification: \"/api/filters/classifications\",\n getManufactures: \"/api/filters/manufactures\",\n getProductBrands: \"/api/filters/productbrands\",\n getHierarchy: \"/api/filters/gethierarchy\",\n getAll: \"/api/filters/all\"\n }\n\n constructor() {\n super();\n }\n\n getClassificationsAsync() {\n return this.getFiltersAsync(this._endpoints.getClassification)\n }\n\n getManofacturesAsync() {\n return this.getFiltersAsync(this._endpoints.getManufactures)\n }\n\n getProductBrandsAsync() {\n return this.getFiltersAsync(this._endpoints.getProductBrands)\n }\n\n async getAllFiltersAsync() {\n return AjaxProxy.getFetch(this._endpoints.getAll, {}).then(async re => {\n if (!re.ok) {\n return { Successful: false, Value: {} };\n }\n const json = await re.json()\n return json;\n }).catch(err => {\n console.error(err)\n return { Successful: false, Value: {} };\n })\n }\n\n async getFiltersAsync(endpoint) {\n return AjaxProxy.getFetch(endpoint, {}).then(async re => {\n if (!re.ok) {\n return { Successful: false, Value: [] };\n }\n const json = await re.json()\n return json;\n }).catch(err => {\n console.error(err)\n return { Successful: false, Value: [] };\n })\n }\n\n /**\n * \n * @param {[]} filterIds\n * @returns\n */\n async getHierarchyAsync(filterIds) {\n const formData = new FormData();\n for (var i = 0; i < filterIds.length; i++) {\n formData.append(`filterIds[${i}]`, filterIds[i])\n }\n return AjaxProxy.postFetch(this._endpoints.getHierarchy, { body: formData }).then(async re => {\n if (!re.ok) {\n return { Successful: false, Value: [] };\n }\n return await re.json();\n }).catch(err => {\n console.error(err)\n return { Successful: false, Value: [] };\n })\n }\n}","import { HandlerBase } from \"../../handler/handler-base\"\nimport { FiltersService } from \"../services/filters-service\"\nimport \"kendo-ui\"\n\nexport class FiltersHandlers extends HandlerBase {\n\n get _classificationElement() {\n return $(\"#checkboxgroup-categories\");\n }\n\n get _classificationCheckboxGroup() {\n return this._classificationElement.data(\"kendoCheckBoxGroup\")\n }\n\n get _classificationFilterInput() {\n return $('#txtFilterCategory');\n }\n\n get _manufacturesElement() {\n return $(\"#checkboxgroup-manufacturers\");\n }\n\n get _manufacturesCheckboxGroup() {\n return this._manufacturesElement.data(\"kendoCheckBoxGroup\");\n }\n\n get _manufactureFilterInput() {\n return $('#txtFilterManufacturer')\n }\n\n get _productBrandsElement() {\n return $(\"#checkboxgroup-brands\");\n }\n\n get _productBrandsCheckboxGroup() {\n return this._productBrandsElement.data(\"kendoCheckBoxGroup\");\n }\n\n get _productBrandsFilterInput() {\n return $('#txtFilterBrands')\n }\n\n get filterButton() {\n return $('#filterProductMain');\n }\n\n get clearButton() {\n return $('#clearFilterProductMain');\n }\n\n _loadingTarget = \".filter__wrapper\"\n\n constructor() {\n super();\n\n this._filtersService = new FiltersService();\n }\n\n init() {\n\n $('#btnFilterCategory').on('click', this.setSearchCategory.bind(this));\n $('#btnFilterManufacturer').on('click', this.setSearchManufacturer.bind(this));\n $('#btnFilterBrands').on('click', this.setSearchBrands.bind(this));\n\n $('#txtFilterCategory').on('keyup', this.setSearchCategory.bind(this));\n $('#txtFilterManufacturer').on('keyup', this.setSearchManufacturer.bind(this));\n $('#txtFilterBrands').on('keyup', this.setSearchBrands.bind(this));\n\n this.loadAllFilters().then(_ => { });\n }\n\n /**\n * (Obsolete) user loadAllFilters instead, better performance\n */\n async loadFiltersAsync() {\n this._loading(true);\n try {\n await Promise.all([\n this.loadClassificationsAsync(),\n this.loadManufacturesAsync(),\n this.loadProductBrandsAsync()\n ]);\n } catch (e) {\n console.log(e);\n } finally {\n this._loading(false);\n }\n }\n\n async loadAllFilters() {\n console.time('loadAllFilters');\n this._loading(true);\n try {\n const response = await this._filtersService.getAllFiltersAsync();\n if (!response || !response.Successful) {\n return;\n }\n\n const { Classifications, Manufactures, ProductBrands } = response.Value;\n await Promise.all([\n this.loadFilterCheckBoxGroup(this._classificationElement, Classifications, \"classification\"),\n this.loadFilterCheckBoxGroup(this._manufacturesElement, Manufactures, \"manufactures\"),\n this.loadFilterCheckBoxGroup(this._productBrandsElement, ProductBrands, \"productBrands\")\n ]);\n\n } catch (e) {\n console.log(e);\n } finally {\n this._loading(false);\n console.timeEnd('loadAllFilters');\n }\n }\n\n /**\n * \n */\n async loadClassificationsAsync(){\n const response = await this._filtersService.getClassificationsAsync();\n if(!response || !response.Successful){\n return;\n }\n\n this.loadFilterCheckBoxGroup(this._classificationElement, response.Value, \"classification\")\n }\n\n /**\n * \n */\n async loadManufacturesAsync() {\n const response = await this._filtersService.getManofacturesAsync();\n if (!response || !response.Successful) {\n return;\n }\n\n this.loadFilterCheckBoxGroup(this._manufacturesElement, response.Value, \"manufactures\")\n }\n\n /**\n * \n */\n async loadProductBrandsAsync() {\n const response = await this._filtersService.getProductBrandsAsync();\n if (!response || !response.Successful) {\n return;\n }\n\n this.loadFilterCheckBoxGroup(this._productBrandsElement, response.Value, \"productBrands\")\n }\n\n /**\n * \n * @param {JQuery} checkBoxGroup\n * @param {[]} filters\n * @param {\"classification\" | \"manufactures\" | \"productBrands\"} type \n */\n loadFilterCheckBoxGroup(checkBoxGroup, filters, type) {\n checkBoxGroup.kendoCheckBoxGroup({\n items: [...filters.map(item => {\n return {\n value: item.Id,\n label: item.Name\n }\n })],\n change: async e => {\n await this.onChangeAsync(e, type)\n }\n })\n }\n\n /**\n * \n * @param {kendo.ui.CheckBoxGroupChangeEvent} e\n * @param {\"classification\" | \"manufactures\" | \"productBrands\"} type \n */\n async onChangeAsync(e, type) {\n \n this._loading(true)\n try {\n const filtersId = [];\n\n if (this._manufacturesCheckboxGroup !== undefined) {\n for (var id of this._manufacturesCheckboxGroup.value()) {\n filtersId.push(id)\n }\n }\n\n if (this._productBrandsCheckboxGroup !== undefined) {\n for (var id of this._productBrandsCheckboxGroup.value()) {\n filtersId.push(id)\n }\n }\n\n if (this._classificationCheckboxGroup) {\n for (var id of this._classificationCheckboxGroup.value()) {\n filtersId.push(id)\n }\n }\n\n const response = await this._filtersService.getHierarchyAsync(filtersId)\n if (!response.Successful) {\n return;\n }\n\n const value = response.Value;\n if (type == \"classification\") {\n if (value.Manufactures && value.Manufactures.length > 0) {\n this.destroyCheckboxGroup(this._manufacturesCheckboxGroup, this._manufacturesElement);\n this.loadFilterCheckBoxGroup(this._manufacturesElement, value.Manufactures, \"manufactures\");\n }\n\n if (value.ProductBrands && value.ProductBrands.length > 0) {\n this.destroyCheckboxGroup(this._productBrandsCheckboxGroup, this._productBrandsElement);\n this.loadFilterCheckBoxGroup(this._productBrandsElement, value.ProductBrands, \"productBrands\");\n }\n } else if (type == \"manufactures\") {\n if (value.ProductBrands && value.ProductBrands.length > 0) {\n this.destroyCheckboxGroup(this._productBrandsCheckboxGroup, this._productBrandsElement);\n this.loadFilterCheckBoxGroup(this._productBrandsElement, value.ProductBrands, \"productBrands\");\n }\n }\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loading(false);\n }\n }\n\n /**\n * \n * @param {kendo.ui.CheckBoxGroup} checkboxGroup\n * @param {JQuery} element\n */\n destroyCheckboxGroup(checkboxGroup, element) {\n checkboxGroup.destroy();\n element.find(\"li\").remove();\n }\n\n /**\n * Clear filters elements\n */\n clearFiltersInputs() {\n\n const classificationKendo = this._classificationCheckboxGroup;\n const manufacturesKendo = this._manufacturesCheckboxGroup;\n const brandsKendo = this._productBrandsCheckboxGroup;\n\n if (classificationKendo) {\n classificationKendo.checkAll(false);\n classificationKendo.items().parent().show();\n this._classificationFilterInput.val(\"\")\n }\n\n if (manufacturesKendo !== undefined) {\n manufacturesKendo.checkAll(false);\n manufacturesKendo.items().parent().show();\n }\n\n if (brandsKendo !== undefined) {\n brandsKendo.checkAll(false);\n brandsKendo.items().parent().show();\n }\n\n // clear filter texbox\n this._manufactureFilterInput.val(\"\")\n this._productBrandsFilterInput.val(\"\")\n\n //change event\n classificationKendo?.trigger(\"change\")\n }\n\n getFilterData() {\n const classificationKendo = this._classificationCheckboxGroup;\n const manufacturesKendo = this._manufacturesCheckboxGroup;\n const brandsKendo = this._productBrandsCheckboxGroup;\n\n let sortCategoriesIds;\n let sortManufacturesIds;\n let sortBrandsIds;\n\n if (classificationKendo) {\n sortCategoriesIds = classificationKendo.value().length > 0 ? classificationKendo.value() : null;\n } else {\n sortCategoriesIds = null;\n }\n\n sortManufacturesIds = manufacturesKendo !== undefined && manufacturesKendo.value().length > 0 ? manufacturesKendo.value() : null;\n sortBrandsIds = brandsKendo !== undefined && brandsKendo.value().length > 0 ? brandsKendo.value() : null;\n\n return {\n classificationIds: sortCategoriesIds,\n manufactureIds: sortManufacturesIds,\n productBrandIds: sortBrandsIds\n }\n }\n\n /**\n * \n * @param {kendo.ui.CheckBoxGroup} checkBoxGroup\n * @param {JQuery} txtFilter\n */\n searchCheckBox(checkBoxGroup, txtFilter) {\n const _checkBoxGroupItems = checkBoxGroup._items;\n const _textToSearch = txtFilter.val().toUpperCase().trim();\n\n for (var i = 0; i < _checkBoxGroupItems.length; i++) {\n if (!_checkBoxGroupItems[i].label.toUpperCase().startsWith(_textToSearch)) {\n checkBoxGroup.item(i).parent().hide();\n } else {\n checkBoxGroup.item(i).parent().show();\n }\n }\n }\n\n setSearchCategory() {\n this.searchCheckBox(this._classificationCheckboxGroup, this._classificationFilterInput);\n }\n\n setSearchManufacturer() {\n if (this._manufacturesCheckboxGroup !== undefined) {\n this.searchCheckBox(this._manufacturesCheckboxGroup, this._manufactureFilterInput);\n }\n }\n\n setSearchBrands() {\n if (this._productBrandsCheckboxGroup !== undefined) {\n this.searchCheckBox(this._productBrandsCheckboxGroup, this._productBrandsFilterInput);\n }\n }\n\n _loading(loading) {\n super._loading(loading, this._loadingTarget)\n }\n\n}","import { ServiceBase } from \"../../service/service-base\"\nimport UrlHelper from '../../../helpers/url-helper.js';\nimport AjaxProxy from '../../../proxies/ajax-proxy.js';\n\nexport class FavoriteListService extends ServiceBase{\n\n _endpoints = {\n getView: \"/Store/FavoriteList\",\n create: \"/Store/FavoriteList?handler=Create\",\n getItem: \"/Store/FavoriteList?handler=Item\",\n getItemHtml: \"/Store/FavoriteList?handler=ItemHtml\",\n addProductFavoriteList: \"/Store/FavoriteList?handler=AddProductFavoriteList\",\n addProductsFavoriteList: \"/Store/FavoriteList?handler=AddProductsFavoriteList\",\n deleteProduct: \"/Store/FavoriteList?handler=DeleteProductFavoriteList\",\n getAddProductHtml: \"/Store/FavoriteList?handler=AddProductHtml\",\n deleteList: \"/Store/FavoriteList?handler=DeleteList\"\n }\n constructor() {\n super();\n }\n\n getViewAsync() {\n return AjaxProxy.getFetch(this._endpoints.getView, {})\n }\n\n create(listName, callback) {\n let url = UrlHelper.createFavoriteList;\n let requestData = { listName: listName };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n createAsync(listName) {\n const data = new FormData()\n data.append(\"listName\", listName);\n return AjaxProxy.postFetch(this._endpoints.create, { body: data });\n }\n\n deleteAsync(listId) {\n const data = new FormData()\n data.append(\"listId\", listId);\n return AjaxProxy.postFetch(this._endpoints.deleteList, { body: data });\n }\n\n update(favoriteList, callback) {\n let url = UrlHelper.updateFavoriteList;\n let requestData = { favoriteList: favoriteList };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n getCollection(callback) {\n let url = UrlHelper.getFavoriteLists;\n let request = {\n url: url,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n get(favoriteListId, callback) {\n let url = UrlHelper.getFavoriteList;\n let requestData = { favoriteListId: favoriteListId };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n getItemAsync(favoriteListId) {\n const data = new FormData()\n data.append(\"favoriteListId\", favoriteListId)\n return AjaxProxy.postFetch(this._endpoints.getItem, { body: data });\n }\n\n getItemHtmlAsync() {\n return AjaxProxy.getFetch(this._endpoints.getItemHtml, { });\n }\n\n getAddProductHtmlAsync() {\n return AjaxProxy.getFetch(this._endpoints.getAddProductHtml, {});\n }\n\n getItemsHtml(favoriteList, callback) {\n let url = UrlHelper.getFavoriteListItemHtml;\n let requestData = { favoriteList: favoriteList };\n let request = {\n url: url,\n data: requestData,\n callback: callback,\n dataType: 'html'\n };\n\n AjaxProxy.post(request);\n }\n\n addProduct(listId, productId, callback) {\n let url = UrlHelper.addProductFavoriteList;\n let requestData = { listId: listId, productId: productId };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n addProductAsync(listId, productId) {\n const data = new FormData()\n data.append(\"listId\", listId);\n data.append(\"productId\", productId);\n return AjaxProxy.postFetch(this._endpoints.addProductFavoriteList, { body: data });\n }\n\n addProductsAsync(listId) {\n const data = new FormData()\n data.append(\"listId\", listId);\n return AjaxProxy.postFetch(this._endpoints.addProductsFavoriteList, { body: data });\n }\n\n deleteProduct(listId, productId, callback) {\n let url = UrlHelper.deleteProductFavoriteList;\n let requestData = { listId: listId, productId: productId };\n let request = {\n url: url,\n data: requestData,\n callback: callback\n };\n\n AjaxProxy.post(request);\n }\n\n deleteProductAsync(listId, productId) {\n const data = new FormData();\n data.append(\"listId\", listId);\n data.append(\"productId\", productId);\n return AjaxProxy.postFetch(this._endpoints.deleteProduct, { body: data });\n }\n\n}","import { Subject } from 'rxjs'\n\nexport class AddProductToListEvent {\n\n constructor() {\n this._subject = new Subject();\n this.event$ = this._subject.asObservable();\n }\n\n /**\n * \n * @param {{favoriteListId: string, productId: string }} args\n */\n add(args) {\n this._subject.next({\n favoriteListId: args.favoriteListId,\n productId: args.productId\n });\n }\n}\n\nconst event = new AddProductToListEvent();\nexport default event;","import { FavoriteListService } from \"../services/favorite-list-service\";\nimport { HandlerBase } from \"../../handler/handler-base\"\nimport { BrowserCommunicatorService } from \"../../../services/browser-communicator-service\";\nimport { $applicationMonitoringService } from \"../../application-monitoring\"\nimport ProductHelper from \"../../../helpers/product-helper\"\nimport ModalHelper from \"../../../helpers/modal-helper\";\nimport AddProductToListEvent from \"../events/add-product-to-list-event\"\nimport { appConstants } from \"../../../enums/site-enum\";\nimport { Subscription } from \"rxjs\"\nimport ShoppingCartService from \"../../shopping-cart/services/shopping-cart-service\";\nimport AddedProductFavoriteListEvent from \"../events/added-product-favorite-list-event\"\nimport { ProductDetailService } from \"../../../product-detail/services/product-detail-service\";\n\nexport class FavoriteListHandlers extends HandlerBase {\n\n get _newListButton() {\n return $('.new-list-btn');\n }\n\n get _saveListButton() {\n return $('.save-list-btn');\n }\n\n get _addListToCartButton() {\n return $('.add-list-to-car');\n }\n\n get _deleteListButton() {\n return $(\".delete-list\");\n }\n\n get _selectControl() {\n return $('.favorite-list-set');\n }\n\n get _favoriteTrigger() {\n return $(\".mh__favorites-trigger\");\n }\n\n get _modal() {\n return $(\"#favoritosModal\")\n }\n\n get _loadingTarget() {\n return \"#favoritosModal\";\n }\n\n get _loadingAddProductTarget() {\n return \"#addProductToFavoriteListModal\";\n }\n\n get _addProductModal() {\n return $('#addProductToFavoriteListModal');\n }\n\n /** @type{Subscription}*/\n _addproductSub;\n\n constructor() {\n super();\n\n this._favoriteListService = new FavoriteListService();\n this._browserCommunicatorService = new BrowserCommunicatorService();\n this.shoppingCart = new ShoppingCartService();\n this._productDetailService = new ProductDetailService();\n }\n\n init() {\n this.bindFavoriteList();\n \n this._addproductSub?.unsubscribe();\n this._addproductSub = AddProductToListEvent.event$.subscribe(async arg => {\n\n const productId = arg.productId\n\n // Add traker add favorite list.\n try {\n let productEl = document.querySelector(`.product-id-contaniner[data-product='${productId}']`)\n let productStr = productEl.getAttribute(\"data-json\")\n let productDTO = JSON.parse(productStr)\n\n $applicationMonitoringService\n .then(function (service) {\n service.trackFavoriteList(\n appConstants.currency, productDTO.Price, [{\n itemId: productDTO.ReferenceCode,\n itemName: productDTO.Name,\n currency: appConstants.currency,\n discount: productDTO.Discount,\n itemCategory: productDTO.ProductCategory,\n itemCategory2: productDTO.ProductGroup,\n classification: productDTO.ClassificationName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n department: productDTO.DepartmentName ?? analytics.AnalyticsConstants.DefaultParameterValue,\n price: productDTO.Price,\n quantity: 1\n }])\n })\n .catch(function (err) {\n console.error(err);\n })\n } catch (e) {\n console.error(e)\n }\n\n // Shows up the add product to favorite list popup\n const modal = this._addProductModal;\n\n // show modal\n modal.modal('show')\n\n this._loadingAddProduct(true);\n\n try {\n const response = await this._favoriteListService.getAddProductHtmlAsync();\n if (!response.ok) {\n return;\n }\n\n const responseHtml = await response.text();\n ModalHelper.clearBody(modal);\n ModalHelper.setHtmlBody(modal, responseHtml);\n\n const productDTO = await this._getProductDetail(productId)\n var productDetail = $('.product-card-detail');\n var productImage = productDetail.find('.product-image')[0].src;\n var productName = productDTO.Name;\n var productUnitMeasure = productDTO.UnitMeasure;\n var productPrice = productDTO.NewPrice > 0 ? productDTO.NewPrice : productDTO.Price;\n\n let html = '
      ';\n html += '
    • ';\n html += '\"\"';\n html += '
      ';\n html += '
      ' + productName + '
      ';\n html += '' + productUnitMeasure + '';\n html += '
      ';\n html += '' + productPrice + '';\n html += '
    ';\n\n $('.add-product-favorite-list-wrapper').html(html);\n\n } catch (e) {\n console.error(e);\n } finally {\n this._loadingAddProduct(false);\n }\n \n $('.save-product-to-list-btn').off('click');\n $('.save-product-to-list-btn').on('click', async (event) => {\n var favoriteList = $('.add-product-favorite-list-set')[0].selectedOptions[0];\n\n if (favoriteList == null) {\n await this._browserCommunicatorService.displayWarningAlert({\n description: 'Primero debes crear una lista.',\n html: true\n })\n return;\n }\n\n var listId = favoriteList.value;\n this._loadingAddProduct(true) \n try {\n const response = await this._favoriteListService.addProductAsync(listId, productId);\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.Message,\n html: true\n });\n return;\n }\n\n modal.modal('hide');\n\n } catch (e) {\n console.error(e)\n } finally {\n this._loadingAddProduct(false);\n }\n });\n })\n }\n\n async _getProductDetail(productId) {\n const response = await this._productDetailService.getProductDetail(productId);\n if (!response.ok) {\n return;\n }\n return (await response.json()).Value.ProductDetailInformation;\n }\n\n bindButtonList() {\n $('.btn-favorite-list').off('click');\n $('.btn-favorite-list').on('click', async (e) => {\n await this.addProductToCartClick(e);\n });\n\n $('.btn-favorite-delete').off('click');\n $('.btn-favorite-delete').on('click', async (e) => {\n await this.deleteProductFavoriteListClick(e)\n });\n\n $('.add-all-from-favority-list').off('click');\n $('.add-all-from-favority-list').on('click', async (e) => {\n await this.addAllProductsToCartClick(e)\n });\n }\n\n bindList() {\n //create favorite list\n this._newListButton.on('click', async (event) => {\n event.stopPropagation();\n \n var listName = $('.list-name-input').val();\n\n if (listName == \"\") {\n await this._browserCommunicatorService.displayErrorAlert({\n description: 'Por favor ingrese el nombre de la lista a crear.'\n })\n return;\n }\n\n this._loading(true);\n try {\n const response = await this._favoriteListService.createAsync(listName);\n if (!response.ok) {\n return;\n }\n\n const json = await response.json();\n if (!json.Successful) {\n await this._browserCommunicatorService.displayErrorAlert({\n description: json.UserMessage\n })\n return;\n }\n\n const favoriteList = json.Value;\n\n var dropdown = $('.favorite-list-set');\n dropdown.append($(\"