Merge laatste worktree in master

Neemt de laatste PantryHub-implementatie over in de hoofdbranch.\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-08-07 20:46:00 +02:00
21 changed files with 345 additions and 1128 deletions
+2 -11
View File
@@ -1,14 +1,5 @@
node_modules/
.env
database.sqlite
storage/logs/*
storage/backups/*
public/uploads/*
.vscode
.idea
*.sqlite-shm
*.sqlite-wal
+5
View File
@@ -10,6 +10,11 @@ const socketHandlers = require("./sockets/handlers");
const app = createApp();
const server = http.createServer(app);
const io = new Server(server);
io.use((socket, next) => session(socket.request, {}, next));
socketHandlers(io);
app.locals.io = io;
const io = new Server(server, {
cors: {
+19 -16
View File
@@ -57,24 +57,29 @@ module.exports = () => {
app.use(session);
app.use(flash());
app.use(flash());
app.use(userMiddleware);
app.use(userMiddleware);
app.use((req, res, next) => {
res.locals.user = req.user || null;
res.locals.success = req.flash("success");
res.locals.error = req.flash("error");
res.locals.info = req.flash("info");
res.locals.warning = req.flash("warning");
res.locals.title = res.locals.title || "PantryHub";
next();
app.use((req, res, next) => {
res.set("X-PantryHub-Worktree", __dirname);
res.locals.user = req.user || null;
res.locals.success = req.flash("success");
res.locals.error = req.flash("error");
res.locals.info = req.flash("info");
res.locals.warning = req.flash("warning");
res.locals.title = "PantryHub";
next();
});
app.get("/__version", (req, res) => {
res.set("Cache-Control", "no-store");
res.json({
app: "PantryHub",
root: path.join(__dirname, ".."),
pid: process.pid
});
});
app.use(
@@ -84,13 +89,11 @@ module.exports = () => {
);
// API Routes
app.use(
"/api",
require("../routes/api")
);
// Web Routes
app.use(
"/",
require("../routes/auth")
+2 -1
View File
@@ -1,8 +1,9 @@
const session = require("express-session");
const BetterSqlite3Store = require("better-sqlite3-session-store")(session);
const Database = require("better-sqlite3");
const path = require("path");
const db = new Database("sessions.sqlite");
const db = new Database(path.join(__dirname, "..", "sessions.sqlite"));
module.exports = session({
+19 -16
View File
@@ -3,51 +3,54 @@ require("../services/ProductService");
const db = require("../config/database");
class ProductController {
index(req, res) {
const products =
ProductService.getProducts();
const categories = db.prepare(`
SELECT * FROM categories ORDER BY name
`).all();
res.locals.title = "Producten";
const categories = db.prepare(
"SELECT * FROM categories ORDER BY name"
).all();
res.render(
"products/index",
{
title:"Producten",
products,
categories,
user: req.user
categories
}
);
}
create(req, res) {
const name = (req.body.name || "").trim();
const categoryId = req.body.category_id
? Number.parseInt(req.body.category_id, 10)
: null;
const { name, category_id } = req.body;
if (!name || name.trim().length === 0) {
req.flash("error", "Geef een productnaam op");
if (!name || (categoryId !== null && !Number.isInteger(categoryId))) {
req.flash("error", "Geef een geldige productnaam en categorie op.");
return res.redirect("/products");
}
ProductService.createProduct({
name: name.trim(),
category_id: category_id || null
name,
category_id: categoryId
});
req.flash("success", "Product toegevoegd");
req.flash("success", "Product toegevoegd.");
res.redirect("/products");
}
}
module.exports =
new ProductController();
+36 -144
View File
@@ -1,179 +1,71 @@
const ShoppingListRepository = require("../repositories/ShoppingListRepository");
const ProductRepository = require("../repositories/ProductRepository");
const ShoppingListRepository = require("../repositories/ShoppingListRepository");
class ShoppingListController {
index(req, res) {
const lists = ShoppingListRepository.getByHousehold(
req.user.household_id
);
const lists = ShoppingListRepository.getByHousehold(req.user.household_id);
res.locals.title = "Boodschappenlijsten";
res.render("lists/index", {
lists,
user: req.user
});
res.render("lists/index", { lists, user: req.user });
}
create(req, res) {
const { name } = req.body;
if (!name || name.trim().length === 0) {
req.flash("error", "Geef een naam op");
const name = (req.body.name || "").trim();
if (!name) {
req.flash("error", "Geef een lijstnaam op");
return res.redirect("/lists");
}
// Check if user has a household
if (!req.user || !req.user.household_id) {
req.flash("error", "Je bent niet aan een huishouden gekoppeld");
return res.redirect("/lists");
}
ShoppingListRepository.create({
household_id: req.user.household_id,
name: name.trim()
});
ShoppingListRepository.create(req.user.household_id, name);
req.flash("success", "Boodschappenlijst aangemaakt");
res.redirect("/lists");
}
show(req, res) {
const { id } = req.params;
const list = ShoppingListRepository.getById(id);
if (!list) {
return res.status(404).render("errors/404");
}
if (list.household_id !== req.user.household_id) {
return res.status(403).render("errors/404");
}
const items = ShoppingListRepository.getItems(id);
const list = ShoppingListRepository.findById(req.params.id, req.user.household_id);
if (!list) return res.status(404).render("errors/404");
res.locals.title = list.name;
res.render("lists/show", {
list,
items,
items: ShoppingListRepository.getItems(list.id),
products: ProductRepository.getAll(),
user: req.user
});
}
addItem(req, res) {
const { id } = req.params;
const { product_id, amount } = req.body;
const list = ShoppingListRepository.getById(id);
if (!list) {
return res.status(404).json({ error: "Lijst niet gevonden" });
const list = ShoppingListRepository.findById(req.params.id, req.user.household_id);
const productId = Number.parseInt(req.body.product_id, 10);
const amount = Number.parseFloat(req.body.amount || "1");
const product = Number.isInteger(productId) ? ProductRepository.findById(productId) : null;
if (!list || !product || !Number.isFinite(amount) || amount <= 0) {
req.flash("error", "Ongeldig product of ongeldige hoeveelheid");
return res.redirect(`/lists/${req.params.id}`);
}
if (list.household_id !== req.user.household_id) {
return res.status(403).json({ error: "Niet gemachtigd" });
}
const product = ProductRepository.findById(product_id);
if (!product) {
return res.status(404).json({ error: "Product niet gevonden" });
}
const quantity = Number(amount);
if (!Number.isFinite(quantity) || quantity <= 0 || quantity > 999) {
req.flash("error", "Vul een geldige hoeveelheid in");
return res.redirect(`/lists/${id}`);
}
const item = ShoppingListRepository.addItem({
list_id: id,
product_id,
amount: quantity
});
req.app.locals.io.to(`household:${req.user.household_id}`).emit("item:added", {
listId: Number(id)
});
req.flash("success", "Product toegevoegd");
if (req.xhr || req.headers.accept?.includes("application/json")) {
return res.json({ success: true, item });
}
res.redirect(`/lists/${id}`);
ShoppingListRepository.addItem(list.id, product.id, amount);
res.redirect(`/lists/${list.id}`);
}
toggleItem(req, res) {
const { id, itemId } = req.params;
const list = ShoppingListRepository.getById(id);
if (!list || list.household_id !== req.user.household_id) {
return res.status(403).json({ error: "Niet gemachtigd" });
}
if (!ShoppingListRepository.findItem(id, itemId)) {
return res.status(404).json({ error: "Item niet gevonden" });
}
ShoppingListRepository.toggleItem(itemId);
req.app.locals.io.to(`household:${req.user.household_id}`).emit("item:toggled", {
listId: Number(id), itemId: Number(itemId)
});
if (req.xhr || req.headers.accept?.includes("application/json")) {
return res.json({ success: true });
}
res.redirect(`/lists/${id}`);
const list = ShoppingListRepository.findById(req.params.id, req.user.household_id);
if (!list) return res.status(404).render("errors/404");
ShoppingListRepository.toggleItem(list.id, req.params.itemId);
this.broadcastUpdate(req, list.id);
res.redirect(`/lists/${list.id}`);
}
deleteItem(req, res) {
const { id, itemId } = req.params;
const list = ShoppingListRepository.getById(id);
if (!list || list.household_id !== req.user.household_id) {
return res.status(403).json({ error: "Niet gemachtigd" });
}
if (!ShoppingListRepository.findItem(id, itemId)) {
return res.status(404).json({ error: "Item niet gevonden" });
}
ShoppingListRepository.deleteItem(itemId);
req.app.locals.io.to(`household:${req.user.household_id}`).emit("item:removed", {
listId: Number(id), itemId: Number(itemId)
});
req.flash("success", "Product verwijderd");
if (req.method === "DELETE" || req.xhr || req.headers.accept?.includes("application/json")) {
return res.json({ success: true });
}
res.redirect(`/lists/${id}`);
const list = ShoppingListRepository.findById(req.params.id, req.user.household_id);
if (!list) return res.status(404).json({ error: "Lijst niet gevonden" });
const result = ShoppingListRepository.deleteItem(list.id, req.params.itemId);
if (result.changes === 0) return res.status(404).json({ error: "Product niet gevonden" });
this.broadcastUpdate(req, list.id);
res.json({ success: true });
}
broadcastUpdate(req, listId) {
if (req.app.locals.io) {
req.app.locals.io.to(`list:${listId}`).emit("list:updated", { listId });
}
}
}
module.exports = new ShoppingListController();
+17 -71
View File
@@ -2,96 +2,42 @@ require("dotenv").config();
const db = require("../config/database");
const categories = [
["Groente", "🥬"],
["Fruit", "🍎"],
["Zuivel", "🥛"],
["Brood", "🍞"],
["Dranken", "🥤"],
["Huishouden", "🧻"]
];
const products = [
[
"Melk",
3
],
[
"Bananen",
2
],
[
"Brood",
4
],
[
"Koffie",
5
],
[
"WC papier",
6
]
["Melk", "Zuivel"],
["Bananen", "Fruit"],
["Brood", "Brood"],
["Koffie", "Dranken"],
["WC papier", "Huishouden"]
];
const insertCategory = db.prepare(`
INSERT INTO categories (name, icon)
SELECT ?, ?
WHERE NOT EXISTS (SELECT 1 FROM categories WHERE name = ?)
INSERT OR IGNORE INTO categories (name, icon) VALUES (?, ?)
`);
const seedCategories = db.transaction(() => {
for (const category of categories) {
insertCategory.run(category[0], category[1], category[0]);
}
});
seedCategories();
const insertProduct = db.prepare(`
INSERT INTO products (name, category_id)
SELECT ?, ?
WHERE NOT EXISTS (SELECT 1 FROM products WHERE name = ?)
INSERT OR IGNORE INTO products (name, category_id) VALUES (?, ?)
`);
const seedProducts = db.transaction(() => {
for(const product of products){
insertProduct.run(product[0], product[1], product[0]);
db.transaction(() => {
for (const category of categories) {
insertCategory.run(category);
}
});
seedProducts();
for (const [name, categoryName] of products) {
const category = db.prepare(
"SELECT id FROM categories WHERE name = ?"
).get(categoryName);
insertProduct.run(name, category.id);
}
})();
console.log("Seed voltooid.");
+9 -46
View File
@@ -1,48 +1,11 @@
// Socket.IO Client
const socket = typeof io === 'function' ? io() : null;
(() => {
const socket = window.io && window.io();
if (!socket) return;
// Join household room if available
const householdId = document.querySelector('[data-household-id]')?.dataset.householdId;
if (socket && householdId) {
socket.emit('join:household', householdId);
}
const listMatch = window.location.pathname.match(/^\/lists\/(\d+)$/);
if (listMatch) socket.emit("list:join", listMatch[1]);
// Real-time list updates
socket?.on('list:updated', (data) => {
console.log('📝 Lijst bijgewerkt:', data);
window.location.reload();
});
socket?.on('item:added', (data) => {
console.log(' Item toegevoegd:', data);
window.location.reload();
});
socket?.on('item:toggled', (data) => {
console.log('✓ Item afgevinkt:', data);
window.location.reload();
});
socket?.on('item:removed', (data) => {
console.log('✕ Item verwijderd:', data);
window.location.reload();
});
// Auto-remove alerts
document.addEventListener("DOMContentLoaded", () => {
setTimeout(() => {
document
.querySelectorAll(".alert")
.forEach(alert => {
alert.remove();
});
}, 4000);
});
console.log('✅ PantryHub app geladen');
socket.on("list:updated", ({ listId }) => {
if (window.location.pathname === `/lists/${listId}`) window.location.reload();
});
})();
+37 -92
View File
@@ -1,98 +1,43 @@
const CACHE_NAME = 'pantryhub-v2';
const urlsToCache = [
'/',
'/css/style.css',
'/js/app.js',
'/manifest.json',
'/icons/icon.svg'
];
const CACHE_NAME = "pantryhub-static-v3";
// Install event
self.addEventListener('install', (event) => {
self.addEventListener("install", () => {
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(urlsToCache).catch(err => {
console.log('Cache addAll error:', err);
caches.keys().then((keys) =>
Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
)
).then(() => self.clients.claim())
);
});
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
const url = new URL(event.request.url);
if (url.origin !== self.location.origin) return;
// Authenticated HTML and API responses must never be served from stale cache.
if (event.request.mode === "navigate" || url.pathname.startsWith("/api/")) {
event.respondWith(fetch(event.request));
return;
}
event.respondWith(
caches.match(event.request).then((cached) => {
if (cached) return cached;
return fetch(event.request).then((response) => {
if (response.ok && response.type === "basic") {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy));
}
return response;
});
})
);
});
// Activate event
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
})
);
});
// Fetch event
self.addEventListener('fetch', (event) => {
// Skip non-GET requests
if (event.request.method !== 'GET') {
return;
}
// Browser extensions and third-party resources cannot be stored by Cache API.
// Only handle same-origin HTTP(S) requests belonging to PantryHub.
const url = new URL(event.request.url);
if (!['http:', 'https:'].includes(url.protocol) || url.origin !== self.location.origin) {
return;
}
// For API calls, use network-first strategy
if (event.request.url.includes('/api/')) {
event.respondWith(
fetch(event.request)
.then(response => {
const responseClone = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, responseClone);
});
return response;
})
.catch(() => {
return caches.match(event.request);
})
);
return;
}
// For other requests, use cache-first strategy
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
return response;
}
return fetch(event.request).then(response => {
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
const responseClone = response.clone();
caches.open(CACHE_NAME)
.then(cache => {
cache.put(event.request, responseClone);
});
return response;
});
})
.catch(() => {
// Return offline page or empty response
return new Response('Offline - pagina niet beschikbaar', {
status: 503,
statusText: 'Service Unavailable',
headers: new Headers({
'Content-Type': 'text/plain'
})
});
})
);
});
+34 -71
View File
@@ -1,108 +1,71 @@
const db = require("../config/database");
class ShoppingListRepository {
getByHousehold(householdId) {
return db.prepare(`
SELECT
shopping_lists.*,
COUNT(shopping_list_items.id) as item_count,
SUM(CASE WHEN shopping_list_items.checked = 1 THEN 1 ELSE 0 END) as checked_count
SELECT shopping_lists.*,
COUNT(shopping_list_items.id) AS item_count,
COALESCE(SUM(shopping_list_items.checked), 0) AS checked_count
FROM shopping_lists
LEFT JOIN shopping_list_items
ON shopping_lists.id = shopping_list_items.list_id
WHERE shopping_lists.household_id = ?
AND shopping_lists.archived = 0
LEFT JOIN shopping_list_items
ON shopping_list_items.list_id = shopping_lists.id
WHERE shopping_lists.household_id = ? AND shopping_lists.archived = 0
GROUP BY shopping_lists.id
ORDER BY shopping_lists.created_at DESC
ORDER BY shopping_lists.created_at DESC, shopping_lists.id DESC
`).all(householdId);
}
getById(id) {
findById(id, householdId) {
return db.prepare(`
SELECT * FROM shopping_lists WHERE id = ?
`).get(id);
}
create(data) {
return db.prepare(`
INSERT INTO shopping_lists
(household_id, name)
VALUES (?, ?)
`).run(data.household_id, data.name);
SELECT * FROM shopping_lists
WHERE id = ? AND household_id = ?
`).get(id, householdId);
}
getItems(listId) {
return db.prepare(`
SELECT
shopping_list_items.*,
products.name as product_name,
categories.name as category_name,
categories.icon as category_icon
SELECT shopping_list_items.*, products.name AS product_name,
categories.name AS category_name, categories.icon AS category_icon
FROM shopping_list_items
JOIN products ON products.id = shopping_list_items.product_id
LEFT JOIN categories ON categories.id = products.category_id
WHERE shopping_list_items.list_id = ?
ORDER BY shopping_list_items.checked ASC, shopping_list_items.sort_order ASC
ORDER BY shopping_list_items.checked ASC,
shopping_list_items.sort_order ASC,
shopping_list_items.created_at ASC
`).all(listId);
}
addItem(data) {
create(householdId, name) {
return db.prepare(`
INSERT INTO shopping_list_items
(list_id, product_id, amount)
VALUES (?, ?, ?)
`).run(data.list_id, data.product_id, data.amount);
INSERT INTO shopping_lists (household_id, name) VALUES (?, ?)
`).run(householdId, name);
}
findItem(listId, itemId) {
addItem(listId, productId, amount) {
const nextSortOrder = db.prepare(`
SELECT COALESCE(MAX(sort_order), -1) + 1 AS value
FROM shopping_list_items WHERE list_id = ?
`).get(listId).value;
return db.prepare(`
SELECT id FROM shopping_list_items
WHERE id = ? AND list_id = ?
`).get(itemId, listId);
INSERT INTO shopping_list_items (list_id, product_id, amount, sort_order)
VALUES (?, ?, ?, ?)
`).run(listId, productId, amount, nextSortOrder);
}
toggleItem(itemId) {
toggleItem(listId, itemId) {
return db.prepare(`
UPDATE shopping_list_items
SET checked = CASE WHEN checked = 1 THEN 0 ELSE 1 END
WHERE id = ?
`).run(itemId);
SET checked = CASE checked WHEN 0 THEN 1 ELSE 0 END
WHERE id = ? AND list_id = ?
`).run(itemId, listId);
}
deleteItem(itemId) {
deleteItem(listId, itemId) {
return db.prepare(`
DELETE FROM shopping_list_items
WHERE id = ?
`).run(itemId);
DELETE FROM shopping_list_items WHERE id = ? AND list_id = ?
`).run(itemId, listId);
}
archiveList(listId) {
return db.prepare(`
UPDATE shopping_lists
SET archived = 1
WHERE id = ?
`).run(listId);
}
}
module.exports = new ShoppingListRepository();
+2 -37
View File
@@ -1,43 +1,8 @@
const router = require("express").Router();
const auth = require("../middleware/auth");
const ProductRepository = require("../repositories/ProductRepository");
const ShoppingListRepository = require("../repositories/ShoppingListRepository");
// Get all products
router.get("/products", auth, (req, res) => {
const products = ProductRepository.getAll();
res.json(products);
});
// Get shopping lists for household
router.get("/lists", auth, (req, res) => {
const lists = ShoppingListRepository.getByHousehold(
req.user.household_id
);
res.json(lists);
});
// Get shopping list items
router.get("/lists/:id/items", auth, (req, res) => {
const list = ShoppingListRepository.getById(req.params.id);
if (!list || list.household_id !== req.user.household_id) {
return res.status(403).json({ error: "Not authorized" });
}
const items = ShoppingListRepository.getItems(req.params.id);
res.json(items);
});
router.use(auth);
router.get("/products", (req, res) => res.json(ProductRepository.getAll()));
module.exports = router;
+21 -18
View File
@@ -20,6 +20,27 @@ router.get(
DashboardController.index
);
router.get(
"/household",
auth,
HouseholdController.index.bind(HouseholdController)
);
router.get(
"/products",
auth,
ProductController.index.bind(ProductController)
);
router.post(
"/products",
auth,
ProductController.create.bind(ProductController)
);
router.get(
"/lists",
auth,
@@ -56,22 +77,4 @@ router.delete(
ShoppingListController.deleteItem.bind(ShoppingListController)
);
router.get(
"/household",
auth,
HouseholdController.index.bind(HouseholdController)
);
router.get(
"/products",
auth,
ProductController.index.bind(ProductController)
);
router.post(
"/products",
auth,
ProductController.create.bind(ProductController)
);
module.exports = router;
+4 -47
View File
@@ -1,55 +1,12 @@
const UserRepository = require("../repositories/UserRepository");
module.exports = function(io) {
module.exports = function registerSocketHandlers(io) {
io.on("connection", (socket) => {
const userId = socket.request.session?.userId;
const userId = socket.request.session && socket.request.session.userId;
const user = userId && UserRepository.findById(userId);
if (!user || !user.household_id) {
socket.disconnect(true);
return;
}
if (!user || !user.household_id) return socket.disconnect(true);
socket.join(`household:${user.household_id}`);
console.log("🔌 Gebruiker verbonden:", socket.id);
socket.on("join:household", () => {
// The room is derived from the authenticated session above.
});
socket.on("list:updated", (data) => {
io.to(`household:${data.householdId}`).emit("list:updated", data);
});
socket.on("item:added", (data) => {
io.to(`household:${data.householdId}`).emit("item:added", data);
});
socket.on("item:toggled", (data) => {
io.to(`household:${data.householdId}`).emit("item:toggled", data);
});
socket.on("item:removed", (data) => {
io.to(`household:${data.householdId}`).emit("item:removed", data);
});
socket.on("disconnect", () => {
console.log("❌ Gebruiker verbroken:", socket.id);
});
socket.on("list:join", (listId) => socket.join(`list:${listId}`));
});
};
+4
View File
@@ -78,6 +78,10 @@
</form>
<p class="text-secondary mt-3">
Nog geen account? <a href="/register">Registreren</a>
</p>
</div>
+26 -13
View File
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="nl" data-household-id="<%= user?.household_id || '' %>">
<!doctype html>
<html lang="nl">
<head>
@@ -7,26 +7,39 @@
</head>
<body>
<div class="page">
<%- include("../partials/navbar") %>
<main class="container-xl mt-4">
<%- include("../partials/flash") %>
<div class="page-wrapper">
<%- body %>
</main>
<div class="container-xl">
<%- include("../partials/footer") %>
<%- include("../partials/flash") %>
<%- body %>
<script src="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/js/tabler.bundle.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/js/app.js"></script>
</div>
<%- include("../partials/footer") %>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/js/tabler.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/js/app.js"></script>
</body>
</html>
</html>
+11 -65
View File
@@ -1,96 +1,42 @@
<div class="page-header mb-4">
<h1>🛒 Boodschappenlijsten</h1>
<h1>Boodschappenlijsten</h1>
</div>
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<% if(lists.length === 0) { %>
<p class="text-secondary">Je hebt nog geen boodschappenlijsten. Maak er een aan!</p>
<% if (lists.length === 0) { %>
<p class="text-secondary">Je hebt nog geen boodschappenlijsten.</p>
<% } else { %>
<div class="list-group">
<% lists.forEach(list => { %>
<a href="/lists/<%= list.id %>" class="list-group-item list-group-item-action">
<div class="d-flex justify-content-between">
<strong><%= list.name %></strong>
<small class="text-secondary">
<%= list.checked_count || 0 %>/<%= list.item_count || 0 %> gedaan
</small>
<span><%= list.checked_count || 0 %>/<%= list.item_count || 0 %> gedaan</span>
</div>
<small class="text-muted">
Aangemaakt <%= new Date(list.created_at).toLocaleDateString('nl-NL') %>
Aangemaakt <%= new Date(list.created_at).toLocaleDateString("nl-NL") %>
</small>
</a>
<% }) %>
<% }); %>
</div>
<% } %>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">
<h3 class="card-title">Nieuwe lijst</h3>
</div>
<div class="card-header"><h3 class="card-title">Nieuwe lijst</h3></div>
<div class="card-body">
<form method="post" action="/lists">
<div class="mb-3">
<label class="form-label">Lijstnaam</label>
<input
type="text"
class="form-control"
name="name"
placeholder="bijv. Weekboodschappen"
required>
</div>
<button class="btn btn-primary w-100">
Lijst aanmaken
</button>
<label class="form-label" for="list-name">Lijstnaam</label>
<input id="list-name" class="form-control mb-3" type="text" name="name"
placeholder="bijv. Weekboodschappen" required maxlength="120">
<button class="btn btn-primary w-100" type="submit">Lijst aanmaken</button>
</form>
</div>
</div>
</div>
</div>
+38 -190
View File
@@ -1,221 +1,69 @@
<div class="page-header mb-4">
<a href="/lists" class="btn btn-link btn-icon">&larr;</a>
<a href="/lists" class="btn btn-link">&larr; Terug</a>
<h1><%= list.name %></h1>
</div>
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<% if(items.length === 0) { %>
<% if (items.length === 0) { %>
<p class="text-secondary">Nog geen producten op de lijst.</p>
<% } else { %>
<div class="list-group">
<% items.forEach(item => { %>
<div class="list-group-item">
<div class="d-flex align-items-center">
<form method="post" action="/lists/<%= list.id %>/items/<%= item.id %>/toggle" style="display: inline;">
<input type="hidden" name="_method" value="POST">
<button class="btn btn-sm" style="border: none; background: none; padding: 0; margin-right: 10px;"
onclick="this.closest('form').submit(); return false;">
<i class="icon icon-check" style="font-size: 20px; <% if(item.checked) { %>color: #00a651;<% } else { %>color: #ccc;<% } %>"></i>
</button>
</form>
<div class="flex-grow-1">
<strong <% if(item.checked) { %>style="text-decoration: line-through; color: #999;"<% } %>>
<%= item.product_name %>
</strong>
<% if(item.amount && item.amount !== 1) { %>
<span class="badge bg-info"><%= item.amount %></span>
<% } %>
<br>
<small class="text-secondary">
<%= item.category_icon || "" %> <%= item.category_name || "Geen categorie" %>
</small>
</div>
<form class="delete-item-form" action="/lists/<%= list.id %>/items/<%= item.id %>" style="display: inline;">
<button class="btn btn-sm btn-link text-danger" style="border: none;">✕</button>
</form>
<div class="list-group-item d-flex align-items-center">
<form method="post" action="/lists/<%= list.id %>/items/<%= item.id %>/toggle">
<button class="btn btn-sm me-2" type="submit" aria-label="Product afvinken">
<%= item.checked ? "☑" : "☐" %>
</button>
</form>
<div class="flex-grow-1">
<strong<% if (item.checked) { %> style="text-decoration: line-through"<% } %>>
<%= item.product_name %>
</strong>
<% if (item.amount !== 1) { %><span class="badge bg-info"><%= item.amount %></span><% } %>
<div class="small text-secondary"><%= item.category_icon || "" %> <%= item.category_name || "Geen categorie" %></div>
</div>
<form class="delete-item-form" method="post" action="/lists/<%= list.id %>/items/<%= item.id %>">
<button class="btn btn-sm btn-link text-danger" type="submit">Verwijder</button>
</form>
</div>
<% }) %>
<% }); %>
</div>
<% } %>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">
<h3 class="card-title">Product toevoegen</h3>
</div>
<div class="card-header"><h3 class="card-title">Product toevoegen</h3></div>
<div class="card-body">
<form method="post" action="/lists/<%= list.id %>/items" id="addItemForm">
<div class="mb-3">
<label class="form-label">Product</label>
<input type="text" id="productSearch" class="form-control" placeholder="Zoek product..." autocomplete="off">
<div id="productList" class="list-group mt-2" style="display: none; max-height: 300px; overflow-y: auto;"></div>
<input type="hidden" id="productId" name="product_id" required>
<small id="selectedProduct" class="text-secondary"></small>
</div>
<div class="mb-3">
<label class="form-label">Hoeveelheid</label>
<input
type="number"
class="form-control"
name="amount"
value="1"
step="0.5"
min="0.5">
</div>
<button class="btn btn-primary w-100" type="submit" id="submitBtn" disabled>
Toevoegen
</button>
<form method="post" action="/lists/<%= list.id %>/items">
<label class="form-label" for="product-id">Product</label>
<select id="product-id" class="form-select mb-3" name="product_id" required>
<option value="">Kies een product</option>
<% (products || []).forEach(product => { %>
<option value="<%= product.id %>"><%= product.name %></option>
<% }); %>
</select>
<label class="form-label" for="amount">Hoeveelheid</label>
<input id="amount" class="form-control mb-3" type="number" name="amount"
value="1" min="0.5" step="0.5" required>
<button class="btn btn-primary w-100" type="submit">Toevoegen</button>
</form>
</div>
</div>
</div>
</div>
<script>
let allProducts = [];
// Load products from API
fetch('/api/products')
.then(r => r.json())
.then(products => {
allProducts = products;
document.querySelectorAll(".delete-item-form").forEach((form) => {
form.addEventListener("submit", async (event) => {
event.preventDefault();
if (!confirm("Product verwijderen?")) return;
const response = await fetch(form.action, { method: "DELETE" });
if (response.ok) window.location.reload();
});
});
// Product search
document.getElementById('productSearch').addEventListener('input', function() {
const search = this.value.toLowerCase();
const listEl = document.getElementById('productList');
if (!search) {
listEl.style.display = 'none';
return;
}
const filtered = allProducts.filter(p =>
p.name.toLowerCase().includes(search) ||
(p.category_name && p.category_name.toLowerCase().includes(search))
);
listEl.replaceChildren();
filtered.forEach(product => {
const category = `${product.category_icon || ''} ${product.category_name || 'Geen categorie'}`.trim();
const button = document.createElement('button');
button.type = 'button';
button.className = 'list-group-item list-group-item-action text-start';
const name = document.createElement('strong');
name.textContent = product.name;
const categoryLabel = document.createElement('small');
categoryLabel.className = 'text-secondary';
categoryLabel.textContent = category;
button.append(name, document.createElement('br'), categoryLabel);
button.addEventListener('click', () => selectProduct(product.id, product.name, category));
listEl.append(button);
});
listEl.style.display = 'block';
});
function selectProduct(id, name, category) {
document.getElementById('productId').value = id;
document.getElementById('productSearch').value = '';
document.getElementById('selectedProduct').textContent = name + ' - ' + category;
document.getElementById('productList').style.display = 'none';
document.getElementById('submitBtn').disabled = false;
}
// Handle form deletion
document.querySelectorAll('.delete-item-form').forEach(form => {
form.addEventListener('submit', function(e) {
e.preventDefault();
if(confirm('Zeker weten?')) {
fetch(form.action, { method: 'DELETE' })
.then(r => r.json())
.then(() => window.location.reload());
}
});
});
// Close product list when clicking outside
document.addEventListener('click', function(e) {
if (!e.target.closest('#productSearch') && !e.target.closest('#productList')) {
document.getElementById('productList').style.display = 'none';
}
});
</script>
+9 -63
View File
@@ -1,66 +1,12 @@
<% if(success.length) { %>
<div class="alert alert-success alert-dismissible" role="alert">
<%= success[0] %>
<button
type="button"
class="btn-close"
data-bs-dismiss="alert">
</button>
</div>
<% if (success && success.length) { %>
<div class="alert alert-success" role="alert"><%= success[0] %></div>
<% } %>
<% if(error.length) { %>
<div class="alert alert-danger alert-dismissible" role="alert">
<%= error[0] %>
<button
type="button"
class="btn-close"
data-bs-dismiss="alert">
</button>
</div>
<% if (error && error.length) { %>
<div class="alert alert-danger" role="alert"><%= error[0] %></div>
<% } %>
<% if(info.length) { %>
<div class="alert alert-info alert-dismissible" role="alert">
<%= info[0] %>
<button
type="button"
class="btn-close"
data-bs-dismiss="alert">
</button>
</div>
<% if (info && info.length) { %>
<div class="alert alert-info" role="alert"><%= info[0] %></div>
<% } %>
<% if (warning && warning.length) { %>
<div class="alert alert-warning" role="alert"><%= warning[0] %></div>
<% } %>
<% if(warning.length) { %>
<div class="alert alert-warning alert-dismissible" role="alert">
<%= warning[0] %>
<button
type="button"
class="btn-close"
data-bs-dismiss="alert">
</button>
</div>
<% } %>
+10 -16
View File
@@ -2,29 +2,23 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#0066cc">
<meta name="description" content="PantryHub - Realtime boodschappenapp">
<title>
<%= title || "PantryHub" %>
</title>
<link rel="manifest" href="/manifest.json">
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<link href="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/css/tabler.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@tabler/icons@latest/tabler-icons.css" rel="stylesheet">
<link href="/css/style.css" rel="stylesheet">
<link
href="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/css/tabler.min.css"
rel="stylesheet">
<script>
// Register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(reg => console.log('✅ Service Worker registered'))
.catch(err => console.log('❌ Service Worker registration failed:', err));
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js", { updateViaCache: "none" });
}
</script>
<link
href="/css/style.css"
rel="stylesheet">
+16 -91
View File
@@ -1,99 +1,24 @@
<header class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
<header class="navbar navbar-expand-md navbar-light d-print-none">
<div class="container-xl">
<div class="container-xl">
<a class="navbar-brand fw-bold" href="/">
🛒 PantryHub
</a>
<a class="navbar-brand" href="/">
<button class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarMenu">
🛒 PantryHub
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarMenu">
<% if (user) { %>
<ul class="navbar-nav me-auto">
<li class="nav-item">
<a class="nav-link" href="/">Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/lists">🛒 Lijsten</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/products">📦 Producten</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/household">👨‍👩‍👧 Huishouden</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle"
href="#"
data-bs-toggle="dropdown">
👤 <%= user.name %>
</a>
<div class="dropdown-menu dropdown-menu-end">
<span class="dropdown-item-text text-muted">
<%= user.household_name %>
</span>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/profile">
Profiel
</a>
<a class="dropdown-item" href="/settings">
Instellingen
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger"
href="/logout">
Uitloggen
</a>
</div>
</li>
</ul>
<% } else { %>
<div class="ms-auto">
<a href="/login" class="btn btn-primary">
Inloggen
</a>
</div>
<% } %>
</div>
</a>
<% if (user) { %>
<div class="navbar-nav flex-row ms-auto">
<a class="nav-link" href="/">Dashboard</a>
<a class="nav-link" href="/lists">Lijsten</a>
<a class="nav-link" href="/products">Producten</a>
<a class="nav-link" href="/household">Huishouden</a>
<a class="nav-link text-danger" href="/logout">Uitloggen</a>
</div>
<% } %>
</div>
</header>
+24 -120
View File
@@ -1,149 +1,53 @@
<div class="page-header mb-4">
<h1>📦 Producten</h1>
<h1>
📦 Producten
</h1>
</div>
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<% if(products.length === 0) { %>
<% if (products.length === 0) { %>
<p class="text-secondary">Nog geen producten.</p>
<% } else { %>
<div class="list-group">
<%
const grouped = {};
products.forEach(p => {
const cat = p.category_name || 'Overig';
if (!grouped[cat]) grouped[cat] = [];
grouped[cat].push(p);
});
%>
<% Object.keys(grouped).sort().forEach(cat => { %>
<div class="list-group-item list-group-item-info">
<strong><%= cat %></strong>
<% products.forEach(product => { %>
<div class="list-group-item">
<strong><%= product.category_icon || "" %> <%= product.name %></strong>
<div class="text-secondary"><%= product.category_name || "Geen categorie" %></div>
</div>
<% grouped[cat].forEach(product => { %>
<div class="list-group-item">
<div class="d-flex justify-content-between">
<strong>
<%= product.category_icon || "" %>
<%= product.name %>
</strong>
<small class="text-secondary">
<% if(product.barcode) { %>
📊 <%= product.barcode %>
<% } %>
</small>
</div>
</div>
<% }) %>
<% }) %>
<% }); %>
</div>
<% } %>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">
<h3 class="card-title">Nieuw product</h3>
</div>
<div class="card-header"><h3 class="card-title">Nieuw product</h3></div>
<div class="card-body">
<form method="post" action="/products">
<label class="form-label" for="product-name">Productnaam</label>
<input id="product-name" class="form-control mb-3" type="text" name="name"
placeholder="bijv. Melk" maxlength="120" required>
<div class="mb-3">
<label class="form-label">Productnaam</label>
<input
type="text"
class="form-control"
name="name"
placeholder="bijv. Melk"
required>
</div>
<div class="mb-3">
<label class="form-label">Categorie</label>
<select class="form-select" name="category_id">
<option value="">-- Geen categorie --</option>
<% if(categories) { %>
<% categories.forEach(cat => { %>
<option value="<%= cat.id %>">
<%= cat.icon || "" %> <%= cat.name %>
</option>
<% }) %>
<% } %>
</select>
</div>
<button class="btn btn-primary w-100">
Product toevoegen
</button>
<label class="form-label" for="category-id">Categorie</label>
<select id="category-id" class="form-select mb-3" name="category_id">
<option value="">Geen categorie</option>
<% (categories || []).forEach(category => { %>
<option value="<%= category.id %>"><%= category.icon || "" %> <%= category.name %></option>
<% }); %>
</select>
<button class="btn btn-primary w-100" type="submit">Product toevoegen</button>
</form>
</div>
</div>
</div>
</div>
</div>