new features
This commit is contained in:
@@ -2,10 +2,12 @@ import express, { Application, Request, Response } from 'express';
|
||||
import cors from 'cors';
|
||||
import helmet from 'helmet';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import path from 'path';
|
||||
import environment from './config/environment';
|
||||
import logger from './utils/logger';
|
||||
import { errorHandler, notFoundHandler } from './middleware/error.middleware';
|
||||
import { requestTimeout } from './middleware/request-timeout.middleware';
|
||||
import { authenticate } from './middleware/auth.middleware';
|
||||
|
||||
const app: Application = express();
|
||||
|
||||
@@ -93,11 +95,13 @@ import bookingRoutes from './routes/booking.routes';
|
||||
import notificationRoutes from './routes/notification.routes';
|
||||
import bookstackRoutes from './routes/bookstack.routes';
|
||||
import vikunjaRoutes from './routes/vikunja.routes';
|
||||
import bestellungRoutes from './routes/bestellung.routes';
|
||||
import configRoutes from './routes/config.routes';
|
||||
import serviceMonitorRoutes from './routes/serviceMonitor.routes';
|
||||
import settingsRoutes from './routes/settings.routes';
|
||||
import bannerRoutes from './routes/banner.routes';
|
||||
import permissionRoutes from './routes/permission.routes';
|
||||
import shopRoutes from './routes/shop.routes';
|
||||
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/user', userRoutes);
|
||||
@@ -114,12 +118,17 @@ app.use('/api/bookings', bookingRoutes);
|
||||
app.use('/api/notifications', notificationRoutes);
|
||||
app.use('/api/bookstack', bookstackRoutes);
|
||||
app.use('/api/vikunja', vikunjaRoutes);
|
||||
app.use('/api/bestellungen', bestellungRoutes);
|
||||
app.use('/api/config', configRoutes);
|
||||
app.use('/api/admin', serviceMonitorRoutes);
|
||||
app.use('/api/admin/settings', settingsRoutes);
|
||||
app.use('/api/settings', settingsRoutes);
|
||||
app.use('/api/banners', bannerRoutes);
|
||||
app.use('/api/permissions', permissionRoutes);
|
||||
app.use('/api/shop', shopRoutes);
|
||||
|
||||
// Static file serving for uploads (authenticated)
|
||||
app.use('/uploads', authenticate, express.static(path.resolve(__dirname, '../../uploads')));
|
||||
|
||||
// 404 handler
|
||||
app.use(notFoundHandler);
|
||||
|
||||
466
backend/src/controllers/bestellung.controller.ts
Normal file
466
backend/src/controllers/bestellung.controller.ts
Normal file
@@ -0,0 +1,466 @@
|
||||
import { Request, Response } from 'express';
|
||||
import bestellungService from '../services/bestellung.service';
|
||||
import logger from '../utils/logger';
|
||||
import fs from 'fs';
|
||||
|
||||
// Helper to safely extract a route param as string
|
||||
const param = (req: Request, key: string): string => req.params[key] as string;
|
||||
|
||||
class BestellungController {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vendors
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async listVendors(_req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const vendors = await bestellungService.getVendors();
|
||||
res.status(200).json({ success: true, data: vendors });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.listVendors error', { error });
|
||||
res.status(500).json({ success: false, message: 'Lieferanten konnten nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async createVendor(req: Request, res: Response): Promise<void> {
|
||||
const { name } = req.body;
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
res.status(400).json({ success: false, message: 'Name ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const vendor = await bestellungService.createVendor(req.body, req.user!.id);
|
||||
res.status(201).json({ success: true, data: vendor });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.createVendor error', { error });
|
||||
res.status(500).json({ success: false, message: 'Lieferant konnte nicht erstellt werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async updateVendor(req: Request, res: Response): Promise<void> {
|
||||
const id = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const vendor = await bestellungService.updateVendor(id, req.body, req.user!.id);
|
||||
if (!vendor) {
|
||||
res.status(404).json({ success: false, message: 'Lieferant nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: vendor });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.updateVendor error', { error });
|
||||
res.status(500).json({ success: false, message: 'Lieferant konnte nicht aktualisiert werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteVendor(req: Request, res: Response): Promise<void> {
|
||||
const id = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const deleted = await bestellungService.deleteVendor(id);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ success: false, message: 'Lieferant nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, message: 'Lieferant gelöscht' });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.deleteVendor error', { error });
|
||||
res.status(500).json({ success: false, message: 'Lieferant konnte nicht gelöscht werden' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Orders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async listOrders(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const filters: { status?: string; lieferant_id?: number; besteller_id?: string } = {};
|
||||
if (req.query.status) filters.status = req.query.status as string;
|
||||
if (req.query.lieferant_id) filters.lieferant_id = parseInt(req.query.lieferant_id as string, 10);
|
||||
if (req.query.besteller_id) filters.besteller_id = req.query.besteller_id as string;
|
||||
|
||||
const orders = await bestellungService.getOrders(filters);
|
||||
res.status(200).json({ success: true, data: orders });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.listOrders error', { error });
|
||||
res.status(500).json({ success: false, message: 'Bestellungen konnten nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async getOrder(req: Request, res: Response): Promise<void> {
|
||||
const id = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const order = await bestellungService.getOrderById(id);
|
||||
if (!order) {
|
||||
res.status(404).json({ success: false, message: 'Bestellung nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: order });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.getOrder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Bestellung konnte nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async createOrder(req: Request, res: Response): Promise<void> {
|
||||
const { titel } = req.body;
|
||||
if (!titel || typeof titel !== 'string' || titel.trim().length === 0) {
|
||||
res.status(400).json({ success: false, message: 'Titel ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const order = await bestellungService.createOrder(req.body, req.user!.id);
|
||||
res.status(201).json({ success: true, data: order });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.createOrder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Bestellung konnte nicht erstellt werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async updateOrder(req: Request, res: Response): Promise<void> {
|
||||
const id = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const order = await bestellungService.updateOrder(id, req.body, req.user!.id);
|
||||
if (!order) {
|
||||
res.status(404).json({ success: false, message: 'Bestellung nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: order });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.updateOrder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Bestellung konnte nicht aktualisiert werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteOrder(req: Request, res: Response): Promise<void> {
|
||||
const id = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const deleted = await bestellungService.deleteOrder(id, req.user!.id);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ success: false, message: 'Bestellung nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, message: 'Bestellung gelöscht' });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.deleteOrder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Bestellung konnte nicht gelöscht werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async updateStatus(req: Request, res: Response): Promise<void> {
|
||||
const id = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige ID' });
|
||||
return;
|
||||
}
|
||||
const { status } = req.body;
|
||||
if (!status || typeof status !== 'string') {
|
||||
res.status(400).json({ success: false, message: 'Status ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const order = await bestellungService.updateOrderStatus(id, status, req.user!.id);
|
||||
if (!order) {
|
||||
res.status(404).json({ success: false, message: 'Bestellung nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: order });
|
||||
} catch (error: any) {
|
||||
if (error.message?.includes('Ungültiger Statusübergang')) {
|
||||
res.status(400).json({ success: false, message: error.message });
|
||||
return;
|
||||
}
|
||||
logger.error('BestellungController.updateStatus error', { error });
|
||||
res.status(500).json({ success: false, message: 'Status konnte nicht aktualisiert werden' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Line Items
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async addLineItem(req: Request, res: Response): Promise<void> {
|
||||
const bestellungId = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(bestellungId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Bestellungs-ID' });
|
||||
return;
|
||||
}
|
||||
const { artikel, menge } = req.body;
|
||||
if (!artikel || typeof artikel !== 'string' || artikel.trim().length === 0) {
|
||||
res.status(400).json({ success: false, message: 'Artikel ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
if (menge === undefined || menge === null || menge <= 0) {
|
||||
res.status(400).json({ success: false, message: 'Menge muss größer als 0 sein' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const item = await bestellungService.addLineItem(bestellungId, req.body, req.user!.id);
|
||||
res.status(201).json({ success: true, data: item });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.addLineItem error', { error });
|
||||
res.status(500).json({ success: false, message: 'Position konnte nicht hinzugefügt werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async updateLineItem(req: Request, res: Response): Promise<void> {
|
||||
const itemId = parseInt(param(req, 'itemId'), 10);
|
||||
if (isNaN(itemId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Position-ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const item = await bestellungService.updateLineItem(itemId, req.body, req.user!.id);
|
||||
if (!item) {
|
||||
res.status(404).json({ success: false, message: 'Position nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: item });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.updateLineItem error', { error });
|
||||
res.status(500).json({ success: false, message: 'Position konnte nicht aktualisiert werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteLineItem(req: Request, res: Response): Promise<void> {
|
||||
const itemId = parseInt(param(req, 'itemId'), 10);
|
||||
if (isNaN(itemId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Position-ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const deleted = await bestellungService.deleteLineItem(itemId, req.user!.id);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ success: false, message: 'Position nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, message: 'Position gelöscht' });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.deleteLineItem error', { error });
|
||||
res.status(500).json({ success: false, message: 'Position konnte nicht gelöscht werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async updateReceivedQuantity(req: Request, res: Response): Promise<void> {
|
||||
const itemId = parseInt(param(req, 'itemId'), 10);
|
||||
if (isNaN(itemId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Position-ID' });
|
||||
return;
|
||||
}
|
||||
const { menge } = req.body;
|
||||
if (menge === undefined || menge === null || menge < 0) {
|
||||
res.status(400).json({ success: false, message: 'Erhaltene Menge muss >= 0 sein' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const item = await bestellungService.updateReceivedQuantity(itemId, menge, req.user!.id);
|
||||
if (!item) {
|
||||
res.status(404).json({ success: false, message: 'Position nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: item });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.updateReceivedQuantity error', { error });
|
||||
res.status(500).json({ success: false, message: 'Liefermenge konnte nicht aktualisiert werden' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Files
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async uploadFile(req: Request, res: Response): Promise<void> {
|
||||
const bestellungId = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(bestellungId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Bestellungs-ID' });
|
||||
return;
|
||||
}
|
||||
const file = (req as any).file;
|
||||
if (!file) {
|
||||
res.status(400).json({ success: false, message: 'Keine Datei hochgeladen' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const fileRecord = await bestellungService.addFile(bestellungId, {
|
||||
dateiname: file.originalname,
|
||||
dateipfad: file.path,
|
||||
dateityp: file.mimetype,
|
||||
dateigroesse: file.size,
|
||||
}, req.user!.id);
|
||||
res.status(201).json({ success: true, data: fileRecord });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.uploadFile error', { error });
|
||||
res.status(500).json({ success: false, message: 'Datei konnte nicht hochgeladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteFile(req: Request, res: Response): Promise<void> {
|
||||
const fileId = parseInt(param(req, 'fileId'), 10);
|
||||
if (isNaN(fileId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Datei-ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await bestellungService.deleteFile(fileId, req.user!.id);
|
||||
if (!result) {
|
||||
res.status(404).json({ success: false, message: 'Datei nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
// Remove from disk
|
||||
try {
|
||||
if (result.dateipfad && fs.existsSync(result.dateipfad)) {
|
||||
fs.unlinkSync(result.dateipfad);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('Failed to delete file from disk', { path: result.dateipfad, error: err });
|
||||
}
|
||||
res.status(200).json({ success: true, message: 'Datei gelöscht' });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.deleteFile error', { error });
|
||||
res.status(500).json({ success: false, message: 'Datei konnte nicht gelöscht werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async listFiles(req: Request, res: Response): Promise<void> {
|
||||
const bestellungId = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(bestellungId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Bestellungs-ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const files = await bestellungService.getFilesByOrder(bestellungId);
|
||||
res.status(200).json({ success: true, data: files });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.listFiles error', { error });
|
||||
res.status(500).json({ success: false, message: 'Dateien konnten nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reminders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async addReminder(req: Request, res: Response): Promise<void> {
|
||||
const bestellungId = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(bestellungId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Bestellungs-ID' });
|
||||
return;
|
||||
}
|
||||
const { titel, faellig_am } = req.body;
|
||||
if (!titel || typeof titel !== 'string' || titel.trim().length === 0) {
|
||||
res.status(400).json({ success: false, message: 'Titel ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
if (!faellig_am) {
|
||||
res.status(400).json({ success: false, message: 'Fälligkeitsdatum ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const reminder = await bestellungService.addReminder(bestellungId, req.body, req.user!.id);
|
||||
res.status(201).json({ success: true, data: reminder });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.addReminder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Erinnerung konnte nicht erstellt werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async markReminderDone(req: Request, res: Response): Promise<void> {
|
||||
const remId = parseInt(param(req, 'remId'), 10);
|
||||
if (isNaN(remId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Erinnerungs-ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const reminder = await bestellungService.markReminderDone(remId, req.user!.id);
|
||||
if (!reminder) {
|
||||
res.status(404).json({ success: false, message: 'Erinnerung nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: reminder });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.markReminderDone error', { error });
|
||||
res.status(500).json({ success: false, message: 'Erinnerung konnte nicht als erledigt markiert werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteReminder(req: Request, res: Response): Promise<void> {
|
||||
const remId = parseInt(param(req, 'remId'), 10);
|
||||
if (isNaN(remId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Erinnerungs-ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const deleted = await bestellungService.deleteReminder(remId);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ success: false, message: 'Erinnerung nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, message: 'Erinnerung gelöscht' });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.deleteReminder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Erinnerung konnte nicht gelöscht werden' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// History
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async getHistory(req: Request, res: Response): Promise<void> {
|
||||
const bestellungId = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(bestellungId)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige Bestellungs-ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const history = await bestellungService.getHistory(bestellungId);
|
||||
res.status(200).json({ success: true, data: history });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.getHistory error', { error });
|
||||
res.status(500).json({ success: false, message: 'Historie konnte nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Export (placeholder — returns order detail as JSON for now)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async exportOrder(req: Request, res: Response): Promise<void> {
|
||||
const id = parseInt(param(req, 'id'), 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ success: false, message: 'Ungültige ID' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const order = await bestellungService.getOrderById(id);
|
||||
if (!order) {
|
||||
res.status(404).json({ success: false, message: 'Bestellung nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: order });
|
||||
} catch (error) {
|
||||
logger.error('BestellungController.exportOrder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Export fehlgeschlagen' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new BestellungController();
|
||||
256
backend/src/controllers/shop.controller.ts
Normal file
256
backend/src/controllers/shop.controller.ts
Normal file
@@ -0,0 +1,256 @@
|
||||
import { Request, Response } from 'express';
|
||||
import shopService from '../services/shop.service';
|
||||
import notificationService from '../services/notification.service';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
class ShopController {
|
||||
// -------------------------------------------------------------------------
|
||||
// Catalog Items
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async getItems(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const kategorie = req.query.kategorie as string | undefined;
|
||||
const aktiv = req.query.aktiv !== undefined ? req.query.aktiv === 'true' : undefined;
|
||||
const items = await shopService.getItems({ kategorie, aktiv });
|
||||
res.status(200).json({ success: true, data: items });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.getItems error', { error });
|
||||
res.status(500).json({ success: false, message: 'Artikel konnten nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async getItemById(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const id = Number(req.params.id);
|
||||
const item = await shopService.getItemById(id);
|
||||
if (!item) {
|
||||
res.status(404).json({ success: false, message: 'Artikel nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: item });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.getItemById error', { error });
|
||||
res.status(500).json({ success: false, message: 'Artikel konnte nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async createItem(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { bezeichnung } = req.body;
|
||||
if (!bezeichnung || bezeichnung.trim().length === 0) {
|
||||
res.status(400).json({ success: false, message: 'Bezeichnung ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
const item = await shopService.createItem(req.body, req.user!.id);
|
||||
res.status(201).json({ success: true, data: item });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.createItem error', { error });
|
||||
res.status(500).json({ success: false, message: 'Artikel konnte nicht erstellt werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async updateItem(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const id = Number(req.params.id);
|
||||
const item = await shopService.updateItem(id, req.body, req.user!.id);
|
||||
if (!item) {
|
||||
res.status(404).json({ success: false, message: 'Artikel nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: item });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.updateItem error', { error });
|
||||
res.status(500).json({ success: false, message: 'Artikel konnte nicht aktualisiert werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteItem(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const id = Number(req.params.id);
|
||||
await shopService.deleteItem(id);
|
||||
res.status(200).json({ success: true, message: 'Artikel gelöscht' });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.deleteItem error', { error });
|
||||
res.status(500).json({ success: false, message: 'Artikel konnte nicht gelöscht werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async getCategories(_req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const categories = await shopService.getCategories();
|
||||
res.status(200).json({ success: true, data: categories });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.getCategories error', { error });
|
||||
res.status(500).json({ success: false, message: 'Kategorien konnten nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Requests
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async getRequests(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const status = req.query.status as string | undefined;
|
||||
const anfrager_id = req.query.anfrager_id as string | undefined;
|
||||
const requests = await shopService.getRequests({ status, anfrager_id });
|
||||
res.status(200).json({ success: true, data: requests });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.getRequests error', { error });
|
||||
res.status(500).json({ success: false, message: 'Anfragen konnten nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async getMyRequests(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const requests = await shopService.getMyRequests(req.user!.id);
|
||||
res.status(200).json({ success: true, data: requests });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.getMyRequests error', { error });
|
||||
res.status(500).json({ success: false, message: 'Anfragen konnten nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async getRequestById(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const id = Number(req.params.id);
|
||||
const request = await shopService.getRequestById(id);
|
||||
if (!request) {
|
||||
res.status(404).json({ success: false, message: 'Anfrage nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ success: true, data: request });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.getRequestById error', { error });
|
||||
res.status(500).json({ success: false, message: 'Anfrage konnte nicht geladen werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async createRequest(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { items, notizen } = req.body as {
|
||||
items?: { artikel_id?: number; bezeichnung: string; menge: number; notizen?: string }[];
|
||||
notizen?: string;
|
||||
};
|
||||
|
||||
if (!items || items.length === 0) {
|
||||
res.status(400).json({ success: false, message: 'Mindestens eine Position ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
|
||||
for (const item of items) {
|
||||
if (!item.bezeichnung || item.bezeichnung.trim().length === 0) {
|
||||
res.status(400).json({ success: false, message: 'Bezeichnung ist für alle Positionen erforderlich' });
|
||||
return;
|
||||
}
|
||||
if (!item.menge || item.menge < 1) {
|
||||
res.status(400).json({ success: false, message: 'Menge muss mindestens 1 sein' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const request = await shopService.createRequest(req.user!.id, items, notizen);
|
||||
res.status(201).json({ success: true, data: request });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.createRequest error', { error });
|
||||
res.status(500).json({ success: false, message: 'Anfrage konnte nicht erstellt werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async updateRequestStatus(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const id = Number(req.params.id);
|
||||
const { status, admin_notizen } = req.body as {
|
||||
status?: string;
|
||||
admin_notizen?: string;
|
||||
};
|
||||
|
||||
if (!status) {
|
||||
res.status(400).json({ success: false, message: 'Status ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
|
||||
const validStatuses = ['offen', 'genehmigt', 'abgelehnt', 'bestellt', 'erledigt'];
|
||||
if (!validStatuses.includes(status)) {
|
||||
res.status(400).json({ success: false, message: `Ungültiger Status. Erlaubt: ${validStatuses.join(', ')}` });
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch request to get anfrager_id for notification
|
||||
const existing = await shopService.getRequestById(id);
|
||||
if (!existing) {
|
||||
res.status(404).json({ success: false, message: 'Anfrage nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
|
||||
const updated = await shopService.updateRequestStatus(id, status, admin_notizen, req.user!.id);
|
||||
|
||||
// Notify requester on status changes
|
||||
if (['genehmigt', 'abgelehnt', 'bestellt', 'erledigt'].includes(status)) {
|
||||
await notificationService.createNotification({
|
||||
user_id: existing.anfrager_id,
|
||||
typ: 'shop_anfrage',
|
||||
titel: status === 'genehmigt' ? 'Anfrage genehmigt' : status === 'abgelehnt' ? 'Anfrage abgelehnt' : `Anfrage ${status}`,
|
||||
nachricht: `Deine Shop-Anfrage #${id} wurde ${status === 'genehmigt' ? 'genehmigt' : status === 'abgelehnt' ? 'abgelehnt' : status}.`,
|
||||
schwere: status === 'abgelehnt' ? 'warnung' : 'info',
|
||||
link: '/shop',
|
||||
quell_id: String(id),
|
||||
quell_typ: 'shop_anfrage',
|
||||
});
|
||||
}
|
||||
|
||||
res.status(200).json({ success: true, data: updated });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.updateRequestStatus error', { error });
|
||||
res.status(500).json({ success: false, message: 'Status konnte nicht aktualisiert werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteRequest(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const id = Number(req.params.id);
|
||||
await shopService.deleteRequest(id);
|
||||
res.status(200).json({ success: true, message: 'Anfrage gelöscht' });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.deleteRequest error', { error });
|
||||
res.status(500).json({ success: false, message: 'Anfrage konnte nicht gelöscht werden' });
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Linking
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async linkToOrder(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const anfrageId = Number(req.params.id);
|
||||
const { bestellung_id } = req.body as { bestellung_id?: number };
|
||||
|
||||
if (!bestellung_id) {
|
||||
res.status(400).json({ success: false, message: 'bestellung_id ist erforderlich' });
|
||||
return;
|
||||
}
|
||||
|
||||
await shopService.linkToOrder(anfrageId, bestellung_id);
|
||||
res.status(200).json({ success: true, message: 'Verknüpfung erstellt' });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.linkToOrder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Verknüpfung konnte nicht erstellt werden' });
|
||||
}
|
||||
}
|
||||
|
||||
async unlinkFromOrder(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const anfrageId = Number(req.params.id);
|
||||
const bestellungId = Number(req.params.bestellungId);
|
||||
await shopService.unlinkFromOrder(anfrageId, bestellungId);
|
||||
res.status(200).json({ success: true, message: 'Verknüpfung entfernt' });
|
||||
} catch (error) {
|
||||
logger.error('ShopController.unlinkFromOrder error', { error });
|
||||
res.status(500).json({ success: false, message: 'Verknüpfung konnte nicht entfernt werden' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new ShopController();
|
||||
145
backend/src/database/migrations/038_create_bestellungen.sql
Normal file
145
backend/src/database/migrations/038_create_bestellungen.sql
Normal file
@@ -0,0 +1,145 @@
|
||||
-- Migration 038: Bestellungen (Vendor Orders) system
|
||||
-- Tables for vendors, orders, line items, file attachments, reminders, and audit trail.
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 1. Lieferanten (Vendors)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS lieferanten (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
kontakt_name TEXT,
|
||||
email TEXT,
|
||||
telefon TEXT,
|
||||
adresse TEXT,
|
||||
website TEXT,
|
||||
notizen TEXT,
|
||||
erstellt_von UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
erstellt_am TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
aktualisiert_am TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_lieferanten_name ON lieferanten(name);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 2. Bestellungen (Orders)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bestellungen (
|
||||
id SERIAL PRIMARY KEY,
|
||||
bezeichnung TEXT NOT NULL,
|
||||
lieferant_id INT REFERENCES lieferanten(id) ON DELETE SET NULL,
|
||||
besteller_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
status TEXT NOT NULL DEFAULT 'entwurf'
|
||||
CHECK (status IN ('entwurf','erstellt','bestellt','teillieferung','vollstaendig','abgeschlossen')),
|
||||
budget NUMERIC(10,2),
|
||||
notizen TEXT,
|
||||
erstellt_von UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
erstellt_am TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
aktualisiert_am TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
bestellt_am TIMESTAMPTZ,
|
||||
abgeschlossen_am TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bestellungen_status ON bestellungen(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_bestellungen_lieferant ON bestellungen(lieferant_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_bestellungen_besteller ON bestellungen(besteller_id);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 3. Bestellpositionen (Order Line Items)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bestellpositionen (
|
||||
id SERIAL PRIMARY KEY,
|
||||
bestellung_id INT NOT NULL REFERENCES bestellungen(id) ON DELETE CASCADE,
|
||||
bezeichnung TEXT NOT NULL,
|
||||
artikelnummer TEXT,
|
||||
menge NUMERIC NOT NULL DEFAULT 1,
|
||||
einheit TEXT DEFAULT 'Stk',
|
||||
einzelpreis NUMERIC(10,2),
|
||||
erhalten_menge NUMERIC NOT NULL DEFAULT 0,
|
||||
notizen TEXT,
|
||||
erstellt_am TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
aktualisiert_am TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bestellpositionen_bestellung ON bestellpositionen(bestellung_id);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 4. Bestellung Dateien (Order File Attachments)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bestellung_dateien (
|
||||
id SERIAL PRIMARY KEY,
|
||||
bestellung_id INT NOT NULL REFERENCES bestellungen(id) ON DELETE CASCADE,
|
||||
dateiname TEXT NOT NULL,
|
||||
dateipfad TEXT NOT NULL,
|
||||
dateityp TEXT NOT NULL,
|
||||
dateigroesse INT,
|
||||
thumbnail_pfad TEXT,
|
||||
hochgeladen_von UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
hochgeladen_am TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bestellung_dateien_bestellung ON bestellung_dateien(bestellung_id);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 5. Bestellung Erinnerungen (Order Reminders)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bestellung_erinnerungen (
|
||||
id SERIAL PRIMARY KEY,
|
||||
bestellung_id INT NOT NULL REFERENCES bestellungen(id) ON DELETE CASCADE,
|
||||
faellig_am TIMESTAMPTZ NOT NULL,
|
||||
nachricht TEXT,
|
||||
erledigt BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
erstellt_von UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
erstellt_am TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bestellung_erinnerungen_faellig ON bestellung_erinnerungen(faellig_am) WHERE NOT erledigt;
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 6. Bestellung Historie (Audit Trail)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bestellung_historie (
|
||||
id SERIAL PRIMARY KEY,
|
||||
bestellung_id INT NOT NULL REFERENCES bestellungen(id) ON DELETE CASCADE,
|
||||
aktion TEXT NOT NULL,
|
||||
details JSONB,
|
||||
erstellt_von UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
erstellt_am TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bestellung_historie_bestellung ON bestellung_historie(bestellung_id);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 7. Auto-update aktualisiert_am triggers
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE OR REPLACE FUNCTION update_aktualisiert_am()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.aktualisiert_am = NOW();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'trg_lieferanten_aktualisiert') THEN
|
||||
CREATE TRIGGER trg_lieferanten_aktualisiert BEFORE UPDATE ON lieferanten
|
||||
FOR EACH ROW EXECUTE FUNCTION update_aktualisiert_am();
|
||||
END IF;
|
||||
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'trg_bestellungen_aktualisiert') THEN
|
||||
CREATE TRIGGER trg_bestellungen_aktualisiert BEFORE UPDATE ON bestellungen
|
||||
FOR EACH ROW EXECUTE FUNCTION update_aktualisiert_am();
|
||||
END IF;
|
||||
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'trg_bestellpositionen_aktualisiert') THEN
|
||||
CREATE TRIGGER trg_bestellpositionen_aktualisiert BEFORE UPDATE ON bestellpositionen
|
||||
FOR EACH ROW EXECUTE FUNCTION update_aktualisiert_am();
|
||||
END IF;
|
||||
END $$;
|
||||
84
backend/src/database/migrations/039_create_shop.sql
Normal file
84
backend/src/database/migrations/039_create_shop.sql
Normal file
@@ -0,0 +1,84 @@
|
||||
-- Migration 039: Internal Shop system
|
||||
-- Tables for catalog items, member requests, request line items, and order linking.
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 1. Shop Artikel (Catalog Items)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shop_artikel (
|
||||
id SERIAL PRIMARY KEY,
|
||||
bezeichnung TEXT NOT NULL,
|
||||
beschreibung TEXT,
|
||||
kategorie TEXT,
|
||||
bild_pfad TEXT,
|
||||
geschaetzter_preis NUMERIC(10,2),
|
||||
aktiv BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
erstellt_von UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
erstellt_am TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
aktualisiert_am TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_shop_artikel_kategorie ON shop_artikel(kategorie);
|
||||
CREATE INDEX IF NOT EXISTS idx_shop_artikel_aktiv ON shop_artikel(aktiv);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 2. Shop Anfragen (Member Requests)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shop_anfragen (
|
||||
id SERIAL PRIMARY KEY,
|
||||
anfrager_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
status TEXT NOT NULL DEFAULT 'offen'
|
||||
CHECK (status IN ('offen','genehmigt','abgelehnt','bestellt','erledigt')),
|
||||
notizen TEXT,
|
||||
admin_notizen TEXT,
|
||||
bearbeitet_von UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
erstellt_am TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
aktualisiert_am TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_shop_anfragen_anfrager ON shop_anfragen(anfrager_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_shop_anfragen_status ON shop_anfragen(status);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 3. Shop Anfrage Positionen (Request Line Items)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shop_anfrage_positionen (
|
||||
id SERIAL PRIMARY KEY,
|
||||
anfrage_id INT NOT NULL REFERENCES shop_anfragen(id) ON DELETE CASCADE,
|
||||
artikel_id INT REFERENCES shop_artikel(id) ON DELETE SET NULL,
|
||||
bezeichnung TEXT NOT NULL,
|
||||
menge NUMERIC NOT NULL DEFAULT 1,
|
||||
notizen TEXT,
|
||||
erstellt_am TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_shop_anfrage_positionen_anfrage ON shop_anfrage_positionen(anfrage_id);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 4. Shop Anfrage ↔ Bestellung Link
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shop_anfrage_bestellung (
|
||||
anfrage_id INT NOT NULL REFERENCES shop_anfragen(id) ON DELETE CASCADE,
|
||||
bestellung_id INT NOT NULL REFERENCES bestellungen(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (anfrage_id, bestellung_id)
|
||||
);
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 5. Auto-update triggers
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'trg_shop_artikel_aktualisiert') THEN
|
||||
CREATE TRIGGER trg_shop_artikel_aktualisiert BEFORE UPDATE ON shop_artikel
|
||||
FOR EACH ROW EXECUTE FUNCTION update_aktualisiert_am();
|
||||
END IF;
|
||||
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'trg_shop_anfragen_aktualisiert') THEN
|
||||
CREATE TRIGGER trg_shop_anfragen_aktualisiert BEFORE UPDATE ON shop_anfragen
|
||||
FOR EACH ROW EXECUTE FUNCTION update_aktualisiert_am();
|
||||
END IF;
|
||||
END $$;
|
||||
158
backend/src/database/migrations/040_update_permissions.sql
Normal file
158
backend/src/database/migrations/040_update_permissions.sql
Normal file
@@ -0,0 +1,158 @@
|
||||
-- Migration 040: Permission updates
|
||||
-- 1. Add bestellungen + shop feature groups and their permissions
|
||||
-- 2. Simplify calendar permissions from 13 → 4
|
||||
-- 3. Migrate existing group_permissions to new calendar scheme
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 1. New feature groups
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
INSERT INTO feature_groups (id, label, sort_order) VALUES
|
||||
('bestellungen', 'Bestellungen', 11),
|
||||
('shop', 'Shop', 12)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 2. Bestellungen permissions
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
INSERT INTO permissions (id, feature_group_id, label, description, sort_order) VALUES
|
||||
('bestellungen:view', 'bestellungen', 'Ansehen', 'Bestellungen einsehen', 1),
|
||||
('bestellungen:create', 'bestellungen', 'Erstellen/Bearbeiten', 'Bestellungen erstellen und bearbeiten', 2),
|
||||
('bestellungen:delete', 'bestellungen', 'Löschen', 'Bestellungen löschen', 3),
|
||||
('bestellungen:manage_vendors', 'bestellungen', 'Lieferanten verwalten','Lieferanten-Datenbank verwalten', 4),
|
||||
('bestellungen:export', 'bestellungen', 'PDF Export', 'Bestellungen als PDF exportieren', 5),
|
||||
('bestellungen:manage_reminders', 'bestellungen', 'Erinnerungen', 'Erinnerungen für Bestellungen verwalten', 6),
|
||||
('bestellungen:widget', 'bestellungen', 'Widget', 'Dashboard-Widget für Bestellungen', 7)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 3. Shop permissions
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
INSERT INTO permissions (id, feature_group_id, label, description, sort_order) VALUES
|
||||
('shop:view', 'shop', 'Katalog ansehen', 'Shop-Katalog einsehen', 1),
|
||||
('shop:create_request', 'shop', 'Anfrage stellen', 'Bestellanfragen an Admin stellen', 2),
|
||||
('shop:manage_catalog', 'shop', 'Katalog verwalten', 'Artikel im Shop-Katalog verwalten', 3),
|
||||
('shop:approve_requests', 'shop', 'Anfragen genehmigen', 'Bestellanfragen genehmigen oder ablehnen', 4),
|
||||
('shop:link_orders', 'shop', 'Mit Bestellung verknüpfen', 'Anfragen mit Lieferantenbestellungen verknüpfen', 5),
|
||||
('shop:widget', 'shop', 'Widget', 'Dashboard-Widget für Shop-Anfragen', 6)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 4. Calendar permission simplification (13 → 4)
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- New scheme:
|
||||
-- kalender:view — see events + widgets
|
||||
-- kalender:create — create/edit/cancel events, mark attendance, manage categories, view reports
|
||||
-- kalender:view_bookings — see bookings + booking widgets
|
||||
-- kalender:manage_bookings — create/edit/cancel/delete bookings
|
||||
|
||||
-- 4a. Collect which groups had which old permissions, then map to new ones.
|
||||
-- We use a temp table so we don't lose data during the transition.
|
||||
|
||||
CREATE TEMP TABLE _cal_migration AS
|
||||
SELECT DISTINCT authentik_group,
|
||||
CASE
|
||||
-- Any group that had kalender:create OR kalender:cancel OR kalender:manage_categories
|
||||
-- OR kalender:view_reports OR kalender:mark_attendance → gets kalender:create
|
||||
WHEN permission_id IN ('kalender:create','kalender:cancel','kalender:manage_categories',
|
||||
'kalender:view_reports','kalender:mark_attendance')
|
||||
THEN 'kalender:create'
|
||||
-- Widget permissions → kalender:view (they already have it if they had widget perms)
|
||||
WHEN permission_id IN ('kalender:widget_events','kalender:widget_quick_add')
|
||||
THEN 'kalender:view'
|
||||
-- Booking-related view widgets → kalender:view_bookings
|
||||
WHEN permission_id IN ('kalender:widget_bookings')
|
||||
THEN 'kalender:view_bookings'
|
||||
-- All booking write ops → kalender:manage_bookings
|
||||
WHEN permission_id IN ('kalender:create_bookings','kalender:edit_bookings',
|
||||
'kalender:cancel_own_bookings','kalender:delete_bookings')
|
||||
THEN 'kalender:manage_bookings'
|
||||
ELSE permission_id
|
||||
END AS new_perm
|
||||
FROM group_permissions
|
||||
WHERE permission_id LIKE 'kalender:%';
|
||||
|
||||
-- 4b. Delete old calendar permissions from group_permissions
|
||||
DELETE FROM group_permissions WHERE permission_id LIKE 'kalender:%';
|
||||
|
||||
-- 4c. Delete old calendar permission definitions
|
||||
DELETE FROM permissions WHERE id LIKE 'kalender:%';
|
||||
|
||||
-- 4d. Insert new calendar permissions
|
||||
INSERT INTO permissions (id, feature_group_id, label, description, sort_order) VALUES
|
||||
('kalender:view', 'kalender', 'Termine ansehen', 'Kalender-Termine und Widgets einsehen', 1),
|
||||
('kalender:create', 'kalender', 'Termine verwalten', 'Termine erstellen/bearbeiten/absagen, Kategorien, Berichte', 2),
|
||||
('kalender:view_bookings', 'kalender', 'Buchungen ansehen', 'Fahrzeugbuchungen und Buchungs-Widget einsehen', 3),
|
||||
('kalender:manage_bookings', 'kalender', 'Buchungen verwalten', 'Buchungen erstellen/bearbeiten/stornieren/löschen', 4)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- 4e. Re-insert migrated grants (only valid new permissions)
|
||||
INSERT INTO group_permissions (authentik_group, permission_id)
|
||||
SELECT DISTINCT authentik_group, new_perm
|
||||
FROM _cal_migration
|
||||
WHERE new_perm IN ('kalender:view','kalender:create','kalender:view_bookings','kalender:manage_bookings')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- Also ensure everyone who had any calendar perm gets kalender:view
|
||||
INSERT INTO group_permissions (authentik_group, permission_id)
|
||||
SELECT DISTINCT authentik_group, 'kalender:view'
|
||||
FROM _cal_migration
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- And everyone who had any booking perm gets kalender:view_bookings
|
||||
INSERT INTO group_permissions (authentik_group, permission_id)
|
||||
SELECT DISTINCT authentik_group, 'kalender:view_bookings'
|
||||
FROM _cal_migration
|
||||
WHERE new_perm = 'kalender:manage_bookings'
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
DROP TABLE _cal_migration;
|
||||
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- 5. Seed bestellungen + shop permissions for existing groups
|
||||
-- ═══════════════════════════════════════════════════════════════════════════
|
||||
-- kommando gets full access, other groups get view + shop request
|
||||
|
||||
INSERT INTO group_permissions (authentik_group, permission_id) VALUES
|
||||
-- Kommando: full bestellungen + shop
|
||||
('dashboard_kommando', 'bestellungen:view'),
|
||||
('dashboard_kommando', 'bestellungen:create'),
|
||||
('dashboard_kommando', 'bestellungen:delete'),
|
||||
('dashboard_kommando', 'bestellungen:manage_vendors'),
|
||||
('dashboard_kommando', 'bestellungen:export'),
|
||||
('dashboard_kommando', 'bestellungen:manage_reminders'),
|
||||
('dashboard_kommando', 'bestellungen:widget'),
|
||||
('dashboard_kommando', 'shop:view'),
|
||||
('dashboard_kommando', 'shop:create_request'),
|
||||
('dashboard_kommando', 'shop:manage_catalog'),
|
||||
('dashboard_kommando', 'shop:approve_requests'),
|
||||
('dashboard_kommando', 'shop:link_orders'),
|
||||
('dashboard_kommando', 'shop:widget'),
|
||||
-- Fahrmeister: view orders + shop request
|
||||
('dashboard_fahrmeister', 'bestellungen:view'),
|
||||
('dashboard_fahrmeister', 'bestellungen:widget'),
|
||||
('dashboard_fahrmeister', 'shop:view'),
|
||||
('dashboard_fahrmeister', 'shop:create_request'),
|
||||
-- Zeugmeister: view orders + shop request
|
||||
('dashboard_zeugmeister', 'bestellungen:view'),
|
||||
('dashboard_zeugmeister', 'bestellungen:widget'),
|
||||
('dashboard_zeugmeister', 'shop:view'),
|
||||
('dashboard_zeugmeister', 'shop:create_request'),
|
||||
-- Chargen: view orders + shop request
|
||||
('dashboard_chargen', 'bestellungen:view'),
|
||||
('dashboard_chargen', 'bestellungen:widget'),
|
||||
('dashboard_chargen', 'shop:view'),
|
||||
('dashboard_chargen', 'shop:create_request'),
|
||||
-- Moderator: view orders + shop request
|
||||
('dashboard_moderator', 'bestellungen:view'),
|
||||
('dashboard_moderator', 'shop:view'),
|
||||
('dashboard_moderator', 'shop:create_request'),
|
||||
-- Atemschutz: shop request only
|
||||
('dashboard_atemschutz', 'shop:view'),
|
||||
('dashboard_atemschutz', 'shop:create_request'),
|
||||
-- Mitglied: shop request only
|
||||
('dashboard_mitglied', 'shop:view'),
|
||||
('dashboard_mitglied', 'shop:create_request')
|
||||
ON CONFLICT DO NOTHING;
|
||||
75
backend/src/jobs/reminder.job.ts
Normal file
75
backend/src/jobs/reminder.job.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import pool from '../config/database';
|
||||
import notificationService from '../services/notification.service';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
const INTERVAL_MS = 15 * 60 * 1000; // 15 minutes
|
||||
let jobInterval: ReturnType<typeof setInterval> | null = null;
|
||||
let isRunning = false;
|
||||
|
||||
async function runReminderCheck(): Promise<void> {
|
||||
if (isRunning) {
|
||||
logger.warn('ReminderJob: previous run still in progress — skipping');
|
||||
return;
|
||||
}
|
||||
isRunning = true;
|
||||
try {
|
||||
// Find due reminders that haven't been processed
|
||||
const result = await pool.query(`
|
||||
SELECT e.id, e.bestellung_id, e.nachricht, e.erstellt_von,
|
||||
b.bezeichnung AS bestellung_bezeichnung, b.besteller_id
|
||||
FROM bestellung_erinnerungen e
|
||||
JOIN bestellungen b ON b.id = e.bestellung_id
|
||||
WHERE e.faellig_am <= NOW()
|
||||
AND e.erledigt = FALSE
|
||||
`);
|
||||
|
||||
for (const row of result.rows) {
|
||||
// Notify the order handler (besteller_id) or the creator
|
||||
const targetUserId = row.besteller_id || row.erstellt_von;
|
||||
if (!targetUserId) continue;
|
||||
|
||||
await notificationService.createNotification({
|
||||
user_id: targetUserId,
|
||||
typ: 'bestellung_erinnerung',
|
||||
titel: 'Bestellungs-Erinnerung',
|
||||
nachricht: row.nachricht || `Erinnerung für Bestellung "${row.bestellung_bezeichnung}"`,
|
||||
schwere: 'info',
|
||||
link: `/bestellungen/${row.bestellung_id}`,
|
||||
quell_id: `bestellung-erinnerung-${row.id}`,
|
||||
quell_typ: 'bestellung_erinnerung',
|
||||
});
|
||||
|
||||
// Mark as done
|
||||
await pool.query('UPDATE bestellung_erinnerungen SET erledigt = TRUE WHERE id = $1', [row.id]);
|
||||
}
|
||||
|
||||
if (result.rows.length > 0) {
|
||||
logger.info(`ReminderJob: processed ${result.rows.length} reminders`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('ReminderJob: unexpected error', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
} finally {
|
||||
isRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
export function startReminderJob(): void {
|
||||
if (jobInterval !== null) {
|
||||
logger.warn('Reminder job already running — skipping duplicate start');
|
||||
return;
|
||||
}
|
||||
// Run once after short delay, then repeat
|
||||
setTimeout(() => runReminderCheck(), 45 * 1000);
|
||||
jobInterval = setInterval(() => runReminderCheck(), INTERVAL_MS);
|
||||
logger.info('Reminder job scheduled (every 15 minutes)');
|
||||
}
|
||||
|
||||
export function stopReminderJob(): void {
|
||||
if (jobInterval !== null) {
|
||||
clearInterval(jobInterval);
|
||||
jobInterval = null;
|
||||
}
|
||||
logger.info('Reminder job stopped');
|
||||
}
|
||||
52
backend/src/middleware/upload.ts
Normal file
52
backend/src/middleware/upload.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
const UPLOAD_DIR = path.resolve(__dirname, '../../../uploads/bestellungen');
|
||||
const THUMBNAIL_DIR = path.resolve(__dirname, '../../../uploads/bestellungen/thumbnails');
|
||||
|
||||
// Ensure directories exist
|
||||
[UPLOAD_DIR, THUMBNAIL_DIR].forEach(dir => {
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
logger.info(`Created upload directory: ${dir}`);
|
||||
}
|
||||
});
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination(_req: any, _file: any, cb: any) {
|
||||
cb(null, UPLOAD_DIR);
|
||||
},
|
||||
filename(_req: any, file: any, cb: any) {
|
||||
const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
|
||||
const ext = path.extname(file.originalname);
|
||||
cb(null, `${uniqueSuffix}${ext}`);
|
||||
},
|
||||
});
|
||||
|
||||
const ALLOWED_TYPES = [
|
||||
'image/jpeg', 'image/png', 'image/gif', 'image/webp',
|
||||
'application/pdf',
|
||||
'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'text/plain', 'text/csv',
|
||||
];
|
||||
|
||||
const multerOptions: any = {
|
||||
storage,
|
||||
fileFilter(_req: any, file: any, cb: any) {
|
||||
if (ALLOWED_TYPES.includes(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error(`Dateityp ${file.mimetype} ist nicht erlaubt.`));
|
||||
}
|
||||
},
|
||||
limits: { fileSize: 20 * 1024 * 1024 }, // 20 MB
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export const uploadBestellung: any = multer(multerOptions);
|
||||
|
||||
export { UPLOAD_DIR, THUMBNAIL_DIR };
|
||||
189
backend/src/routes/bestellung.routes.ts
Normal file
189
backend/src/routes/bestellung.routes.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
import { Router } from 'express';
|
||||
import bestellungController from '../controllers/bestellung.controller';
|
||||
import { authenticate } from '../middleware/auth.middleware';
|
||||
import { requirePermission } from '../middleware/rbac.middleware';
|
||||
import { uploadBestellung } from '../middleware/upload';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vendors (Lieferanten)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get(
|
||||
'/vendors',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:view'),
|
||||
bestellungController.listVendors.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/vendors',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:manage_vendors'),
|
||||
bestellungController.createVendor.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.patch(
|
||||
'/vendors/:id',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:manage_vendors'),
|
||||
bestellungController.updateVendor.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/vendors/:id',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:manage_vendors'),
|
||||
bestellungController.deleteVendor.bind(bestellungController)
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Orders (Bestellungen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get(
|
||||
'/',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:view'),
|
||||
bestellungController.listOrders.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:create'),
|
||||
bestellungController.createOrder.bind(bestellungController)
|
||||
);
|
||||
|
||||
// Export must come before /:id to avoid param capture
|
||||
router.get(
|
||||
'/export/:id',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:export'),
|
||||
bestellungController.exportOrder.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/:id',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:view'),
|
||||
bestellungController.getOrder.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.patch(
|
||||
'/:id',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:create'),
|
||||
bestellungController.updateOrder.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/:id',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:delete'),
|
||||
bestellungController.deleteOrder.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.patch(
|
||||
'/:id/status',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:create'),
|
||||
bestellungController.updateStatus.bind(bestellungController)
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Line Items (Bestellpositionen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post(
|
||||
'/:id/items',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:create'),
|
||||
bestellungController.addLineItem.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.patch(
|
||||
'/items/:itemId',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:create'),
|
||||
bestellungController.updateLineItem.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/items/:itemId',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:delete'),
|
||||
bestellungController.deleteLineItem.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.patch(
|
||||
'/items/:itemId/received',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:create'),
|
||||
bestellungController.updateReceivedQuantity.bind(bestellungController)
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Files (Bestellung Dateien)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post(
|
||||
'/:id/files',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:create'),
|
||||
uploadBestellung.single('datei'),
|
||||
bestellungController.uploadFile.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/files/:fileId',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:delete'),
|
||||
bestellungController.deleteFile.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/:id/files',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:view'),
|
||||
bestellungController.listFiles.bind(bestellungController)
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reminders (Erinnerungen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post(
|
||||
'/:id/reminders',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:manage_reminders'),
|
||||
bestellungController.addReminder.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.patch(
|
||||
'/reminders/:remId',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:manage_reminders'),
|
||||
bestellungController.markReminderDone.bind(bestellungController)
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/reminders/:remId',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:manage_reminders'),
|
||||
bestellungController.deleteReminder.bind(bestellungController)
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// History & Export
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get(
|
||||
'/:id/history',
|
||||
authenticate,
|
||||
requirePermission('bestellungen:view'),
|
||||
bestellungController.getHistory.bind(bestellungController)
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -18,15 +18,15 @@ router.get('/calendar-token', authenticate, bookingController.getCalendarToken.b
|
||||
|
||||
// ── Write operations ──────────────────────────────────────────────────────────
|
||||
|
||||
router.post('/', authenticate, bookingController.create.bind(bookingController));
|
||||
router.patch('/:id', authenticate, requirePermission('kalender:edit_bookings'), bookingController.update.bind(bookingController));
|
||||
router.post('/', authenticate, requirePermission('kalender:manage_bookings'), bookingController.create.bind(bookingController));
|
||||
router.patch('/:id', authenticate, requirePermission('kalender:manage_bookings'), bookingController.update.bind(bookingController));
|
||||
|
||||
// Soft-cancel (sets abgesagt=TRUE) — creator or bookings:write
|
||||
router.delete('/:id', authenticate, bookingController.cancel.bind(bookingController));
|
||||
router.patch('/:id/cancel', authenticate, bookingController.cancel.bind(bookingController));
|
||||
|
||||
// Hard-delete (admin only)
|
||||
router.delete('/:id/force', authenticate, requirePermission('kalender:delete_bookings'), bookingController.hardDelete.bind(bookingController));
|
||||
router.delete('/:id/force', authenticate, requirePermission('kalender:manage_bookings'), bookingController.hardDelete.bind(bookingController));
|
||||
|
||||
// ── Single booking read — after specific routes to avoid path conflicts ───────
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Router } from 'express';
|
||||
import bookstackController from '../controllers/bookstack.controller';
|
||||
import { authenticate } from '../middleware/auth.middleware';
|
||||
import { requirePermission } from '../middleware/rbac.middleware';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/recent', authenticate, bookstackController.getRecent.bind(bookstackController));
|
||||
router.get('/search', authenticate, bookstackController.search.bind(bookstackController));
|
||||
router.get('/pages/:id', authenticate, bookstackController.getPage.bind(bookstackController));
|
||||
router.get('/recent', authenticate, requirePermission('wissen:view'), bookstackController.getRecent.bind(bookstackController));
|
||||
router.get('/search', authenticate, requirePermission('wissen:view'), bookstackController.search.bind(bookstackController));
|
||||
router.get('/pages/:id', authenticate, requirePermission('wissen:view'), bookstackController.getPage.bind(bookstackController));
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -22,7 +22,7 @@ router.get('/kategorien', authenticate, eventsController.listKategorien.bind(eve
|
||||
router.post(
|
||||
'/kategorien',
|
||||
authenticate,
|
||||
requirePermission('kalender:manage_categories'),
|
||||
requirePermission('kalender:create'),
|
||||
eventsController.createKategorie.bind(eventsController)
|
||||
);
|
||||
|
||||
@@ -33,7 +33,7 @@ router.post(
|
||||
router.patch(
|
||||
'/kategorien/:id',
|
||||
authenticate,
|
||||
requirePermission('kalender:manage_categories'),
|
||||
requirePermission('kalender:create'),
|
||||
eventsController.updateKategorie.bind(eventsController)
|
||||
);
|
||||
|
||||
@@ -44,7 +44,7 @@ router.patch(
|
||||
router.delete(
|
||||
'/kategorien/:id',
|
||||
authenticate,
|
||||
requirePermission('kalender:manage_categories'),
|
||||
requirePermission('kalender:create'),
|
||||
eventsController.deleteKategorie.bind(eventsController)
|
||||
);
|
||||
|
||||
|
||||
38
backend/src/routes/shop.routes.ts
Normal file
38
backend/src/routes/shop.routes.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Router } from 'express';
|
||||
import shopController from '../controllers/shop.controller';
|
||||
import { authenticate } from '../middleware/auth.middleware';
|
||||
import { requirePermission } from '../middleware/rbac.middleware';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Catalog Items
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/items', authenticate, requirePermission('shop:view'), shopController.getItems.bind(shopController));
|
||||
router.get('/items/:id', authenticate, requirePermission('shop:view'), shopController.getItemById.bind(shopController));
|
||||
router.post('/items', authenticate, requirePermission('shop:manage_catalog'), shopController.createItem.bind(shopController));
|
||||
router.patch('/items/:id', authenticate, requirePermission('shop:manage_catalog'), shopController.updateItem.bind(shopController));
|
||||
router.delete('/items/:id', authenticate, requirePermission('shop:manage_catalog'), shopController.deleteItem.bind(shopController));
|
||||
|
||||
router.get('/categories', authenticate, requirePermission('shop:view'), shopController.getCategories.bind(shopController));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Requests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/requests', authenticate, requirePermission('shop:approve_requests'), shopController.getRequests.bind(shopController));
|
||||
router.get('/requests/my', authenticate, shopController.getMyRequests.bind(shopController));
|
||||
router.get('/requests/:id', authenticate, shopController.getRequestById.bind(shopController));
|
||||
router.post('/requests', authenticate, requirePermission('shop:create_request'), shopController.createRequest.bind(shopController));
|
||||
router.patch('/requests/:id/status', authenticate, requirePermission('shop:approve_requests'), shopController.updateRequestStatus.bind(shopController));
|
||||
router.delete('/requests/:id', authenticate, requirePermission('shop:approve_requests'), shopController.deleteRequest.bind(shopController));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Linking requests to orders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/requests/:id/link', authenticate, requirePermission('shop:link_orders'), shopController.linkToOrder.bind(shopController));
|
||||
router.delete('/requests/:id/link/:bestellungId', authenticate, requirePermission('shop:link_orders'), shopController.unlinkFromOrder.bind(shopController));
|
||||
|
||||
export default router;
|
||||
@@ -1,12 +1,13 @@
|
||||
import { Router } from 'express';
|
||||
import vikunjaController from '../controllers/vikunja.controller';
|
||||
import { authenticate } from '../middleware/auth.middleware';
|
||||
import { requirePermission } from '../middleware/rbac.middleware';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/tasks', authenticate, vikunjaController.getMyTasks.bind(vikunjaController));
|
||||
router.get('/tasks', authenticate, requirePermission('vikunja:widget_tasks'), vikunjaController.getMyTasks.bind(vikunjaController));
|
||||
router.get('/overdue', authenticate, vikunjaController.getOverdueTasks.bind(vikunjaController));
|
||||
router.get('/projects', authenticate, vikunjaController.getProjects.bind(vikunjaController));
|
||||
router.post('/tasks', authenticate, vikunjaController.createTask.bind(vikunjaController));
|
||||
router.get('/projects', authenticate, requirePermission('vikunja:create_tasks'), vikunjaController.getProjects.bind(vikunjaController));
|
||||
router.post('/tasks', authenticate, requirePermission('vikunja:create_tasks'), vikunjaController.createTask.bind(vikunjaController));
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -4,6 +4,7 @@ import logger from './utils/logger';
|
||||
import { testConnection, closePool, runMigrations } from './config/database';
|
||||
import { startAuditCleanupJob, stopAuditCleanupJob } from './jobs/audit-cleanup.job';
|
||||
import { startNotificationJob, stopNotificationJob } from './jobs/notification-generation.job';
|
||||
import { startReminderJob, stopReminderJob } from './jobs/reminder.job';
|
||||
import { permissionService } from './services/permission.service';
|
||||
|
||||
const startServer = async (): Promise<void> => {
|
||||
@@ -28,6 +29,9 @@ const startServer = async (): Promise<void> => {
|
||||
// Start the notification generation job
|
||||
startNotificationJob();
|
||||
|
||||
// Start the order reminder job
|
||||
startReminderJob();
|
||||
|
||||
// Start the server
|
||||
const server = app.listen(environment.port, () => {
|
||||
logger.info('Server started successfully', {
|
||||
@@ -51,6 +55,7 @@ const startServer = async (): Promise<void> => {
|
||||
// Stop scheduled jobs first
|
||||
stopAuditCleanupJob();
|
||||
stopNotificationJob();
|
||||
stopReminderJob();
|
||||
|
||||
server.close(async () => {
|
||||
logger.info('HTTP server closed');
|
||||
|
||||
607
backend/src/services/bestellung.service.ts
Normal file
607
backend/src/services/bestellung.service.ts
Normal file
@@ -0,0 +1,607 @@
|
||||
// =============================================================================
|
||||
// Bestellung (Order) Service
|
||||
// =============================================================================
|
||||
|
||||
import pool from '../config/database';
|
||||
import logger from '../utils/logger';
|
||||
import fs from 'fs';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vendors (Lieferanten)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function getVendors() {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT * FROM lieferanten ORDER BY name`
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getVendors failed', { error });
|
||||
throw new Error('Lieferanten konnten nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function getVendorById(id: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT * FROM lieferanten WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getVendorById failed', { error, id });
|
||||
throw new Error('Lieferant konnte nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function createVendor(data: { name: string; kontakt_person?: string; email?: string; telefon?: string; adresse?: string; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO lieferanten (name, kontakt_person, email, telefon, adresse, notizen, erstellt_von)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING *`,
|
||||
[data.name, data.kontakt_person || null, data.email || null, data.telefon || null, data.adresse || null, data.notizen || null, userId]
|
||||
);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.createVendor failed', { error });
|
||||
throw new Error('Lieferant konnte nicht erstellt werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateVendor(id: number, data: { name?: string; kontakt_person?: string; email?: string; telefon?: string; adresse?: string; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`UPDATE lieferanten
|
||||
SET name = COALESCE($1, name),
|
||||
kontakt_person = COALESCE($2, kontakt_person),
|
||||
email = COALESCE($3, email),
|
||||
telefon = COALESCE($4, telefon),
|
||||
adresse = COALESCE($5, adresse),
|
||||
notizen = COALESCE($6, notizen),
|
||||
aktualisiert_am = NOW()
|
||||
WHERE id = $7
|
||||
RETURNING *`,
|
||||
[data.name, data.kontakt_person, data.email, data.telefon, data.adresse, data.notizen, id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
await logAction(0, 'Lieferant aktualisiert', `Lieferant "${result.rows[0].name}" bearbeitet`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateVendor failed', { error, id });
|
||||
throw new Error('Lieferant konnte nicht aktualisiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteVendor(id: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`DELETE FROM lieferanten WHERE id = $1 RETURNING id`,
|
||||
[id]
|
||||
);
|
||||
return (result.rowCount ?? 0) > 0;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteVendor failed', { error, id });
|
||||
throw new Error('Lieferant konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Orders (Bestellungen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function getOrders(filters?: { status?: string; lieferant_id?: number; besteller_id?: string }) {
|
||||
try {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (filters?.status) {
|
||||
conditions.push(`b.status = $${paramIndex++}`);
|
||||
params.push(filters.status);
|
||||
}
|
||||
if (filters?.lieferant_id) {
|
||||
conditions.push(`b.lieferant_id = $${paramIndex++}`);
|
||||
params.push(filters.lieferant_id);
|
||||
}
|
||||
if (filters?.besteller_id) {
|
||||
conditions.push(`b.erstellt_von = $${paramIndex++}`);
|
||||
params.push(filters.besteller_id);
|
||||
}
|
||||
|
||||
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||
|
||||
const result = await pool.query(
|
||||
`SELECT b.*,
|
||||
l.name AS lieferant_name,
|
||||
u.display_name AS besteller_name,
|
||||
COALESCE(pos.total_cost, 0) AS total_cost,
|
||||
COALESCE(pos.items_count, 0) AS items_count
|
||||
FROM bestellungen b
|
||||
LEFT JOIN lieferanten l ON l.id = b.lieferant_id
|
||||
LEFT JOIN users u ON u.id = b.erstellt_von
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT SUM(einzelpreis * menge) AS total_cost,
|
||||
COUNT(*) AS items_count
|
||||
FROM bestellpositionen
|
||||
WHERE bestellung_id = b.id
|
||||
) pos ON true
|
||||
${whereClause}
|
||||
ORDER BY b.erstellt_am DESC`,
|
||||
params
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getOrders failed', { error });
|
||||
throw new Error('Bestellungen konnten nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrderById(id: number) {
|
||||
try {
|
||||
const orderResult = await pool.query(
|
||||
`SELECT b.*,
|
||||
l.name AS lieferant_name,
|
||||
u.display_name AS besteller_name
|
||||
FROM bestellungen b
|
||||
LEFT JOIN lieferanten l ON l.id = b.lieferant_id
|
||||
LEFT JOIN users u ON u.id = b.erstellt_von
|
||||
WHERE b.id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (orderResult.rows.length === 0) return null;
|
||||
|
||||
const [positionen, dateien, erinnerungen, historie] = await Promise.all([
|
||||
pool.query(`SELECT * FROM bestellpositionen WHERE bestellung_id = $1 ORDER BY id`, [id]),
|
||||
pool.query(`SELECT * FROM bestellung_dateien WHERE bestellung_id = $1 ORDER BY hochgeladen_am DESC`, [id]),
|
||||
pool.query(`SELECT * FROM bestellung_erinnerungen WHERE bestellung_id = $1 ORDER BY faellig_am`, [id]),
|
||||
pool.query(`SELECT h.*, u.display_name AS benutzer_name FROM bestellung_historie h LEFT JOIN users u ON u.id = h.benutzer_id WHERE h.bestellung_id = $1 ORDER BY h.erstellt_am DESC`, [id]),
|
||||
]);
|
||||
|
||||
return {
|
||||
...orderResult.rows[0],
|
||||
positionen: positionen.rows,
|
||||
dateien: dateien.rows,
|
||||
erinnerungen: erinnerungen.rows,
|
||||
historie: historie.rows,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getOrderById failed', { error, id });
|
||||
throw new Error('Bestellung konnte nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function createOrder(data: { titel: string; lieferant_id?: number; beschreibung?: string; prioritaet?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO bestellungen (titel, lieferant_id, beschreibung, prioritaet, erstellt_von)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *`,
|
||||
[data.titel, data.lieferant_id || null, data.beschreibung || null, data.prioritaet || 'normal', userId]
|
||||
);
|
||||
const order = result.rows[0];
|
||||
await logAction(order.id, 'Bestellung erstellt', `Bestellung "${data.titel}" erstellt`, userId);
|
||||
return order;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.createOrder failed', { error });
|
||||
throw new Error('Bestellung konnte nicht erstellt werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateOrder(id: number, data: { titel?: string; lieferant_id?: number; beschreibung?: string; prioritaet?: string; status?: string }, userId: string) {
|
||||
try {
|
||||
// Check current order for status change detection
|
||||
const current = await pool.query(`SELECT * FROM bestellungen WHERE id = $1`, [id]);
|
||||
if (current.rows.length === 0) return null;
|
||||
|
||||
const oldStatus = current.rows[0].status;
|
||||
const newStatus = data.status || oldStatus;
|
||||
|
||||
let bestellt_am = current.rows[0].bestellt_am;
|
||||
let abgeschlossen_am = current.rows[0].abgeschlossen_am;
|
||||
|
||||
if (newStatus !== oldStatus) {
|
||||
if (newStatus === 'bestellt' && !bestellt_am) {
|
||||
bestellt_am = new Date();
|
||||
}
|
||||
if (newStatus === 'abgeschlossen' && !abgeschlossen_am) {
|
||||
abgeschlossen_am = new Date();
|
||||
}
|
||||
}
|
||||
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellungen
|
||||
SET titel = COALESCE($1, titel),
|
||||
lieferant_id = COALESCE($2, lieferant_id),
|
||||
beschreibung = COALESCE($3, beschreibung),
|
||||
prioritaet = COALESCE($4, prioritaet),
|
||||
status = COALESCE($5, status),
|
||||
bestellt_am = $6,
|
||||
abgeschlossen_am = $7,
|
||||
aktualisiert_am = NOW()
|
||||
WHERE id = $8
|
||||
RETURNING *`,
|
||||
[data.titel, data.lieferant_id, data.beschreibung, data.prioritaet, data.status, bestellt_am, abgeschlossen_am, id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
const changes: string[] = [];
|
||||
if (data.titel) changes.push(`Titel geändert`);
|
||||
if (data.lieferant_id) changes.push(`Lieferant geändert`);
|
||||
if (data.status && data.status !== oldStatus) changes.push(`Status: ${oldStatus} → ${data.status}`);
|
||||
if (data.prioritaet) changes.push(`Priorität geändert`);
|
||||
|
||||
await logAction(id, 'Bestellung aktualisiert', changes.join(', ') || 'Bestellung bearbeitet', userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateOrder failed', { error, id });
|
||||
throw new Error('Bestellung konnte nicht aktualisiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteOrder(id: number, _userId: string) {
|
||||
try {
|
||||
// Get file paths before deleting
|
||||
const filesResult = await pool.query(
|
||||
`SELECT dateipfad FROM bestellung_dateien WHERE bestellung_id = $1`,
|
||||
[id]
|
||||
);
|
||||
const filePaths = filesResult.rows.map((r: { dateipfad: string }) => r.dateipfad);
|
||||
|
||||
const result = await pool.query(
|
||||
`DELETE FROM bestellungen WHERE id = $1 RETURNING id`,
|
||||
[id]
|
||||
);
|
||||
if ((result.rowCount ?? 0) === 0) return false;
|
||||
|
||||
// Remove files from disk
|
||||
for (const filePath of filePaths) {
|
||||
try {
|
||||
if (filePath && fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('Failed to delete file from disk', { filePath, error: err });
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteOrder failed', { error, id });
|
||||
throw new Error('Bestellung konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
const VALID_STATUS_TRANSITIONS: Record<string, string[]> = {
|
||||
entwurf: ['bestellt', 'storniert'],
|
||||
bestellt: ['teillieferung', 'vollstaendig', 'storniert'],
|
||||
teillieferung: ['vollstaendig', 'storniert'],
|
||||
vollstaendig: ['abgeschlossen'],
|
||||
abgeschlossen: [],
|
||||
storniert: ['entwurf'],
|
||||
};
|
||||
|
||||
async function updateOrderStatus(id: number, status: string, userId: string) {
|
||||
try {
|
||||
const current = await pool.query(`SELECT status FROM bestellungen WHERE id = $1`, [id]);
|
||||
if (current.rows.length === 0) return null;
|
||||
|
||||
const oldStatus = current.rows[0].status;
|
||||
const allowed = VALID_STATUS_TRANSITIONS[oldStatus] || [];
|
||||
if (!allowed.includes(status)) {
|
||||
throw new Error(`Ungültiger Statusübergang: ${oldStatus} → ${status}`);
|
||||
}
|
||||
|
||||
const updates: string[] = ['status = $1', 'aktualisiert_am = NOW()'];
|
||||
const params: unknown[] = [status];
|
||||
let paramIndex = 2;
|
||||
|
||||
if (status === 'bestellt') {
|
||||
updates.push(`bestellt_am = COALESCE(bestellt_am, NOW())`);
|
||||
}
|
||||
if (status === 'abgeschlossen') {
|
||||
updates.push(`abgeschlossen_am = COALESCE(abgeschlossen_am, NOW())`);
|
||||
}
|
||||
|
||||
params.push(id);
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellungen SET ${updates.join(', ')} WHERE id = $${paramIndex} RETURNING *`,
|
||||
params
|
||||
);
|
||||
|
||||
await logAction(id, 'Status geändert', `${oldStatus} → ${status}`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateOrderStatus failed', { error, id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Line Items (Bestellpositionen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function addLineItem(bestellungId: number, data: { artikel: string; menge: number; einheit?: string; einzelpreis?: number; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO bestellpositionen (bestellung_id, artikel, menge, einheit, einzelpreis, notizen)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING *`,
|
||||
[bestellungId, data.artikel, data.menge, data.einheit || 'Stück', data.einzelpreis || 0, data.notizen || null]
|
||||
);
|
||||
await logAction(bestellungId, 'Position hinzugefügt', `"${data.artikel}" x${data.menge}`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.addLineItem failed', { error, bestellungId });
|
||||
throw new Error('Position konnte nicht hinzugefügt werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateLineItem(id: number, data: { artikel?: string; menge?: number; einheit?: string; einzelpreis?: number; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellpositionen
|
||||
SET artikel = COALESCE($1, artikel),
|
||||
menge = COALESCE($2, menge),
|
||||
einheit = COALESCE($3, einheit),
|
||||
einzelpreis = COALESCE($4, einzelpreis),
|
||||
notizen = COALESCE($5, notizen)
|
||||
WHERE id = $6
|
||||
RETURNING *`,
|
||||
[data.artikel, data.menge, data.einheit, data.einzelpreis, data.notizen, id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
const item = result.rows[0];
|
||||
await logAction(item.bestellung_id, 'Position aktualisiert', `"${item.artikel}" bearbeitet`, userId);
|
||||
return item;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateLineItem failed', { error, id });
|
||||
throw new Error('Position konnte nicht aktualisiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLineItem(id: number, userId: string) {
|
||||
try {
|
||||
const item = await pool.query(`SELECT * FROM bestellpositionen WHERE id = $1`, [id]);
|
||||
if (item.rows.length === 0) return false;
|
||||
|
||||
await pool.query(`DELETE FROM bestellpositionen WHERE id = $1`, [id]);
|
||||
await logAction(item.rows[0].bestellung_id, 'Position entfernt', `"${item.rows[0].artikel}" entfernt`, userId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteLineItem failed', { error, id });
|
||||
throw new Error('Position konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateReceivedQuantity(id: number, menge: number, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellpositionen SET erhalten_menge = $1 WHERE id = $2 RETURNING *`,
|
||||
[menge, id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
const item = result.rows[0];
|
||||
await logAction(item.bestellung_id, 'Liefermenge aktualisiert', `"${item.artikel}": ${menge} von ${item.menge} erhalten`, userId);
|
||||
|
||||
// Check if all items for this order are fully received
|
||||
const allItems = await pool.query(
|
||||
`SELECT menge, erhalten_menge FROM bestellpositionen WHERE bestellung_id = $1`,
|
||||
[item.bestellung_id]
|
||||
);
|
||||
const allReceived = allItems.rows.every((r: { menge: number; erhalten_menge: number }) => r.erhalten_menge >= r.menge);
|
||||
const someReceived = allItems.rows.some((r: { menge: number; erhalten_menge: number }) => (r.erhalten_menge ?? 0) > 0);
|
||||
|
||||
// Auto-update order status if currently 'bestellt'
|
||||
const order = await pool.query(`SELECT status FROM bestellungen WHERE id = $1`, [item.bestellung_id]);
|
||||
if (order.rows.length > 0 && (order.rows[0].status === 'bestellt' || order.rows[0].status === 'teillieferung')) {
|
||||
if (allReceived) {
|
||||
await pool.query(
|
||||
`UPDATE bestellungen SET status = 'vollstaendig', aktualisiert_am = NOW() WHERE id = $1`,
|
||||
[item.bestellung_id]
|
||||
);
|
||||
await logAction(item.bestellung_id, 'Status geändert', 'Alle Positionen vollständig erhalten → vollstaendig', userId);
|
||||
} else if (someReceived && order.rows[0].status === 'bestellt') {
|
||||
await pool.query(
|
||||
`UPDATE bestellungen SET status = 'teillieferung', aktualisiert_am = NOW() WHERE id = $1`,
|
||||
[item.bestellung_id]
|
||||
);
|
||||
await logAction(item.bestellung_id, 'Status geändert', 'Teillieferung eingegangen → teillieferung', userId);
|
||||
}
|
||||
}
|
||||
|
||||
return item;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateReceivedQuantity failed', { error, id });
|
||||
throw new Error('Liefermenge konnte nicht aktualisiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Files (Bestellung Dateien)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function addFile(bestellungId: number, fileData: { dateiname: string; dateipfad: string; dateityp: string; dateigroesse: number }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO bestellung_dateien (bestellung_id, dateiname, dateipfad, dateityp, dateigroesse, hochgeladen_von)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING *`,
|
||||
[bestellungId, fileData.dateiname, fileData.dateipfad, fileData.dateityp, fileData.dateigroesse, userId]
|
||||
);
|
||||
await logAction(bestellungId, 'Datei hochgeladen', `"${fileData.dateiname}"`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.addFile failed', { error, bestellungId });
|
||||
throw new Error('Datei konnte nicht gespeichert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFile(id: number, userId: string) {
|
||||
try {
|
||||
const fileResult = await pool.query(
|
||||
`SELECT * FROM bestellung_dateien WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (fileResult.rows.length === 0) return null;
|
||||
|
||||
const file = fileResult.rows[0];
|
||||
await pool.query(`DELETE FROM bestellung_dateien WHERE id = $1`, [id]);
|
||||
await logAction(file.bestellung_id, 'Datei gelöscht', `"${file.dateiname}"`, userId);
|
||||
|
||||
return { dateipfad: file.dateipfad, dateiname: file.dateiname };
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteFile failed', { error, id });
|
||||
throw new Error('Datei konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function getFilesByOrder(bestellungId: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT * FROM bestellung_dateien WHERE bestellung_id = $1 ORDER BY hochgeladen_am DESC`,
|
||||
[bestellungId]
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getFilesByOrder failed', { error, bestellungId });
|
||||
throw new Error('Dateien konnten nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reminders (Bestellung Erinnerungen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function addReminder(bestellungId: number, data: { titel: string; faellig_am: string; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO bestellung_erinnerungen (bestellung_id, titel, faellig_am, notizen, erstellt_von)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *`,
|
||||
[bestellungId, data.titel, data.faellig_am, data.notizen || null, userId]
|
||||
);
|
||||
await logAction(bestellungId, 'Erinnerung erstellt', `"${data.titel}" fällig am ${data.faellig_am}`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.addReminder failed', { error, bestellungId });
|
||||
throw new Error('Erinnerung konnte nicht erstellt werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function markReminderDone(id: number, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellung_erinnerungen SET erledigt = TRUE WHERE id = $1 RETURNING *`,
|
||||
[id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
const reminder = result.rows[0];
|
||||
await logAction(reminder.bestellung_id, 'Erinnerung erledigt', `"${reminder.titel}"`, userId);
|
||||
return reminder;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.markReminderDone failed', { error, id });
|
||||
throw new Error('Erinnerung konnte nicht als erledigt markiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteReminder(id: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`DELETE FROM bestellung_erinnerungen WHERE id = $1 RETURNING id`,
|
||||
[id]
|
||||
);
|
||||
return (result.rowCount ?? 0) > 0;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteReminder failed', { error, id });
|
||||
throw new Error('Erinnerung konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function getDueReminders() {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT e.*, b.titel AS bestellung_titel, b.erstellt_von AS besteller_id
|
||||
FROM bestellung_erinnerungen e
|
||||
JOIN bestellungen b ON b.id = e.bestellung_id
|
||||
WHERE e.faellig_am <= NOW() AND e.erledigt = FALSE
|
||||
ORDER BY e.faellig_am`
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getDueReminders failed', { error });
|
||||
throw new Error('Fällige Erinnerungen konnten nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Audit History (Bestellung Historie)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function logAction(bestellungId: number, aktion: string, details: string, userId: string) {
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO bestellung_historie (bestellung_id, benutzer_id, aktion, details)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[bestellungId, userId, aktion, details]
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.logAction failed', { error, bestellungId, aktion });
|
||||
// Non-fatal — don't propagate
|
||||
}
|
||||
}
|
||||
|
||||
async function getHistory(bestellungId: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT h.*, u.display_name AS benutzer_name
|
||||
FROM bestellung_historie h
|
||||
LEFT JOIN users u ON u.id = h.benutzer_id
|
||||
WHERE h.bestellung_id = $1
|
||||
ORDER BY h.erstellt_am DESC`,
|
||||
[bestellungId]
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getHistory failed', { error, bestellungId });
|
||||
throw new Error('Historie konnte nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
// Vendors
|
||||
getVendors,
|
||||
getVendorById,
|
||||
createVendor,
|
||||
updateVendor,
|
||||
deleteVendor,
|
||||
// Orders
|
||||
getOrders,
|
||||
getOrderById,
|
||||
createOrder,
|
||||
updateOrder,
|
||||
deleteOrder,
|
||||
updateOrderStatus,
|
||||
// Line Items
|
||||
addLineItem,
|
||||
updateLineItem,
|
||||
deleteLineItem,
|
||||
updateReceivedQuantity,
|
||||
// Files
|
||||
addFile,
|
||||
deleteFile,
|
||||
getFilesByOrder,
|
||||
// Reminders
|
||||
addReminder,
|
||||
markReminderDone,
|
||||
deleteReminder,
|
||||
getDueReminders,
|
||||
// Audit
|
||||
logAction,
|
||||
getHistory,
|
||||
};
|
||||
323
backend/src/services/shop.service.ts
Normal file
323
backend/src/services/shop.service.ts
Normal file
@@ -0,0 +1,323 @@
|
||||
import pool from '../config/database';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Catalog Items (shop_artikel)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function getItems(filters?: { kategorie?: string; aktiv?: boolean }) {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (filters?.kategorie) {
|
||||
params.push(filters.kategorie);
|
||||
conditions.push(`kategorie = $${params.length}`);
|
||||
}
|
||||
if (filters?.aktiv !== undefined) {
|
||||
params.push(filters.aktiv);
|
||||
conditions.push(`aktiv = $${params.length}`);
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||
const result = await pool.query(
|
||||
`SELECT * FROM shop_artikel ${where} ORDER BY kategorie, bezeichnung`,
|
||||
params,
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async function getItemById(id: number) {
|
||||
const result = await pool.query('SELECT * FROM shop_artikel WHERE id = $1', [id]);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async function createItem(
|
||||
data: {
|
||||
bezeichnung: string;
|
||||
beschreibung?: string;
|
||||
kategorie?: string;
|
||||
geschaetzte_kosten?: number;
|
||||
url?: string;
|
||||
aktiv?: boolean;
|
||||
},
|
||||
userId: string,
|
||||
) {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO shop_artikel (bezeichnung, beschreibung, kategorie, geschaetzte_kosten, url, aktiv, erstellt_von)
|
||||
VALUES ($1, $2, $3, $4, $5, COALESCE($6, true), $7)
|
||||
RETURNING *`,
|
||||
[data.bezeichnung, data.beschreibung || null, data.kategorie || null, data.geschaetzte_kosten || null, data.url || null, data.aktiv ?? true, userId],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async function updateItem(
|
||||
id: number,
|
||||
data: {
|
||||
bezeichnung?: string;
|
||||
beschreibung?: string;
|
||||
kategorie?: string;
|
||||
geschaetzte_kosten?: number;
|
||||
url?: string;
|
||||
aktiv?: boolean;
|
||||
},
|
||||
userId: string,
|
||||
) {
|
||||
const fields: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (data.bezeichnung !== undefined) {
|
||||
params.push(data.bezeichnung);
|
||||
fields.push(`bezeichnung = $${params.length}`);
|
||||
}
|
||||
if (data.beschreibung !== undefined) {
|
||||
params.push(data.beschreibung);
|
||||
fields.push(`beschreibung = $${params.length}`);
|
||||
}
|
||||
if (data.kategorie !== undefined) {
|
||||
params.push(data.kategorie);
|
||||
fields.push(`kategorie = $${params.length}`);
|
||||
}
|
||||
if (data.geschaetzte_kosten !== undefined) {
|
||||
params.push(data.geschaetzte_kosten);
|
||||
fields.push(`geschaetzte_kosten = $${params.length}`);
|
||||
}
|
||||
if (data.url !== undefined) {
|
||||
params.push(data.url);
|
||||
fields.push(`url = $${params.length}`);
|
||||
}
|
||||
if (data.aktiv !== undefined) {
|
||||
params.push(data.aktiv);
|
||||
fields.push(`aktiv = $${params.length}`);
|
||||
}
|
||||
|
||||
if (fields.length === 0) {
|
||||
return getItemById(id);
|
||||
}
|
||||
|
||||
params.push(userId);
|
||||
fields.push(`aktualisiert_von = $${params.length}`);
|
||||
params.push(new Date());
|
||||
fields.push(`aktualisiert_am = $${params.length}`);
|
||||
|
||||
params.push(id);
|
||||
const result = await pool.query(
|
||||
`UPDATE shop_artikel SET ${fields.join(', ')} WHERE id = $${params.length} RETURNING *`,
|
||||
params,
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async function deleteItem(id: number) {
|
||||
await pool.query('DELETE FROM shop_artikel WHERE id = $1', [id]);
|
||||
}
|
||||
|
||||
async function getCategories() {
|
||||
const result = await pool.query(
|
||||
'SELECT DISTINCT kategorie FROM shop_artikel WHERE kategorie IS NOT NULL ORDER BY kategorie',
|
||||
);
|
||||
return result.rows.map((r: { kategorie: string }) => r.kategorie);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Requests (shop_anfragen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function getRequests(filters?: { status?: string; anfrager_id?: string }) {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (filters?.status) {
|
||||
params.push(filters.status);
|
||||
conditions.push(`a.status = $${params.length}`);
|
||||
}
|
||||
if (filters?.anfrager_id) {
|
||||
params.push(filters.anfrager_id);
|
||||
conditions.push(`a.anfrager_id = $${params.length}`);
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||
const result = await pool.query(
|
||||
`SELECT a.*,
|
||||
u.vorname || ' ' || u.nachname AS anfrager_name,
|
||||
u2.vorname || ' ' || u2.nachname AS bearbeitet_von_name,
|
||||
(SELECT COUNT(*)::int FROM shop_anfrage_positionen p WHERE p.anfrage_id = a.id) AS positionen_count
|
||||
FROM shop_anfragen a
|
||||
LEFT JOIN users u ON u.id = a.anfrager_id
|
||||
LEFT JOIN users u2 ON u2.id = a.bearbeitet_von
|
||||
${where}
|
||||
ORDER BY a.erstellt_am DESC`,
|
||||
params,
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async function getMyRequests(userId: string) {
|
||||
const result = await pool.query(
|
||||
`SELECT a.*,
|
||||
(SELECT COUNT(*)::int FROM shop_anfrage_positionen p WHERE p.anfrage_id = a.id) AS positionen_count
|
||||
FROM shop_anfragen a
|
||||
WHERE a.anfrager_id = $1
|
||||
ORDER BY a.erstellt_am DESC`,
|
||||
[userId],
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async function getRequestById(id: number) {
|
||||
const reqResult = await pool.query(
|
||||
`SELECT a.*,
|
||||
u.vorname || ' ' || u.nachname AS anfrager_name,
|
||||
u2.vorname || ' ' || u2.nachname AS bearbeitet_von_name
|
||||
FROM shop_anfragen a
|
||||
LEFT JOIN users u ON u.id = a.anfrager_id
|
||||
LEFT JOIN users u2 ON u2.id = a.bearbeitet_von
|
||||
WHERE a.id = $1`,
|
||||
[id],
|
||||
);
|
||||
if (reqResult.rows.length === 0) return null;
|
||||
|
||||
const positionen = await pool.query(
|
||||
`SELECT p.*, sa.bezeichnung AS artikel_bezeichnung, sa.kategorie AS artikel_kategorie
|
||||
FROM shop_anfrage_positionen p
|
||||
LEFT JOIN shop_artikel sa ON sa.id = p.artikel_id
|
||||
WHERE p.anfrage_id = $1
|
||||
ORDER BY p.id`,
|
||||
[id],
|
||||
);
|
||||
|
||||
const bestellungen = await pool.query(
|
||||
`SELECT b.*
|
||||
FROM shop_anfrage_bestellung ab
|
||||
JOIN bestellungen b ON b.id = ab.bestellung_id
|
||||
WHERE ab.anfrage_id = $1`,
|
||||
[id],
|
||||
);
|
||||
|
||||
return {
|
||||
...reqResult.rows[0],
|
||||
positionen: positionen.rows,
|
||||
bestellungen: bestellungen.rows,
|
||||
};
|
||||
}
|
||||
|
||||
async function createRequest(
|
||||
userId: string,
|
||||
items: { artikel_id?: number; bezeichnung: string; menge: number; notizen?: string }[],
|
||||
notizen?: string,
|
||||
) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
const anfrageResult = await client.query(
|
||||
`INSERT INTO shop_anfragen (anfrager_id, notizen)
|
||||
VALUES ($1, $2)
|
||||
RETURNING *`,
|
||||
[userId, notizen || null],
|
||||
);
|
||||
const anfrage = anfrageResult.rows[0];
|
||||
|
||||
for (const item of items) {
|
||||
let bezeichnung = item.bezeichnung;
|
||||
|
||||
// If artikel_id is provided, copy bezeichnung from catalog
|
||||
if (item.artikel_id) {
|
||||
const artikelResult = await client.query(
|
||||
'SELECT bezeichnung FROM shop_artikel WHERE id = $1',
|
||||
[item.artikel_id],
|
||||
);
|
||||
if (artikelResult.rows.length > 0) {
|
||||
bezeichnung = artikelResult.rows[0].bezeichnung;
|
||||
}
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`INSERT INTO shop_anfrage_positionen (anfrage_id, artikel_id, bezeichnung, menge, notizen)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
[anfrage.id, item.artikel_id || null, bezeichnung, item.menge, item.notizen || null],
|
||||
);
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
return getRequestById(anfrage.id);
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
logger.error('shopService.createRequest failed', { error });
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function updateRequestStatus(
|
||||
id: number,
|
||||
status: string,
|
||||
adminNotizen?: string,
|
||||
bearbeitetVon?: string,
|
||||
) {
|
||||
const result = await pool.query(
|
||||
`UPDATE shop_anfragen
|
||||
SET status = $1,
|
||||
admin_notizen = COALESCE($2, admin_notizen),
|
||||
bearbeitet_von = COALESCE($3, bearbeitet_von),
|
||||
bearbeitet_am = NOW()
|
||||
WHERE id = $4
|
||||
RETURNING *`,
|
||||
[status, adminNotizen || null, bearbeitetVon || null, id],
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async function deleteRequest(id: number) {
|
||||
await pool.query('DELETE FROM shop_anfragen WHERE id = $1', [id]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Linking (shop_anfrage_bestellung)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function linkToOrder(anfrageId: number, bestellungId: number) {
|
||||
await pool.query(
|
||||
`INSERT INTO shop_anfrage_bestellung (anfrage_id, bestellung_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT DO NOTHING`,
|
||||
[anfrageId, bestellungId],
|
||||
);
|
||||
}
|
||||
|
||||
async function unlinkFromOrder(anfrageId: number, bestellungId: number) {
|
||||
await pool.query(
|
||||
'DELETE FROM shop_anfrage_bestellung WHERE anfrage_id = $1 AND bestellung_id = $2',
|
||||
[anfrageId, bestellungId],
|
||||
);
|
||||
}
|
||||
|
||||
async function getLinkedOrders(anfrageId: number) {
|
||||
const result = await pool.query(
|
||||
`SELECT b.*
|
||||
FROM shop_anfrage_bestellung ab
|
||||
JOIN bestellungen b ON b.id = ab.bestellung_id
|
||||
WHERE ab.anfrage_id = $1`,
|
||||
[anfrageId],
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
export default {
|
||||
getItems,
|
||||
getItemById,
|
||||
createItem,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
getCategories,
|
||||
getRequests,
|
||||
getMyRequests,
|
||||
getRequestById,
|
||||
createRequest,
|
||||
updateRequestStatus,
|
||||
deleteRequest,
|
||||
linkToOrder,
|
||||
unlinkFromOrder,
|
||||
getLinkedOrders,
|
||||
};
|
||||
44
backend/src/services/upload.service.ts
Normal file
44
backend/src/services/upload.service.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import logger from '../utils/logger';
|
||||
import { THUMBNAIL_DIR } from '../middleware/upload';
|
||||
|
||||
let sharp: any = null;
|
||||
try {
|
||||
sharp = require('sharp');
|
||||
} catch {
|
||||
logger.warn('sharp not installed — thumbnail generation disabled');
|
||||
}
|
||||
|
||||
async function generateThumbnail(filePath: string, mimeType: string): Promise<string | null> {
|
||||
if (!sharp) return null;
|
||||
if (!mimeType.startsWith('image/')) return null;
|
||||
|
||||
try {
|
||||
const ext = path.extname(filePath);
|
||||
const baseName = path.basename(filePath, ext);
|
||||
const thumbPath = path.join(THUMBNAIL_DIR, `${baseName}_thumb.webp`);
|
||||
|
||||
await sharp(filePath)
|
||||
.resize(200, 200, { fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 70 })
|
||||
.toFile(thumbPath);
|
||||
|
||||
return thumbPath;
|
||||
} catch (error) {
|
||||
logger.error('Thumbnail generation failed', { filePath, error });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function deleteFile(filePath: string): void {
|
||||
try {
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('File deletion failed', { filePath, error });
|
||||
}
|
||||
}
|
||||
|
||||
export default { generateThumbnail, deleteFile };
|
||||
@@ -26,6 +26,9 @@ import UebungDetail from './pages/UebungDetail';
|
||||
import Veranstaltungen from './pages/Veranstaltungen';
|
||||
import VeranstaltungKategorien from './pages/VeranstaltungKategorien';
|
||||
import Wissen from './pages/Wissen';
|
||||
import Bestellungen from './pages/Bestellungen';
|
||||
import BestellungDetail from './pages/BestellungDetail';
|
||||
import Shop from './pages/Shop';
|
||||
import AdminDashboard from './pages/AdminDashboard';
|
||||
import AdminSettings from './pages/AdminSettings';
|
||||
import NotFound from './pages/NotFound';
|
||||
@@ -216,6 +219,30 @@ function App() {
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/bestellungen"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<Bestellungen />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/bestellungen/:id"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<BestellungDetail />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/shop"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<Shop />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
|
||||
167
frontend/src/components/admin/BestellungenTab.tsx
Normal file
167
frontend/src/components/admin/BestellungenTab.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Paper,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Chip,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
CircularProgress,
|
||||
} from '@mui/material';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { bestellungApi } from '../../services/bestellung';
|
||||
import { shopApi } from '../../services/shop';
|
||||
import { BESTELLUNG_STATUS_LABELS, BESTELLUNG_STATUS_COLORS } from '../../types/bestellung.types';
|
||||
import { SHOP_STATUS_LABELS, SHOP_STATUS_COLORS } from '../../types/shop.types';
|
||||
import type { BestellungStatus } from '../../types/bestellung.types';
|
||||
import type { ShopAnfrageStatus } from '../../types/shop.types';
|
||||
|
||||
function BestellungenTab() {
|
||||
const navigate = useNavigate();
|
||||
const [statusFilter, setStatusFilter] = useState<string>('');
|
||||
|
||||
const { data: orders, isLoading: ordersLoading } = useQuery({
|
||||
queryKey: ['admin-bestellungen', statusFilter],
|
||||
queryFn: () => bestellungApi.getOrders(statusFilter ? { status: statusFilter } : undefined),
|
||||
});
|
||||
|
||||
const { data: requests, isLoading: requestsLoading } = useQuery({
|
||||
queryKey: ['admin-shop-requests'],
|
||||
queryFn: () => shopApi.getRequests({ status: 'offen' }),
|
||||
});
|
||||
|
||||
const formatCurrency = (value?: number) =>
|
||||
value != null ? new Intl.NumberFormat('de-AT', { style: 'currency', currency: 'EUR' }).format(value) : '–';
|
||||
|
||||
return (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
|
||||
{/* Pending Shop Requests */}
|
||||
{(requests?.length ?? 0) > 0 && (
|
||||
<Paper sx={{ p: 2 }}>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Offene Shop-Anfragen ({requests?.length})
|
||||
</Typography>
|
||||
{requestsLoading ? (
|
||||
<CircularProgress size={24} />
|
||||
) : (
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>#</TableCell>
|
||||
<TableCell>Anfrager</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Erstellt am</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{(requests ?? []).map((req) => (
|
||||
<TableRow
|
||||
key={req.id}
|
||||
hover
|
||||
sx={{ cursor: 'pointer' }}
|
||||
onClick={() => navigate('/shop?tab=2')}
|
||||
>
|
||||
<TableCell>{req.id}</TableCell>
|
||||
<TableCell>{req.anfrager_name || '–'}</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={SHOP_STATUS_LABELS[req.status as ShopAnfrageStatus]}
|
||||
color={SHOP_STATUS_COLORS[req.status as ShopAnfrageStatus]}
|
||||
size="small"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>{new Date(req.erstellt_am).toLocaleDateString('de-AT')}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)}
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Orders Overview */}
|
||||
<Paper sx={{ p: 2 }}>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||
<Typography variant="h6">Bestellungen</Typography>
|
||||
<FormControl size="small" sx={{ minWidth: 180 }}>
|
||||
<InputLabel>Status</InputLabel>
|
||||
<Select
|
||||
value={statusFilter}
|
||||
label="Status"
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
>
|
||||
<MenuItem value="">Alle</MenuItem>
|
||||
{Object.entries(BESTELLUNG_STATUS_LABELS).map(([key, label]) => (
|
||||
<MenuItem key={key} value={key}>{label}</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
{ordersLoading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : (
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Bezeichnung</TableCell>
|
||||
<TableCell>Lieferant</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell align="right">Positionen</TableCell>
|
||||
<TableCell align="right">Gesamt</TableCell>
|
||||
<TableCell>Erstellt am</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{(orders ?? []).length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} align="center">
|
||||
<Typography variant="body2" color="text.secondary">Keine Bestellungen</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
(orders ?? []).map((order) => (
|
||||
<TableRow
|
||||
key={order.id}
|
||||
hover
|
||||
sx={{ cursor: 'pointer' }}
|
||||
onClick={() => navigate(`/bestellungen/${order.id}`)}
|
||||
>
|
||||
<TableCell>{order.bezeichnung}</TableCell>
|
||||
<TableCell>{order.lieferant_name || '–'}</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={BESTELLUNG_STATUS_LABELS[order.status as BestellungStatus]}
|
||||
color={BESTELLUNG_STATUS_COLORS[order.status as BestellungStatus]}
|
||||
size="small"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="right">{order.items_count ?? 0}</TableCell>
|
||||
<TableCell align="right">{formatCurrency(order.total_cost)}</TableCell>
|
||||
<TableCell>{new Date(order.erstellt_am).toLocaleDateString('de-AT')}</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)}
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default BestellungenTab;
|
||||
@@ -124,8 +124,6 @@ function NotificationBroadcastTab() {
|
||||
setTargetDienstgrad(typeof value === 'string' ? value.split(',') : value);
|
||||
};
|
||||
|
||||
const filtersActive = !alleBenutzer && (targetGroup.trim() || targetDienstgrad.length > 0);
|
||||
|
||||
const filterDescription = (() => {
|
||||
if (alleBenutzer) return 'alle aktiven Benutzer';
|
||||
const parts: string[] = [];
|
||||
|
||||
@@ -86,6 +86,38 @@ function buildReverseHierarchy(hierarchy: Record<string, string[]>): Record<stri
|
||||
return reverse;
|
||||
}
|
||||
|
||||
// ── Visual sub-groups for permission matrix ──
|
||||
// Maps feature_group → { subGroupLabel: actionSuffix[] }
|
||||
// Actions not listed get placed in a default group.
|
||||
|
||||
const PERMISSION_SUB_GROUPS: Record<string, Record<string, string[]>> = {
|
||||
kalender: {
|
||||
'Termine': ['view', 'create'],
|
||||
'Buchungen': ['view_bookings', 'manage_bookings'],
|
||||
},
|
||||
bestellungen: {
|
||||
'Bestellungen': ['view', 'create', 'delete', 'export'],
|
||||
'Lieferanten': ['manage_vendors'],
|
||||
'Erinnerungen': ['manage_reminders'],
|
||||
'Widget': ['widget'],
|
||||
},
|
||||
shop: {
|
||||
'Katalog': ['view', 'manage_catalog'],
|
||||
'Anfragen': ['create_request', 'approve_requests', 'link_orders'],
|
||||
'Widget': ['widget'],
|
||||
},
|
||||
};
|
||||
|
||||
function getSubGroupLabel(featureGroupId: string, permId: string): string | null {
|
||||
const subGroups = PERMISSION_SUB_GROUPS[featureGroupId];
|
||||
if (!subGroups) return null;
|
||||
const action = permId.includes(':') ? permId.split(':')[1] : permId;
|
||||
for (const [label, actions] of Object.entries(subGroups)) {
|
||||
if (actions.includes(action)) return label;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Component ──
|
||||
|
||||
function PermissionMatrixTab() {
|
||||
@@ -412,11 +444,29 @@ function PermissionMatrixTab() {
|
||||
<Collapse in={isExpanded} timeout="auto" unmountOnExit>
|
||||
<Table size="small">
|
||||
<TableBody>
|
||||
{fgPerms.map((perm: Permission) => {
|
||||
const depTooltip = getDepTooltip(perm.id);
|
||||
const tooltipText = [perm.description, depTooltip].filter(Boolean).join('\n');
|
||||
return (
|
||||
<TableRow key={perm.id} hover>
|
||||
{(() => {
|
||||
let lastSubGroup: string | null | undefined = undefined;
|
||||
return fgPerms.map((perm: Permission) => {
|
||||
const depTooltip = getDepTooltip(perm.id);
|
||||
const tooltipText = [perm.description, depTooltip].filter(Boolean).join('\n');
|
||||
const subGroup = getSubGroupLabel(fg.id, perm.id);
|
||||
const showSubGroupHeader = subGroup !== lastSubGroup && subGroup !== null;
|
||||
lastSubGroup = subGroup;
|
||||
return (
|
||||
<React.Fragment key={perm.id}>
|
||||
{showSubGroupHeader && (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={2 + nonAdminGroups.length}
|
||||
sx={{ pl: 5, py: 0.5, bgcolor: 'action.selected', position: 'sticky', left: 0, zIndex: 1 }}
|
||||
>
|
||||
<Typography variant="caption" sx={{ fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, color: 'text.secondary' }}>
|
||||
{subGroup}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
<TableRow hover>
|
||||
<TableCell sx={{ pl: 6, minWidth: 250, position: 'sticky', left: 0, zIndex: 1, bgcolor: 'background.paper' }}>
|
||||
<Tooltip title={tooltipText || ''} placement="right"><span>{perm.label}</span></Tooltip>
|
||||
</TableCell>
|
||||
@@ -441,8 +491,10 @@ function PermissionMatrixTab() {
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</React.Fragment>
|
||||
);
|
||||
});
|
||||
})()}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Collapse>
|
||||
|
||||
@@ -60,7 +60,7 @@ const ContentOverlay: React.FC<ContentOverlayProps> = ({ open, onClose, mode, co
|
||||
onClose={onClose}
|
||||
maxWidth="lg"
|
||||
fullWidth
|
||||
slotProps={{ paper: { sx: { bgcolor: mode === 'image' ? 'black' : 'background.paper', m: 1 } } }}
|
||||
PaperProps={{ sx: { bgcolor: mode === 'image' ? 'black' : 'background.paper', m: 1 } }}
|
||||
>
|
||||
<DialogContent sx={{ p: 0, position: 'relative', display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 200 }}>
|
||||
{mode === 'image' && (
|
||||
|
||||
109
frontend/src/components/dashboard/BestellungenWidget.tsx
Normal file
109
frontend/src/components/dashboard/BestellungenWidget.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import { Card, CardContent, Typography, Box, Chip, List, ListItem, ListItemText, Divider, Skeleton } from '@mui/material';
|
||||
import { LocalShipping } from '@mui/icons-material';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { bestellungApi } from '../../services/bestellung';
|
||||
import { BESTELLUNG_STATUS_LABELS, BESTELLUNG_STATUS_COLORS } from '../../types/bestellung.types';
|
||||
import type { BestellungStatus } from '../../types/bestellung.types';
|
||||
|
||||
function BestellungenWidget() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: orders, isLoading, isError } = useQuery({
|
||||
queryKey: ['bestellungen-widget'],
|
||||
queryFn: () => bestellungApi.getOrders(),
|
||||
refetchInterval: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const openOrders = (orders ?? []).filter(
|
||||
(o) => !['abgeschlossen'].includes(o.status)
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>Bestellungen</Typography>
|
||||
<Skeleton variant="rectangular" height={60} />
|
||||
<Skeleton variant="rectangular" height={60} sx={{ mt: 1 }} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>Bestellungen</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Bestellungen konnten nicht geladen werden.
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (openOrders.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>Bestellungen</Typography>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: 'text.secondary' }}>
|
||||
<LocalShipping fontSize="small" />
|
||||
<Typography variant="body2">Keine offenen Bestellungen</Typography>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
|
||||
<Typography variant="h6">Bestellungen</Typography>
|
||||
<Chip label={`${openOrders.length} offen`} size="small" color="primary" />
|
||||
</Box>
|
||||
<List dense disablePadding>
|
||||
{openOrders.slice(0, 5).map((order, idx) => (
|
||||
<Box key={order.id}>
|
||||
{idx > 0 && <Divider />}
|
||||
<ListItem
|
||||
disablePadding
|
||||
sx={{ cursor: 'pointer', py: 0.5, '&:hover': { bgcolor: 'action.hover' } }}
|
||||
onClick={() => navigate(`/bestellungen/${order.id}`)}
|
||||
>
|
||||
<ListItemText
|
||||
primary={order.bezeichnung}
|
||||
secondary={order.lieferant_name || 'Kein Lieferant'}
|
||||
primaryTypographyProps={{ variant: 'body2', noWrap: true }}
|
||||
secondaryTypographyProps={{ variant: 'caption' }}
|
||||
/>
|
||||
<Chip
|
||||
label={BESTELLUNG_STATUS_LABELS[order.status as BestellungStatus]}
|
||||
color={BESTELLUNG_STATUS_COLORS[order.status as BestellungStatus]}
|
||||
size="small"
|
||||
sx={{ ml: 1 }}
|
||||
/>
|
||||
</ListItem>
|
||||
</Box>
|
||||
))}
|
||||
</List>
|
||||
{openOrders.length > 5 && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="primary"
|
||||
sx={{ cursor: 'pointer', mt: 1, display: 'block' }}
|
||||
onClick={() => navigate('/bestellungen')}
|
||||
>
|
||||
Alle {openOrders.length} Bestellungen anzeigen
|
||||
</Typography>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default BestellungenWidget;
|
||||
106
frontend/src/components/dashboard/ShopWidget.tsx
Normal file
106
frontend/src/components/dashboard/ShopWidget.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import { Card, CardContent, Typography, Box, Chip, List, ListItem, ListItemText, Divider, Skeleton } from '@mui/material';
|
||||
import { Store } from '@mui/icons-material';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { shopApi } from '../../services/shop';
|
||||
import { SHOP_STATUS_LABELS, SHOP_STATUS_COLORS } from '../../types/shop.types';
|
||||
import type { ShopAnfrageStatus } from '../../types/shop.types';
|
||||
|
||||
function ShopWidget() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: requests, isLoading, isError } = useQuery({
|
||||
queryKey: ['shop-widget-requests'],
|
||||
queryFn: () => shopApi.getRequests({ status: 'offen' }),
|
||||
refetchInterval: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>Shop-Anfragen</Typography>
|
||||
<Skeleton variant="rectangular" height={60} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>Shop-Anfragen</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Anfragen konnten nicht geladen werden.
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const pendingCount = requests?.length ?? 0;
|
||||
|
||||
if (pendingCount === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>Shop-Anfragen</Typography>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: 'text.secondary' }}>
|
||||
<Store fontSize="small" />
|
||||
<Typography variant="body2">Keine offenen Anfragen</Typography>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
|
||||
<Typography variant="h6">Shop-Anfragen</Typography>
|
||||
<Chip label={`${pendingCount} offen`} size="small" color="warning" />
|
||||
</Box>
|
||||
<List dense disablePadding>
|
||||
{(requests ?? []).slice(0, 5).map((req, idx) => (
|
||||
<Box key={req.id}>
|
||||
{idx > 0 && <Divider />}
|
||||
<ListItem
|
||||
disablePadding
|
||||
sx={{ cursor: 'pointer', py: 0.5, '&:hover': { bgcolor: 'action.hover' } }}
|
||||
onClick={() => navigate('/shop?tab=2')}
|
||||
>
|
||||
<ListItemText
|
||||
primary={`Anfrage #${req.id}`}
|
||||
secondary={req.anfrager_name || 'Unbekannt'}
|
||||
primaryTypographyProps={{ variant: 'body2' }}
|
||||
secondaryTypographyProps={{ variant: 'caption' }}
|
||||
/>
|
||||
<Chip
|
||||
label={SHOP_STATUS_LABELS[req.status as ShopAnfrageStatus]}
|
||||
color={SHOP_STATUS_COLORS[req.status as ShopAnfrageStatus]}
|
||||
size="small"
|
||||
sx={{ ml: 1 }}
|
||||
/>
|
||||
</ListItem>
|
||||
</Box>
|
||||
))}
|
||||
</List>
|
||||
{pendingCount > 5 && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="primary"
|
||||
sx={{ cursor: 'pointer', mt: 1, display: 'block' }}
|
||||
onClick={() => navigate('/shop?tab=2')}
|
||||
>
|
||||
Alle {pendingCount} Anfragen anzeigen
|
||||
</Typography>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default ShopWidget;
|
||||
@@ -18,3 +18,5 @@ export { default as AnnouncementBanner } from './AnnouncementBanner';
|
||||
export { default as BannerWidget } from './BannerWidget';
|
||||
export { default as LinksWidget } from './LinksWidget';
|
||||
export { default as WidgetGroup } from './WidgetGroup';
|
||||
export { default as BestellungenWidget } from './BestellungenWidget';
|
||||
export { default as ShopWidget } from './ShopWidget';
|
||||
|
||||
@@ -25,6 +25,8 @@ import {
|
||||
Menu as MenuIcon,
|
||||
ExpandMore,
|
||||
ExpandLess,
|
||||
LocalShipping,
|
||||
Store,
|
||||
} from '@mui/icons-material';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
@@ -61,6 +63,7 @@ const adminSubItems: SubItem[] = [
|
||||
{ text: 'Wartung', path: '/admin?tab=5' },
|
||||
{ text: 'FDISK Sync', path: '/admin?tab=6' },
|
||||
{ text: 'Berechtigungen', path: '/admin?tab=7' },
|
||||
{ text: 'Bestellungen', path: '/admin?tab=8' },
|
||||
];
|
||||
|
||||
const baseNavigationItems: NavigationItem[] = [
|
||||
@@ -106,6 +109,22 @@ const baseNavigationItems: NavigationItem[] = [
|
||||
path: '/wissen',
|
||||
permission: 'wissen:view',
|
||||
},
|
||||
{
|
||||
text: 'Bestellungen',
|
||||
icon: <LocalShipping />,
|
||||
path: '/bestellungen',
|
||||
subItems: [
|
||||
{ text: 'Übersicht', path: '/bestellungen?tab=0' },
|
||||
{ text: 'Lieferanten', path: '/bestellungen?tab=1' },
|
||||
],
|
||||
permission: 'bestellungen:view',
|
||||
},
|
||||
{
|
||||
text: 'Shop',
|
||||
icon: <Store />,
|
||||
path: '/shop',
|
||||
permission: 'shop:view',
|
||||
},
|
||||
];
|
||||
|
||||
const adminItem: NavigationItem = {
|
||||
|
||||
@@ -13,6 +13,8 @@ export const WIDGETS = [
|
||||
{ key: 'eventQuickAdd', label: 'Termin erstellen', defaultVisible: true },
|
||||
{ key: 'adminStatus', label: 'Admin Status', defaultVisible: true },
|
||||
{ key: 'links', label: 'Links', defaultVisible: true },
|
||||
{ key: 'bestellungen', label: 'Bestellungen', defaultVisible: true },
|
||||
{ key: 'shopRequests', label: 'Shop-Anfragen', defaultVisible: true },
|
||||
] as const;
|
||||
|
||||
export type WidgetKey = typeof WIDGETS[number]['key'];
|
||||
|
||||
@@ -10,6 +10,7 @@ import BannerManagementTab from '../components/admin/BannerManagementTab';
|
||||
import ServiceModeTab from '../components/admin/ServiceModeTab';
|
||||
import FdiskSyncTab from '../components/admin/FdiskSyncTab';
|
||||
import PermissionMatrixTab from '../components/admin/PermissionMatrixTab';
|
||||
import BestellungenTab from '../components/admin/BestellungenTab';
|
||||
import { usePermissionContext } from '../contexts/PermissionContext';
|
||||
|
||||
interface TabPanelProps {
|
||||
@@ -23,7 +24,7 @@ function TabPanel({ children, value, index }: TabPanelProps) {
|
||||
return <Box sx={{ pt: 3 }}>{children}</Box>;
|
||||
}
|
||||
|
||||
const ADMIN_TAB_COUNT = 8;
|
||||
const ADMIN_TAB_COUNT = 9;
|
||||
|
||||
function AdminDashboard() {
|
||||
const navigate = useNavigate();
|
||||
@@ -57,6 +58,7 @@ function AdminDashboard() {
|
||||
<Tab label="Wartung" />
|
||||
<Tab label="FDISK Sync" />
|
||||
<Tab label="Berechtigungen" />
|
||||
<Tab label="Bestellungen" />
|
||||
</Tabs>
|
||||
</Box>
|
||||
|
||||
@@ -84,6 +86,9 @@ function AdminDashboard() {
|
||||
<TabPanel value={tab} index={7}>
|
||||
<PermissionMatrixTab />
|
||||
</TabPanel>
|
||||
<TabPanel value={tab} index={8}>
|
||||
<BestellungenTab />
|
||||
</TabPanel>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogTitle,
|
||||
Fab,
|
||||
FormControl,
|
||||
FormControlLabel,
|
||||
Grid,
|
||||
@@ -318,7 +317,7 @@ function Atemschutz() {
|
||||
leistungstest_datum: normalizeDate(form.leistungstest_datum || undefined),
|
||||
leistungstest_gueltig_bis: normalizeDate(form.leistungstest_gueltig_bis || undefined),
|
||||
leistungstest_bestanden: form.leistungstest_bestanden,
|
||||
bemerkung: form.bemerkung || null,
|
||||
bemerkung: form.bemerkung || undefined,
|
||||
};
|
||||
await atemschutzApi.update(editingId, payload);
|
||||
notification.showSuccess('Atemschutzträger erfolgreich aktualisiert.');
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
Chip,
|
||||
CircularProgress,
|
||||
Container,
|
||||
Fab,
|
||||
FormControl,
|
||||
FormControlLabel,
|
||||
Grid,
|
||||
|
||||
686
frontend/src/pages/BestellungDetail.tsx
Normal file
686
frontend/src/pages/BestellungDetail.tsx
Normal file
@@ -0,0 +1,686 @@
|
||||
import { useState, useRef } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Paper,
|
||||
Button,
|
||||
Chip,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TextField,
|
||||
IconButton,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Grid,
|
||||
Card,
|
||||
CardContent,
|
||||
LinearProgress,
|
||||
Checkbox,
|
||||
} from '@mui/material';
|
||||
import {
|
||||
ArrowBack,
|
||||
Add as AddIcon,
|
||||
Delete as DeleteIcon,
|
||||
Edit as EditIcon,
|
||||
Check as CheckIcon,
|
||||
Close as CloseIcon,
|
||||
AttachFile,
|
||||
Alarm,
|
||||
History,
|
||||
Upload as UploadIcon,
|
||||
} from '@mui/icons-material';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import DashboardLayout from '../components/dashboard/DashboardLayout';
|
||||
import { useNotification } from '../contexts/NotificationContext';
|
||||
import { usePermissionContext } from '../contexts/PermissionContext';
|
||||
import { bestellungApi } from '../services/bestellung';
|
||||
import { BESTELLUNG_STATUS_LABELS, BESTELLUNG_STATUS_COLORS } from '../types/bestellung.types';
|
||||
import type { BestellungStatus, BestellpositionFormData, ErinnerungFormData, Bestellposition } from '../types/bestellung.types';
|
||||
|
||||
// ── Helpers ──
|
||||
|
||||
const formatCurrency = (value?: number) =>
|
||||
value != null ? new Intl.NumberFormat('de-AT', { style: 'currency', currency: 'EUR' }).format(value) : '–';
|
||||
|
||||
const formatDate = (iso?: string) =>
|
||||
iso ? new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' }) : '–';
|
||||
|
||||
const formatDateTime = (iso?: string) =>
|
||||
iso ? new Date(iso).toLocaleString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : '–';
|
||||
|
||||
const formatFileSize = (bytes?: number) => {
|
||||
if (!bytes) return '–';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
};
|
||||
|
||||
// Status flow
|
||||
const STATUS_FLOW: BestellungStatus[] = ['entwurf', 'erstellt', 'bestellt', 'teillieferung', 'vollstaendig', 'abgeschlossen'];
|
||||
|
||||
function getNextStatus(current: BestellungStatus): BestellungStatus | null {
|
||||
const idx = STATUS_FLOW.indexOf(current);
|
||||
return idx >= 0 && idx < STATUS_FLOW.length - 1 ? STATUS_FLOW[idx + 1] : null;
|
||||
}
|
||||
|
||||
// Empty line item form
|
||||
const emptyItem: BestellpositionFormData = { bezeichnung: '', artikelnummer: '', menge: 1, einheit: 'Stk', einzelpreis: undefined };
|
||||
|
||||
// ══════════════════════════════════════════════════════════════════════════════
|
||||
// Component
|
||||
// ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
export default function BestellungDetail() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const { showSuccess, showError } = useNotification();
|
||||
const { hasPermission } = usePermissionContext();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const orderId = Number(id);
|
||||
|
||||
// ── State ──
|
||||
const [newItem, setNewItem] = useState<BestellpositionFormData>({ ...emptyItem });
|
||||
const [editingItemId, setEditingItemId] = useState<number | null>(null);
|
||||
const [editingItemData, setEditingItemData] = useState<Partial<BestellpositionFormData>>({});
|
||||
const [statusConfirmOpen, setStatusConfirmOpen] = useState(false);
|
||||
const [deleteItemTarget, setDeleteItemTarget] = useState<number | null>(null);
|
||||
const [deleteFileTarget, setDeleteFileTarget] = useState<number | null>(null);
|
||||
|
||||
const [reminderForm, setReminderForm] = useState<ErinnerungFormData>({ faellig_am: '', nachricht: '' });
|
||||
const [reminderFormOpen, setReminderFormOpen] = useState(false);
|
||||
const [deleteReminderTarget, setDeleteReminderTarget] = useState<number | null>(null);
|
||||
|
||||
// ── Query ──
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ['bestellung', orderId],
|
||||
queryFn: () => bestellungApi.getOrder(orderId),
|
||||
enabled: !!orderId,
|
||||
});
|
||||
|
||||
const bestellung = data?.bestellung;
|
||||
const positionen = data?.positionen ?? [];
|
||||
const dateien = data?.dateien ?? [];
|
||||
const erinnerungen = data?.erinnerungen ?? [];
|
||||
const historie = data?.historie ?? [];
|
||||
|
||||
const canEdit = hasPermission('bestellungen:edit');
|
||||
const nextStatus = bestellung ? getNextStatus(bestellung.status) : null;
|
||||
|
||||
// ── Mutations ──
|
||||
|
||||
const updateStatus = useMutation({
|
||||
mutationFn: (status: string) => bestellungApi.updateStatus(orderId, status),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
showSuccess('Status aktualisiert');
|
||||
setStatusConfirmOpen(false);
|
||||
},
|
||||
onError: () => showError('Fehler beim Aktualisieren des Status'),
|
||||
});
|
||||
|
||||
const addItem = useMutation({
|
||||
mutationFn: (data: BestellpositionFormData) => bestellungApi.addLineItem(orderId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
setNewItem({ ...emptyItem });
|
||||
showSuccess('Position hinzugefügt');
|
||||
},
|
||||
onError: () => showError('Fehler beim Hinzufügen der Position'),
|
||||
});
|
||||
|
||||
const updateItem = useMutation({
|
||||
mutationFn: ({ itemId, data }: { itemId: number; data: Partial<BestellpositionFormData> }) =>
|
||||
bestellungApi.updateLineItem(itemId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
setEditingItemId(null);
|
||||
showSuccess('Position aktualisiert');
|
||||
},
|
||||
onError: () => showError('Fehler beim Aktualisieren der Position'),
|
||||
});
|
||||
|
||||
const deleteItem = useMutation({
|
||||
mutationFn: (itemId: number) => bestellungApi.deleteLineItem(itemId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
setDeleteItemTarget(null);
|
||||
showSuccess('Position gelöscht');
|
||||
},
|
||||
onError: () => showError('Fehler beim Löschen der Position'),
|
||||
});
|
||||
|
||||
const updateReceived = useMutation({
|
||||
mutationFn: ({ itemId, menge }: { itemId: number; menge: number }) =>
|
||||
bestellungApi.updateReceivedQty(itemId, menge),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
},
|
||||
onError: () => showError('Fehler beim Aktualisieren'),
|
||||
});
|
||||
|
||||
const uploadFile = useMutation({
|
||||
mutationFn: (file: File) => bestellungApi.uploadFile(orderId, file),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
showSuccess('Datei hochgeladen');
|
||||
},
|
||||
onError: () => showError('Fehler beim Hochladen der Datei'),
|
||||
});
|
||||
|
||||
const deleteFile = useMutation({
|
||||
mutationFn: (fileId: number) => bestellungApi.deleteFile(fileId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
setDeleteFileTarget(null);
|
||||
showSuccess('Datei gelöscht');
|
||||
},
|
||||
onError: () => showError('Fehler beim Löschen der Datei'),
|
||||
});
|
||||
|
||||
const addReminder = useMutation({
|
||||
mutationFn: (data: ErinnerungFormData) => bestellungApi.addReminder(orderId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
setReminderForm({ faellig_am: '', nachricht: '' });
|
||||
setReminderFormOpen(false);
|
||||
showSuccess('Erinnerung erstellt');
|
||||
},
|
||||
onError: () => showError('Fehler beim Erstellen der Erinnerung'),
|
||||
});
|
||||
|
||||
const markReminderDone = useMutation({
|
||||
mutationFn: (reminderId: number) => bestellungApi.markReminderDone(reminderId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
},
|
||||
onError: () => showError('Fehler beim Aktualisieren'),
|
||||
});
|
||||
|
||||
const deleteReminder = useMutation({
|
||||
mutationFn: (reminderId: number) => bestellungApi.deleteReminder(reminderId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellung', orderId] });
|
||||
setDeleteReminderTarget(null);
|
||||
showSuccess('Erinnerung gelöscht');
|
||||
},
|
||||
onError: () => showError('Fehler beim Löschen'),
|
||||
});
|
||||
|
||||
// ── Handlers ──
|
||||
|
||||
function startEditItem(item: Bestellposition) {
|
||||
setEditingItemId(item.id);
|
||||
setEditingItemData({
|
||||
bezeichnung: item.bezeichnung,
|
||||
artikelnummer: item.artikelnummer || '',
|
||||
menge: item.menge,
|
||||
einheit: item.einheit,
|
||||
einzelpreis: item.einzelpreis,
|
||||
});
|
||||
}
|
||||
|
||||
function saveEditItem() {
|
||||
if (editingItemId == null) return;
|
||||
updateItem.mutate({ itemId: editingItemId, data: editingItemData });
|
||||
}
|
||||
|
||||
function handleAddItem() {
|
||||
if (!newItem.bezeichnung.trim()) return;
|
||||
addItem.mutate(newItem);
|
||||
}
|
||||
|
||||
function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) uploadFile.mutate(file);
|
||||
e.target.value = '';
|
||||
}
|
||||
|
||||
// Compute totals
|
||||
const totalCost = positionen.reduce((sum, p) => sum + (p.einzelpreis ?? 0) * p.menge, 0);
|
||||
const totalReceived = positionen.length > 0
|
||||
? positionen.reduce((sum, p) => sum + p.erhalten_menge, 0)
|
||||
: 0;
|
||||
const totalOrdered = positionen.reduce((sum, p) => sum + p.menge, 0);
|
||||
const receivedPercent = totalOrdered > 0 ? Math.round((totalReceived / totalOrdered) * 100) : 0;
|
||||
|
||||
// ── Loading / Error ──
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<Box sx={{ p: 4, textAlign: 'center' }}><Typography>Laden...</Typography></Box>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError || !bestellung) {
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<Box sx={{ p: 4, textAlign: 'center' }}>
|
||||
<Typography color="error">Bestellung nicht gefunden.</Typography>
|
||||
<Button sx={{ mt: 2 }} onClick={() => navigate('/bestellungen')}>Zurück</Button>
|
||||
</Box>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
{/* ── Header ── */}
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
|
||||
<IconButton onClick={() => navigate('/bestellungen')}>
|
||||
<ArrowBack />
|
||||
</IconButton>
|
||||
<Typography variant="h4" sx={{ flexGrow: 1 }}>{bestellung.bezeichnung}</Typography>
|
||||
<Chip
|
||||
label={BESTELLUNG_STATUS_LABELS[bestellung.status]}
|
||||
color={BESTELLUNG_STATUS_COLORS[bestellung.status]}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{/* ── Info Cards ── */}
|
||||
<Grid container spacing={2} sx={{ mb: 3 }}>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<Card variant="outlined"><CardContent>
|
||||
<Typography variant="caption" color="text.secondary">Lieferant</Typography>
|
||||
<Typography>{bestellung.lieferant_name || '–'}</Typography>
|
||||
</CardContent></Card>
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<Card variant="outlined"><CardContent>
|
||||
<Typography variant="caption" color="text.secondary">Besteller</Typography>
|
||||
<Typography>{bestellung.besteller_name || '–'}</Typography>
|
||||
</CardContent></Card>
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<Card variant="outlined"><CardContent>
|
||||
<Typography variant="caption" color="text.secondary">Budget</Typography>
|
||||
<Typography>{formatCurrency(bestellung.budget)}</Typography>
|
||||
</CardContent></Card>
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<Card variant="outlined"><CardContent>
|
||||
<Typography variant="caption" color="text.secondary">Erstellt am</Typography>
|
||||
<Typography>{formatDate(bestellung.erstellt_am)}</Typography>
|
||||
</CardContent></Card>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* ── Status Action ── */}
|
||||
{canEdit && nextStatus && (
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Button variant="contained" onClick={() => setStatusConfirmOpen(true)}>
|
||||
Status ändern: {BESTELLUNG_STATUS_LABELS[nextStatus]}
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* ── Delivery Progress ── */}
|
||||
{positionen.length > 0 && (
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 0.5 }}>
|
||||
Lieferfortschritt: {totalReceived} / {totalOrdered} ({receivedPercent}%)
|
||||
</Typography>
|
||||
<LinearProgress variant="determinate" value={receivedPercent} sx={{ height: 8, borderRadius: 4 }} />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
{/* Positionen */}
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
<Paper sx={{ p: 2, mb: 3 }}>
|
||||
<Typography variant="h6" sx={{ mb: 2 }}>Positionen</Typography>
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Bezeichnung</TableCell>
|
||||
<TableCell>Artikelnr.</TableCell>
|
||||
<TableCell align="right">Menge</TableCell>
|
||||
<TableCell>Einheit</TableCell>
|
||||
<TableCell align="right">Einzelpreis</TableCell>
|
||||
<TableCell align="right">Gesamt</TableCell>
|
||||
<TableCell align="right">Erhalten</TableCell>
|
||||
{canEdit && <TableCell align="right">Aktionen</TableCell>}
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{positionen.map((p) =>
|
||||
editingItemId === p.id ? (
|
||||
<TableRow key={p.id}>
|
||||
<TableCell>
|
||||
<TextField size="small" value={editingItemData.bezeichnung || ''} onChange={(e) => setEditingItemData((d) => ({ ...d, bezeichnung: e.target.value }))} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField size="small" value={editingItemData.artikelnummer || ''} onChange={(e) => setEditingItemData((d) => ({ ...d, artikelnummer: e.target.value }))} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField size="small" type="number" sx={{ width: 80 }} value={editingItemData.menge ?? ''} onChange={(e) => setEditingItemData((d) => ({ ...d, menge: Number(e.target.value) }))} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField size="small" sx={{ width: 80 }} value={editingItemData.einheit || ''} onChange={(e) => setEditingItemData((d) => ({ ...d, einheit: e.target.value }))} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField size="small" type="number" sx={{ width: 100 }} value={editingItemData.einzelpreis ?? ''} onChange={(e) => setEditingItemData((d) => ({ ...d, einzelpreis: e.target.value ? Number(e.target.value) : undefined }))} />
|
||||
</TableCell>
|
||||
<TableCell align="right">{formatCurrency((editingItemData.einzelpreis ?? 0) * (editingItemData.menge ?? 0))}</TableCell>
|
||||
<TableCell align="right">{p.erhalten_menge}</TableCell>
|
||||
<TableCell align="right">
|
||||
<IconButton size="small" color="primary" onClick={saveEditItem}><CheckIcon fontSize="small" /></IconButton>
|
||||
<IconButton size="small" onClick={() => setEditingItemId(null)}><CloseIcon fontSize="small" /></IconButton>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
<TableRow key={p.id}>
|
||||
<TableCell>{p.bezeichnung}</TableCell>
|
||||
<TableCell>{p.artikelnummer || '–'}</TableCell>
|
||||
<TableCell align="right">{p.menge}</TableCell>
|
||||
<TableCell>{p.einheit}</TableCell>
|
||||
<TableCell align="right">{formatCurrency(p.einzelpreis)}</TableCell>
|
||||
<TableCell align="right">{formatCurrency((p.einzelpreis ?? 0) * p.menge)}</TableCell>
|
||||
<TableCell align="right">
|
||||
{canEdit ? (
|
||||
<TextField
|
||||
size="small"
|
||||
type="number"
|
||||
sx={{ width: 70 }}
|
||||
value={p.erhalten_menge}
|
||||
inputProps={{ min: 0, max: p.menge }}
|
||||
onChange={(e) => updateReceived.mutate({ itemId: p.id, menge: Number(e.target.value) })}
|
||||
/>
|
||||
) : (
|
||||
p.erhalten_menge
|
||||
)}
|
||||
</TableCell>
|
||||
{canEdit && (
|
||||
<TableCell align="right">
|
||||
<IconButton size="small" onClick={() => startEditItem(p)}><EditIcon fontSize="small" /></IconButton>
|
||||
<IconButton size="small" color="error" onClick={() => setDeleteItemTarget(p.id)}><DeleteIcon fontSize="small" /></IconButton>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
),
|
||||
)}
|
||||
|
||||
{/* ── Add Item Row ── */}
|
||||
{canEdit && (
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
<TextField size="small" placeholder="Bezeichnung" value={newItem.bezeichnung} onChange={(e) => setNewItem((f) => ({ ...f, bezeichnung: e.target.value }))} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField size="small" placeholder="Artikelnr." value={newItem.artikelnummer || ''} onChange={(e) => setNewItem((f) => ({ ...f, artikelnummer: e.target.value }))} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField size="small" type="number" sx={{ width: 80 }} value={newItem.menge} onChange={(e) => setNewItem((f) => ({ ...f, menge: Number(e.target.value) }))} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField size="small" sx={{ width: 80 }} value={newItem.einheit || 'Stk'} onChange={(e) => setNewItem((f) => ({ ...f, einheit: e.target.value }))} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField size="small" type="number" sx={{ width: 100 }} placeholder="Preis" value={newItem.einzelpreis ?? ''} onChange={(e) => setNewItem((f) => ({ ...f, einzelpreis: e.target.value ? Number(e.target.value) : undefined }))} />
|
||||
</TableCell>
|
||||
<TableCell align="right">{formatCurrency((newItem.einzelpreis ?? 0) * newItem.menge)}</TableCell>
|
||||
<TableCell />
|
||||
<TableCell align="right">
|
||||
<IconButton size="small" color="primary" onClick={handleAddItem} disabled={!newItem.bezeichnung.trim() || addItem.isPending}>
|
||||
<AddIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
|
||||
{/* ── Totals Row ── */}
|
||||
{positionen.length > 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} align="right"><strong>Gesamtsumme</strong></TableCell>
|
||||
<TableCell align="right"><strong>{formatCurrency(totalCost)}</strong></TableCell>
|
||||
<TableCell colSpan={canEdit ? 2 : 1} />
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</Paper>
|
||||
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
{/* Dateien */}
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
<Paper sx={{ p: 2, mb: 3 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
|
||||
<AttachFile sx={{ mr: 1 }} />
|
||||
<Typography variant="h6" sx={{ flexGrow: 1 }}>Dateien</Typography>
|
||||
{canEdit && (
|
||||
<>
|
||||
<input ref={fileInputRef} type="file" hidden onChange={handleFileSelect} />
|
||||
<Button size="small" startIcon={<UploadIcon />} onClick={() => fileInputRef.current?.click()} disabled={uploadFile.isPending}>
|
||||
Hochladen
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
{dateien.length === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary">Keine Dateien vorhanden</Typography>
|
||||
) : (
|
||||
<Grid container spacing={2}>
|
||||
{dateien.map((d) => (
|
||||
<Grid item xs={12} sm={6} md={4} key={d.id}>
|
||||
<Card variant="outlined">
|
||||
{d.thumbnail_pfad && (
|
||||
<Box
|
||||
component="img"
|
||||
src={`/api/bestellungen/files/${d.id}/thumbnail`}
|
||||
alt={d.dateiname}
|
||||
sx={{ width: '100%', height: 120, objectFit: 'cover' }}
|
||||
/>
|
||||
)}
|
||||
<CardContent sx={{ py: 1, '&:last-child': { pb: 1 } }}>
|
||||
<Typography variant="body2" noWrap>{d.dateiname}</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{formatFileSize(d.dateigroesse)} · {formatDate(d.hochgeladen_am)}
|
||||
</Typography>
|
||||
{canEdit && (
|
||||
<Box sx={{ mt: 0.5 }}>
|
||||
<IconButton size="small" color="error" onClick={() => setDeleteFileTarget(d.id)}>
|
||||
<DeleteIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
{/* Erinnerungen */}
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
<Paper sx={{ p: 2, mb: 3 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
|
||||
<Alarm sx={{ mr: 1 }} />
|
||||
<Typography variant="h6" sx={{ flexGrow: 1 }}>Erinnerungen</Typography>
|
||||
{canEdit && (
|
||||
<Button size="small" startIcon={<AddIcon />} onClick={() => setReminderFormOpen(true)}>
|
||||
Neue Erinnerung
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
{erinnerungen.length === 0 && !reminderFormOpen ? (
|
||||
<Typography variant="body2" color="text.secondary">Keine Erinnerungen</Typography>
|
||||
) : (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
|
||||
{erinnerungen.map((r) => (
|
||||
<Box key={r.id} sx={{ display: 'flex', alignItems: 'center', gap: 1, opacity: r.erledigt ? 0.5 : 1 }}>
|
||||
<Checkbox
|
||||
checked={r.erledigt}
|
||||
disabled={r.erledigt || !canEdit}
|
||||
onChange={() => markReminderDone.mutate(r.id)}
|
||||
size="small"
|
||||
/>
|
||||
<Box sx={{ flexGrow: 1 }}>
|
||||
<Typography variant="body2" sx={{ textDecoration: r.erledigt ? 'line-through' : 'none' }}>
|
||||
{r.nachricht || 'Erinnerung'}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
Fällig: {formatDate(r.faellig_am)}
|
||||
</Typography>
|
||||
</Box>
|
||||
{canEdit && (
|
||||
<IconButton size="small" color="error" onClick={() => setDeleteReminderTarget(r.id)}>
|
||||
<DeleteIcon fontSize="small" />
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Inline Add Reminder Form */}
|
||||
{reminderFormOpen && (
|
||||
<Box sx={{ display: 'flex', gap: 1, mt: 2, alignItems: 'flex-end' }}>
|
||||
<TextField
|
||||
size="small"
|
||||
type="date"
|
||||
label="Fällig am"
|
||||
InputLabelProps={{ shrink: true }}
|
||||
value={reminderForm.faellig_am}
|
||||
onChange={(e) => setReminderForm((f) => ({ ...f, faellig_am: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Nachricht"
|
||||
sx={{ flexGrow: 1 }}
|
||||
value={reminderForm.nachricht || ''}
|
||||
onChange={(e) => setReminderForm((f) => ({ ...f, nachricht: e.target.value }))}
|
||||
/>
|
||||
<Button
|
||||
size="small"
|
||||
variant="contained"
|
||||
disabled={!reminderForm.faellig_am || addReminder.isPending}
|
||||
onClick={() => addReminder.mutate(reminderForm)}
|
||||
>
|
||||
Speichern
|
||||
</Button>
|
||||
<Button size="small" onClick={() => { setReminderFormOpen(false); setReminderForm({ faellig_am: '', nachricht: '' }); }}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
{/* Historie */}
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
<Paper sx={{ p: 2, mb: 3 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
|
||||
<History sx={{ mr: 1 }} />
|
||||
<Typography variant="h6">Historie</Typography>
|
||||
</Box>
|
||||
{historie.length === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary">Keine Einträge</Typography>
|
||||
) : (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
|
||||
{historie.map((h) => (
|
||||
<Box key={h.id} sx={{ display: 'flex', gap: 1 }}>
|
||||
<Box sx={{ width: 6, minHeight: '100%', borderRadius: 3, bgcolor: 'divider', flexShrink: 0 }} />
|
||||
<Box>
|
||||
<Typography variant="body2">{h.aktion}</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{h.erstellt_von_name || 'System'} · {formatDateTime(h.erstellt_am)}
|
||||
</Typography>
|
||||
{h.details && (
|
||||
<Typography variant="caption" display="block" color="text.secondary">
|
||||
{Object.entries(h.details).map(([k, v]) => `${k}: ${v}`).join(', ')}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* ── Notizen ── */}
|
||||
{bestellung.notizen && (
|
||||
<Paper sx={{ p: 2, mb: 3 }}>
|
||||
<Typography variant="h6" sx={{ mb: 1 }}>Notizen</Typography>
|
||||
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>{bestellung.notizen}</Typography>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
{/* Dialogs */}
|
||||
{/* ══════════════════════════════════════════════════════════════════════ */}
|
||||
|
||||
{/* Status Confirmation */}
|
||||
<Dialog open={statusConfirmOpen} onClose={() => setStatusConfirmOpen(false)}>
|
||||
<DialogTitle>Status ändern</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography>
|
||||
Status von <strong>{BESTELLUNG_STATUS_LABELS[bestellung.status]}</strong> auf{' '}
|
||||
<strong>{nextStatus ? BESTELLUNG_STATUS_LABELS[nextStatus] : ''}</strong> ändern?
|
||||
</Typography>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setStatusConfirmOpen(false)}>Abbrechen</Button>
|
||||
<Button variant="contained" onClick={() => nextStatus && updateStatus.mutate(nextStatus)} disabled={updateStatus.isPending}>
|
||||
Bestätigen
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Item Confirmation */}
|
||||
<Dialog open={deleteItemTarget != null} onClose={() => setDeleteItemTarget(null)}>
|
||||
<DialogTitle>Position löschen</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography>Soll diese Position wirklich gelöscht werden?</Typography>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDeleteItemTarget(null)}>Abbrechen</Button>
|
||||
<Button color="error" variant="contained" onClick={() => deleteItemTarget != null && deleteItem.mutate(deleteItemTarget)} disabled={deleteItem.isPending}>
|
||||
Löschen
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete File Confirmation */}
|
||||
<Dialog open={deleteFileTarget != null} onClose={() => setDeleteFileTarget(null)}>
|
||||
<DialogTitle>Datei löschen</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography>Soll diese Datei wirklich gelöscht werden?</Typography>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDeleteFileTarget(null)}>Abbrechen</Button>
|
||||
<Button color="error" variant="contained" onClick={() => deleteFileTarget != null && deleteFile.mutate(deleteFileTarget)} disabled={deleteFile.isPending}>
|
||||
Löschen
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Reminder Confirmation */}
|
||||
<Dialog open={deleteReminderTarget != null} onClose={() => setDeleteReminderTarget(null)}>
|
||||
<DialogTitle>Erinnerung löschen</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography>Soll diese Erinnerung wirklich gelöscht werden?</Typography>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDeleteReminderTarget(null)}>Abbrechen</Button>
|
||||
<Button color="error" variant="contained" onClick={() => deleteReminderTarget != null && deleteReminder.mutate(deleteReminderTarget)} disabled={deleteReminder.isPending}>
|
||||
Löschen
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
434
frontend/src/pages/Bestellungen.tsx
Normal file
434
frontend/src/pages/Bestellungen.tsx
Normal file
@@ -0,0 +1,434 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Tab,
|
||||
Tabs,
|
||||
Typography,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Paper,
|
||||
Chip,
|
||||
IconButton,
|
||||
Button,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
TextField,
|
||||
MenuItem,
|
||||
Select,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Tooltip,
|
||||
Autocomplete,
|
||||
} from '@mui/material';
|
||||
import { Add as AddIcon, Edit as EditIcon, Delete as DeleteIcon } from '@mui/icons-material';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import DashboardLayout from '../components/dashboard/DashboardLayout';
|
||||
import ChatAwareFab from '../components/shared/ChatAwareFab';
|
||||
import { useNotification } from '../contexts/NotificationContext';
|
||||
import { usePermissionContext } from '../contexts/PermissionContext';
|
||||
import { bestellungApi } from '../services/bestellung';
|
||||
import { BESTELLUNG_STATUS_LABELS, BESTELLUNG_STATUS_COLORS } from '../types/bestellung.types';
|
||||
import type { BestellungStatus, BestellungFormData, LieferantFormData, Lieferant } from '../types/bestellung.types';
|
||||
|
||||
// ── Helpers ──
|
||||
|
||||
const formatCurrency = (value?: number) =>
|
||||
value != null ? new Intl.NumberFormat('de-AT', { style: 'currency', currency: 'EUR' }).format(value) : '–';
|
||||
|
||||
const formatDate = (iso?: string) =>
|
||||
iso ? new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' }) : '–';
|
||||
|
||||
// ── Tab Panel ──
|
||||
|
||||
interface TabPanelProps { children: React.ReactNode; index: number; value: number }
|
||||
function TabPanel({ children, value, index }: TabPanelProps) {
|
||||
if (value !== index) return null;
|
||||
return <Box sx={{ pt: 3 }}>{children}</Box>;
|
||||
}
|
||||
|
||||
const TAB_COUNT = 2;
|
||||
|
||||
// ── Status options for filter ──
|
||||
|
||||
const ALL_STATUSES: BestellungStatus[] = ['entwurf', 'erstellt', 'bestellt', 'teillieferung', 'vollstaendig', 'abgeschlossen'];
|
||||
|
||||
// ── Empty form data ──
|
||||
|
||||
const emptyOrderForm: BestellungFormData = { bezeichnung: '', lieferant_id: undefined, besteller_id: '', budget: undefined, notizen: '' };
|
||||
const emptyVendorForm: LieferantFormData = { name: '', kontakt_name: '', email: '', telefon: '', adresse: '', website: '', notizen: '' };
|
||||
|
||||
// ══════════════════════════════════════════════════════════════════════════════
|
||||
// Component
|
||||
// ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
export default function Bestellungen() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const { showSuccess, showError } = useNotification();
|
||||
const { hasPermission } = usePermissionContext();
|
||||
|
||||
// Tab from URL
|
||||
const [tab, setTab] = useState(() => {
|
||||
const t = Number(searchParams.get('tab'));
|
||||
return t >= 0 && t < TAB_COUNT ? t : 0;
|
||||
});
|
||||
useEffect(() => {
|
||||
const t = Number(searchParams.get('tab'));
|
||||
if (t >= 0 && t < TAB_COUNT) setTab(t);
|
||||
}, [searchParams]);
|
||||
|
||||
// ── State ──
|
||||
const [statusFilter, setStatusFilter] = useState<string>('');
|
||||
const [orderDialogOpen, setOrderDialogOpen] = useState(false);
|
||||
const [orderForm, setOrderForm] = useState<BestellungFormData>({ ...emptyOrderForm });
|
||||
|
||||
const [vendorDialogOpen, setVendorDialogOpen] = useState(false);
|
||||
const [vendorForm, setVendorForm] = useState<LieferantFormData>({ ...emptyVendorForm });
|
||||
const [editingVendor, setEditingVendor] = useState<Lieferant | null>(null);
|
||||
|
||||
const [deleteVendorTarget, setDeleteVendorTarget] = useState<Lieferant | null>(null);
|
||||
|
||||
// ── Queries ──
|
||||
const { data: orders = [], isLoading: ordersLoading } = useQuery({
|
||||
queryKey: ['bestellungen', statusFilter],
|
||||
queryFn: () => bestellungApi.getOrders(statusFilter ? { status: statusFilter } : undefined),
|
||||
});
|
||||
|
||||
const { data: vendors = [], isLoading: vendorsLoading } = useQuery({
|
||||
queryKey: ['lieferanten'],
|
||||
queryFn: bestellungApi.getVendors,
|
||||
});
|
||||
|
||||
// ── Mutations ──
|
||||
const createOrder = useMutation({
|
||||
mutationFn: (data: BestellungFormData) => bestellungApi.createOrder(data),
|
||||
onSuccess: (created) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bestellungen'] });
|
||||
showSuccess('Bestellung erstellt');
|
||||
setOrderDialogOpen(false);
|
||||
setOrderForm({ ...emptyOrderForm });
|
||||
navigate(`/bestellungen/${created.id}`);
|
||||
},
|
||||
onError: () => showError('Fehler beim Erstellen der Bestellung'),
|
||||
});
|
||||
|
||||
const createVendor = useMutation({
|
||||
mutationFn: (data: LieferantFormData) => bestellungApi.createVendor(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['lieferanten'] });
|
||||
showSuccess('Lieferant erstellt');
|
||||
closeVendorDialog();
|
||||
},
|
||||
onError: () => showError('Fehler beim Erstellen des Lieferanten'),
|
||||
});
|
||||
|
||||
const updateVendor = useMutation({
|
||||
mutationFn: ({ id, data }: { id: number; data: LieferantFormData }) => bestellungApi.updateVendor(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['lieferanten'] });
|
||||
showSuccess('Lieferant aktualisiert');
|
||||
closeVendorDialog();
|
||||
},
|
||||
onError: () => showError('Fehler beim Aktualisieren des Lieferanten'),
|
||||
});
|
||||
|
||||
const deleteVendor = useMutation({
|
||||
mutationFn: (id: number) => bestellungApi.deleteVendor(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['lieferanten'] });
|
||||
showSuccess('Lieferant gelöscht');
|
||||
setDeleteVendorTarget(null);
|
||||
},
|
||||
onError: () => showError('Fehler beim Löschen des Lieferanten'),
|
||||
});
|
||||
|
||||
// ── Dialog helpers ──
|
||||
|
||||
function openEditVendor(v: Lieferant) {
|
||||
setEditingVendor(v);
|
||||
setVendorForm({ name: v.name, kontakt_name: v.kontakt_name || '', email: v.email || '', telefon: v.telefon || '', adresse: v.adresse || '', website: v.website || '', notizen: v.notizen || '' });
|
||||
setVendorDialogOpen(true);
|
||||
}
|
||||
|
||||
function closeVendorDialog() {
|
||||
setVendorDialogOpen(false);
|
||||
setEditingVendor(null);
|
||||
setVendorForm({ ...emptyVendorForm });
|
||||
}
|
||||
|
||||
function handleVendorSave() {
|
||||
if (!vendorForm.name.trim()) return;
|
||||
if (editingVendor) {
|
||||
updateVendor.mutate({ id: editingVendor.id, data: vendorForm });
|
||||
} else {
|
||||
createVendor.mutate(vendorForm);
|
||||
}
|
||||
}
|
||||
|
||||
function handleOrderSave() {
|
||||
if (!orderForm.bezeichnung.trim()) return;
|
||||
createOrder.mutate(orderForm);
|
||||
}
|
||||
|
||||
// ── Render ──
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<Typography variant="h4" sx={{ mb: 3 }}>Bestellungen</Typography>
|
||||
|
||||
<Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
|
||||
<Tabs value={tab} onChange={(_e, v) => { setTab(v); navigate(`/bestellungen?tab=${v}`, { replace: true }); }}>
|
||||
<Tab label="Bestellungen" />
|
||||
<Tab label="Lieferanten" />
|
||||
</Tabs>
|
||||
</Box>
|
||||
|
||||
{/* ── Tab 0: Orders ── */}
|
||||
<TabPanel value={tab} index={0}>
|
||||
<Box sx={{ mb: 2, display: 'flex', gap: 2, alignItems: 'center' }}>
|
||||
<FormControl size="small" sx={{ minWidth: 200 }}>
|
||||
<InputLabel>Status Filter</InputLabel>
|
||||
<Select
|
||||
value={statusFilter}
|
||||
label="Status Filter"
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
>
|
||||
<MenuItem value="">Alle</MenuItem>
|
||||
{ALL_STATUSES.map((s) => (
|
||||
<MenuItem key={s} value={s}>{BESTELLUNG_STATUS_LABELS[s]}</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
<TableContainer component={Paper}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Bezeichnung</TableCell>
|
||||
<TableCell>Lieferant</TableCell>
|
||||
<TableCell>Besteller</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell align="right">Positionen</TableCell>
|
||||
<TableCell align="right">Gesamtpreis</TableCell>
|
||||
<TableCell>Erstellt am</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{ordersLoading ? (
|
||||
<TableRow><TableCell colSpan={7} align="center">Laden...</TableCell></TableRow>
|
||||
) : orders.length === 0 ? (
|
||||
<TableRow><TableCell colSpan={7} align="center">Keine Bestellungen vorhanden</TableCell></TableRow>
|
||||
) : (
|
||||
orders.map((o) => (
|
||||
<TableRow
|
||||
key={o.id}
|
||||
hover
|
||||
sx={{ cursor: 'pointer' }}
|
||||
onClick={() => navigate(`/bestellungen/${o.id}`)}
|
||||
>
|
||||
<TableCell>{o.bezeichnung}</TableCell>
|
||||
<TableCell>{o.lieferant_name || '–'}</TableCell>
|
||||
<TableCell>{o.besteller_name || '–'}</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={BESTELLUNG_STATUS_LABELS[o.status]}
|
||||
color={BESTELLUNG_STATUS_COLORS[o.status]}
|
||||
size="small"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="right">{o.items_count ?? 0}</TableCell>
|
||||
<TableCell align="right">{formatCurrency(o.total_cost)}</TableCell>
|
||||
<TableCell>{formatDate(o.erstellt_am)}</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
|
||||
{hasPermission('bestellungen:create') && (
|
||||
<ChatAwareFab onClick={() => setOrderDialogOpen(true)} aria-label="Neue Bestellung">
|
||||
<AddIcon />
|
||||
</ChatAwareFab>
|
||||
)}
|
||||
</TabPanel>
|
||||
|
||||
{/* ── Tab 1: Vendors ── */}
|
||||
<TabPanel value={tab} index={1}>
|
||||
<Box sx={{ mb: 2, display: 'flex', justifyContent: 'flex-end' }}>
|
||||
{hasPermission('bestellungen:create') && (
|
||||
<Button variant="contained" startIcon={<AddIcon />} onClick={() => setVendorDialogOpen(true)}>
|
||||
Lieferant hinzufügen
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<TableContainer component={Paper}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Name</TableCell>
|
||||
<TableCell>Kontakt</TableCell>
|
||||
<TableCell>E-Mail</TableCell>
|
||||
<TableCell>Telefon</TableCell>
|
||||
<TableCell>Website</TableCell>
|
||||
<TableCell align="right">Aktionen</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{vendorsLoading ? (
|
||||
<TableRow><TableCell colSpan={6} align="center">Laden...</TableCell></TableRow>
|
||||
) : vendors.length === 0 ? (
|
||||
<TableRow><TableCell colSpan={6} align="center">Keine Lieferanten vorhanden</TableCell></TableRow>
|
||||
) : (
|
||||
vendors.map((v) => (
|
||||
<TableRow key={v.id}>
|
||||
<TableCell>{v.name}</TableCell>
|
||||
<TableCell>{v.kontakt_name || '–'}</TableCell>
|
||||
<TableCell>{v.email ? <a href={`mailto:${v.email}`}>{v.email}</a> : '–'}</TableCell>
|
||||
<TableCell>{v.telefon || '–'}</TableCell>
|
||||
<TableCell>
|
||||
{v.website ? (
|
||||
<a href={v.website} target="_blank" rel="noopener noreferrer">{v.website}</a>
|
||||
) : '–'}
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Tooltip title="Bearbeiten">
|
||||
<IconButton size="small" onClick={() => openEditVendor(v)}><EditIcon fontSize="small" /></IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="Löschen">
|
||||
<IconButton size="small" color="error" onClick={() => setDeleteVendorTarget(v)}><DeleteIcon fontSize="small" /></IconButton>
|
||||
</Tooltip>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</TabPanel>
|
||||
|
||||
{/* ── Create Order Dialog ── */}
|
||||
<Dialog open={orderDialogOpen} onClose={() => setOrderDialogOpen(false)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>Neue Bestellung</DialogTitle>
|
||||
<DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '16px !important' }}>
|
||||
<TextField
|
||||
label="Bezeichnung"
|
||||
required
|
||||
value={orderForm.bezeichnung}
|
||||
onChange={(e) => setOrderForm((f) => ({ ...f, bezeichnung: e.target.value }))}
|
||||
/>
|
||||
<Autocomplete
|
||||
options={vendors}
|
||||
getOptionLabel={(o) => o.name}
|
||||
value={vendors.find((v) => v.id === orderForm.lieferant_id) || null}
|
||||
onChange={(_e, v) => setOrderForm((f) => ({ ...f, lieferant_id: v?.id }))}
|
||||
renderInput={(params) => <TextField {...params} label="Lieferant" />}
|
||||
/>
|
||||
<TextField
|
||||
label="Besteller"
|
||||
value={orderForm.besteller_id || ''}
|
||||
onChange={(e) => setOrderForm((f) => ({ ...f, besteller_id: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="Budget"
|
||||
type="number"
|
||||
value={orderForm.budget ?? ''}
|
||||
onChange={(e) => setOrderForm((f) => ({ ...f, budget: e.target.value ? Number(e.target.value) : undefined }))}
|
||||
inputProps={{ min: 0, step: 0.01 }}
|
||||
/>
|
||||
<TextField
|
||||
label="Notizen"
|
||||
multiline
|
||||
rows={3}
|
||||
value={orderForm.notizen || ''}
|
||||
onChange={(e) => setOrderForm((f) => ({ ...f, notizen: e.target.value }))}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setOrderDialogOpen(false)}>Abbrechen</Button>
|
||||
<Button variant="contained" onClick={handleOrderSave} disabled={!orderForm.bezeichnung.trim() || createOrder.isPending}>
|
||||
Erstellen
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* ── Create/Edit Vendor Dialog ── */}
|
||||
<Dialog open={vendorDialogOpen} onClose={closeVendorDialog} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>{editingVendor ? 'Lieferant bearbeiten' : 'Neuer Lieferant'}</DialogTitle>
|
||||
<DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '16px !important' }}>
|
||||
<TextField
|
||||
label="Name"
|
||||
required
|
||||
value={vendorForm.name}
|
||||
onChange={(e) => setVendorForm((f) => ({ ...f, name: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="Kontakt-Name"
|
||||
value={vendorForm.kontakt_name || ''}
|
||||
onChange={(e) => setVendorForm((f) => ({ ...f, kontakt_name: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="E-Mail"
|
||||
type="email"
|
||||
value={vendorForm.email || ''}
|
||||
onChange={(e) => setVendorForm((f) => ({ ...f, email: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="Telefon"
|
||||
value={vendorForm.telefon || ''}
|
||||
onChange={(e) => setVendorForm((f) => ({ ...f, telefon: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="Adresse"
|
||||
value={vendorForm.adresse || ''}
|
||||
onChange={(e) => setVendorForm((f) => ({ ...f, adresse: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="Website"
|
||||
value={vendorForm.website || ''}
|
||||
onChange={(e) => setVendorForm((f) => ({ ...f, website: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="Notizen"
|
||||
multiline
|
||||
rows={3}
|
||||
value={vendorForm.notizen || ''}
|
||||
onChange={(e) => setVendorForm((f) => ({ ...f, notizen: e.target.value }))}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={closeVendorDialog}>Abbrechen</Button>
|
||||
<Button variant="contained" onClick={handleVendorSave} disabled={!vendorForm.name.trim() || createVendor.isPending || updateVendor.isPending}>
|
||||
{editingVendor ? 'Speichern' : 'Erstellen'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* ── Delete Vendor Confirm ── */}
|
||||
<Dialog open={!!deleteVendorTarget} onClose={() => setDeleteVendorTarget(null)}>
|
||||
<DialogTitle>Lieferant löschen</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography>
|
||||
Soll der Lieferant <strong>{deleteVendorTarget?.name}</strong> wirklich gelöscht werden?
|
||||
</Typography>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDeleteVendorTarget(null)}>Abbrechen</Button>
|
||||
<Button color="error" variant="contained" onClick={() => deleteVendorTarget && deleteVendor.mutate(deleteVendorTarget.id)} disabled={deleteVendor.isPending}>
|
||||
Löschen
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,8 @@ import EventQuickAddWidget from '../components/dashboard/EventQuickAddWidget';
|
||||
import LinksWidget from '../components/dashboard/LinksWidget';
|
||||
import BannerWidget from '../components/dashboard/BannerWidget';
|
||||
import WidgetGroup from '../components/dashboard/WidgetGroup';
|
||||
import BestellungenWidget from '../components/dashboard/BestellungenWidget';
|
||||
import ShopWidget from '../components/dashboard/ShopWidget';
|
||||
import { preferencesApi } from '../services/settings';
|
||||
import { configApi } from '../services/config';
|
||||
import { WidgetKey } from '../constants/widgets';
|
||||
@@ -130,11 +132,27 @@ function Dashboard() {
|
||||
</Box>
|
||||
</Fade>
|
||||
)}
|
||||
|
||||
{hasPermission('bestellungen:widget') && widgetVisible('bestellungen') && (
|
||||
<Fade in={!dataLoading} timeout={600} style={{ transitionDelay: '460ms' }}>
|
||||
<Box>
|
||||
<BestellungenWidget />
|
||||
</Box>
|
||||
</Fade>
|
||||
)}
|
||||
|
||||
{hasPermission('shop:widget') && widgetVisible('shopRequests') && (
|
||||
<Fade in={!dataLoading} timeout={600} style={{ transitionDelay: '470ms' }}>
|
||||
<Box>
|
||||
<ShopWidget />
|
||||
</Box>
|
||||
</Fade>
|
||||
)}
|
||||
</WidgetGroup>
|
||||
|
||||
{/* Kalender Group */}
|
||||
<WidgetGroup title="Kalender" gridColumn="1 / -1">
|
||||
{hasPermission('kalender:widget_events') && widgetVisible('events') && (
|
||||
{hasPermission('kalender:view') && widgetVisible('events') && (
|
||||
<Fade in={!dataLoading} timeout={600} style={{ transitionDelay: '480ms' }}>
|
||||
<Box>
|
||||
<UpcomingEventsWidget />
|
||||
@@ -142,7 +160,7 @@ function Dashboard() {
|
||||
</Fade>
|
||||
)}
|
||||
|
||||
{hasPermission('kalender:widget_bookings') && widgetVisible('vehicleBookingList') && (
|
||||
{hasPermission('kalender:view_bookings') && widgetVisible('vehicleBookingList') && (
|
||||
<Fade in={!dataLoading} timeout={600} style={{ transitionDelay: '520ms' }}>
|
||||
<Box>
|
||||
<VehicleBookingListWidget />
|
||||
@@ -150,7 +168,7 @@ function Dashboard() {
|
||||
</Fade>
|
||||
)}
|
||||
|
||||
{hasPermission('kalender:create_bookings') && widgetVisible('vehicleBooking') && (
|
||||
{hasPermission('kalender:manage_bookings') && widgetVisible('vehicleBooking') && (
|
||||
<Fade in={!dataLoading} timeout={600} style={{ transitionDelay: '560ms' }}>
|
||||
<Box>
|
||||
<VehicleBookingQuickAddWidget />
|
||||
@@ -158,7 +176,7 @@ function Dashboard() {
|
||||
</Fade>
|
||||
)}
|
||||
|
||||
{hasPermission('kalender:widget_quick_add') && widgetVisible('eventQuickAdd') && (
|
||||
{hasPermission('kalender:create') && widgetVisible('eventQuickAdd') && (
|
||||
<Fade in={!dataLoading} timeout={600} style={{ transitionDelay: '600ms' }}>
|
||||
<Box>
|
||||
<EventQuickAddWidget />
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
MenuItem,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Fab,
|
||||
CircularProgress,
|
||||
Alert,
|
||||
Popover,
|
||||
|
||||
@@ -202,15 +202,6 @@ function formatDateLong(d: Date): string {
|
||||
return `${days[d.getDay()]}, ${d.getDate()}. ${MONTH_LABELS[d.getMonth()]} ${d.getFullYear()}`;
|
||||
}
|
||||
|
||||
function fromDatetimeLocal(value: string): string {
|
||||
if (!value) return new Date().toISOString();
|
||||
const dtIso = fromGermanDateTime(value);
|
||||
if (dtIso) return new Date(dtIso).toISOString();
|
||||
const dIso = fromGermanDate(value);
|
||||
if (dIso) return new Date(dIso).toISOString();
|
||||
return new Date(value).toISOString();
|
||||
}
|
||||
|
||||
/** ISO string → YYYY-MM-DDTHH:MM (for type="datetime-local") */
|
||||
function toDatetimeLocalValue(iso: string | null | undefined): string {
|
||||
if (!iso) return '';
|
||||
|
||||
622
frontend/src/pages/Shop.tsx
Normal file
622
frontend/src/pages/Shop.tsx
Normal file
@@ -0,0 +1,622 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import {
|
||||
Box, Tab, Tabs, Typography, Card, CardContent, CardActions, Grid, Button, Chip,
|
||||
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper,
|
||||
Dialog, DialogTitle, DialogContent, DialogActions, TextField, IconButton,
|
||||
Badge, MenuItem, Select, FormControl, InputLabel, Autocomplete, Collapse,
|
||||
Divider, Tooltip,
|
||||
} from '@mui/material';
|
||||
import {
|
||||
Add as AddIcon, Delete as DeleteIcon, Edit as EditIcon, ShoppingCart,
|
||||
Check as CheckIcon, Close as CloseIcon, Link as LinkIcon,
|
||||
ExpandMore, ExpandLess,
|
||||
} from '@mui/icons-material';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import DashboardLayout from '../components/dashboard/DashboardLayout';
|
||||
import ChatAwareFab from '../components/shared/ChatAwareFab';
|
||||
import { useNotification } from '../contexts/NotificationContext';
|
||||
import { usePermissionContext } from '../contexts/PermissionContext';
|
||||
import { shopApi } from '../services/shop';
|
||||
import { bestellungApi } from '../services/bestellung';
|
||||
import { SHOP_STATUS_LABELS, SHOP_STATUS_COLORS } from '../types/shop.types';
|
||||
import type { ShopArtikel, ShopArtikelFormData, ShopAnfrageFormItem, ShopAnfrageDetailResponse, ShopAnfrageStatus } from '../types/shop.types';
|
||||
import type { Bestellung } from '../types/bestellung.types';
|
||||
|
||||
const priceFormat = new Intl.NumberFormat('de-AT', { style: 'currency', currency: 'EUR' });
|
||||
|
||||
// ─── Catalog Tab ────────────────────────────────────────────────────────────
|
||||
|
||||
interface DraftItem {
|
||||
artikel_id?: number;
|
||||
bezeichnung: string;
|
||||
menge: number;
|
||||
notizen?: string;
|
||||
}
|
||||
|
||||
function KatalogTab() {
|
||||
const { showSuccess, showError } = useNotification();
|
||||
const { hasPermission } = usePermissionContext();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const canManage = hasPermission('shop:manage_catalog');
|
||||
const canCreate = hasPermission('shop:create_request');
|
||||
|
||||
const [filterKategorie, setFilterKategorie] = useState<string>('');
|
||||
const [draft, setDraft] = useState<DraftItem[]>([]);
|
||||
const [customText, setCustomText] = useState('');
|
||||
const [submitOpen, setSubmitOpen] = useState(false);
|
||||
const [submitNotizen, setSubmitNotizen] = useState('');
|
||||
const [artikelDialogOpen, setArtikelDialogOpen] = useState(false);
|
||||
const [editArtikel, setEditArtikel] = useState<ShopArtikel | null>(null);
|
||||
const [artikelForm, setArtikelForm] = useState<ShopArtikelFormData>({ bezeichnung: '' });
|
||||
|
||||
const { data: items = [], isLoading } = useQuery({
|
||||
queryKey: ['shop', 'items', filterKategorie],
|
||||
queryFn: () => shopApi.getItems(filterKategorie ? { kategorie: filterKategorie } : undefined),
|
||||
});
|
||||
|
||||
const { data: categories = [] } = useQuery({
|
||||
queryKey: ['shop', 'categories'],
|
||||
queryFn: () => shopApi.getCategories(),
|
||||
});
|
||||
|
||||
const createItemMut = useMutation({
|
||||
mutationFn: (data: ShopArtikelFormData) => shopApi.createItem(data),
|
||||
onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['shop'] }); showSuccess('Artikel erstellt'); setArtikelDialogOpen(false); },
|
||||
onError: () => showError('Fehler beim Erstellen'),
|
||||
});
|
||||
const updateItemMut = useMutation({
|
||||
mutationFn: ({ id, data }: { id: number; data: Partial<ShopArtikelFormData> }) => shopApi.updateItem(id, data),
|
||||
onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['shop'] }); showSuccess('Artikel aktualisiert'); setArtikelDialogOpen(false); },
|
||||
onError: () => showError('Fehler beim Aktualisieren'),
|
||||
});
|
||||
const deleteItemMut = useMutation({
|
||||
mutationFn: (id: number) => shopApi.deleteItem(id),
|
||||
onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['shop'] }); showSuccess('Artikel gelöscht'); },
|
||||
onError: () => showError('Fehler beim Löschen'),
|
||||
});
|
||||
const createRequestMut = useMutation({
|
||||
mutationFn: ({ items, notizen }: { items: ShopAnfrageFormItem[]; notizen?: string }) => shopApi.createRequest(items, notizen),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shop'] });
|
||||
showSuccess('Anfrage gesendet');
|
||||
setDraft([]);
|
||||
setSubmitOpen(false);
|
||||
setSubmitNotizen('');
|
||||
},
|
||||
onError: () => showError('Fehler beim Senden der Anfrage'),
|
||||
});
|
||||
|
||||
const addToDraft = (item: ShopArtikel) => {
|
||||
setDraft(prev => {
|
||||
const existing = prev.find(d => d.artikel_id === item.id);
|
||||
if (existing) return prev.map(d => d.artikel_id === item.id ? { ...d, menge: d.menge + 1 } : d);
|
||||
return [...prev, { artikel_id: item.id, bezeichnung: item.bezeichnung, menge: 1 }];
|
||||
});
|
||||
};
|
||||
|
||||
const addCustomToDraft = () => {
|
||||
const text = customText.trim();
|
||||
if (!text) return;
|
||||
setDraft(prev => [...prev, { bezeichnung: text, menge: 1 }]);
|
||||
setCustomText('');
|
||||
};
|
||||
|
||||
const removeDraftItem = (idx: number) => setDraft(prev => prev.filter((_, i) => i !== idx));
|
||||
const updateDraftMenge = (idx: number, menge: number) => {
|
||||
if (menge < 1) return;
|
||||
setDraft(prev => prev.map((d, i) => i === idx ? { ...d, menge } : d));
|
||||
};
|
||||
|
||||
const openNewArtikel = () => {
|
||||
setEditArtikel(null);
|
||||
setArtikelForm({ bezeichnung: '' });
|
||||
setArtikelDialogOpen(true);
|
||||
};
|
||||
const openEditArtikel = (a: ShopArtikel) => {
|
||||
setEditArtikel(a);
|
||||
setArtikelForm({ bezeichnung: a.bezeichnung, beschreibung: a.beschreibung, kategorie: a.kategorie, geschaetzter_preis: a.geschaetzter_preis });
|
||||
setArtikelDialogOpen(true);
|
||||
};
|
||||
const saveArtikel = () => {
|
||||
if (!artikelForm.bezeichnung.trim()) return;
|
||||
if (editArtikel) updateItemMut.mutate({ id: editArtikel.id, data: artikelForm });
|
||||
else createItemMut.mutate(artikelForm);
|
||||
};
|
||||
|
||||
const handleSubmitRequest = () => {
|
||||
if (draft.length === 0) return;
|
||||
createRequestMut.mutate({
|
||||
items: draft.map(d => ({ artikel_id: d.artikel_id, bezeichnung: d.bezeichnung, menge: d.menge, notizen: d.notizen })),
|
||||
notizen: submitNotizen || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
{/* Filter */}
|
||||
<Box sx={{ display: 'flex', gap: 2, mb: 3, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<FormControl size="small" sx={{ minWidth: 200 }}>
|
||||
<InputLabel>Kategorie</InputLabel>
|
||||
<Select value={filterKategorie} label="Kategorie" onChange={e => setFilterKategorie(e.target.value)}>
|
||||
<MenuItem value="">Alle</MenuItem>
|
||||
{categories.map(c => <MenuItem key={c} value={c}>{c}</MenuItem>)}
|
||||
</Select>
|
||||
</FormControl>
|
||||
{canCreate && (
|
||||
<Badge badgeContent={draft.length} color="primary">
|
||||
<Button startIcon={<ShoppingCart />} variant="outlined" onClick={() => draft.length > 0 && setSubmitOpen(true)} disabled={draft.length === 0}>
|
||||
Anfrage ({draft.length})
|
||||
</Button>
|
||||
</Badge>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Catalog grid */}
|
||||
{isLoading ? (
|
||||
<Typography color="text.secondary">Lade Katalog...</Typography>
|
||||
) : items.length === 0 ? (
|
||||
<Typography color="text.secondary">Keine Artikel vorhanden.</Typography>
|
||||
) : (
|
||||
<Grid container spacing={2}>
|
||||
{items.map(item => (
|
||||
<Grid item xs={12} sm={6} md={4} key={item.id}>
|
||||
<Card variant="outlined" sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
{item.bild_pfad ? (
|
||||
<Box sx={{ height: 160, backgroundImage: `url(${item.bild_pfad})`, backgroundSize: 'cover', backgroundPosition: 'center', borderBottom: '1px solid', borderColor: 'divider' }} />
|
||||
) : (
|
||||
<Box sx={{ height: 160, display: 'flex', alignItems: 'center', justifyContent: 'center', bgcolor: 'action.hover', borderBottom: '1px solid', borderColor: 'divider' }}>
|
||||
<ShoppingCart sx={{ fontSize: 48, color: 'text.disabled' }} />
|
||||
</Box>
|
||||
)}
|
||||
<CardContent sx={{ flexGrow: 1 }}>
|
||||
<Typography variant="subtitle1" fontWeight={600}>{item.bezeichnung}</Typography>
|
||||
{item.beschreibung && <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>{item.beschreibung}</Typography>}
|
||||
<Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center' }}>
|
||||
{item.kategorie && <Chip label={item.kategorie} size="small" />}
|
||||
{item.geschaetzter_preis != null && (
|
||||
<Typography variant="body2" color="text.secondary">ca. {priceFormat.format(item.geschaetzter_preis)}</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</CardContent>
|
||||
<CardActions sx={{ justifyContent: 'space-between' }}>
|
||||
{canCreate && (
|
||||
<Button size="small" startIcon={<AddIcon />} onClick={() => addToDraft(item)}>Hinzufügen</Button>
|
||||
)}
|
||||
{canManage && (
|
||||
<Box>
|
||||
<IconButton size="small" onClick={() => openEditArtikel(item)}><EditIcon fontSize="small" /></IconButton>
|
||||
<IconButton size="small" color="error" onClick={() => deleteItemMut.mutate(item.id)}><DeleteIcon fontSize="small" /></IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</CardActions>
|
||||
</Card>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
)}
|
||||
|
||||
{/* Custom item + draft summary */}
|
||||
{canCreate && draft.length > 0 && (
|
||||
<Paper variant="outlined" sx={{ mt: 3, p: 2 }}>
|
||||
<Typography variant="subtitle2" sx={{ mb: 1 }}>Anfrage-Entwurf</Typography>
|
||||
{draft.map((d, idx) => (
|
||||
<Box key={idx} sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
|
||||
<Typography variant="body2" sx={{ flexGrow: 1 }}>{d.bezeichnung}</Typography>
|
||||
<TextField size="small" type="number" value={d.menge} onChange={e => updateDraftMenge(idx, Number(e.target.value))} sx={{ width: 70 }} inputProps={{ min: 1 }} />
|
||||
<IconButton size="small" onClick={() => removeDraftItem(idx)}><DeleteIcon fontSize="small" /></IconButton>
|
||||
</Box>
|
||||
))}
|
||||
<Divider sx={{ my: 1 }} />
|
||||
<Box sx={{ display: 'flex', gap: 1 }}>
|
||||
<TextField size="small" placeholder="Eigener Artikel (Freitext)" value={customText} onChange={e => setCustomText(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addCustomToDraft(); }} sx={{ flexGrow: 1 }} />
|
||||
<Button size="small" onClick={addCustomToDraft} disabled={!customText.trim()}>Hinzufügen</Button>
|
||||
</Box>
|
||||
<Button variant="contained" sx={{ mt: 1.5 }} startIcon={<ShoppingCart />} onClick={() => setSubmitOpen(true)}>Anfrage absenden</Button>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Submit dialog */}
|
||||
<Dialog open={submitOpen} onClose={() => setSubmitOpen(false)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>Anfrage absenden</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography variant="body2" sx={{ mb: 1 }}>Folgende Positionen werden angefragt:</Typography>
|
||||
{draft.map((d, idx) => (
|
||||
<Typography key={idx} variant="body2">- {d.menge}x {d.bezeichnung}</Typography>
|
||||
))}
|
||||
<TextField fullWidth label="Notizen (optional)" value={submitNotizen} onChange={e => setSubmitNotizen(e.target.value)} multiline rows={2} sx={{ mt: 2 }} />
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setSubmitOpen(false)}>Abbrechen</Button>
|
||||
<Button variant="contained" onClick={handleSubmitRequest} disabled={createRequestMut.isPending}>Absenden</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Artikel create/edit dialog */}
|
||||
<Dialog open={artikelDialogOpen} onClose={() => setArtikelDialogOpen(false)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>{editArtikel ? 'Artikel bearbeiten' : 'Neuer Artikel'}</DialogTitle>
|
||||
<DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 1 }}>
|
||||
<TextField label="Bezeichnung" required value={artikelForm.bezeichnung} onChange={e => setArtikelForm(f => ({ ...f, bezeichnung: e.target.value }))} />
|
||||
<TextField label="Beschreibung" multiline rows={2} value={artikelForm.beschreibung ?? ''} onChange={e => setArtikelForm(f => ({ ...f, beschreibung: e.target.value }))} />
|
||||
<Autocomplete
|
||||
freeSolo
|
||||
options={categories}
|
||||
value={artikelForm.kategorie ?? ''}
|
||||
onInputChange={(_, val) => setArtikelForm(f => ({ ...f, kategorie: val || undefined }))}
|
||||
renderInput={params => <TextField {...params} label="Kategorie" />}
|
||||
/>
|
||||
<TextField
|
||||
label="Geschätzter Preis (EUR)"
|
||||
type="number"
|
||||
value={artikelForm.geschaetzter_preis ?? ''}
|
||||
onChange={e => setArtikelForm(f => ({ ...f, geschaetzter_preis: e.target.value ? Number(e.target.value) : undefined }))}
|
||||
inputProps={{ min: 0, step: 0.01 }}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setArtikelDialogOpen(false)}>Abbrechen</Button>
|
||||
<Button variant="contained" onClick={saveArtikel} disabled={!artikelForm.bezeichnung.trim() || createItemMut.isPending || updateItemMut.isPending}>
|
||||
Speichern
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* FAB for new catalog item */}
|
||||
{canManage && (
|
||||
<ChatAwareFab onClick={openNewArtikel} aria-label="Artikel hinzufügen">
|
||||
<AddIcon />
|
||||
</ChatAwareFab>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── My Requests Tab ────────────────────────────────────────────────────────
|
||||
|
||||
function MeineAnfragenTab() {
|
||||
const [expandedId, setExpandedId] = useState<number | null>(null);
|
||||
|
||||
const { data: requests = [], isLoading } = useQuery({
|
||||
queryKey: ['shop', 'myRequests'],
|
||||
queryFn: () => shopApi.getMyRequests(),
|
||||
});
|
||||
|
||||
const { data: detail } = useQuery<ShopAnfrageDetailResponse>({
|
||||
queryKey: ['shop', 'request', expandedId],
|
||||
queryFn: () => shopApi.getRequest(expandedId!),
|
||||
enabled: expandedId != null,
|
||||
});
|
||||
|
||||
if (isLoading) return <Typography color="text.secondary">Lade Anfragen...</Typography>;
|
||||
if (requests.length === 0) return <Typography color="text.secondary">Keine Anfragen vorhanden.</Typography>;
|
||||
|
||||
return (
|
||||
<TableContainer component={Paper} variant="outlined">
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell width={40} />
|
||||
<TableCell>#</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Positionen</TableCell>
|
||||
<TableCell>Erstellt am</TableCell>
|
||||
<TableCell>Admin Notizen</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{requests.map(r => (
|
||||
<>
|
||||
<TableRow key={r.id} hover sx={{ cursor: 'pointer' }} onClick={() => setExpandedId(prev => prev === r.id ? null : r.id)}>
|
||||
<TableCell>{expandedId === r.id ? <ExpandLess fontSize="small" /> : <ExpandMore fontSize="small" />}</TableCell>
|
||||
<TableCell>{r.id}</TableCell>
|
||||
<TableCell><Chip label={SHOP_STATUS_LABELS[r.status]} color={SHOP_STATUS_COLORS[r.status]} size="small" /></TableCell>
|
||||
<TableCell>{r.items_count ?? '-'}</TableCell>
|
||||
<TableCell>{new Date(r.erstellt_am).toLocaleDateString('de-AT')}</TableCell>
|
||||
<TableCell>{r.admin_notizen || '-'}</TableCell>
|
||||
</TableRow>
|
||||
{expandedId === r.id && (
|
||||
<TableRow key={`${r.id}-detail`}>
|
||||
<TableCell colSpan={6} sx={{ py: 0 }}>
|
||||
<Collapse in timeout="auto" unmountOnExit>
|
||||
<Box sx={{ p: 2 }}>
|
||||
{r.notizen && <Typography variant="body2" sx={{ mb: 1 }}>Notizen: {r.notizen}</Typography>}
|
||||
{detail ? (
|
||||
<>
|
||||
{detail.positionen.map(p => (
|
||||
<Typography key={p.id} variant="body2">- {p.menge}x {p.bezeichnung}{p.notizen ? ` (${p.notizen})` : ''}</Typography>
|
||||
))}
|
||||
{detail.linked_bestellungen && detail.linked_bestellungen.length > 0 && (
|
||||
<Box sx={{ mt: 1 }}>
|
||||
<Typography variant="caption" color="text.secondary">Verknüpfte Bestellungen:</Typography>
|
||||
{detail.linked_bestellungen.map(b => (
|
||||
<Chip key={b.id} label={`#${b.id} ${b.bezeichnung}`} size="small" sx={{ ml: 0.5 }} />
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<Typography variant="body2" color="text.secondary">Lade Details...</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Collapse>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Admin All Requests Tab ─────────────────────────────────────────────────
|
||||
|
||||
function AlleAnfragenTab() {
|
||||
const { showSuccess, showError } = useNotification();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [statusFilter, setStatusFilter] = useState<string>('');
|
||||
const [expandedId, setExpandedId] = useState<number | null>(null);
|
||||
const [actionDialog, setActionDialog] = useState<{ id: number; action: 'genehmigt' | 'abgelehnt' } | null>(null);
|
||||
const [adminNotizen, setAdminNotizen] = useState('');
|
||||
const [linkDialog, setLinkDialog] = useState<number | null>(null);
|
||||
const [selectedBestellung, setSelectedBestellung] = useState<Bestellung | null>(null);
|
||||
|
||||
const { data: requests = [], isLoading } = useQuery({
|
||||
queryKey: ['shop', 'requests', statusFilter],
|
||||
queryFn: () => shopApi.getRequests(statusFilter ? { status: statusFilter } : undefined),
|
||||
});
|
||||
|
||||
const { data: detail } = useQuery<ShopAnfrageDetailResponse>({
|
||||
queryKey: ['shop', 'request', expandedId],
|
||||
queryFn: () => shopApi.getRequest(expandedId!),
|
||||
enabled: expandedId != null,
|
||||
});
|
||||
|
||||
const { data: bestellungen = [] } = useQuery({
|
||||
queryKey: ['bestellungen'],
|
||||
queryFn: () => bestellungApi.getOrders(),
|
||||
enabled: linkDialog != null,
|
||||
});
|
||||
|
||||
const statusMut = useMutation({
|
||||
mutationFn: ({ id, status, notes }: { id: number; status: string; notes?: string }) => shopApi.updateRequestStatus(id, status, notes),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shop'] });
|
||||
showSuccess('Status aktualisiert');
|
||||
setActionDialog(null);
|
||||
setAdminNotizen('');
|
||||
},
|
||||
onError: () => showError('Fehler beim Aktualisieren'),
|
||||
});
|
||||
|
||||
const linkMut = useMutation({
|
||||
mutationFn: ({ anfrageId, bestellungId }: { anfrageId: number; bestellungId: number }) => shopApi.linkToOrder(anfrageId, bestellungId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shop'] });
|
||||
showSuccess('Verknüpfung erstellt');
|
||||
setLinkDialog(null);
|
||||
setSelectedBestellung(null);
|
||||
},
|
||||
onError: () => showError('Fehler beim Verknüpfen'),
|
||||
});
|
||||
|
||||
const handleAction = () => {
|
||||
if (!actionDialog) return;
|
||||
statusMut.mutate({ id: actionDialog.id, status: actionDialog.action, notes: adminNotizen || undefined });
|
||||
};
|
||||
|
||||
if (isLoading) return <Typography color="text.secondary">Lade Anfragen...</Typography>;
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<FormControl size="small" sx={{ minWidth: 200, mb: 2 }}>
|
||||
<InputLabel>Status Filter</InputLabel>
|
||||
<Select value={statusFilter} label="Status Filter" onChange={e => setStatusFilter(e.target.value)}>
|
||||
<MenuItem value="">Alle</MenuItem>
|
||||
{(Object.keys(SHOP_STATUS_LABELS) as ShopAnfrageStatus[]).map(s => (
|
||||
<MenuItem key={s} value={s}>{SHOP_STATUS_LABELS[s]}</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{requests.length === 0 ? (
|
||||
<Typography color="text.secondary">Keine Anfragen vorhanden.</Typography>
|
||||
) : (
|
||||
<TableContainer component={Paper} variant="outlined">
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell width={40} />
|
||||
<TableCell>#</TableCell>
|
||||
<TableCell>Anfrager</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Positionen</TableCell>
|
||||
<TableCell>Erstellt am</TableCell>
|
||||
<TableCell>Aktionen</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{requests.map(r => (
|
||||
<>
|
||||
<TableRow key={r.id} hover sx={{ cursor: 'pointer' }} onClick={() => setExpandedId(prev => prev === r.id ? null : r.id)}>
|
||||
<TableCell>{expandedId === r.id ? <ExpandLess fontSize="small" /> : <ExpandMore fontSize="small" />}</TableCell>
|
||||
<TableCell>{r.id}</TableCell>
|
||||
<TableCell>{r.anfrager_name || r.anfrager_id}</TableCell>
|
||||
<TableCell><Chip label={SHOP_STATUS_LABELS[r.status]} color={SHOP_STATUS_COLORS[r.status]} size="small" /></TableCell>
|
||||
<TableCell>{r.items_count ?? '-'}</TableCell>
|
||||
<TableCell>{new Date(r.erstellt_am).toLocaleDateString('de-AT')}</TableCell>
|
||||
<TableCell onClick={e => e.stopPropagation()}>
|
||||
<Box sx={{ display: 'flex', gap: 0.5 }}>
|
||||
{r.status === 'offen' && (
|
||||
<>
|
||||
<Tooltip title="Genehmigen">
|
||||
<IconButton size="small" color="success" onClick={() => { setActionDialog({ id: r.id, action: 'genehmigt' }); setAdminNotizen(''); }}>
|
||||
<CheckIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="Ablehnen">
|
||||
<IconButton size="small" color="error" onClick={() => { setActionDialog({ id: r.id, action: 'abgelehnt' }); setAdminNotizen(''); }}>
|
||||
<CloseIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
{r.status === 'genehmigt' && (
|
||||
<Tooltip title="Mit Bestellung verknüpfen">
|
||||
<IconButton size="small" color="primary" onClick={() => setLinkDialog(r.id)}>
|
||||
<LinkIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Box>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{expandedId === r.id && (
|
||||
<TableRow key={`${r.id}-detail`}>
|
||||
<TableCell colSpan={7} sx={{ py: 0 }}>
|
||||
<Collapse in timeout="auto" unmountOnExit>
|
||||
<Box sx={{ p: 2 }}>
|
||||
{r.notizen && <Typography variant="body2" sx={{ mb: 1 }}>Notizen: {r.notizen}</Typography>}
|
||||
{r.admin_notizen && <Typography variant="body2" sx={{ mb: 1 }}>Admin Notizen: {r.admin_notizen}</Typography>}
|
||||
{detail && detail.anfrage.id === r.id ? (
|
||||
<>
|
||||
{detail.positionen.map(p => (
|
||||
<Typography key={p.id} variant="body2">- {p.menge}x {p.bezeichnung}{p.notizen ? ` (${p.notizen})` : ''}</Typography>
|
||||
))}
|
||||
{detail.linked_bestellungen && detail.linked_bestellungen.length > 0 && (
|
||||
<Box sx={{ mt: 1 }}>
|
||||
<Typography variant="caption" color="text.secondary">Verknüpfte Bestellungen:</Typography>
|
||||
{detail.linked_bestellungen.map(b => (
|
||||
<Chip key={b.id} label={`#${b.id} ${b.bezeichnung}`} size="small" sx={{ ml: 0.5 }} />
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<Typography variant="body2" color="text.secondary">Lade Details...</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Collapse>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)}
|
||||
|
||||
{/* Approve/Reject dialog */}
|
||||
<Dialog open={actionDialog != null} onClose={() => setActionDialog(null)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>{actionDialog?.action === 'genehmigt' ? 'Anfrage genehmigen' : 'Anfrage ablehnen'}</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Admin Notizen (optional)"
|
||||
value={adminNotizen}
|
||||
onChange={e => setAdminNotizen(e.target.value)}
|
||||
multiline
|
||||
rows={2}
|
||||
sx={{ mt: 1 }}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setActionDialog(null)}>Abbrechen</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
color={actionDialog?.action === 'genehmigt' ? 'success' : 'error'}
|
||||
onClick={handleAction}
|
||||
disabled={statusMut.isPending}
|
||||
>
|
||||
{actionDialog?.action === 'genehmigt' ? 'Genehmigen' : 'Ablehnen'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Link to order dialog */}
|
||||
<Dialog open={linkDialog != null} onClose={() => { setLinkDialog(null); setSelectedBestellung(null); }} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>Mit Bestellung verknüpfen</DialogTitle>
|
||||
<DialogContent>
|
||||
<Autocomplete
|
||||
options={bestellungen}
|
||||
getOptionLabel={(o) => `#${o.id} – ${o.bezeichnung}`}
|
||||
value={selectedBestellung}
|
||||
onChange={(_, v) => setSelectedBestellung(v)}
|
||||
renderInput={params => <TextField {...params} label="Bestellung auswählen" sx={{ mt: 1 }} />}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => { setLinkDialog(null); setSelectedBestellung(null); }}>Abbrechen</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!selectedBestellung || linkMut.isPending}
|
||||
onClick={() => { if (linkDialog && selectedBestellung) linkMut.mutate({ anfrageId: linkDialog, bestellungId: selectedBestellung.id }); }}
|
||||
>
|
||||
Verknüpfen
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Page ──────────────────────────────────────────────────────────────
|
||||
|
||||
export default function Shop() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { hasPermission } = usePermissionContext();
|
||||
|
||||
const canView = hasPermission('shop:view');
|
||||
const canCreate = hasPermission('shop:create_request');
|
||||
const canApprove = hasPermission('shop:approve_requests');
|
||||
|
||||
const tabCount = 1 + (canCreate ? 1 : 0) + (canApprove ? 1 : 0);
|
||||
|
||||
const [activeTab, setActiveTab] = useState(() => {
|
||||
const t = Number(searchParams.get('tab'));
|
||||
return t >= 0 && t < tabCount ? t : 0;
|
||||
});
|
||||
|
||||
const handleTabChange = (_: React.SyntheticEvent, val: number) => {
|
||||
setActiveTab(val);
|
||||
setSearchParams({ tab: String(val) }, { replace: true });
|
||||
};
|
||||
|
||||
const tabIndex = useMemo(() => {
|
||||
const map: Record<string, number> = { katalog: 0 };
|
||||
let next = 1;
|
||||
if (canCreate) { map.meine = next; next++; }
|
||||
if (canApprove) { map.alle = next; }
|
||||
return map;
|
||||
}, [canCreate, canApprove]);
|
||||
|
||||
if (!canView) {
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<Typography>Keine Berechtigung.</Typography>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<Typography variant="h5" fontWeight={700} sx={{ mb: 2 }}>Shop</Typography>
|
||||
|
||||
<Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
|
||||
<Tabs value={activeTab} onChange={handleTabChange}>
|
||||
<Tab label="Katalog" />
|
||||
{canCreate && <Tab label="Meine Anfragen" />}
|
||||
{canApprove && <Tab label="Alle Anfragen" />}
|
||||
</Tabs>
|
||||
</Box>
|
||||
|
||||
{activeTab === tabIndex.katalog && <KatalogTab />}
|
||||
{canCreate && activeTab === tabIndex.meine && <MeineAnfragenTab />}
|
||||
{canApprove && activeTab === tabIndex.alle && <AlleAnfragenTab />}
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
117
frontend/src/services/bestellung.ts
Normal file
117
frontend/src/services/bestellung.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { api } from './api';
|
||||
import type {
|
||||
Lieferant,
|
||||
LieferantFormData,
|
||||
Bestellung,
|
||||
BestellungFormData,
|
||||
BestellungDetailResponse,
|
||||
Bestellposition,
|
||||
BestellpositionFormData,
|
||||
BestellungDatei,
|
||||
BestellungErinnerung,
|
||||
ErinnerungFormData,
|
||||
BestellungHistorie,
|
||||
} from '../types/bestellung.types';
|
||||
|
||||
export const bestellungApi = {
|
||||
// ── Vendors ──
|
||||
getVendors: async (): Promise<Lieferant[]> => {
|
||||
const r = await api.get('/api/bestellungen/vendors');
|
||||
return r.data.data;
|
||||
},
|
||||
getVendor: async (id: number): Promise<Lieferant> => {
|
||||
const r = await api.get(`/api/bestellungen/vendors/${id}`);
|
||||
return r.data.data;
|
||||
},
|
||||
createVendor: async (data: LieferantFormData): Promise<Lieferant> => {
|
||||
const r = await api.post('/api/bestellungen/vendors', data);
|
||||
return r.data.data;
|
||||
},
|
||||
updateVendor: async (id: number, data: LieferantFormData): Promise<Lieferant> => {
|
||||
const r = await api.patch(`/api/bestellungen/vendors/${id}`, data);
|
||||
return r.data.data;
|
||||
},
|
||||
deleteVendor: async (id: number): Promise<void> => {
|
||||
await api.delete(`/api/bestellungen/vendors/${id}`);
|
||||
},
|
||||
|
||||
// ── Orders ──
|
||||
getOrders: async (filters?: { status?: string; lieferant_id?: number }): Promise<Bestellung[]> => {
|
||||
const params = new URLSearchParams();
|
||||
if (filters?.status) params.set('status', filters.status);
|
||||
if (filters?.lieferant_id) params.set('lieferant_id', String(filters.lieferant_id));
|
||||
const r = await api.get(`/api/bestellungen?${params.toString()}`);
|
||||
return r.data.data;
|
||||
},
|
||||
getOrder: async (id: number): Promise<BestellungDetailResponse> => {
|
||||
const r = await api.get(`/api/bestellungen/${id}`);
|
||||
return r.data.data;
|
||||
},
|
||||
createOrder: async (data: BestellungFormData): Promise<Bestellung> => {
|
||||
const r = await api.post('/api/bestellungen', data);
|
||||
return r.data.data;
|
||||
},
|
||||
updateOrder: async (id: number, data: Partial<BestellungFormData>): Promise<Bestellung> => {
|
||||
const r = await api.patch(`/api/bestellungen/${id}`, data);
|
||||
return r.data.data;
|
||||
},
|
||||
deleteOrder: async (id: number): Promise<void> => {
|
||||
await api.delete(`/api/bestellungen/${id}`);
|
||||
},
|
||||
updateStatus: async (id: number, status: string): Promise<Bestellung> => {
|
||||
const r = await api.patch(`/api/bestellungen/${id}/status`, { status });
|
||||
return r.data.data;
|
||||
},
|
||||
|
||||
// ── Line Items ──
|
||||
addLineItem: async (orderId: number, data: BestellpositionFormData): Promise<Bestellposition> => {
|
||||
const r = await api.post(`/api/bestellungen/${orderId}/items`, data);
|
||||
return r.data.data;
|
||||
},
|
||||
updateLineItem: async (itemId: number, data: Partial<BestellpositionFormData>): Promise<Bestellposition> => {
|
||||
const r = await api.patch(`/api/bestellungen/items/${itemId}`, data);
|
||||
return r.data.data;
|
||||
},
|
||||
deleteLineItem: async (itemId: number): Promise<void> => {
|
||||
await api.delete(`/api/bestellungen/items/${itemId}`);
|
||||
},
|
||||
updateReceivedQty: async (itemId: number, menge: number): Promise<Bestellposition> => {
|
||||
const r = await api.patch(`/api/bestellungen/items/${itemId}/received`, { erhalten_menge: menge });
|
||||
return r.data.data;
|
||||
},
|
||||
|
||||
// ── Files ──
|
||||
uploadFile: async (orderId: number, file: File): Promise<BestellungDatei> => {
|
||||
const formData = new FormData();
|
||||
formData.append('datei', file);
|
||||
const r = await api.post(`/api/bestellungen/${orderId}/files`, formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
return r.data.data;
|
||||
},
|
||||
deleteFile: async (fileId: number): Promise<void> => {
|
||||
await api.delete(`/api/bestellungen/files/${fileId}`);
|
||||
},
|
||||
getFiles: async (orderId: number): Promise<BestellungDatei[]> => {
|
||||
const r = await api.get(`/api/bestellungen/${orderId}/files`);
|
||||
return r.data.data;
|
||||
},
|
||||
|
||||
// ── Reminders ──
|
||||
addReminder: async (orderId: number, data: ErinnerungFormData): Promise<BestellungErinnerung> => {
|
||||
const r = await api.post(`/api/bestellungen/${orderId}/reminders`, data);
|
||||
return r.data.data;
|
||||
},
|
||||
markReminderDone: async (reminderId: number): Promise<void> => {
|
||||
await api.patch(`/api/bestellungen/reminders/${reminderId}`, { erledigt: true });
|
||||
},
|
||||
deleteReminder: async (reminderId: number): Promise<void> => {
|
||||
await api.delete(`/api/bestellungen/reminders/${reminderId}`);
|
||||
},
|
||||
|
||||
// ── History ──
|
||||
getHistory: async (orderId: number): Promise<BestellungHistorie[]> => {
|
||||
const r = await api.get(`/api/bestellungen/${orderId}/history`);
|
||||
return r.data.data;
|
||||
},
|
||||
};
|
||||
73
frontend/src/services/shop.ts
Normal file
73
frontend/src/services/shop.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { api } from './api';
|
||||
import type {
|
||||
ShopArtikel,
|
||||
ShopArtikelFormData,
|
||||
ShopAnfrage,
|
||||
ShopAnfrageDetailResponse,
|
||||
ShopAnfrageFormItem,
|
||||
} from '../types/shop.types';
|
||||
|
||||
export const shopApi = {
|
||||
// ── Catalog Items ──
|
||||
getItems: async (filters?: { kategorie?: string; aktiv?: boolean }): Promise<ShopArtikel[]> => {
|
||||
const params = new URLSearchParams();
|
||||
if (filters?.kategorie) params.set('kategorie', filters.kategorie);
|
||||
if (filters?.aktiv !== undefined) params.set('aktiv', String(filters.aktiv));
|
||||
const r = await api.get(`/api/shop/items?${params.toString()}`);
|
||||
return r.data.data;
|
||||
},
|
||||
getItem: async (id: number): Promise<ShopArtikel> => {
|
||||
const r = await api.get(`/api/shop/items/${id}`);
|
||||
return r.data.data;
|
||||
},
|
||||
createItem: async (data: ShopArtikelFormData): Promise<ShopArtikel> => {
|
||||
const r = await api.post('/api/shop/items', data);
|
||||
return r.data.data;
|
||||
},
|
||||
updateItem: async (id: number, data: Partial<ShopArtikelFormData>): Promise<ShopArtikel> => {
|
||||
const r = await api.patch(`/api/shop/items/${id}`, data);
|
||||
return r.data.data;
|
||||
},
|
||||
deleteItem: async (id: number): Promise<void> => {
|
||||
await api.delete(`/api/shop/items/${id}`);
|
||||
},
|
||||
getCategories: async (): Promise<string[]> => {
|
||||
const r = await api.get('/api/shop/categories');
|
||||
return r.data.data;
|
||||
},
|
||||
|
||||
// ── Requests ──
|
||||
getRequests: async (filters?: { status?: string }): Promise<ShopAnfrage[]> => {
|
||||
const params = new URLSearchParams();
|
||||
if (filters?.status) params.set('status', filters.status);
|
||||
const r = await api.get(`/api/shop/requests?${params.toString()}`);
|
||||
return r.data.data;
|
||||
},
|
||||
getMyRequests: async (): Promise<ShopAnfrage[]> => {
|
||||
const r = await api.get('/api/shop/requests/my');
|
||||
return r.data.data;
|
||||
},
|
||||
getRequest: async (id: number): Promise<ShopAnfrageDetailResponse> => {
|
||||
const r = await api.get(`/api/shop/requests/${id}`);
|
||||
return r.data.data;
|
||||
},
|
||||
createRequest: async (items: ShopAnfrageFormItem[], notizen?: string): Promise<ShopAnfrage> => {
|
||||
const r = await api.post('/api/shop/requests', { items, notizen });
|
||||
return r.data.data;
|
||||
},
|
||||
updateRequestStatus: async (id: number, status: string, admin_notizen?: string): Promise<ShopAnfrage> => {
|
||||
const r = await api.patch(`/api/shop/requests/${id}/status`, { status, admin_notizen });
|
||||
return r.data.data;
|
||||
},
|
||||
deleteRequest: async (id: number): Promise<void> => {
|
||||
await api.delete(`/api/shop/requests/${id}`);
|
||||
},
|
||||
|
||||
// ── Linking ──
|
||||
linkToOrder: async (anfrageId: number, bestellungId: number): Promise<void> => {
|
||||
await api.post(`/api/shop/requests/${anfrageId}/link`, { bestellung_id: bestellungId });
|
||||
},
|
||||
unlinkFromOrder: async (anfrageId: number, bestellungId: number): Promise<void> => {
|
||||
await api.delete(`/api/shop/requests/${anfrageId}/link/${bestellungId}`);
|
||||
},
|
||||
};
|
||||
156
frontend/src/types/bestellung.types.ts
Normal file
156
frontend/src/types/bestellung.types.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
// Bestellungen (Vendor Orders) types
|
||||
|
||||
// ── Vendors ──
|
||||
|
||||
export interface Lieferant {
|
||||
id: number;
|
||||
name: string;
|
||||
kontakt_name?: string;
|
||||
email?: string;
|
||||
telefon?: string;
|
||||
adresse?: string;
|
||||
website?: string;
|
||||
notizen?: string;
|
||||
erstellt_von?: string;
|
||||
erstellt_am: string;
|
||||
aktualisiert_am: string;
|
||||
}
|
||||
|
||||
export interface LieferantFormData {
|
||||
name: string;
|
||||
kontakt_name?: string;
|
||||
email?: string;
|
||||
telefon?: string;
|
||||
adresse?: string;
|
||||
website?: string;
|
||||
notizen?: string;
|
||||
}
|
||||
|
||||
// ── Orders ──
|
||||
|
||||
export type BestellungStatus = 'entwurf' | 'erstellt' | 'bestellt' | 'teillieferung' | 'vollstaendig' | 'abgeschlossen';
|
||||
|
||||
export const BESTELLUNG_STATUS_LABELS: Record<BestellungStatus, string> = {
|
||||
entwurf: 'Entwurf',
|
||||
erstellt: 'Erstellt',
|
||||
bestellt: 'Bestellt',
|
||||
teillieferung: 'Teillieferung',
|
||||
vollstaendig: 'Vollständig',
|
||||
abgeschlossen: 'Abgeschlossen',
|
||||
};
|
||||
|
||||
export const BESTELLUNG_STATUS_COLORS: Record<BestellungStatus, 'default' | 'info' | 'primary' | 'warning' | 'success'> = {
|
||||
entwurf: 'default',
|
||||
erstellt: 'info',
|
||||
bestellt: 'primary',
|
||||
teillieferung: 'warning',
|
||||
vollstaendig: 'success',
|
||||
abgeschlossen: 'success',
|
||||
};
|
||||
|
||||
export interface Bestellung {
|
||||
id: number;
|
||||
bezeichnung: string;
|
||||
lieferant_id?: number;
|
||||
lieferant_name?: string;
|
||||
besteller_id?: string;
|
||||
besteller_name?: string;
|
||||
status: BestellungStatus;
|
||||
budget?: number;
|
||||
notizen?: string;
|
||||
erstellt_von?: string;
|
||||
erstellt_am: string;
|
||||
aktualisiert_am: string;
|
||||
bestellt_am?: string;
|
||||
abgeschlossen_am?: string;
|
||||
// Computed
|
||||
total_cost?: number;
|
||||
items_count?: number;
|
||||
}
|
||||
|
||||
export interface BestellungFormData {
|
||||
bezeichnung: string;
|
||||
lieferant_id?: number;
|
||||
besteller_id?: string;
|
||||
status?: BestellungStatus;
|
||||
budget?: number;
|
||||
notizen?: string;
|
||||
}
|
||||
|
||||
// ── Line Items ──
|
||||
|
||||
export interface Bestellposition {
|
||||
id: number;
|
||||
bestellung_id: number;
|
||||
bezeichnung: string;
|
||||
artikelnummer?: string;
|
||||
menge: number;
|
||||
einheit: string;
|
||||
einzelpreis?: number;
|
||||
erhalten_menge: number;
|
||||
notizen?: string;
|
||||
erstellt_am: string;
|
||||
aktualisiert_am: string;
|
||||
}
|
||||
|
||||
export interface BestellpositionFormData {
|
||||
bezeichnung: string;
|
||||
artikelnummer?: string;
|
||||
menge: number;
|
||||
einheit?: string;
|
||||
einzelpreis?: number;
|
||||
notizen?: string;
|
||||
}
|
||||
|
||||
// ── File Attachments ──
|
||||
|
||||
export interface BestellungDatei {
|
||||
id: number;
|
||||
bestellung_id: number;
|
||||
dateiname: string;
|
||||
dateipfad: string;
|
||||
dateityp: string;
|
||||
dateigroesse?: number;
|
||||
thumbnail_pfad?: string;
|
||||
hochgeladen_von?: string;
|
||||
hochgeladen_am: string;
|
||||
}
|
||||
|
||||
// ── Reminders ──
|
||||
|
||||
export interface BestellungErinnerung {
|
||||
id: number;
|
||||
bestellung_id: number;
|
||||
faellig_am: string;
|
||||
nachricht?: string;
|
||||
erledigt: boolean;
|
||||
erstellt_von?: string;
|
||||
erstellt_am: string;
|
||||
}
|
||||
|
||||
export interface ErinnerungFormData {
|
||||
faellig_am: string;
|
||||
nachricht?: string;
|
||||
}
|
||||
|
||||
// ── Audit Trail ──
|
||||
|
||||
export interface BestellungHistorie {
|
||||
id: number;
|
||||
bestellung_id: number;
|
||||
aktion: string;
|
||||
details?: Record<string, unknown>;
|
||||
erstellt_von?: string;
|
||||
erstellt_von_name?: string;
|
||||
erstellt_am: string;
|
||||
}
|
||||
|
||||
// ── API Response Types ──
|
||||
|
||||
export interface BestellungDetailResponse {
|
||||
bestellung: Bestellung;
|
||||
positionen: Bestellposition[];
|
||||
dateien: BestellungDatei[];
|
||||
erinnerungen: BestellungErinnerung[];
|
||||
historie: BestellungHistorie[];
|
||||
}
|
||||
83
frontend/src/types/shop.types.ts
Normal file
83
frontend/src/types/shop.types.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
// Shop (Internal Ordering) types
|
||||
|
||||
// ── Catalog Items ──
|
||||
|
||||
export interface ShopArtikel {
|
||||
id: number;
|
||||
bezeichnung: string;
|
||||
beschreibung?: string;
|
||||
kategorie?: string;
|
||||
bild_pfad?: string;
|
||||
geschaetzter_preis?: number;
|
||||
aktiv: boolean;
|
||||
erstellt_von?: string;
|
||||
erstellt_am: string;
|
||||
aktualisiert_am: string;
|
||||
}
|
||||
|
||||
export interface ShopArtikelFormData {
|
||||
bezeichnung: string;
|
||||
beschreibung?: string;
|
||||
kategorie?: string;
|
||||
geschaetzter_preis?: number;
|
||||
aktiv?: boolean;
|
||||
}
|
||||
|
||||
// ── Requests ──
|
||||
|
||||
export type ShopAnfrageStatus = 'offen' | 'genehmigt' | 'abgelehnt' | 'bestellt' | 'erledigt';
|
||||
|
||||
export const SHOP_STATUS_LABELS: Record<ShopAnfrageStatus, string> = {
|
||||
offen: 'Offen',
|
||||
genehmigt: 'Genehmigt',
|
||||
abgelehnt: 'Abgelehnt',
|
||||
bestellt: 'Bestellt',
|
||||
erledigt: 'Erledigt',
|
||||
};
|
||||
|
||||
export const SHOP_STATUS_COLORS: Record<ShopAnfrageStatus, 'default' | 'info' | 'error' | 'primary' | 'success'> = {
|
||||
offen: 'default',
|
||||
genehmigt: 'info',
|
||||
abgelehnt: 'error',
|
||||
bestellt: 'primary',
|
||||
erledigt: 'success',
|
||||
};
|
||||
|
||||
export interface ShopAnfrage {
|
||||
id: number;
|
||||
anfrager_id: string;
|
||||
anfrager_name?: string;
|
||||
status: ShopAnfrageStatus;
|
||||
notizen?: string;
|
||||
admin_notizen?: string;
|
||||
bearbeitet_von?: string;
|
||||
bearbeitet_von_name?: string;
|
||||
erstellt_am: string;
|
||||
aktualisiert_am: string;
|
||||
items_count?: number;
|
||||
}
|
||||
|
||||
export interface ShopAnfragePosition {
|
||||
id: number;
|
||||
anfrage_id: number;
|
||||
artikel_id?: number;
|
||||
bezeichnung: string;
|
||||
menge: number;
|
||||
notizen?: string;
|
||||
erstellt_am: string;
|
||||
}
|
||||
|
||||
export interface ShopAnfrageFormItem {
|
||||
artikel_id?: number;
|
||||
bezeichnung: string;
|
||||
menge: number;
|
||||
notizen?: string;
|
||||
}
|
||||
|
||||
// ── API Response Types ──
|
||||
|
||||
export interface ShopAnfrageDetailResponse {
|
||||
anfrage: ShopAnfrage;
|
||||
positionen: ShopAnfragePosition[];
|
||||
linked_bestellungen?: { id: number; bezeichnung: string; status: string }[];
|
||||
}
|
||||
Reference in New Issue
Block a user