0% found this document useful (0 votes)
18 views6 pages

Function

Uploaded by

Tecki Mikey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

Function

Uploaded by

Tecki Mikey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

<!

DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inventory</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.1/xlsx.full.min.js"></script>
</head>
<body>
<h1>Inventory Management</h1>

<div id="status">Connecting to Firebase...</div>

<table id="inventoryTable">
<thead>
<tr>
<th>Date</th>
<th>Item Code</th>
<th>Name</th>
<th>Category</th>
<th>Quantity</th>
<th>Cost Price</th>
<th>Selling Price</th>
<th>Consumer Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- Data will be dynamically inserted here -->
</tbody>
</table>

<!-- Form to Add/Edit Item -->


<form id="addItemForm">
<h2 id="formTitle">Add New Item</h2>
<input type="text" id="itemCode" placeholder="Item Code" required><br>
<input type="text" id="itemName" placeholder="Name" required><br>
<input type="text" id="itemCategory" placeholder="Category" required><br>
<input type="number" id="itemQuantity" placeholder="Quantity" required><br>
<input type="number" id="itemCostPrice" placeholder="Cost Price"
required><br>
<input type="number" id="itemSellerPrice" placeholder="Selling Price"
required><br>
<input type="number" id="itemConsumerPrice" placeholder="Consumer Price"
required><br>
<input type="date" id="itemDate" placeholder="Date" required><br> <!--
Added date field -->
<button type="submit" id="submitButton">Add Item</button>
<button type="button" id="clearButton" style="display:none;">Clear</button>
</form>

<button id="downloadButton">Download Inventory as Excel</button>


<input type="file" id="uploadFile" accept=".xlsx">
<button id="uploadButton">Upload Inventory</button>

<script type="module">
import { initializeApp } from
"https://www.gstatic.com/firebasejs/10.3.0/firebase-app.js";
import { getDatabase, ref, onValue, set, remove, get, update } from
"https://www.gstatic.com/firebasejs/10.3.0/firebase-database.js";

const firebaseConfig = {
apiKey: "AIzaSyC3JRUCohz7pZZ2kZ1vSItq6vjalorZTa0",
authDomain: "systemstore-e0c45.firebaseapp.com",
databaseURL: "https://systemstore-e0c45-default-rtdb.asia-
southeast1.firebasedatabase.app",
projectId: "systemstore-e0c45",
storageBucket: "systemstore-e0c45.appspot.com",
messagingSenderId: "252593844424",
appId: "1:252593844424:web:2a8385f44b48dff586f5fd",
measurementId: "G-QS8881KHKK"
};

const app = initializeApp(firebaseConfig);


const database = getDatabase(app);
const productsRef = ref(database, 'products');

const statusElement = document.getElementById('status');


const tableBody = document.getElementById('tableBody');
const downloadButton = document.getElementById('downloadButton');
const uploadButton = document.getElementById('uploadButton');
const uploadFileInput = document.getElementById('uploadFile');

let editMode = false;


let currentItemCode = null;

// Function to save or edit an item


function saveItem(itemCode, name, category, quantity, costPrice,
sellerPrice, consumerPrice, date) {
const itemRef = ref(database, 'products/' + itemCode);
set(itemRef, {
name: name,
category: category,
quantity: quantity,
costPrice: costPrice,
sellerPrice: sellerPrice,
consumerPrice: consumerPrice,
date: date // Include date
}).then(() => {
alert(editMode ? "Item updated successfully!" : "Item added
successfully!");
resetForm();
}).catch((error) => {
alert("Failed to save item: " + error.message);
});
}

// Function to delete an item


function deleteItem(itemCode) {
const confirmDelete = confirm("Are you sure you want to delete this
item?");
if (confirmDelete) {
const itemRef = ref(database, 'products/' + itemCode);
remove(itemRef).then(() => {
alert("Item deleted successfully!");
}).catch((error) => {
alert("Failed to delete item: " + error.message);
});
} else {
alert("Item deletion canceled.");
}
}

// Function to populate the form with item data for editing


function editItem(itemCode, product) {
document.getElementById('itemCode').value = itemCode;
document.getElementById('itemName').value = product.name;
document.getElementById('itemCategory').value = product.category;
document.getElementById('itemQuantity').value = product.quantity;
document.getElementById('itemCostPrice').value = product.costPrice;
document.getElementById('itemSellerPrice').value = product.sellerPrice;
document.getElementById('itemConsumerPrice').value =
product.consumerPrice;
document.getElementById('itemDate').value = product.date || ''; //
Populate date field

document.getElementById('formTitle').textContent = "Edit Item";


document.getElementById('submitButton').textContent = "Save Changes";
document.getElementById('clearButton').style.display = "inline-block";

editMode = true;
currentItemCode = itemCode;
}

// Function to reset the form to default state


function resetForm() {
document.getElementById('addItemForm').reset();
document.getElementById('formTitle').textContent = "Add New Item";
document.getElementById('submitButton').textContent = "Add Item";
document.getElementById('clearButton').style.display = "none";

editMode = false;
currentItemCode = null;
}

// Function to display items in the table


function displayItems(products) {
tableBody.innerHTML = ''; // Clear the table before inserting new data
products.forEach((product) => {
const itemCode = product.key;
const productData = product.val();
const row = document.createElement('tr');

const dateCell = document.createElement('td');


dateCell.textContent = productData.date || '';
row.appendChild(dateCell);

const codeCell = document.createElement('td');


codeCell.textContent = itemCode;
row.appendChild(codeCell);

const nameCell = document.createElement('td');


nameCell.textContent = productData.name;
row.appendChild(nameCell);

const categoryCell = document.createElement('td');


categoryCell.textContent = productData.category;
row.appendChild(categoryCell);

const quantityCell = document.createElement('td');


quantityCell.textContent = productData.quantity;
row.appendChild(quantityCell);

const costPriceCell = document.createElement('td');


costPriceCell.textContent = productData.costPrice;
row.appendChild(costPriceCell);

const sellerPriceCell = document.createElement('td');


sellerPriceCell.textContent = productData.sellerPrice;
row.appendChild(sellerPriceCell);

const consumerPriceCell = document.createElement('td');


consumerPriceCell.textContent = productData.consumerPrice;
row.appendChild(consumerPriceCell);

// Create action buttons


const actionCell = document.createElement('td');

const editButton = document.createElement('button');


editButton.textContent = "Edit";
editButton.onclick = () => editItem(itemCode, productData);
actionCell.appendChild(editButton);

const deleteButton = document.createElement('button');


deleteButton.textContent = "Delete";
deleteButton.onclick = () => deleteItem(itemCode);
actionCell.appendChild(deleteButton);

row.appendChild(actionCell);

tableBody.appendChild(row); // Add the row to the table body


});
}

// Function to download data as an Excel file


function downloadExcel(data) {
const ws = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Inventory");
const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

const blob = new Blob([wbout], { type: "application/octet-stream" });


const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'Inventory.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}

// Function to upload data from an Excel file


function uploadExcel(file) {
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(sheet);

jsonData.forEach((item) => {
const itemCode = item['Item Code'];
if (itemCode) {
const itemRef = ref(database, 'products/' + itemCode);
set(itemRef, item).catch((error) => {
alert("Failed to upload item: " + error.message);
});
}
});

alert("Inventory uploaded successfully!");


};
reader.readAsArrayBuffer(file);
}

// Event listener for form submission


document.getElementById('addItemForm').addEventListener('submit', (e) => {
e.preventDefault();
const itemCode = document.getElementById('itemCode').value;
const name = document.getElementById('itemName').value;
const category = document.getElementById('itemCategory').value;
const quantity = document.getElementById('itemQuantity').value;
const costPrice = document.getElementById('itemCostPrice').value;
const sellerPrice = document.getElementById('itemSellerPrice').value;
const consumerPrice =
document.getElementById('itemConsumerPrice').value;
const date = document.getElementById('itemDate').value; // Get date
value

saveItem(itemCode, name, category, quantity, costPrice, sellerPrice,


consumerPrice, date);
});

// Event listener for clear button


document.getElementById('clearButton').addEventListener('click', (e) => {
resetForm();
});

// Event listener for download button


downloadButton.addEventListener('click', () => {
get(productsRef).then((snapshot) => {
const data = [];
snapshot.forEach((product) => {
const productData = product.val();
data.push({
'Date': productData.date,
'Item Code': product.key,
'Name': productData.name,
'Category': productData.category,
'Quantity': productData.quantity,
'Cost Price': productData.costPrice,
'Selling Price': productData.sellerPrice,
'Consumer Price': productData.consumerPrice
});
});
downloadExcel(data);
}).catch((error) => {
alert("Failed to download data: " + error.message);
});
});

// Event listener for upload button


uploadButton.addEventListener('click', () => {
const file = uploadFileInput.files[0];
if (file) {
uploadExcel(file);
} else {
alert("Please select a file to upload.");
}
});

// Fetch and display data from Firebase


onValue(productsRef, (snapshot) => {
const products = [];
snapshot.forEach((product) => {
products.push(product);
});
displayItems(products);
statusElement.textContent = 'Connected to Firebase';
statusElement.className = 'connected';
}, (error) => {
statusElement.textContent = 'Disconnected from Firebase';
statusElement.className = 'disconnected';
});
</script>
</body>
</html>

You might also like