(async () => { const lastCartState = []; const bodyLabels = document.body.className.match(/\bex-l-\d{4}/g)?.map((key) => key.replace("ex-l-", "")) || []; const addToCartByLabel = {}; const isInCart = !!document.querySelector(".ex-cart"); bodyLabels.forEach((label) => { if (label in addToCartByLabel_original) { const transformed = Object.fromEntries( Object.entries(addToCartByLabel_original[label]).map(([key, value]) => [key, { product_sku: value }]), ); Object.assign(addToCartByLabel, transformed); // merge into final object } }); if (Object.keys(addToCartByLabel).length === 0) return; const productWrapper = document.createElement("div"); productWrapper.classList.add("fetched-product", "hide"); const bodyFooter = document.querySelector("footer.footer"); if (bodyFooter) bodyFooter.append(productWrapper); else document.body.append(productWrapper); /* FUNCTIONS */ // Checks for obj_XXXXXXX or creates global variable const createProductObject = (scriptElement) => { const scriptContent = scriptElement.textContent; // Extract object name const objNameMatch = scriptContent.match(/var\s+(obj_\d+)/); if (!objNameMatch) return; // Check if already exists const objName = objNameMatch[1]; if (window[objName] && typeof window[objName] === "object") { return; } // Create it globally by injecting script tag try { const script = document.createElement("script"); script.textContent = scriptContent; document.head.appendChild(script); document.head.removeChild(script); } catch (error) { return; } }; // Hide plus, minus and delete buttons const hideButtons = (id) => { if (isInCart) { return; } else { const items = document.querySelectorAll(`.minicart tr.item[data-itemid="${id}"]`); items.forEach((e) => { e.querySelector(".plus-minus")?.classList.add("hide"); e.querySelector(".delete")?.classList.add("hide"); e.querySelector(".minicart_qty")?.setAttribute("readonly", true); }); } }; // Create style for hiding buttons and input const createStyle = () => { const style = document.createElement("style"); let text = ""; Object.values(addToCartByLabel).forEach((e) => { text = `${text} .minicart .item[data-itemid="${e.product_id}"] .minicart_qty, .item_${e.product_id} .quantity{ pointer-events: none!important; } .minicart .item[data-itemid="${e.product_id}"] .plus-minus, .minicart .item[data-itemid="${e.product_id}"] .delete, .item_${e.product_id} .incr-btn, .item_${e.product_id} .delete-btn { display: none!important; } `; }); style.innerHTML = text; document.head.append(style); }; // Check if Id exists in object function checkIdExists(object, idToFind) { return Object.values(object).some((item) => item.product_id == idToFind); } // Update last cart state const updateLastCartState = () => { lastCartState.length = 0; $mini_cart.forEach((e) => { lastCartState.push({ item_id: e.item_id, item_sku: e.item_sku, item_qty: e.item_order_qty, }); }); }; // Create item from get request and append it to footer const createItems = (domObj) => { const createOneItem = (productAddToCart) => { const productButton = productAddToCart.querySelector("button.btn-add-to-cart"); if (!productButton) return; productButton.removeAttribute("disabled"); const addCartWrapper = productAddToCart.querySelector(".live-inventory-v2-add-to-cart-wrapper"); addCartWrapper.insertAdjacentHTML("beforeend", ''); const productSku = productAddToCart.getAttribute("data-sku") || ""; const objKey = Object.keys(addToCartByLabel).find((k) => addToCartByLabel[k].product_sku === productSku); if (!objKey) return; if (addToCartByLabel[objKey].product_button && addToCartByLabel[objKey].product_input && addToCartByLabel[objKey].product_id) { return; } const productInput = productAddToCart.querySelector("input.inputquantity") || {}; const productId = productAddToCart.getAttribute("data-item-id") || ""; if (!(productButton && productInput && productId)) return; addToCartByLabel[objKey].product_button = productButton; addToCartByLabel[objKey].product_input = productInput; addToCartByLabel[objKey].product_id = productId; addToCartByLabel[objKey].product_in_cart = 0; addToCartByLabel[objKey].product_in_cart_add = 0; const productScript = productAddToCart.querySelector(".buttons.group script"); if (!productScript) return; createProductObject(productScript); productWrapper.append(productAddToCart); productWrapper.classList.add("product-added"); }; let products; if (domObj.querySelector("body.ex-product")) { products = domObj.querySelectorAll(".productaddtocart_container .product"); } if (domObj.querySelector("body.ex-searchresult")) { products = domObj.querySelectorAll(".productsgrid_container .tileparent.product"); } if (!products.length) return; products.forEach((product) => { createOneItem(product); }); }; // Get needed items from request const getItemsRequest = async () => { const addCartWrappers = document.querySelectorAll(".ex-product .productaddtocart_container .live-inventory-v2-add-to-cart-wrapper"); const cartDropdownAll = document.querySelector(".cart-dropdown"); const cartItemlistsAll = document.querySelector(".ex-cart .row.main "); const allTobeDisabled = [ ...(addCartWrappers ? [...addCartWrappers] : []), ...(cartDropdownAll ? [cartDropdownAll] : []), ...(cartItemlistsAll ? [cartItemlistsAll] : []), ]; allTobeDisabled.forEach((element) => { element.style.pointerEvents = "none"; element.style.opacity = "0.3"; }); const itemsSku = Object.values(addToCartByLabel).flatMap((innerObj) => Object.values(innerObj)); console.log(itemsSku); //const querySku = `/search?query=${encodeURIComponent(itemsSku.join("+"))}&p=1`; const querySku = `/search?query=${itemsSku.join("+")}&p=1`; console.log(querySku); try { const response = await fetch(`${window.location.origin}${querySku}`); const htmlText = await response.text(); const parser = new DOMParser(); const doc = parser.parseFromString(htmlText, "text/html"); createItems(doc); } catch (err) { } finally { allTobeDisabled.forEach((element) => { element.style.pointerEvents = ""; element.style.opacity = ""; }); } }; // Main logic const addItems = (detail) => { const actionType = detail.type; const itemSKU = detail.item.sku; const itemId = detail.item.item; const itemTitle = detail.item.name; const itemQty = detail.item.qty; // Find item labels and return label id if it's in addToCartByLabel const findLabel = () => { for (let element of $mini_cart) { if (element.item_id !== itemId) continue; const labelIds = element.product_labels?.split(" ") || []; const foundId = labelIds.find((id) => addToCartByLabel[id]); return foundId; } return undefined; }; const addNewItem = () => { const labelId = findLabel(); if (!labelId) return; addToCartByLabel[labelId].product_input.value = itemQty; addToCartByLabel[labelId].product_button.click(); }; const updateItem = () => { const labelId = findLabel(); if (!labelId) return; const extraId = addToCartByLabel[labelId].product_id; let foundElement; $mini_cart.forEach((element, index) => { if (element.item_order_qty === itemQty && element.item_id === itemId) { const allItems = isInCart ? document.querySelectorAll(".shopping-cart .items-list tr.item") : document.querySelectorAll(".minicart > tr.item"); const mainItem = allItems[index]; const extraItem = allItems[index - 1]; const mainValue = mainItem.querySelector(".minicart_qty") || mainItem.querySelector(".quantity"); const extraValue = extraItem.querySelector(".minicart_qty") || extraItem.querySelector(".quantity"); if (extraValue && mainValue && extraValue.value !== mainValue.value) { extraValue.value = mainValue.value; extraValue.dispatchEvent(new Event("change", { bubbles: true })); } } }); }; const removeItem = () => { $mini_cart.forEach((element, index) => { if (element.item_order_qty === itemQty) { let labelId = ""; Object.entries(addToCartByLabel).forEach(([key, value]) => { if (value.product_id == element.item_id) { labelId = key; } }); if (labelId && $mini_cart[index + 1]) { if (!new RegExp(labelId).test($mini_cart[index + 1].product_labels)) { const allItems = isInCart ? document.querySelectorAll(".shopping-cart .items-list tr.item") : document.querySelectorAll(".minicart > tr.item"); const deleteBtn = isInCart ? allItems[index].querySelector(".delete-btn") : allItems[index].querySelector(".delete"); deleteBtn.dispatchEvent(new Event("click", { bubbles: true })); } } else if (labelId && !$mini_cart[index + 1]) { const allItems = isInCart ? document.querySelectorAll(".shopping-cart .items-list tr.item") : document.querySelectorAll(".minicart > tr.item"); const deleteBtn = isInCart ? allItems[index].querySelector(".delete-btn") : allItems[index].querySelector(".delete"); deleteBtn.dispatchEvent(new Event("click", { bubbles: true })); } } }); }; if (actionType === "add-item") { addNewItem(); } else if (actionType === "update-quantity") { updateItem(); } else if (actionType === "remove-item") { removeItem(); } }; await getItemsRequest(); createStyle(); document.addEventListener("cart-total-update", function (e) { setTimeout(() => { addItems(e.detail); }, 100); }); })();