(async () => { if (!document.querySelector(".ex-a-3463648")) return; let allTiles; let dropdownCart; let productLines; let isProcessing = false; const tierObj = { 1: { tier: 75, items: [383884476, 383884477, 383884478, 383884479], }, 2: { tier: 150, items: [383908819, 383908821, 383908822], }, 3: { tier: 250, items: [383908824, 383908828, 383908829], }, }; function moveItems() { const allMerch = document.querySelectorAll(".item-merchandising.gift-container"); const promoRewardsSection = document.querySelector(".promo-rewards-section"); if (allMerch.length === 0 || !promoRewardsSection) return; allMerch.forEach((e) => { const fragment = document.createDocumentFragment(); const col = e.querySelectorAll(".tileparent:not(.tileparent_placeholder)"); fragment.append(...col); const tier = [...e.classList] .find((cls) => cls.startsWith("gift-container-")) .split("-") .slice(-1)[0]; console.log(tier); const target = promoRewardsSection.querySelector(`.${tier}-tier .promo-rewards-merch__body`); console.log(target); if (target) { target.appendChild(fragment); } }); } function removeBtnInpt() { const allArr = Object.values(tierObj).reduce((acc, tier) => [...acc, ...tier.items], []); if (!document.querySelector(".ex-cart")) { dropdownCart = document.querySelector(".minicart_container .cart-dropdown table.minicart"); if (!dropdownCart) return; dropdownCart.querySelectorAll("tr.item").forEach((item) => { const itemId = parseInt(item.dataset.itemid); if (allArr.includes(itemId)) { const inpt = item.querySelector(".right-td"); if (inpt) inpt.innerHTML = ""; } }); } else { productLines = document.querySelector(".cartproductlines_container table.items-list"); if (!productLines) return; productLines.querySelectorAll("tr.item").forEach((item) => { const itemId = parseInt([...item.classList].find((cls) => cls.startsWith("item_")).split("_")[1]); if (allArr.includes(itemId)) { const inpt = item.querySelector(".qnt-count"); if (inpt) inpt.innerHTML = ""; } }); } } function checkIsProductInCart(itemId) { return $mini_cart.some((item) => item.item_id === parseInt(itemId)); } // check if any product from the tier is already in the cart function checkIsTierProductInCart() { let arr = []; Object.values(tierObj).forEach((tier) => { if (tier.tier <= ($mini_cart[0].cart_sub_total || 0)) { arr.push(...tier.items); } }); //const tierItems = tierObj[tierIndex].items; return $mini_cart.some((cartItem) => arr.includes(cartItem.item_id)); } // get not allowed items based on cart total function getNotAllowedArr() { const arr = []; for (let i = 1; i <= Object.keys(tierObj).length; i++) { if (($mini_cart[0].cart_sub_total || 0) < tierObj[i].tier) { arr.push(...tierObj[i].items); } } return arr; } // get allowed items based on cart total function getAllowedArr() { const arr = []; for (let i = 1; i <= Object.keys(tierObj).length; i++) { if (($mini_cart[0].cart_sub_total || 0) >= tierObj[i].tier) { arr.push(...tierObj[i].items); } } return arr; } // delete items from dropdown cart or cart page based on the provided array of item ids function deleteItemsFromDropdown(arr) { if (!document.querySelector(".ex-cart")) { dropdownCart = document.querySelector(".minicart_container .cart-dropdown table.minicart"); if (!dropdownCart) return; dropdownCart.querySelectorAll("tr.item").forEach((item) => { const itemId = parseInt(item.dataset.itemid); if (arr.includes(itemId)) { const deleteBtn = item.querySelector(".delete"); deleteBtn && deleteBtn.click(); } }); } else { productLines = document.querySelector(".cartproductlines_container table.items-list"); if (!productLines) return; productLines.querySelectorAll("tr.item").forEach((item) => { const itemId = parseInt([...item.classList].find((cls) => cls.startsWith("item_")).split("_")[1]); if (arr.includes(itemId)) { const deleteBtn = item.querySelector(".delete .delete-btn"); deleteBtn && deleteBtn.click(); } }); } } // add or remove gift item logic with API call async function updateGiftCart(giftItem, reqMethod, reqUrl, giftQty, msg) { const productData = {}; if (msg === "add-item") productData.product = JSON.stringify(giftItem); else if (msg === "delete-item") productData.item = JSON.stringify(giftItem); giftQty && (productData.qty = giftQty); try { const res = await fetch(`/cart/${reqUrl}`, { method: reqMethod, headers: { "Content-Type": "application/x-www-form-urlencoded", "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content, "X-Requested-With": "XMLHttpRequest", }, body: new URLSearchParams(productData), }); let e; const text = await res.text(); if (!text) return (e = { status: "error" }); e = JSON.parse(text); updateminicart(e, !1, msg); return e; } catch (error) { return { status: "error" }; } } // handle click on gift item button async function handleButtonClick(event) { event.preventDefault(); const tile = event.target.closest(".tile.product"); const itemId = tile.dataset.itemId; const tierIndex = Object.values(tierObj).findIndex((tier) => tier.items.includes(parseInt(itemId))); const addObj = { item_catalog_id: 1000, item_catalog_item_id: tile.dataset.pid, item_cost_center_id: 0, item_department_id: 0, item_id: tile.dataset.itemId, item_image_thumbnail: tile.dataset.itemImage?.split("/").slice(-1)[0] || "", item_image_thumbnail_path: tile.dataset.itemImage, item_is_contract: 0, item_is_multiple: 0, item_maximum_order: 0, item_minimum_order: 1, item_multiple_qty: 0, item_name: tile.dataset.itemName, item_pack: tile.dataset.pack, item_price_type: 0, item_price_unit: 1, item_sku: tile.dataset.sku, item_supplier_id: tile.dataset.supplierId || 1000, line_ref: "", modifiers: null, pack_uom: tile.dataset.packUom || "EA", }; // check if product is in the tier object if (tierIndex === -1) return; // check if cart total meets the tier requirement if (!$mini_cart[0].cart_sub_total || $mini_cart[0].cart_sub_total < tierObj[tierIndex + 1].tier) { swal({ title: "Spend more", text: `Add more items worth $${(tierObj[tierIndex + 1].tier - $mini_cart[0].cart_sub_total).toFixed(2)} to unlock this gift!`, type: "warning", icon: "warning", button: "OK", }); return; } // check if product is already in the cart if (checkIsProductInCart(itemId)) { swal({ title: "Item in a cart", text: "This item is already in a cart.", type: "warning", icon: "warning", button: "OK", }); return; } //check if any product from the tier is already in the cart if (checkIsTierProductInCart()) { let arr = []; Object.values(tierObj).forEach((tier) => { if (tier.tier <= ($mini_cart[0].cart_sub_total || 0)) { arr.push(...tier.items); } }); const existingCartItem = $mini_cart.find((cartItem) => arr.includes(cartItem.item_id)); const confirmed = await new Promise((resolve) => { swal( { title: "Replace Item?", text: "You have already added a gift from this tier. Do you want delete the existing one and add this item?", imageUrl: `${existingCartItem.item_image_thumbnail_path}${existingCartItem.item_image_thumbnail}`, showCancelButton: true, confirmButtonText: "Yes, replace it!", closeOnConfirm: true, }, function (isConfirm) { resolve(isConfirm); }, ); }); if (!confirmed) { return; } isProcessing = true; const deleteObj = { session_cart_id: existingCartItem.session_cart_id, item_id: existingCartItem.item_id, catalog_id: 1000, supplier_id: 1000, costcenter_id: 0, department_id: 0, remove_all: 0, }; await new Promise((r) => setTimeout(r, 200)); swal({ title: "Processing...", text: "Please wait.", showConfirmButton: false, // hide OK button allowOutsideClick: false, // prevent closing allowEscapeKey: false, }); await updateGiftCart(deleteObj, "POST", "deleteitem", 0, "delete-item"); } swal({ title: "Processing...", text: "Please wait.", showConfirmButton: false, // hide OK button allowOutsideClick: false, // prevent closing allowEscapeKey: false, }); const res = await updateGiftCart(addObj, "POST", "addcart", 1, "add-item"); isProcessing = false; if (document.querySelector(".ex-cart")) { setTimeout(() => { location.reload(); }, 200); } else { swal("Done!", "Item added to cart.", "success"); } } // update mini dropdown cart by deleting not allowed items based on cart total and added gift items function updateMiniDropdownCart() { if (isProcessing) return; const arrNotAllowed = getNotAllowedArr(); deleteItemsFromDropdown(arrNotAllowed); } // create buttons for gift items if they don't exist and add event listener to them function createButtonsForGiftItems() { document.querySelectorAll(".gift-container .tile.product").forEach((tile) => { if (tile.querySelector(".add-to-cart-btn")) return; const button = document.createElement("button"); button.addEventListener("click", handleButtonClick); button.innerHTML = `Redeem`; button.classList.add("btn", "btn-primary", "add-to-cart-btn"); tile.appendChild(button); }); } // update the state of gift item buttons based on allowed and not allowed items function updateButtonsState() { const allowedArr = getAllowedArr(); const notAllowedArr = getNotAllowedArr(); allTiles.forEach((tile) => { const itemId = parseInt(tile.dataset.itemId); const button = tile.querySelector(".add-to-cart-btn"); if (allowedArr.includes(itemId)) { button.disabled = false; button.querySelector("span").textContent = "Redeem"; if ($mini_cart.some((item) => item.item_id === itemId)) { button.disabled = true; button.querySelector("span").textContent = "In Cart"; } } if (notAllowedArr.includes(itemId)) { button.disabled = true; button.querySelector("span").textContent = "Locked"; } }); } // update link to checkout page in mini dropdown cart and cart page function updateLinkToCheckout() { document.querySelectorAll('a[href*="/checkout"], button[data-url*="/checkout"]').forEach((btn) => { let isRequestInProgress = false; btn.addEventListener("click", function (e) { e.preventDefault(); if (isRequestInProgress) { return; } isRequestInProgress = true; setTimeout(() => { updateMiniDropdownCart(); window.location.href = "/checkout"; }, 1000); }); }); } document.addEventListener("cart-total-update", () => { updateMiniDropdownCart(); updateButtonsState(); removeBtnInpt(); }); document.addEventListener("live-inventory-done", () => { updateMiniDropdownCart(); updateButtonsState(); removeBtnInpt(); }); document.addEventListener("DOMContentLoaded", () => { allTiles = document.querySelectorAll(".gift-container .tile"); createButtonsForGiftItems(); updateMiniDropdownCart(); updateButtonsState(); updateLinkToCheckout(); moveItems(); removeBtnInpt(); }); })();