Skip to content

(feat) LIVE LET's Code #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions live/lets-code/inventory/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
.git
package-lock.json
yarn.lock
21 changes: 21 additions & 0 deletions live/lets-code/inventory/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 tapaScript

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions live/lets-code/inventory/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# js-base-setup
Empty file.
24 changes: 24 additions & 0 deletions live/lets-code/inventory/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "js-base-setup",
"version": "1.0.0",
"description": "javascript setup",
"main": "main.js",
"scripts": {
"start": "concurrently \"serve pages -p 3000\" \"npx @tailwindcss/cli -i ./pages/input.css -o ./pages/output.css --watch\"",
"build": "npx @tailwindcss/cli -i ./pages/input.css -o ./pages/output.css"
},
"keywords": [
"javascript",
"base"
],
"author": "tapaScript | learn@tapascript.io",
"license": "MIT",
"devDependencies": {
"concurrently": "^9.1.2",
"serve": "^14.2.4"
},
"dependencies": {
"@tailwindcss/cli": "^4.1.2",
"tailwindcss": "^4.1.2"
}
}
29 changes: 29 additions & 0 deletions live/lets-code/inventory/pages/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Inventory Dashboard</title>
<link href="./output.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script defer src="./inventory.js"></script>
</head>

<body class="bg-gray-100 text-gray-900">
<div class="container mx-auto p-4">
<h1 class="text-3xl font-bold mb-6 text-center">Inventory Dashboard</h1>

<div id="productContainer" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6"></div>

<div id="loading">Loading...</div>
<div id="error" class="text-red-500 mb-2"></div>

<div class="bg-white p-4 rounded shadow">
<h2 class="text-xl font-semibold mb-2">Stock vs Sold Chart</h2>
<canvas id="inventoryChart" height="200"></canvas>
</div>
</div>
</body>

</html>
1 change: 1 addition & 0 deletions live/lets-code/inventory/pages/input.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@import "tailwindcss";
151 changes: 151 additions & 0 deletions live/lets-code/inventory/pages/inventory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
console.log("Inventory");

const container = document.getElementById("productContainer");
const loading = document.getElementById("loading");
const errorElem = document.getElementById("error");
const inventoryChart = document.getElementById("inventoryChart");

/** Getting Current Stock Data of a Product */
async function getCurrentStock(productId) {
const product = await apiRequest(
`http://localhost:3001/products/${productId}`
);
return product?.stock;
}

/** Attach All handlers */
function addRestockListeners() {
const buttons = document.querySelectorAll(".restock-btn");
buttons.forEach((button) => {
button.addEventListener("click", async () => {
const id = parseInt(button.dataset.id);
await restockItem(id);
});
});
}

/** Restock item by increasing stock */
async function restockItem(productId) {
const currentStock = await getCurrentStock(productId);
const data = await apiRequest(
`http://localhost:3001/products/${productId}`,
"PATCH",
{ stock: currentStock + 5 }
);
console.log(data);
displayProducts();
}

/** Display products */
async function displayProducts() {
try {
const products = await apiRequest("http://localhost:3001/products");

container.innerHTML = "";

products.forEach((product) => {
container.innerHTML += `
<div class="bg-white p-4 rounded shadow">
<h3 class="text-lg font-semibold mb-2">${product.name}</h3>
<p><strong>Category:</strong> ${product.category}</p>
<p><strong>Stock:</strong> <span id="stock-${product.id}">${
product.stock
}</span></p>
<p><strong>Sold:</strong> ${product.sold}</p>
<p><strong>Price:</strong> $${product.price.toFixed(2)}</p>
<p class="text-sm text-gray-600 mt-2">Last Updated: ${
product.lastUpdated
}</p>
<button data-id=${
product.id
} class="restock-btn mt-2 bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600">Restock</button>
</div>`;
});
addRestockListeners();
renderChart(products);
} catch (error) {
const message = error.message;
console.error(message);
errorElem.textContent = message;
} finally {
loading.textContent = "";
}
}

/** Render chart showing stock vs sold */
function renderChart(products) {
const ctx = inventoryChart.getContext("2d");
const labels = products.map((p) => p.name);
const stockData = products.map((p) => p.stock);
const soldData = products.map((p) => p.sold);

if (
window.inventoryChart &&
typeof window.inventoryChart.destroy === "function"
) {
window.inventoryChart.destroy(); // clear existing chart safely
} else if (window.inventoryChart) {
window.inventoryChart = null; // ensure proper reinitialization if chart is not valid
}

window.inventoryChart = new Chart(ctx, {
type: "bar",
data: {
labels,
datasets: [
{
label: "Stock",
data: stockData,
backgroundColor: "#3B82F6",
},
{
label: "Sold",
data: soldData,
backgroundColor: "#10B981",
},
],
},
options: {
responsive: true,
plugins: {
legend: {
position: "top",
},
},
},
});
}

displayProducts();

async function apiRequest(url, method = "GET", body = null) {
try {
loading.textContent = "Loading...";

const options = {
method,
headers: {
"Content-Type": "application/json",
},
};

if (body) {
options.body = JSON.stringify(body);
}

const response = await fetch(url, options);

if (!response.ok) {
throw new Error(
`API error: ${response.status} ${response.statusText}`
);
}

return await response.json(); // success
} catch (error) {
console.error(error.message);
errorElem.textContent = error.message;
} finally {
loading.textContent = "";
}
}
Loading