get_live_fresh.js

Home   »   get_live_fresh.js

const settings = {
    cart_url: "/api/storefront/carts/",
}
/**
 * Gets the current cart
 * @returns cart data in BC format
 */
async function getCart(){
    const storefrontCartURL = new URL( settings.cart_url, window.location.origin );
    storefrontCartURL.searchParams.append('include', 'lineItems.digitalItems.options,lineItems.physicalItems.options');
    return fetch( storefrontCartURL.href ).then( response => {
        return response.json()
    });
}

/**
 * Create cart and add item to it 
 * @param {cartItems } cartItems line_item to be added in the cart 
 * @returns 
 */
async function createCart( cartItems) {
    const response = await fetch(settings.cart_url, {
        method: "POST",
        credentials: "same-origin",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(cartItems),
    });
    return await response.json();
};

/**
 * Retrieves the line_item_id of a product from bigcommerce
 * @param {*} cartData Cart object in BC format
 * @param {*} productID ID of the current product
 * @returns line_item_id
 */
function getlineIDFromCart( cartData, productID ){
    const item_types = ['physicalItems', 'digitalItems', 'customItems'];
    for ( const item_type of item_types ){
        let line_item = cartData.lineItems[item_type].find(item => item.productId === productID);
        if( line_item ){
            return line_item.id;
        }
    }
}
 
/**
 * Add product to the current cart
 * @param {*} cartId Of the current cart
 * @param {*} cartItems Items to be added in the cart
 * @returns update cart response
 */
async function addCartItem(cartId, cartItems) {
    const storefrontCartURL = new URL( settings.cart_url + cartId + '/items', window.location.origin );
    debugger;
    const response = await fetch(storefrontCartURL.href, {
        method: "POST",
        credentials: "same-origin",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(cartItems),
    });
    return await response.json();
};

/**
 * Retrieves the variant ID from a product ID 
 * @param {*} cartData Cart object in BC format
 * @param {*} productID Product id of the current product
 * @returns variant_id
 */

function getVariantIDFromCart( cartData, productID ){
    const item_types = ['physicalItems', 'digitalItems', 'customItems'];
    for ( const item_type of item_types ){
        let line_item = cartData.lineItems[item_type].find(item => item.productId === productID);
        if( line_item ){
            return line_item.variantId;
        }
    }
}

/**
 * Function to be called when the user clicks on add to cart button
 * @param {*} event 
 */
async function addToCartCallback(event) {
    event.stopPropagation();
    event.preventDefault();
    const form = event.target.closest('form');
    const productID = parseInt(form.querySelector('input[name="product_id"]').value);
    const cartResponse = await getCart();
    const cartID = cartResponse.length > 0 ? cartResponse[0].id : false;
    const isSubscription = form.querySelector('.subscription_p input').checked;
    const selectedFrequency = "30";
    let line_item = {
        "lineItems": [
          {
            "quantity": 1,
            "productId": productID,
          }
        ]
      }

    if( cartID ){
        const cartData =  await addCartItem( cartID, line_item );
        const line_item_id = getlineIDFromCart( cartData, productID );
        saveSubscription( cartData, line_item_id, isSubscription, selectedFrequency ).then(response => {
            console.log(response);
            window.location.href = window.location.origin + '/cart.php';
        });
       
    } else {
        const cartData =  await createCart( line_item );
        const line_item_id = getlineIDFromCart( cartData, productID );
        sessionStorage.setItem('cartID', cartData.id);
        saveSubscription( cartData, line_item_id, isSubscription, selectedFrequency ).then(response => {
            console.log(response);
            window.location.href = window.location.origin + '/cart.php';
        });
    }
}

/**
 * Save subscription in Vuex to be used by the RC Adapter
 * @param {Object} cart_data 
 * @param {int} productID 
 * @param {Bool} isSubscription 
 * @param {String} selectedFrequency 
 */
function saveSubscription( cart_data, productID, isSubscription, selectedFrequency ){
    const variant_id = getVariantIDFromCart( cart_data, productID );
    const product_data = RCA_DATA.getProductByBCProductID( productID );
    const subscription_data = product_data.subscriptions && product_data.subscriptions.length ? product_data.subscriptions[0] : null;
    return RCAInterface.subscription.addProductToSubscriptions(
        productID,
        variant_id, 
        cart_data, 
        subscription_data,
        isSubscription, 
        selectedFrequency
    );
}

/**
 * Init the custom snippet
 */
// Check for the presence of RCA_DATA
let checkExist = setInterval(function () {
    if (typeof RCA_DATA !== 'undefined') {
        clearInterval(checkExist);
        const addToCart = document.querySelectorAll('#form-action-addToCart');
        addToCart.forEach( button => {
            button.addEventListener( 'click', addToCartCallback);
            console.log("STARTED");
        } )
    }
}, 20);
// Stop checking for RCA_DATA. It either loaded or clearly is not here.
setTimeout(clearInterval, 3000, checkExist)

Leave a Reply

Your email address will not be published.