smufa / Aliexpress fixer

// ==UserScript==
// @name        Aliexpress fixer
// @namespace   Violentmonkey Scripts
// @match       https://www.aliexpress.com/*
// @grant       GM_xmlhttpRequest
// @grant       GM_addStyle
// @connect     aliexpress.com
// @version     1.0
// @author      smufa
// @license GPL-3.0-or-later
// @description 9/20/2025, 12:57:15 PM
// ==/UserScript==

(function() {
    'use strict';

    // Add custom CSS for shipping info display and bundle deal highlighting
    GM_addStyle(`
        .shipping-info {
            font-size: 12px;
            color: #ff6d00;
            margin-top: 5px;
            font-weight: bold;
        }
        .free-shipping {
            color: #2e7d32;
        }
        .loading-shipping {
            color: #888;
            font-style: italic;
        }
        /* Bundle deal highlighting */
        .bundle-deal {
            background-color: rgba(255, 230, 230, 0.7) !important;
            border-radius: 4px;
        }
    `);

    // Function to get product ID from card using href
    function getProductId(card) {
        const link = card.querySelector('a.kc_b.io_it.search-card-item');
        if (!link) return null;

        let href = link.href;

        // Check if it's a bundle deal URL
        if (href.includes('/ssr/300000512/BundleDeals2')) {
            // Extract the first product ID from the URL
            const productIdMatch = href.match(/productIds=(\d+):/);
            if (productIdMatch) {
                // Change the href to the regular product page
                link.href = `https://www.aliexpress.com/item/${productIdMatch[1]}.html`;
                return productIdMatch[1];
            }
        }

        // Extract product ID from href for regular items
        const match = href.match(/\/item\/(\d+)\.html/);
        return match ? match[1] : null;
    }

    // Function to check if item is a "Choice" item
    function isChoiceItem(card) {
        // Look for the specific Choice badge image
        const choiceBadge = card.querySelector('img.mx_m0[src*="S1887a285b60743859ac7bdbfca5e0896Z/154x64.png"]');
        return !!choiceBadge;
    }

    // Function to check if item is a bundle deal
    function isBundleDeal(card) {
        const link = card.querySelector('a.kc_b.io_it.search-card-item');
        return link && link.href.includes('/ssr/300000512/BundleDeals2');
    }

    // Function to find the preview modal
    function findPreviewModal() {
        // Use the specific class for the modal
        return document.querySelector('.comet-v2-modal-body');
    }

    // Function to extract shipping info from preview
    function extractShippingFromPreview() {
        // Find the preview modal
        const modal = findPreviewModal();
        if (!modal) {
            return null; // No modal found
        }

        // Look for shipping info in the specific structure within the modal
        const shippingContainer = modal.querySelector('.shipping--content--ulA3urO .dynamic-shipping');
        if (!shippingContainer) {
            return null;
        }

        // Try to find the shipping title line
        const shippingTitleLine = shippingContainer.querySelector('.dynamic-shipping-line.dynamic-shipping-titleLayout');
        if (shippingTitleLine) {
            const shippingText = shippingTitleLine.textContent.trim();
            // Extract just the shipping cost (e.g., "Shipping: €1.04")
            const shippingMatch = shippingText.match(/Shipping:\s*([^\s]+)/);
            if (shippingMatch) {
                return shippingMatch[1];
            }
            return shippingText;
        }

        return null; // Return null if no shipping info found
    }

    // Function to hide any visible modals
    function hideAllModals() {
        // Hide modal elements directly
        const modals = document.querySelectorAll('.comet-v2-modal-mask, .comet-v2-modal-wrap, .comet-v2-modal-body, .comet-v2-modal');
        modals.forEach(modal => {
            modal.style.setProperty('display', 'none', 'important');
            modal.style.setProperty('visibility', 'hidden', 'important');
            modal.style.setProperty('opacity', '0', 'important');
            modal.style.setProperty('pointer-events', 'none', 'important');
            modal.style.setProperty('position', 'absolute', 'important');
            modal.style.setProperty('left', '-9999px', 'important');
            modal.style.setProperty('top', '-9999px', 'important');
            modal.style.setProperty('width', '0', 'important');
            modal.style.setProperty('height', '0', 'important');
            modal.style.setProperty('overflow', 'hidden', 'important');
            modal.style.setProperty('z-index', '-9999', 'important');
        });

        // Also hide any elements that might be modals based on class names
        const possibleModals = document.querySelectorAll('[class*="modal"], [class*="popup"], [class*="dialog"]');
        possibleModals.forEach(modal => {
            modal.style.setProperty('display', 'none', 'important');
            modal.style.setProperty('visibility', 'hidden', 'important');
            modal.style.setProperty('opacity', '0', 'important');
            modal.style.setProperty('pointer-events', 'none', 'important');
        });
    }

    // Function to get shipping info using preview
    function getShippingInfoViaPreview(card, callback) {
        // Find the "See preview" button
        const previewButton = card.querySelector('.kc_kj .kc_bs');
        if (!previewButton) {
            callback("Preview button not found");
            return;
        }

        // Hide any existing modals before opening a new one
        hideAllModals();

        // Click the preview button
        previewButton.click();

        // Set up a mutation observer to hide any modals that appear
        const modalObserver = new MutationObserver(function(mutations) {
            hideAllModals();
        });

        // Start observing the document body for added nodes
        modalObserver.observe(document.body, {
            childList: true,
            subtree: true
        });

        // Also set up an interval to repeatedly hide modals
        const modalHidingInterval = setInterval(hideAllModals, 100);

        // Wait for preview to load and shipping info to be available
        let attempts = 0;
        const maxAttempts = 20; // Maximum number of attempts (10 seconds)

        const checkInterval = setInterval(() => {
            attempts++;

            // Try to extract shipping info
            const shippingText = extractShippingFromPreview();

            // If shipping info is found or we've reached max attempts
            if (shippingText !== null || attempts >= maxAttempts) {
                clearInterval(checkInterval);
                clearInterval(modalHidingInterval);

                // Disconnect the modal observer
                modalObserver.disconnect();

                // Close the preview using the specific close button class
                const closeButton = document.querySelector('.comet-v2-modal-close');
                if (closeButton) {
                    closeButton.click();
                } else {
                    // Fallback: press Escape key
                    const escEvent = new KeyboardEvent('keydown', {
                        key: 'Escape',
                        keyCode: 27,
                        which: 27,
                        bubbles: true
                    });
                    document.dispatchEvent(escEvent);
                }

                // Return shipping info with "Shipping:" prefix
                if (shippingText) {
                    callback("Shipping: " + shippingText);
                } else {
                    callback("Shipping info not found");
                }
            }
        }, 500); // Check every 500ms
    }

    // Function to add shipping info to card
    function addShippingInfo(card) {
        if (card.querySelector('.shipping-info')) return; // Already added

        // Get product ID (this will also modify bundle deal URLs)
        const productId = getProductId(card);
        if (!productId) return;

        // Check if it's a bundle deal and add the class
        if (isBundleDeal(card)) {
            const cardWrapper = card.closest('.search-item-card-wrapper-gallery');
            if (cardWrapper) {
                cardWrapper.classList.add('bundle-deal');
            }
        }

        const shippingContainer = document.createElement('div');
        shippingContainer.className = 'shipping-info';

        // Check if it's a Choice item (free shipping)
        if (isChoiceItem(card)) {
            // For Choice items, immediately show free shipping without waiting
            shippingContainer.classList.add('free-shipping');
            shippingContainer.textContent = '✓ Free Shipping';
        } else {
            // For non-Choice items, show loading and fetch shipping info
            shippingContainer.classList.add('loading-shipping');
            shippingContainer.textContent = 'Loading shipping...';

            // Get shipping info via preview
            getShippingInfoViaPreview(card, function(shippingText) {
                shippingContainer.textContent = shippingText;
                shippingContainer.classList.remove('loading-shipping');
            });
        }

        // Find where to insert the shipping info
        const priceElement = card.querySelector('.kc_gh');
        if (priceElement) {
            priceElement.parentNode.insertBefore(shippingContainer, priceElement.nextSibling);
        } else {
            card.appendChild(shippingContainer);
        }
    }

    // Function to process all product cards
    function processCards() {
        const productCards = document.querySelectorAll('.kc_kq');

        // Process cards one at a time with a delay to avoid overwhelming the page
        let index = 0;

        function processNextCard() {
            if (index < productCards.length) {
                addShippingInfo(productCards[index]);
                index++;
                // For non-Choice items, we need to wait for the preview to load
                // For Choice items, we can process faster since we don't open preview
                const isChoice = isChoiceItem(productCards[index-1]);
                // Click the annoying close icon if it exists with the specific class
                setTimeout(() => {
                    const annoyingClose = document.querySelector('.comet-icon-close32.kc_a0');
                    if (annoyingClose) {
                        annoyingClose.click();
                    }
                }, 100);
                setTimeout(processNextCard, isChoice ? 100 : 1000);
            }
        }

        processNextCard();
    }

    // Initial processing
    setTimeout(processCards, 2000);

    // Handle dynamic content loading with shorter debounce time
    const observer = new MutationObserver(function(mutations) {
        if (mutations.some(mutation => mutation.addedNodes.length > 0)) {
            // Debounce to avoid too many calls - reduced from 2000ms to 500ms
            clearTimeout(window.processCardsTimeout);
            window.processCardsTimeout = setTimeout(processCards, 1000);
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();