new features

This commit is contained in:
Matthias Hochmeister
2026-03-23 13:08:19 +01:00
parent 83b84664ce
commit 5032e1593b
41 changed files with 5157 additions and 40 deletions

View File

@@ -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>
);
}

View File

@@ -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.');

View File

@@ -9,7 +9,6 @@ import {
Chip,
CircularProgress,
Container,
Fab,
FormControl,
FormControlLabel,
Grid,

View 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)} &middot; {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'} &middot; {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>
);
}

View 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>
);
}

View File

@@ -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 />

View File

@@ -22,7 +22,6 @@ import {
MenuItem,
FormControl,
InputLabel,
Fab,
CircularProgress,
Alert,
Popover,

View File

@@ -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
View 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>
);
}