diff --git a/backend/src/tools/bestellungen/routes.js b/backend/src/tools/bestellungen/routes.js index 895dfd6..4c8faf3 100644 --- a/backend/src/tools/bestellungen/routes.js +++ b/backend/src/tools/bestellungen/routes.js @@ -4,6 +4,19 @@ const { authenticate } = require('../../middleware/auth'); const router = express.Router(); const uid = req => req.user.id; +// Status der Bestellung automatisch aus den Stück-Zählern berechnen +const autoUpdateOrderStatus = (orderId) => { + const items = db.prepare('SELECT * FROM order_items WHERE order_id=?').all(orderId); + if (!items.length) return; + const totalPieces = items.reduce((s,i) => s + (i.stueckzahl||0), 0); + const fertigPieces = items.reduce((s,i) => s + (i.qty_fertig||0), 0); + const arbeitPieces = items.reduce((s,i) => s + (i.qty_in_arbeit||0), 0); + let newStatus = 'warteliste'; + if (fertigPieces >= totalPieces && totalPieces > 0) newStatus = 'fertig'; + else if (fertigPieces > 0 || arbeitPieces > 0) newStatus = 'in_arbeit'; + db.prepare('UPDATE orders SET status=?,updated_at=CURRENT_TIMESTAMP WHERE id=?').run(newStatus, orderId); +}; + const loadOrder = (id, userId) => { const order = db.prepare('SELECT * FROM orders WHERE id=? AND user_id=?').get(id, userId); if (!order) return null; @@ -75,6 +88,7 @@ router.post('/:id/items', authenticate, (req, res) => { .run(req.params.id, calc.id, calc.name, calc.preis_freundschaft, calc.preis_normal, calc.preis_auftrag, stueckzahl, custom_price, stueckzahl); } + autoUpdateOrderStatus(req.params.id); res.json(loadOrder(req.params.id, uid(req))); }); @@ -110,6 +124,7 @@ router.put('/:id/items/:itemId', authenticate, (req, res) => { db.prepare('UPDATE order_items SET custom_price=? WHERE id=?').run(req.body.custom_price, item.id); } + autoUpdateOrderStatus(req.params.id); res.json(loadOrder(req.params.id, uid(req))); }); @@ -117,6 +132,7 @@ router.delete('/:id/items/:itemId', authenticate, (req, res) => { const order = db.prepare('SELECT * FROM orders WHERE id=? AND user_id=?').get(req.params.id, uid(req)); if (!order) return res.status(404).json({ error: 'Nicht gefunden' }); db.prepare('DELETE FROM order_items WHERE id=? AND order_id=?').run(req.params.itemId, req.params.id); + autoUpdateOrderStatus(req.params.id); res.json(loadOrder(req.params.id, uid(req))); });