Error Fetching Inventory

Error Fetching Inventory

Jumpwell
Shopify Partner
4 0 1

document.addEventListener('DOMContentLoaded', function() {
  const formatMoney = (amount) => {
    return '₱' + (amount / 100).toFixed(2) + ' PHP';
  };

  const updateCart = (lineItemId, quantity, lineItemElement, maxQuantity) => {
    if (quantity > maxQuantity) {
      alert(`Only ${maxQuantity} items are available in you location.`);
      quantity = maxQuantity;
    }

    fetch('/cart/change.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        id: lineItemId,
        quantity: quantity
      })
    })
    .then(response => response.json())
    .then(cart => {
      const updatedItem = cart.items.find(item => line_item.key === lineItemId);
      if (updatedItem) {
        lineItemElement.querySelector('.quantity').textContent = updatedItem.quantity;
        lineItemElement.querySelector('.line-item-price').textContent = formatMoney(updatedItem.line_price);
      } else {
        lineItemElement.remove();
      }
      updateCartTotal(cart);
    })
    .catch(error => console.error('Error:', error));
  };

  const updateCartTotal = (cart) => {
    document.querySelector('.cart-total').textContent = formatMoney(cart.total_price);
  };

 const getMetroManilaInventory = (variantId) => {
  if (!variantId) {
    console.error('Error: Variant ID is missing');
    return Promise.reject('Variant ID is missing');
  }

  return fetch(`/variants/${variantId}.json`)
    .then(response => {
      if (!response.ok) {
        throw new Error('Variant not found');
      }
      return response.json();
    })
    .then(data => {
      if (!data.variant.inventoryLevels_item || !Array.isArray(data.variant.inventoryLevels_item)) {
        throw new Error('Inventory levels not found or incorrect format');
      }

      const inventoryLevel = data.variant.inventoryLevels_item.find(level => inventoryLevels_item.location.name === 'Metro Manila (Jentec Cold Storage, Luis St., Pasig City)');
      return inventoryLevel ? inventoryLevels_item.available : 0;
    })
    .catch(error => {
      console.error('Error fetching inventory:', error);
      return 0; // Return 0 if there's an error
    });
};


  document.querySelectorAll('.quantity-button').forEach(button => {
    button.addEventListener('click', function() {
      const action = this.dataset.action;
      const lineItemElement = this.closest('.line-item');
      const lineItemId = lineItemElement.dataset.lineItemId;
      const variantId = lineItemElement.dataset.variantId; // Make sure this exists
      const quantityElement = lineItemElement.querySelector('.quantity');
      let quantity = parseInt(quantityElement.textContent);

      const selectedLocationCode = localStorage.getItem('selectedLocationCode');

      if (selectedLocationCode === 'METRO-MANILA') {
        // Fetch inventory quantity for Metro Manila before updating the cart
        getMetroManilaInventory(variantId).then(availableQuantity => {
          if (action === 'increase') {
            quantity++;
          } else if (action === 'decrease' && quantity > 1) {
            quantity--;
          }

          updateCart(lineItemId, quantity, lineItemElement, availableQuantity);
        });
      } else {
        alert("This product is not available for the selected location.");
      }
    });
  });

  document.querySelectorAll('.remove-button').forEach(button => {
    button.addEventListener('click', function() {
      const lineItemElement = this.closest('.line-item');
      const lineItemId = lineItemElement.dataset.lineItemId;

      updateCart(lineItemId, 0, lineItemElement);
    });
  });
});


clipboard_image_a56fad04772b1c73.pngclipboard_image_9d45d0ab43915a50.png

clipboard_image_a9179e0e4b07ebae.png

  

Replies 0 (0)