Untitled

 avatar
user_0417885
plain_text
12 days ago
2.4 kB
1
Indexable
Never
// Firebase initialization and Firestore reference
import { initializeApp } from "firebase/app";
import { getFirestore, collection, addDoc, getDocs, deleteDoc, doc } from "firebase/firestore";

const firebaseConfig = { /* Your Firebase Config Here */ };
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// DOM Elements
const addItemButton = document.getElementById('addItemButton');
const itemNameInput = document.getElementById('itemName');
const itemQuantityInput = document.getElementById('itemQuantity');
const inventoryGrid = document.getElementById('inventoryGrid');
const feedback = document.getElementById('feedback');

// Function to display inventory items
function renderInventory() {
  inventoryGrid.innerHTML = '';  // Clear existing items
  getDocs(collection(db, 'inventory')).then(snapshot => {
    snapshot.forEach(doc => {
      const item = doc.data();
      const card = document.createElement('div');
      card.classList.add('inventory-card');
      card.innerHTML = `
        <h3>${item.name}</h3>
        <p>Quantity: ${item.quantity}</p>
        <button onclick="deleteItem('${doc.id}')">Delete</button>
      `;
      inventoryGrid.appendChild(card);
    });
  }).catch(error => console.error("Error fetching inventory: ", error));
}

// Add new item to Firestore
addItemButton.addEventListener('click', () => {
  const itemName = itemNameInput.value.trim();
  const itemQuantity = Number(itemQuantityInput.value.trim());

  if (itemName && itemQuantity) {
    addDoc(collection(db, 'inventory'), {
      name: itemName,
      quantity: itemQuantity
    }).then(() => {
      feedback.textContent = "Item added successfully!";
      feedback.style.color = "green";
      renderInventory();  // Refresh inventory display
      itemNameInput.value = '';  // Reset inputs
      itemQuantityInput.value = '';
    }).catch(error => console.error("Error adding item: ", error));
  } else {
    feedback.textContent = "Please enter both item name and quantity.";
    feedback.style.color = "red";
  }
});

// Delete an item from Firestore
function deleteItem(itemId) {
  deleteDoc(doc(db, 'inventory', itemId)).then(() => {
    renderInventory();  // Refresh inventory display
  }).catch(error => console.error("Error deleting item: ", error));
}

// Load inventory on page load
window.onload = renderInventory;
Leave a Comment