diff --git a/backend/routes/artikel.js b/backend/routes/artikel.js
index 296e63e..5c8923f 100644
--- a/backend/routes/artikel.js
+++ b/backend/routes/artikel.js
@@ -1,15 +1,21 @@
import express from 'express';
+import fs from 'fs';
+import path from 'path';
import { body, validationResult } from 'express-validator';
import pool from '../config/database.js';
-import { authenticateToken, requireTenant } from '../middleware/auth.js';
+import { authenticateToken, requireTenant, requireRole } from '../middleware/auth.js';
+import { upload } from '../middleware/upload.js';
const router = express.Router();
router.use(authenticateToken, requireTenant);
+// GET alle Artikel (auch Inaktive fuer Admin)
router.get('/', async (req, res) => {
try {
+ const showInactive = req.query.all === '1';
+ const where = showInactive ? 'tenant_id = ?' : 'tenant_id = ? AND aktiv = 1';
const [rows] = await pool.query(
- 'SELECT * FROM artikel WHERE tenant_id = ? ORDER BY bezeichnung ASC',
+ `SELECT * FROM artikel WHERE ${where} ORDER BY bezeichnung ASC`,
[req.user.tenant_id]
);
res.json(rows);
@@ -27,35 +33,49 @@ router.get('/:id', async (req, res) => {
} catch (e) { res.status(500).json({ error: 'Serverfehler' }); }
});
-router.post('/', [
+// POST: Anlegen (Admin only)
+router.post('/', requireRole(['admin']), [
body('bezeichnung').notEmpty().trim(),
- body('pfand_betrag').isFloat({ min: 0 })
+ body('pfand_betrag').isFloat({ min: 0 }),
+ body('beschreibung').optional({ checkFalsy: true }).trim(),
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
try {
await pool.query(
- 'INSERT INTO artikel (id, tenant_id, bezeichnung, pfand_betrag) VALUES (UUID(), ?, ?, ?)',
- [req.user.tenant_id, req.body.bezeichnung, req.body.pfand_betrag]
+ `INSERT INTO artikel (id, tenant_id, bezeichnung, pfand_betrag, beschreibung, aktiv)
+ VALUES (UUID(), ?, ?, ?, ?, 1)`,
+ [req.user.tenant_id, req.body.bezeichnung, req.body.pfand_betrag,
+ req.body.beschreibung || null]
);
const [rows] = await pool.query(
'SELECT * FROM artikel WHERE tenant_id = ? ORDER BY erstellt_am DESC LIMIT 1',
[req.user.tenant_id]
);
res.status(201).json(rows[0]);
- } catch (e) { res.status(500).json({ error: 'Serverfehler' }); }
+ } catch (e) {
+ console.error('POST artikel:', e);
+ res.status(500).json({ error: 'Serverfehler' });
+ }
});
-router.put('/:id', [
+// PUT: Aendern (Admin only)
+router.put('/:id', requireRole(['admin']), [
body('bezeichnung').notEmpty().trim(),
- body('pfand_betrag').isFloat({ min: 0 })
+ body('pfand_betrag').isFloat({ min: 0 }),
+ body('beschreibung').optional({ checkFalsy: true }).trim(),
+ body('aktiv').optional().isBoolean(),
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
try {
+ const aktivVal = req.body.aktiv === undefined ? 1 : (req.body.aktiv ? 1 : 0);
const [r] = await pool.query(
- 'UPDATE artikel SET bezeichnung=?, pfand_betrag=? WHERE id=? AND tenant_id=?',
- [req.body.bezeichnung, req.body.pfand_betrag, req.params.id, req.user.tenant_id]
+ `UPDATE artikel
+ SET bezeichnung=?, pfand_betrag=?, beschreibung=?, aktiv=?
+ WHERE id=? AND tenant_id=?`,
+ [req.body.bezeichnung, req.body.pfand_betrag, req.body.beschreibung || null,
+ aktivVal, req.params.id, req.user.tenant_id]
);
if (r.affectedRows === 0) return res.status(404).json({ error: 'Artikel nicht gefunden' });
const [rows] = await pool.query('SELECT * FROM artikel WHERE id=? AND tenant_id=?',
@@ -64,13 +84,72 @@ router.put('/:id', [
} catch (e) { res.status(500).json({ error: 'Serverfehler' }); }
});
-router.delete('/:id', async (req, res) => {
+// POST Produktbild (Admin only)
+router.post('/:id/bild', requireRole(['admin']), upload.single('foto'), async (req, res) => {
+ if (!req.file) return res.status(400).json({ error: 'Kein Bild hochgeladen' });
try {
+ const [[a]] = await pool.query('SELECT bild_url FROM artikel WHERE id=? AND tenant_id=?',
+ [req.params.id, req.user.tenant_id]);
+ if (!a) {
+ try { fs.unlinkSync(req.file.path); } catch {}
+ return res.status(404).json({ error: 'Artikel nicht gefunden' });
+ }
+ // Altes Bild loeschen (best effort)
+ if (a.bild_url) {
+ const oldPath = path.join(process.env.UPLOAD_DIR || '/app/uploads',
+ a.bild_url.replace(/^\/uploads\//, ''));
+ try { fs.unlinkSync(oldPath); } catch {}
+ }
+ const newUrl = `/uploads/${req.file.filename}`;
+ await pool.query('UPDATE artikel SET bild_url=? WHERE id=? AND tenant_id=?',
+ [newUrl, req.params.id, req.user.tenant_id]);
+ const [rows] = await pool.query('SELECT * FROM artikel WHERE id=? AND tenant_id=?',
+ [req.params.id, req.user.tenant_id]);
+ res.json(rows[0]);
+ } catch (e) {
+ console.error('POST artikel/bild:', e);
+ res.status(500).json({ error: 'Serverfehler' });
+ }
+});
+
+router.delete('/:id/bild', requireRole(['admin']), async (req, res) => {
+ try {
+ const [[a]] = await pool.query('SELECT bild_url FROM artikel WHERE id=? AND tenant_id=?',
+ [req.params.id, req.user.tenant_id]);
+ if (!a) return res.status(404).json({ error: 'Artikel nicht gefunden' });
+ if (a.bild_url) {
+ const p = path.join(process.env.UPLOAD_DIR || '/app/uploads',
+ a.bild_url.replace(/^\/uploads\//, ''));
+ try { fs.unlinkSync(p); } catch {}
+ }
+ await pool.query('UPDATE artikel SET bild_url=NULL WHERE id=? AND tenant_id=?',
+ [req.params.id, req.user.tenant_id]);
+ res.json({ message: 'Bild entfernt' });
+ } catch (e) { res.status(500).json({ error: 'Serverfehler' }); }
+});
+
+router.delete('/:id', requireRole(['admin']), async (req, res) => {
+ try {
+ // Bild-Datei mitloeschen
+ const [[a]] = await pool.query('SELECT bild_url FROM artikel WHERE id=? AND tenant_id=?',
+ [req.params.id, req.user.tenant_id]);
+ if (a?.bild_url) {
+ const p = path.join(process.env.UPLOAD_DIR || '/app/uploads',
+ a.bild_url.replace(/^\/uploads\//, ''));
+ try { fs.unlinkSync(p); } catch {}
+ }
const [r] = await pool.query('DELETE FROM artikel WHERE id=? AND tenant_id=?',
[req.params.id, req.user.tenant_id]);
if (r.affectedRows === 0) return res.status(404).json({ error: 'Artikel nicht gefunden' });
res.json({ message: 'Artikel gelöscht' });
- } catch (e) { res.status(500).json({ error: 'Serverfehler' }); }
+ } catch (e) {
+ if (e.code === 'ER_ROW_IS_REFERENCED' || e.code === 'ER_ROW_IS_REFERENCED_2') {
+ return res.status(400).json({
+ error: 'Artikel wird in Lieferungen/Rücknahmen verwendet — bitte stattdessen auf "Inaktiv" setzen.'
+ });
+ }
+ res.status(500).json({ error: 'Serverfehler' });
+ }
});
export default router;
diff --git a/backend/scripts/bootstrap.js b/backend/scripts/bootstrap.js
index 5ad9586..8d28ef2 100644
--- a/backend/scripts/bootstrap.js
+++ b/backend/scripts/bootstrap.js
@@ -1,18 +1,33 @@
import bcrypt from 'bcrypt';
import pool from '../config/database.js';
-const EXPIRY_COLS = ['notified_7d_at', 'notified_1d_at', 'notified_expired_at'];
+// Spaltenname -> SQL-Definition
+const COLS_TO_ADD = {
+ tenants: {
+ notified_7d_at: 'TIMESTAMP NULL',
+ notified_1d_at: 'TIMESTAMP NULL',
+ notified_expired_at: 'TIMESTAMP NULL',
+ },
+ artikel: {
+ bild_url: 'VARCHAR(500) NULL',
+ beschreibung: 'TEXT NULL',
+ aktiv: 'TINYINT(1) NOT NULL DEFAULT 1',
+ },
+};
-async function ensureExpiryColumns() {
- const [cols] = await pool.query(
- `SELECT COLUMN_NAME FROM information_schema.columns
- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'tenants'`
- );
- const have = new Set(cols.map(c => c.COLUMN_NAME));
- for (const col of EXPIRY_COLS) {
- if (!have.has(col)) {
- await pool.query(`ALTER TABLE tenants ADD COLUMN ${col} TIMESTAMP NULL`);
- console.log('[bootstrap] tenants ALTER ADD', col);
+async function ensureColumns() {
+ for (const [table, cols] of Object.entries(COLS_TO_ADD)) {
+ const [existing] = await pool.query(
+ `SELECT COLUMN_NAME FROM information_schema.columns
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`,
+ [table]
+ );
+ const have = new Set(existing.map(c => c.COLUMN_NAME));
+ for (const [col, def] of Object.entries(cols)) {
+ if (!have.has(col)) {
+ await pool.query(`ALTER TABLE ${table} ADD COLUMN ${col} ${def}`);
+ console.log(`[bootstrap] ${table} ALTER ADD ${col}`);
+ }
}
}
}
@@ -25,7 +40,7 @@ export async function bootstrapSuperAdmin() {
}
// Migrations
- try { await ensureExpiryColumns(); }
+ try { await ensureColumns(); }
catch (e) { console.error('[bootstrap] Migration-Fehler:', e.message); }
const email = process.env.SUPERADMIN_EMAIL;
diff --git a/src/api/client.js b/src/api/client.js
index bfeaa1e..6ebc0f2 100644
--- a/src/api/client.js
+++ b/src/api/client.js
@@ -77,7 +77,21 @@ class ApiClient {
deleteKundenBild(id) { return this.request(`/kunden-bilder/bild/${id}`, { method: 'DELETE' }); }
// Artikel
- getArtikel() { return this.request('/artikel'); }
+ getArtikel(includeInactive) {
+ return this.request('/artikel' + (includeInactive ? '?all=1' : ''));
+ }
+ async uploadArtikelBild(id, file) {
+ const fd = new FormData();
+ fd.append('foto', file);
+ const res = await fetch(`${API_BASE_URL}/artikel/${id}/bild`, {
+ method: 'POST',
+ headers: { 'Authorization': `Bearer ${this.getToken()}` },
+ body: fd,
+ });
+ if (!res.ok) { const e = await res.json().catch(()=>({})); throw new Error(e.error || `HTTP ${res.status}`); }
+ return res.json();
+ }
+ deleteArtikelBild(id) { return this.request(`/artikel/${id}/bild`, { method: 'DELETE' }); }
createArtikel(a) { return this.request('/artikel', { method: 'POST', body: JSON.stringify(a) }); }
updateArtikel(id, a) { return this.request(`/artikel/${id}`, { method: 'PUT', body: JSON.stringify(a) }); }
deleteArtikel(id) { return this.request(`/artikel/${id}`, { method: 'DELETE' }); }
diff --git a/src/components/Dashboard/Dashboard.jsx b/src/components/Dashboard/Dashboard.jsx
index f293538..abf2bbd 100644
--- a/src/components/Dashboard/Dashboard.jsx
+++ b/src/components/Dashboard/Dashboard.jsx
@@ -6,6 +6,7 @@ import AdminDashboard from './AdminDashboard';
import KundenVerwaltung from '../KundenVerwaltung';
import MitarbeiterVerwaltung from '../MitarbeiterVerwaltung';
import Geraete from '../Geraete';
+import Produkte from '../Produkte';
import TourPlanung from '../TourPlanung';
import Account from './Account';
@@ -38,6 +39,7 @@ export default function Dashboard({ user, onLogout }) {
{activeView === 'account' &&
{a.beschreibung}
} +