/** * Woo Cart Coupon Form widget behavior. * * Applies/removes coupons via AJAX and refreshes cart fragments. */ (function ($) { "use strict"; const INIT_FLAG = "kaWooCartCouponInit"; const setNotice = (wrap, html) => { const notice = wrap.querySelector('.ka-woo-cart-coupon__notice'); if (notice) { notice.innerHTML = html || ''; } }; const updateFragments = (data) => { if (data.cart_html && document.querySelector('.ka-cart-table')) { document.querySelectorAll('.ka-cart-table').forEach((table) => { table.innerHTML = data.cart_html; // Those widgets mark a wrapper as bound and skip it next time. The // listeners lived on the markup just replaced, so without clearing the // flag the cart's quantity and remove controls went dead after // applying a coupon from here. if (table.dataset) { delete table.dataset.kaCartTableInit; } if (window.KACartTable && typeof window.KACartTable.init === "function") { window.KACartTable.init(document); } }); } if (data.totals_html !== undefined) { document.querySelectorAll('.ka-woo-cart-totals').forEach((totals) => { totals.innerHTML = data.totals_html || ''; if (totals.dataset) { delete totals.dataset.kaCartTotalsInit; } if (window.KACartTotals && typeof window.KACartTotals.init === "function") { window.KACartTotals.init(document); } }); } if (data.cross_sells_html !== undefined) { document.querySelectorAll('.ka-woo-cart-cross-sells').forEach((cross) => { cross.innerHTML = data.cross_sells_html || ''; if (window.KACartCrossSells && typeof window.KACartCrossSells.init === "function") { window.KACartCrossSells.init(); } }); } if (data.notices) { const container = document.querySelector('.woocommerce-notices-wrapper'); if (container) { container.innerHTML = data.notices; } } document.body.dispatchEvent(new Event('wc_fragments_refreshed')); }; const sendCoupon = (wrap, mode, code) => { const ajaxUrl = wrap.dataset.ajaxUrl; const nonce = wrap.dataset.nonce; if (!ajaxUrl || !nonce || !mode) return; const applyBtn = wrap.querySelector('.ka-woo-cart-coupon__apply'); const removeBtn = wrap.querySelector('.ka-woo-cart-coupon__remove'); [applyBtn, removeBtn].forEach((btn) => { if (btn) { btn.disabled = true; btn.classList.add('is-loading'); } }); const body = new URLSearchParams(); body.append('action', 'ka_cart_coupon'); body.append('nonce', nonce); body.append('mode', mode); body.append('coupon', code || ''); fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: body.toString(), credentials: 'same-origin', }) .then((res) => res.json()) .then((res) => { const data = res && res.data ? res.data : {}; if (data.cart_html || data.totals_html !== undefined || data.notices) { updateFragments(data); } let html = data.notices || ''; if (!html && data.message) { const safe = String(data.message).replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }[ch])); html = '