"use strict"; /*(function () { var throttle = 0; var reported: any = {}; window.onerror = function (msg: string, url: string, line: any, pos: any) { // Return if we've sent more than 10 errors. if (throttle > 10) return; // Log the error. var req = new XMLHttpRequest(); var params = ['js_log_error', msg, url, line, pos]; var token = params.join(''); if (reported[token]) { return; } reported[token] = true; throttle++; // Replace spaces with +, browsers expect this for form POSTs. req.open('POST', 'https://punchout.cloud/log'); req.send(JSON.stringify(params)); } as any; })();*/ var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; } var PunchoutBase = /** @class */ (function () { function PunchoutBase() { this.baseUrl = 'https://punchout.cloud/cart/'; this.cartBtnSelector = ''; this.punchoutButtonLabel = 'Punchout'; this.styles = ''; this.customStyles = '.punchout-custom-input { width:100%; margin-bottom: 16px;}\n .additional-checkout-buttons, .cart-attribute__field {display: none !important;} .cart__bottom_wrap > div:nth-of-type(1) { display: none !important; } '; this.redirectToCart = []; this.xRequestedWith = 'XMLHttpRequest'; this.method = 'POST'; this.replaced = false; this.customFormSelectors = []; this.customFormValidators = {}; this.customFormInputs = []; this.style = ".punchout-loading {\n width:100%;\n text-align: center;\n display: inline-block;\n position: relative;\n width: 120px;\n height: 120px;\n margin:auto;\n position: absolute;\n top: 0px;\n left: 0px;\n right: 0px;\n bottom: 0px;\n justify-content: center;\n }\n .punchout-loading div {\n width:100%;\n margin-top: -10px;\n position: absolute;\n border: 6px solid #fff;\n opacity: 1;\n border-radius: 50%;\n animation: punchout-loading 1s cubic-bezier(0, 0.2, 0.8, 1) infinite;\n display: unset;\n }\n .punchout-loading div:nth-child(2) {\n animation-delay: -0.5s;\n }\n @keyframes punchout-loading {\n 0% {\n top: 90px;\n left: 90px;\n width: 0;\n height: 0;\n opacity: 1;\n }\n 100% {\n top: 0px;\n left: 0px;\n width: 180px;\n height: 180px;\n opacity: 0;\n }\n }\n \n .punchout-block {\n background-color: rgba(0, 0, 0, 0.5);\n width: 100%;\n height: 100%;\n position: fixed; \n top: 0px;\n margin-left: 0px; \n left: 0px;\n z-index: 99999;\n }\n \n #punchout-btn {\n width: 100%;\n min-width: 200px;\n height: 50px;\n font-size: 24px;\n background-color: cornflowerblue;\n color: white;\n }"; if (!Punchout.current) { Punchout.current = this; } var runAgain = function () { return setTimeout(function () { try { Punchout.current.update(); } catch (e) { } runAgain(); }, 300); }; runAgain(); this.injectStyles(this.style + '\n' + this.styles + '\n' + this.customStyles); } PunchoutBase.prototype.getCustomFormSelectors = function () { return this.customFormSelectors.concat(this.customFormInputs.map(function (it) { return it.type == 'radio' ? "input[name=\"".concat(it.name, "\"]") : "input[name=\"".concat(it.value, "\"]"); })); }; PunchoutBase.prototype.getCustomFormData = function () { return this.getCustomFormSelectors().map(PunchoutBase.getValue); }; PunchoutBase.prototype.isCustomFormValid = function () { var _this = this; var data = this.getCustomFormData() .filter(function (it) { return !_this.customFormValidators[it.selector]; }); if (data.find(function (it) { var _a; return typeof (it.value) == 'boolean' ? it.value === false : !((_a = it.value) === null || _a === void 0 ? void 0 : _a.length); })) { return false; } // remove fields with customm validators for (var selector in this.customFormValidators) { var validator = this.customFormValidators[selector]; if (validator) { var value = PunchoutBase.getValue(selector); if (!validator(value.value)) { return false; } } } return true; }; PunchoutBase.prototype.injectStyles = function (styles) { var style = document.createElement('style'); style.innerHTML = styles; document.head.appendChild(style); }; PunchoutBase.prototype.getSessionId = function () { return localStorage.getItem('punchoutSessionId'); }; PunchoutBase.prototype.setSessionId = function (value) { localStorage.setItem('punchoutSessionId', value); }; PunchoutBase.prototype.replaceCartBtnElement = function (elm) { this.replaced = true; var div = document.createElement('div'); div.id = 'punchout-form'; for (var _i = 0, _a = this.customFormInputs; _i < _a.length; _i++) { var input = _a[_i]; if (input.type === 'radio') { var inputDiv = document.createElement('div'); inputDiv.classList.add('punchout-custom-input'); var inputElm = document.createElement('input'); inputElm.setAttribute('placeholder', input.label); inputElm.setAttribute('type', input.type); inputElm.setAttribute('name', input.name || 'radio'); inputElm.setAttribute('value', input.value); inputElm.setAttribute('id', input.value); if (input.checked) { inputElm.setAttribute('checked', 'true'); } var inputLabel = document.createElement('label'); inputLabel.innerText = input.label; inputLabel.setAttribute('for', input.value); inputDiv.appendChild(inputElm); inputDiv.appendChild(inputLabel); div.appendChild(inputDiv); } else { var inputElm = document.createElement('input'); inputElm.classList.add('punchout-custom-input'); inputElm.setAttribute('placeholder', input.label); inputElm.setAttribute('type', input.type); inputElm.setAttribute('name', input.value); inputElm.setAttribute('value', ''); div.appendChild(inputElm); } } var punchoutBtn = this.createPunchoutSubmitBtn(); div.appendChild(punchoutBtn); div.computedStyleMap = elm.computedStyleMap; elm.parentNode.replaceChild(div, elm); }; PunchoutBase.prototype.replaceCartBtn = function () { var _this = this; document.querySelectorAll(this.cartBtnSelector).forEach(function (elm) { return _this.replaceCartBtnElement(elm); }); if (this.replaced) { return; } try { var found = findInShadow(document.body, this.cartBtnSelector, []); if (found.length) { for (var _i = 0, found_1 = found; _i < found_1.length; _i++) { var f = found_1[_i]; this.replaceCartBtnElement(f); } } } catch (error) { } }; PunchoutBase.prototype.createBtn = function (id, label, onclick) { var newElm = document.createElement('button'); // newElm.type = 'button'; newElm.id = id; newElm.innerHTML = label; if (onclick) { newElm.onclick = onclick; } else { newElm.type = 'submit'; } return newElm; }; PunchoutBase.prototype.createPunchoutSubmitBtn = function () { var _this = this; return this.createBtn('punchout-btn', this.punchoutButtonLabel, function (ev) { ev.preventDefault(); _this.submitCart().then(); }); }; PunchoutBase.prototype.sendData = function (body, action) { return __awaiter(this, void 0, void 0, function () { var sessionId, headers, res; return __generator(this, function (_a) { switch (_a.label) { case 0: sessionId = this.getSessionId() || ''; console.log('sendData', sessionId, body); headers = { 'Content-Type': this.requestContentType || 'application/json; charset=utf-8', }; if (this.xRequestedWith) { headers['X-Requested-With'] = this.xRequestedWith; } return [4 /*yield*/, (this.fetch || window.fetch)(this.baseUrl + sessionId, { method: this.method || 'POST', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: headers, redirect: 'follow', referrer: 'no-referrer', body: this.method == 'GET' ? undefined : JSON.stringify(body), })]; case 1: res = _a.sent(); console.log('RES', res); if (res.status < 300) { return [2 /*return*/, res.json()]; } else { return [2 /*return*/, res.text().then(function (data) { alert(data); throw new Error(data); })]; } return [2 /*return*/]; } }); }); }; PunchoutBase.prototype.getCart = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, {}]; }); }); }; PunchoutBase.prototype.getCustomData = function () { var formData = this.getCustomFormData(); return formData.reduce(function (acc, it) { var _a; return (__assign(__assign({}, acc), (_a = {}, _a[it.name || it.selector] = it.value, _a))); }, {}); }; PunchoutBase.prototype.submitCart = function () { return __awaiter(this, void 0, void 0, function () { var cart, formData, custom, res, form, error_1; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 5, , 6]); this.showBlock(); return [4 /*yield*/, this.getCart()]; case 1: cart = _a.sent(); formData = this.getCustomFormData(); if (formData.length) { custom = formData.reduce(function (acc, it) { var _a; return (__assign(__assign({}, acc), (_a = {}, _a[it.name || it.selector] = it.value, _a))); }, {}); if (cart.cart) { cart.custom = custom; } else { Object.assign(cart, custom); } } return [4 /*yield*/, this.sendData(cart)]; case 2: res = _a.sent(); if (res.action == 'redirect_parent') { window.parent.location.href = res.url; return [2 /*return*/]; } if (!res.url || !res.data) { alert(res.message || 'An error happened with punchout'); this.hideBlock(); return [2 /*return*/]; } form = this.createPunchoutForm(res); if (!this.clearCart) return [3 /*break*/, 4]; return [4 /*yield*/, this.clearCart()]; case 3: _a.sent(); _a.label = 4; case 4: localStorage.removeItem('punchoutSessionId'); form.submit(); form.onerror = function () { return _this.hideBlock(); }; form.onsubmit = function () { return localStorage.removeItem('punchoutSessionId'); }; return [3 /*break*/, 6]; case 5: error_1 = _a.sent(); console.log("ERROR", error_1); alert(error_1.message); this.hideBlock(); return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); }; PunchoutBase.prototype.createPunchoutForm = function (_a) { var data = _a.data, url = _a.url, method = _a.method; var form = document.createElement('form'); form.setAttribute('hidden', 'true'); form.setAttribute('method', method || 'POST'); form.setAttribute('action', url); Object.keys(data).forEach(function (key) { var input1 = document.createElement('input'); input1.setAttribute('type', 'text'); input1.setAttribute('name', key); input1.setAttribute('value', data[key]); form.appendChild(input1); }); document.body.appendChild(form); return form; }; PunchoutBase.prototype.showBlock = function () { this._block = this._block || this.createBlock(); document.body.appendChild(this._block); }; PunchoutBase.prototype.hideBlock = function () { this._block = this._block || this.createBlock(); document.body.removeChild(this._block); }; PunchoutBase.prototype.createBlock = function () { var block = document.createElement('div'); block.classList.add('punchout-block'); var loading = document.createElement('div'); loading.classList.add('punchout-loading'); loading.appendChild(document.createElement('div')); loading.appendChild(document.createElement('div')); block.appendChild(loading); return block; }; PunchoutBase.prototype.getCheckoutBtn = function () { return document.querySelector(Punchout.current.cartBtnSelector); }; PunchoutBase.prototype.isActive = function () { return Boolean(this.getSessionId()); }; PunchoutBase.prototype.update = function () { if (this.isActive() && this.getCheckoutBtn()) { this.replaceCartBtn(); } var disabled = Boolean(this.getCustomFormSelectors().length && !this.isCustomFormValid()); document.querySelectorAll('#punchout-btn') .forEach(function (btn) { return btn.disabled = disabled; }); }; PunchoutBase.getValue = function (selector) { var inputs = Array.from(document.querySelectorAll(selector)); if (inputs.length === 0) { try { inputs = Array.from(new Set(findInShadow(document.body, selector, []))); } catch (e) { console.error(e); } } if (inputs.length === 0) { return { selector: selector }; } else if (inputs.length === 1) { var input = inputs[0]; if (input.type === 'checkbox' || input.type === 'radio') { return { name: input.name, value: input.checked, selector: selector }; } else { var accessor = ['input', 'textarea', 'select'].includes(input.tagName.toLowerCase()) ? 'value' : 'innerText'; return { name: input.name, value: input[accessor], selector: selector }; } } else { var input = inputs[0]; if (input.type === 'radio') { return { name: input.name, value: inputs.filter(function (i) { return i.checked; }).map(function (i) { return i.value; })[0], selector: selector }; } else if (input.type === 'checkbox') { return { name: input.name, value: inputs.filter(function (i) { return i.checked; }).map(function (i) { return i.value; }), selector: selector }; } else if (['input', 'textarea', 'select'].includes(input.tagName.toLowerCase())) { return { name: input.name, value: inputs.map(function (i) { return i.value; }).filter(function (it) { return it; }), selector: selector }; } else { return { name: input.name, value: inputs.map(function (i) { return i.innerText; }).filter(function (it) { return it; }), selector: selector }; } } }; return PunchoutBase; }()); function getQueryParams() { return window.location.search .substring(1) .split('&') .map(function (pair) { return pair.split('='); }) .reduce(function (p, n) { p[n[0]] = decodeURIComponent(n[1]); return p; }, {}); } (function login() { var qs = getQueryParams(); if (qs.punchout) { localStorage.setItem('punchoutSessionId', qs.punchout); } })(); function findInShadow(node, selector, out) { if (node.querySelector) { var found = node.querySelectorAll(selector); out.push.apply(out, found); } if (node.shadowRoot) { var found = node.shadowRoot.querySelectorAll(selector); if (found) { out.push.apply(out, found); } } var children = node.children; for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; findInShadow(child, selector, out); } if (node.shadowRoot) { var children = node.shadowRoot.children; for (var _a = 0, children_2 = children; _a < children_2.length; _a++) { var child = children_2[_a]; findInShadow(child, selector, out); } } return out; } "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var sparkPunchoutBtnStyles = "#punchout-btn { \n background: #0b3385;\n color: #fff;\n background-color: #125EF8;\n border-radius: 25px;\n text-transform: none;\n letter-spacing: 0;\n font-weight: 500;\n text-align: center;\n width: 100%;\n padding: 15px;\n border: none;\n cursor: pointer;\n }\n \n #punchout-btn:hover { \n background:#000;\n }"; var Punchout = /** @class */ (function (_super) { __extends(Punchout, _super); function Punchout() { var _this = _super.call(this) || this; _this.emailInputSelector = ['#customer_email', '#CustomerEmail', '#customer-email']; _this.passwordInputSelector = ['#customer_password', '#CustomerPassword', '#customer-password']; _this.loginBtnSelector = ['#customer_login [type=submit]', '#customer_login > button', '#customer_login button']; _this.cartBtnSelector = '[name="checkout"]'; _this.fetch = window.fetch; return _this; } Punchout.prototype.injectStyles = function (styles) { if (this.getSessionId()) { _super.prototype.injectStyles.call(this, styles); } }; Punchout.prototype.getSparkCheckoutBtn = function () { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = document.querySelector('spark-drawer')) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector('spark-cart')) === null || _c === void 0 ? void 0 : _c.shadowRoot) === null || _d === void 0 ? void 0 : _d.querySelector('.proceed-button-wrap'); }; Punchout.prototype.getCheckoutBtn = function () { return _super.prototype.getCheckoutBtn.call(this) || this.getSparkCheckoutBtn(); }; Punchout.prototype.replaceCartBtn = function () { var _a; _super.prototype.replaceCartBtn.call(this); var elm = this.getSparkCheckoutBtn(); if (elm) { var style = document.createElement('style'); style.innerHTML = sparkPunchoutBtnStyles; (_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(style); this.replaceCartBtnElement(elm); } }; Punchout.prototype.getCart = function () { if (window.spark && window.spark.getCart) { return window.spark.getCart() .then(function (cart) { return ({ cart: { ShopifySpark: cart } }); }); } else { if (window.jQuery && window.jQuery.getJson) { return window.jQuery.getJson('/cart.js') .then(function (cart) { return ({ cart: { Shopify: cart } }); }); } else { return (Punchout.current.fetch || fetch)('/cart.js', { headers: { 'Cache-Control': 'no-store', "Pragma": 'no-cache', "Expires": '0', }, }).then(function (response) { return response.json(); }) .then(function (cart) { return ({ cart: { Shopify: cart } }); }); } } }; Punchout.prototype.clearCart = function () { if (window.spark && window.spark.updateCart) { return window.spark.updateCart({ clearCart: true }); } else { return fetch('/cart/clear.js', { method: 'POST', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: { 'Content-Type': 'application/json; charset=utf-8', }, redirect: 'follow', referrer: 'no-referrer', }); } }; Punchout.prototype.attemptLogin = function () { var _this = this; var params = getQueryParams(); if (params.punchout && params.email) { this.injectStyles("#customer_login { display:none; }"); var login = function () { window.onload = function (event) { _this.showBlock(); console.log('page is fully loaded'); setTimeout(function () { var emailInput = _this.emailInputSelector.map(function (it) { return document.querySelector(it); }).find(function (el) { return el; }); emailInput.click(); setTimeout(function () { var passwordInput = _this.passwordInputSelector.map(function (it) { return document.querySelector(it); }).find(function (el) { return el; }); var loginBtn = _this.loginBtnSelector.map(function (it) { return document.querySelector(it); }).find(function (el) { return el; }); emailInput.value = params.email; passwordInput.type = "text"; passwordInput.value = params.punchout; loginBtn.click(); }, 1500); }, 100); }; return; /* } else { this.createPunchoutForm({ url: '/account/login', data: { "customer[email]": params.email, "customer[password]": params.punchout, } } ).submit(); }*/ }; login(); } }; return Punchout; }(PunchoutBase)); (new Punchout()).attemptLogin(); let getCart = Punchout.current.getCart; Punchout.current.getCart = ()=> { let prices = Array.from(document.querySelectorAll('span.pre-money')).map(it=>parseFloat(it.innerText.split('').filter(it=>!isNaN(it) || it=='.').join(''))); return getCart() .then(res=>{ res.cart.Shopify.items.forEach((item,i)=>{ item.price = Math.round(prices[i] * 100 / item.quantity); }); return res; }); }; Punchout.current.punchoutButtonLabel = "Take Cart Back";