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/ node_modules/
.env .env
database.sqlite database.sqlite
*.sqlite-shm
storage/logs/* *.sqlite-wal
storage/backups/*
public/uploads/*
.vscode
.idea
+5
View File
@@ -10,6 +10,11 @@ const socketHandlers = require("./sockets/handlers");
const app = createApp(); const app = createApp();
const server = http.createServer(app); 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, { const io = new Server(server, {
cors: { cors: {
+13 -10
View File
@@ -57,24 +57,29 @@ module.exports = () => {
app.use(session); app.use(session);
app.use(flash()); app.use(flash());
app.use(userMiddleware); app.use(userMiddleware);
app.use((req, res, next) => {
app.use((req, res, next) => {
res.set("X-PantryHub-Worktree", __dirname);
res.locals.user = req.user || null; res.locals.user = req.user || null;
res.locals.success = req.flash("success"); res.locals.success = req.flash("success");
res.locals.error = req.flash("error"); res.locals.error = req.flash("error");
res.locals.info = req.flash("info"); res.locals.info = req.flash("info");
res.locals.warning = req.flash("warning"); res.locals.warning = req.flash("warning");
res.locals.title = "PantryHub";
res.locals.title = res.locals.title || "PantryHub";
next(); 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( app.use(
@@ -84,13 +89,11 @@ module.exports = () => {
); );
// API Routes
app.use( app.use(
"/api", "/api",
require("../routes/api") require("../routes/api")
); );
// Web Routes
app.use( app.use(
"/", "/",
require("../routes/auth") require("../routes/auth")
+2 -1
View File
@@ -1,8 +1,9 @@
const session = require("express-session"); const session = require("express-session");
const BetterSqlite3Store = require("better-sqlite3-session-store")(session); const BetterSqlite3Store = require("better-sqlite3-session-store")(session);
const Database = require("better-sqlite3"); 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({ module.exports = session({
+19 -16
View File
@@ -3,51 +3,54 @@ require("../services/ProductService");
const db = require("../config/database"); const db = require("../config/database");
class ProductController { class ProductController {
index(req, res) { index(req, res) {
const products = const products =
ProductService.getProducts(); ProductService.getProducts();
const categories = db.prepare(` const categories = db.prepare(
SELECT * FROM categories ORDER BY name "SELECT * FROM categories ORDER BY name"
`).all(); ).all();
res.locals.title = "Producten";
res.render( res.render(
"products/index", "products/index",
{ {
title:"Producten",
products, products,
categories, categories
user: req.user
} }
); );
} }
create(req, res) { 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 || (categoryId !== null && !Number.isInteger(categoryId))) {
req.flash("error", "Geef een geldige productnaam en categorie op.");
if (!name || name.trim().length === 0) {
req.flash("error", "Geef een productnaam op");
return res.redirect("/products"); return res.redirect("/products");
} }
ProductService.createProduct({ ProductService.createProduct({
name: name.trim(), name,
category_id: category_id || null category_id: categoryId
}); });
req.flash("success", "Product toegevoegd"); req.flash("success", "Product toegevoegd.");
res.redirect("/products"); res.redirect("/products");
} }
} }
module.exports = module.exports =
new ProductController(); new ProductController();
+34 -142
View File
@@ -1,179 +1,71 @@
const ShoppingListRepository = require("../repositories/ShoppingListRepository");
const ProductRepository = require("../repositories/ProductRepository"); const ProductRepository = require("../repositories/ProductRepository");
const ShoppingListRepository = require("../repositories/ShoppingListRepository");
class ShoppingListController { class ShoppingListController {
index(req, res) { index(req, res) {
const lists = ShoppingListRepository.getByHousehold(req.user.household_id);
const lists = ShoppingListRepository.getByHousehold(
req.user.household_id
);
res.locals.title = "Boodschappenlijsten"; res.locals.title = "Boodschappenlijsten";
res.render("lists/index", { lists, user: req.user });
res.render("lists/index", {
lists,
user: req.user
});
} }
create(req, res) { create(req, res) {
const name = (req.body.name || "").trim();
const { name } = req.body; if (!name) {
req.flash("error", "Geef een lijstnaam op");
if (!name || name.trim().length === 0) {
req.flash("error", "Geef een naam op");
return res.redirect("/lists"); return res.redirect("/lists");
} }
ShoppingListRepository.create(req.user.household_id, name);
// 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()
});
req.flash("success", "Boodschappenlijst aangemaakt"); req.flash("success", "Boodschappenlijst aangemaakt");
res.redirect("/lists"); res.redirect("/lists");
} }
show(req, res) { show(req, res) {
const list = ShoppingListRepository.findById(req.params.id, req.user.household_id);
const { id } = req.params; if (!list) return res.status(404).render("errors/404");
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);
res.locals.title = list.name; res.locals.title = list.name;
res.render("lists/show", { res.render("lists/show", {
list, list,
items, items: ShoppingListRepository.getItems(list.id),
products: ProductRepository.getAll(),
user: req.user user: req.user
}); });
} }
addItem(req, res) { addItem(req, res) {
const list = ShoppingListRepository.findById(req.params.id, req.user.household_id);
const { id } = req.params; const productId = Number.parseInt(req.body.product_id, 10);
const { product_id, amount } = req.body; const amount = Number.parseFloat(req.body.amount || "1");
const product = Number.isInteger(productId) ? ProductRepository.findById(productId) : null;
const list = ShoppingListRepository.getById(id); if (!list || !product || !Number.isFinite(amount) || amount <= 0) {
req.flash("error", "Ongeldig product of ongeldige hoeveelheid");
if (!list) { return res.redirect(`/lists/${req.params.id}`);
return res.status(404).json({ error: "Lijst niet gevonden" });
} }
ShoppingListRepository.addItem(list.id, product.id, amount);
if (list.household_id !== req.user.household_id) { res.redirect(`/lists/${list.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}`);
} }
toggleItem(req, res) { toggleItem(req, res) {
const list = ShoppingListRepository.findById(req.params.id, req.user.household_id);
const { id, itemId } = req.params; if (!list) return res.status(404).render("errors/404");
ShoppingListRepository.toggleItem(list.id, req.params.itemId);
const list = ShoppingListRepository.getById(id); this.broadcastUpdate(req, list.id);
res.redirect(`/lists/${list.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}`);
} }
deleteItem(req, res) { deleteItem(req, res) {
const list = ShoppingListRepository.findById(req.params.id, req.user.household_id);
const { id, itemId } = req.params; if (!list) return res.status(404).json({ error: "Lijst niet gevonden" });
const result = ShoppingListRepository.deleteItem(list.id, req.params.itemId);
const list = ShoppingListRepository.getById(id); if (result.changes === 0) return res.status(404).json({ error: "Product niet gevonden" });
this.broadcastUpdate(req, list.id);
if (!list || list.household_id !== req.user.household_id) { res.json({ success: true });
return res.status(403).json({ error: "Niet gemachtigd" });
} }
if (!ShoppingListRepository.findItem(id, itemId)) { broadcastUpdate(req, listId) {
return res.status(404).json({ error: "Item niet gevonden" }); if (req.app.locals.io) {
req.app.locals.io.to(`list:${listId}`).emit("list:updated", { listId });
} }
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}`);
}
} }
module.exports = new ShoppingListController(); module.exports = new ShoppingListController();
+17 -71
View File
@@ -2,96 +2,42 @@ require("dotenv").config();
const db = require("../config/database"); const db = require("../config/database");
const categories = [ const categories = [
["Groente", "🥬"], ["Groente", "🥬"],
["Fruit", "🍎"], ["Fruit", "🍎"],
["Zuivel", "🥛"], ["Zuivel", "🥛"],
["Brood", "🍞"], ["Brood", "🍞"],
["Dranken", "🥤"], ["Dranken", "🥤"],
["Huishouden", "🧻"] ["Huishouden", "🧻"]
]; ];
const products = [ const products = [
["Melk", "Zuivel"],
[ ["Bananen", "Fruit"],
"Melk", ["Brood", "Brood"],
3 ["Koffie", "Dranken"],
], ["WC papier", "Huishouden"]
[
"Bananen",
2
],
[
"Brood",
4
],
[
"Koffie",
5
],
[
"WC papier",
6
]
]; ];
const insertCategory = db.prepare(` const insertCategory = db.prepare(`
INSERT OR IGNORE INTO categories (name, icon) VALUES (?, ?)
INSERT INTO categories (name, icon)
SELECT ?, ?
WHERE NOT EXISTS (SELECT 1 FROM categories WHERE name = ?)
`); `);
const seedCategories = db.transaction(() => {
for (const category of categories) {
insertCategory.run(category[0], category[1], category[0]);
}
});
seedCategories();
const insertProduct = db.prepare(` const insertProduct = db.prepare(`
INSERT OR IGNORE INTO products (name, category_id) VALUES (?, ?)
INSERT INTO products (name, category_id)
SELECT ?, ?
WHERE NOT EXISTS (SELECT 1 FROM products WHERE name = ?)
`); `);
db.transaction(() => {
for (const category of categories) {
insertCategory.run(category);
const seedProducts = db.transaction(() => {
for(const product of products){
insertProduct.run(product[0], product[1], product[0]);
} }
for (const [name, categoryName] of products) {
}); const category = db.prepare(
"SELECT id FROM categories WHERE name = ?"
).get(categoryName);
seedProducts(); insertProduct.run(name, category.id);
}
})();
console.log("Seed voltooid."); console.log("Seed voltooid.");
+8 -45
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 listMatch = window.location.pathname.match(/^\/lists\/(\d+)$/);
const householdId = document.querySelector('[data-household-id]')?.dataset.householdId; if (listMatch) socket.emit("list:join", listMatch[1]);
if (socket && householdId) {
socket.emit('join:household', householdId);
}
// 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();
socket.on("list:updated", ({ listId }) => {
if (window.location.pathname === `/lists/${listId}`) window.location.reload();
}); });
})();
}, 4000);
});
console.log('✅ PantryHub app geladen');
+26 -81
View File
@@ -1,97 +1,42 @@
const CACHE_NAME = 'pantryhub-v2'; const CACHE_NAME = "pantryhub-static-v3";
const urlsToCache = [
'/',
'/css/style.css',
'/js/app.js',
'/manifest.json',
'/icons/icon.svg'
];
// Install event self.addEventListener("install", () => {
self.addEventListener('install', (event) => { self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil( event.waitUntil(
caches.open(CACHE_NAME).then((cache) => { caches.keys().then((keys) =>
return cache.addAll(urlsToCache).catch(err => { Promise.all(
console.log('Cache addAll error:', err); keys
}); .filter((key) => key !== CACHE_NAME)
}) .map((key) => caches.delete(key))
)
).then(() => self.clients.claim())
); );
}); });
// Activate event self.addEventListener("fetch", (event) => {
self.addEventListener('activate', (event) => { if (event.request.method !== "GET") return;
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); const url = new URL(event.request.url);
if (!['http:', 'https:'].includes(url.protocol) || url.origin !== self.location.origin) { 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; return;
} }
// For API calls, use network-first strategy
if (event.request.url.includes('/api/')) {
event.respondWith( event.respondWith(
fetch(event.request) caches.match(event.request).then((cached) => {
.then(response => { if (cached) return cached;
const responseClone = response.clone(); return fetch(event.request).then((response) => {
caches.open(CACHE_NAME).then(cache => { if (response.ok && response.type === "basic") {
cache.put(event.request, responseClone); const copy = response.clone();
}); caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy));
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 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'
})
}); });
}) })
); );
+33 -70
View File
@@ -1,108 +1,71 @@
const db = require("../config/database"); const db = require("../config/database");
class ShoppingListRepository { class ShoppingListRepository {
getByHousehold(householdId) { getByHousehold(householdId) {
return db.prepare(` return db.prepare(`
SELECT SELECT shopping_lists.*,
shopping_lists.*, COUNT(shopping_list_items.id) AS item_count,
COUNT(shopping_list_items.id) as item_count, COALESCE(SUM(shopping_list_items.checked), 0) AS checked_count
SUM(CASE WHEN shopping_list_items.checked = 1 THEN 1 ELSE 0 END) as checked_count
FROM shopping_lists FROM shopping_lists
LEFT JOIN shopping_list_items LEFT JOIN shopping_list_items
ON shopping_lists.id = shopping_list_items.list_id ON shopping_list_items.list_id = shopping_lists.id
WHERE shopping_lists.household_id = ? WHERE shopping_lists.household_id = ? AND shopping_lists.archived = 0
AND shopping_lists.archived = 0
GROUP BY shopping_lists.id 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); `).all(householdId);
} }
getById(id) { findById(id, householdId) {
return db.prepare(` return db.prepare(`
SELECT * FROM shopping_lists WHERE id = ? SELECT * FROM shopping_lists
`).get(id); WHERE id = ? AND household_id = ?
`).get(id, householdId);
}
create(data) {
return db.prepare(`
INSERT INTO shopping_lists
(household_id, name)
VALUES (?, ?)
`).run(data.household_id, data.name);
} }
getItems(listId) { getItems(listId) {
return db.prepare(` return db.prepare(`
SELECT SELECT shopping_list_items.*, products.name AS product_name,
shopping_list_items.*, categories.name AS category_name, categories.icon AS category_icon
products.name as product_name,
categories.name as category_name,
categories.icon as category_icon
FROM shopping_list_items FROM shopping_list_items
JOIN products ON products.id = shopping_list_items.product_id JOIN products ON products.id = shopping_list_items.product_id
LEFT JOIN categories ON categories.id = products.category_id LEFT JOIN categories ON categories.id = products.category_id
WHERE shopping_list_items.list_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); `).all(listId);
} }
addItem(data) { create(householdId, name) {
return db.prepare(` return db.prepare(`
INSERT INTO shopping_list_items INSERT INTO shopping_lists (household_id, name) VALUES (?, ?)
(list_id, product_id, amount) `).run(householdId, name);
VALUES (?, ?, ?)
`).run(data.list_id, data.product_id, data.amount);
} }
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(` return db.prepare(`
SELECT id FROM shopping_list_items INSERT INTO shopping_list_items (list_id, product_id, amount, sort_order)
WHERE id = ? AND list_id = ? VALUES (?, ?, ?, ?)
`).get(itemId, listId); `).run(listId, productId, amount, nextSortOrder);
} }
toggleItem(itemId) { toggleItem(listId, itemId) {
return db.prepare(` return db.prepare(`
UPDATE shopping_list_items UPDATE shopping_list_items
SET checked = CASE WHEN checked = 1 THEN 0 ELSE 1 END SET checked = CASE checked WHEN 0 THEN 1 ELSE 0 END
WHERE id = ? WHERE id = ? AND list_id = ?
`).run(itemId); `).run(itemId, listId);
} }
deleteItem(itemId) { deleteItem(listId, itemId) {
return db.prepare(` return db.prepare(`
DELETE FROM shopping_list_items DELETE FROM shopping_list_items WHERE id = ? AND list_id = ?
WHERE id = ? `).run(itemId, listId);
`).run(itemId);
} }
archiveList(listId) {
return db.prepare(`
UPDATE shopping_lists
SET archived = 1
WHERE id = ?
`).run(listId);
}
} }
module.exports = new ShoppingListRepository(); module.exports = new ShoppingListRepository();
+2 -37
View File
@@ -1,43 +1,8 @@
const router = require("express").Router(); const router = require("express").Router();
const auth = require("../middleware/auth"); const auth = require("../middleware/auth");
const ProductRepository = require("../repositories/ProductRepository"); const ProductRepository = require("../repositories/ProductRepository");
const ShoppingListRepository = require("../repositories/ShoppingListRepository");
// Get all products router.use(auth);
router.get("/products", auth, (req, res) => { router.get("/products", (req, res) => res.json(ProductRepository.getAll()));
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);
});
module.exports = router; module.exports = router;
+21 -18
View File
@@ -20,6 +20,27 @@ router.get(
DashboardController.index 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( router.get(
"/lists", "/lists",
auth, auth,
@@ -56,22 +77,4 @@ router.delete(
ShoppingListController.deleteItem.bind(ShoppingListController) 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; module.exports = router;
+4 -47
View File
@@ -1,55 +1,12 @@
const UserRepository = require("../repositories/UserRepository"); const UserRepository = require("../repositories/UserRepository");
module.exports = function(io) { module.exports = function registerSocketHandlers(io) {
io.on("connection", (socket) => { io.on("connection", (socket) => {
const userId = socket.request.session && socket.request.session.userId;
const userId = socket.request.session?.userId;
const user = userId && UserRepository.findById(userId); const user = userId && UserRepository.findById(userId);
if (!user || !user.household_id) return socket.disconnect(true);
if (!user || !user.household_id) {
socket.disconnect(true);
return;
}
socket.join(`household:${user.household_id}`); socket.join(`household:${user.household_id}`);
socket.on("list:join", (listId) => socket.join(`list:${listId}`));
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);
});
});
}; };
+4
View File
@@ -78,6 +78,10 @@
</form> </form>
<p class="text-secondary mt-3">
Nog geen account? <a href="/register">Registreren</a>
</p>
</div> </div>
+21 -8
View File
@@ -1,5 +1,5 @@
<!DOCTYPE html> <!doctype html>
<html lang="nl" data-household-id="<%= user?.household_id || '' %>"> <html lang="nl">
<head> <head>
@@ -7,25 +7,38 @@
</head> </head>
<body> <body>
<div class="page">
<%- include("../partials/navbar") %> <%- include("../partials/navbar") %>
<main class="container-xl mt-4">
<div class="page-wrapper">
<div class="container-xl">
<%- include("../partials/flash") %> <%- include("../partials/flash") %>
<%- body %> <%- body %>
</main> </div>
<%- include("../partials/footer") %> <%- include("../partials/footer") %>
<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> </div>
<script src="/js/app.js"></script>
</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> </body>
+11 -65
View File
@@ -1,96 +1,42 @@
<div class="page-header mb-4"> <div class="page-header mb-4">
<h1>Boodschappenlijsten</h1>
<h1>🛒 Boodschappenlijsten</h1>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-8"> <div class="col-md-8">
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<% if (lists.length === 0) { %>
<% if(lists.length === 0) { %> <p class="text-secondary">Je hebt nog geen boodschappenlijsten.</p>
<p class="text-secondary">Je hebt nog geen boodschappenlijsten. Maak er een aan!</p>
<% } else { %> <% } else { %>
<div class="list-group"> <div class="list-group">
<% lists.forEach(list => { %> <% lists.forEach(list => { %>
<a href="/lists/<%= list.id %>" class="list-group-item list-group-item-action"> <a href="/lists/<%= list.id %>" class="list-group-item list-group-item-action">
<div class="d-flex justify-content-between"> <div class="d-flex justify-content-between">
<strong><%= list.name %></strong> <strong><%= list.name %></strong>
<span><%= list.checked_count || 0 %>/<%= list.item_count || 0 %> gedaan</span>
<small class="text-secondary">
<%= list.checked_count || 0 %>/<%= list.item_count || 0 %> gedaan
</small>
</div> </div>
<small class="text-muted"> <small class="text-muted">
Aangemaakt <%= new Date(list.created_at).toLocaleDateString('nl-NL') %> Aangemaakt <%= new Date(list.created_at).toLocaleDateString("nl-NL") %>
</small> </small>
</a> </a>
<% }); %>
<% }) %>
</div> </div>
<% } %> <% } %>
</div> </div>
</div> </div>
</div> </div>
<div class="col-md-4"> <div class="col-md-4">
<div class="card"> <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"> <div class="card-body">
<form method="post" action="/lists"> <form method="post" action="/lists">
<label class="form-label" for="list-name">Lijstnaam</label>
<div class="mb-3"> <input id="list-name" class="form-control mb-3" type="text" name="name"
placeholder="bijv. Weekboodschappen" required maxlength="120">
<label class="form-label">Lijstnaam</label> <button class="btn btn-primary w-100" type="submit">Lijst aanmaken</button>
<input
type="text"
class="form-control"
name="name"
placeholder="bijv. Weekboodschappen"
required>
</div>
<button class="btn btn-primary w-100">
Lijst aanmaken
</button>
</form> </form>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
+31 -183
View File
@@ -1,221 +1,69 @@
<div class="page-header mb-4"> <div class="page-header mb-4">
<a href="/lists" class="btn btn-link">&larr; Terug</a>
<a href="/lists" class="btn btn-link btn-icon">&larr;</a>
<h1><%= list.name %></h1> <h1><%= list.name %></h1>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-8"> <div class="col-md-8">
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<% if (items.length === 0) { %>
<% if(items.length === 0) { %>
<p class="text-secondary">Nog geen producten op de lijst.</p> <p class="text-secondary">Nog geen producten op de lijst.</p>
<% } else { %> <% } else { %>
<div class="list-group"> <div class="list-group">
<% items.forEach(item => { %> <% items.forEach(item => { %>
<div class="list-group-item d-flex align-items-center">
<div class="list-group-item"> <form method="post" action="/lists/<%= list.id %>/items/<%= item.id %>/toggle">
<button class="btn btn-sm me-2" type="submit" aria-label="Product afvinken">
<div class="d-flex align-items-center"> <%= item.checked ? "☑" : "☐" %>
<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> </button>
</form> </form>
<div class="flex-grow-1"> <div class="flex-grow-1">
<strong<% if (item.checked) { %> style="text-decoration: line-through"<% } %>>
<strong <% if(item.checked) { %>style="text-decoration: line-through; color: #999;"<% } %>>
<%= item.product_name %> <%= item.product_name %>
</strong> </strong>
<% if (item.amount !== 1) { %><span class="badge bg-info"><%= item.amount %></span><% } %>
<% if(item.amount && item.amount !== 1) { %> <div class="small text-secondary"><%= item.category_icon || "" %> <%= item.category_name || "Geen categorie" %></div>
<span class="badge bg-info"><%= item.amount %></span>
<% } %>
<br>
<small class="text-secondary">
<%= item.category_icon || "" %> <%= item.category_name || "Geen categorie" %>
</small>
</div> </div>
<form class="delete-item-form" method="post" action="/lists/<%= list.id %>/items/<%= item.id %>">
<form class="delete-item-form" action="/lists/<%= list.id %>/items/<%= item.id %>" style="display: inline;"> <button class="btn btn-sm btn-link text-danger" type="submit">Verwijder</button>
<button class="btn btn-sm btn-link text-danger" style="border: none;">✕</button>
</form> </form>
</div> </div>
<% }); %>
</div> </div>
<% }) %>
</div>
<% } %> <% } %>
</div> </div>
</div> </div>
</div> </div>
<div class="col-md-4"> <div class="col-md-4">
<div class="card"> <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"> <div class="card-body">
<form method="post" action="/lists/<%= list.id %>/items">
<form method="post" action="/lists/<%= list.id %>/items" id="addItemForm"> <label class="form-label" for="product-id">Product</label>
<select id="product-id" class="form-select mb-3" name="product_id" required>
<div class="mb-3"> <option value="">Kies een product</option>
<% (products || []).forEach(product => { %>
<label class="form-label">Product</label> <option value="<%= product.id %>"><%= product.name %></option>
<% }); %>
<input type="text" id="productSearch" class="form-control" placeholder="Zoek product..." autocomplete="off"> </select>
<label class="form-label" for="amount">Hoeveelheid</label>
<div id="productList" class="list-group mt-2" style="display: none; max-height: 300px; overflow-y: auto;"></div> <input id="amount" class="form-control mb-3" type="number" name="amount"
value="1" min="0.5" step="0.5" required>
<input type="hidden" id="productId" name="product_id" required> <button class="btn btn-primary w-100" type="submit">Toevoegen</button>
<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> </form>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<script> <script>
let allProducts = []; document.querySelectorAll(".delete-item-form").forEach((form) => {
form.addEventListener("submit", async (event) => {
// Load products from API event.preventDefault();
fetch('/api/products') if (!confirm("Product verwijderen?")) return;
.then(r => r.json()) const response = await fetch(form.action, { method: "DELETE" });
.then(products => { if (response.ok) window.location.reload();
allProducts = products;
}); });
// 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> </script>
+8 -62
View File
@@ -1,66 +1,12 @@
<% if(success.length) { %> <% if (success && success.length) { %>
<div class="alert alert-success" role="alert"><%= success[0] %></div>
<div class="alert alert-success alert-dismissible" role="alert">
<%= success[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(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 (info && info.length) { %>
<div class="alert alert-info" role="alert"><%= info[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 (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="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#0066cc">
<meta name="description" content="PantryHub - Realtime boodschappenapp">
<title> <title>
<%= title || "PantryHub" %> <%= title || "PantryHub" %>
</title> </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"
<link href="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/css/tabler.min.css" rel="stylesheet"> rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@tabler/icons@latest/tabler-icons.css" rel="stylesheet">
<link href="/css/style.css" rel="stylesheet">
<script> <script>
// Register service worker if ("serviceWorker" in navigator) {
if ('serviceWorker' in navigator) { navigator.serviceWorker.register("/service-worker.js", { updateViaCache: "none" });
navigator.serviceWorker.register('/service-worker.js')
.then(reg => console.log('✅ Service Worker registered'))
.catch(err => console.log('❌ Service Worker registration failed:', err));
} }
</script> </script>
<link
href="/css/style.css"
rel="stylesheet">
+13 -88
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="/"> <a class="navbar-brand" href="/">
🛒 PantryHub
</a>
<button class="navbar-toggler" 🛒 PantryHub
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarMenu">
<span class="navbar-toggler-icon"></span> </a>
</button> <% if (user) { %>
<div class="navbar-nav flex-row ms-auto">
<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> <a class="nav-link" href="/">Dashboard</a>
</li> <a class="nav-link" href="/lists">Lijsten</a>
<a class="nav-link" href="/products">Producten</a>
<li class="nav-item"> <a class="nav-link" href="/household">Huishouden</a>
<a class="nav-link" href="/lists">🛒 Lijsten</a> <a class="nav-link text-danger" href="/logout">Uitloggen</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> </div>
<% } %>
</li>
</ul> </div>
<% } else { %>
<div class="ms-auto">
<a href="/login" class="btn btn-primary">
Inloggen
</a>
</div>
<% } %>
</div>
</div>
</header> </header>
+23 -119
View File
@@ -1,149 +1,53 @@
<div class="page-header mb-4"> <div class="page-header mb-4">
<h1>📦 Producten</h1> <h1>
📦 Producten
</h1>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-8"> <div class="col-md-8">
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<% if (products.length === 0) { %>
<% if(products.length === 0) { %>
<p class="text-secondary">Nog geen producten.</p> <p class="text-secondary">Nog geen producten.</p>
<% } else { %> <% } else { %>
<div class="list-group"> <div class="list-group">
<% products.forEach(product => { %>
<%
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>
</div>
<% grouped[cat].forEach(product => { %>
<div class="list-group-item"> <div class="list-group-item">
<strong><%= product.category_icon || "" %> <%= product.name %></strong>
<div class="d-flex justify-content-between"> <div class="text-secondary"><%= product.category_name || "Geen categorie" %></div>
</div>
<strong> <% }); %>
</div>
<%= product.category_icon || "" %>
<%= product.name %>
</strong>
<small class="text-secondary">
<% if(product.barcode) { %>
📊 <%= product.barcode %>
<% } %> <% } %>
</small>
</div> </div>
</div> </div>
<% }) %>
<% }) %>
</div>
<% } %>
</div>
</div>
</div> </div>
<div class="col-md-4"> <div class="col-md-4">
<div class="card"> <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"> <div class="card-body">
<form method="post" action="/products"> <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" for="category-id">Categorie</label>
<select id="category-id" class="form-select mb-3" name="category_id">
<label class="form-label">Productnaam</label> <option value="">Geen categorie</option>
<% (categories || []).forEach(category => { %>
<input <option value="<%= category.id %>"><%= category.icon || "" %> <%= category.name %></option>
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> </select>
</div> <button class="btn btn-primary w-100" type="submit">Product toevoegen</button>
<button class="btn btn-primary w-100">
Product toevoegen
</button>
</form> </form>
</div> </div>
</div> </div>
</div> </div>
</div> </div>