refactor external orders

This commit is contained in:
Matthias Hochmeister
2026-03-25 14:26:41 +01:00
parent 561334791b
commit 5add6590e5
10 changed files with 740 additions and 259 deletions

View File

@@ -29,6 +29,7 @@ import Wissen from './pages/Wissen';
import Bestellungen from './pages/Bestellungen';
import BestellungDetail from './pages/BestellungDetail';
import BestellungNeu from './pages/BestellungNeu';
import LieferantDetail from './pages/LieferantDetail';
import Ausruestungsanfrage from './pages/Ausruestungsanfrage';
import AusruestungsanfrageDetail from './pages/AusruestungsanfrageDetail';
import AusruestungsanfrageArtikelDetail from './pages/AusruestungsanfrageArtikelDetail';
@@ -242,6 +243,22 @@ function App() {
</ProtectedRoute>
}
/>
<Route
path="/bestellungen/lieferanten/neu"
element={
<ProtectedRoute>
<LieferantDetail />
</ProtectedRoute>
}
/>
<Route
path="/bestellungen/lieferanten/:id"
element={
<ProtectedRoute>
<LieferantDetail />
</ProtectedRoute>
}
/>
<Route
path="/bestellungen/:id"
element={

View File

@@ -24,6 +24,9 @@ import {
Checkbox,
Menu,
MenuItem,
Accordion,
AccordionSummary,
AccordionDetails,
} from '@mui/material';
import {
ArrowBack,
@@ -38,6 +41,7 @@ import {
Upload as UploadIcon,
ArrowDropDown,
MoreVert,
ExpandMore as ExpandMoreIcon,
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
@@ -104,6 +108,8 @@ export default function BestellungDetail() {
const [deleteItemTarget, setDeleteItemTarget] = useState<number | null>(null);
const [deleteFileTarget, setDeleteFileTarget] = useState<number | null>(null);
const [editMode, setEditMode] = useState(false);
const [reminderForm, setReminderForm] = useState<ErinnerungFormData>({ faellig_am: '', nachricht: '' });
const [reminderFormOpen, setReminderFormOpen] = useState(false);
const [deleteReminderTarget, setDeleteReminderTarget] = useState<number | null>(null);
@@ -124,6 +130,7 @@ export default function BestellungDetail() {
const canCreate = hasPermission('bestellungen:create');
const canDelete = hasPermission('bestellungen:delete');
const canManageReminders = hasPermission('bestellungen:manage_reminders');
const canManageOrders = hasPermission('bestellungen:manage_orders');
const validTransitions = bestellung ? STATUS_TRANSITIONS[bestellung.status] : [];
// All statuses except current, for force override
@@ -322,25 +329,19 @@ export default function BestellungDetail() {
{/* ── Info Cards ── */}
<Grid container spacing={2} sx={{ mb: 3 }}>
<Grid item xs={12} sm={6} md={3}>
<Grid item xs={12} sm={6} md={4}>
<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}>
<Grid item xs={12} sm={6} md={4}>
<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}>
<Grid item xs={12} sm={6} md={4}>
<Card variant="outlined"><CardContent>
<Typography variant="caption" color="text.secondary">Erstellt am</Typography>
<Typography>{formatDate(bestellung.erstellt_am)}</Typography>
@@ -349,7 +350,7 @@ export default function BestellungDetail() {
</Grid>
{/* ── Status Action ── */}
{canCreate && (
{canManageOrders && (
<Box sx={{ mb: 3, display: 'flex', gap: 1, alignItems: 'center' }}>
{validTransitions.length === 1 ? (
<Button variant="contained" onClick={() => { setStatusForce(false); setStatusConfirmTarget(validTransitions[0]); }}>
@@ -440,7 +441,19 @@ export default function BestellungDetail() {
{/* Positionen */}
{/* ══════════════════════════════════════════════════════════════════════ */}
<Paper sx={{ p: 2, mb: 3 }}>
<Typography variant="h6" sx={{ mb: 2 }}>Positionen</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
<Typography variant="h6" sx={{ flexGrow: 1 }}>Positionen</Typography>
{canCreate && (
<Button
size="small"
variant={editMode ? 'outlined' : 'text'}
startIcon={editMode ? <CloseIcon /> : <EditIcon />}
onClick={() => setEditMode((m) => !m)}
>
{editMode ? 'Abbrechen' : 'Bearbeiten'}
</Button>
)}
</Box>
<TableContainer>
<Table size="small">
<TableHead>
@@ -457,7 +470,7 @@ export default function BestellungDetail() {
</TableHead>
<TableBody>
{positionen.map((p) =>
editingItemId === p.id ? (
editMode && editingItemId === p.id ? (
<TableRow key={p.id}>
<TableCell>
<TextField size="small" value={editingItemData.bezeichnung || ''} onChange={(e) => setEditingItemData((d) => ({ ...d, bezeichnung: e.target.value }))} />
@@ -490,7 +503,7 @@ export default function BestellungDetail() {
<TableCell align="right">{formatCurrency(p.einzelpreis)}</TableCell>
<TableCell align="right">{formatCurrency((p.einzelpreis ?? 0) * p.menge)}</TableCell>
<TableCell align="right">
{canCreate ? (
{canManageOrders ? (
<TextField
size="small"
type="number"
@@ -505,8 +518,8 @@ export default function BestellungDetail() {
</TableCell>
{(canCreate || canDelete) && (
<TableCell align="right">
{canCreate && <IconButton size="small" onClick={() => startEditItem(p)}><EditIcon fontSize="small" /></IconButton>}
{canDelete && <IconButton size="small" color="error" onClick={() => setDeleteItemTarget(p.id)}><DeleteIcon fontSize="small" /></IconButton>}
{editMode && canCreate && <IconButton size="small" onClick={() => startEditItem(p)}><EditIcon fontSize="small" /></IconButton>}
{editMode && canDelete && <IconButton size="small" color="error" onClick={() => setDeleteItemTarget(p.id)}><DeleteIcon fontSize="small" /></IconButton>}
</TableCell>
)}
</TableRow>
@@ -514,7 +527,7 @@ export default function BestellungDetail() {
)}
{/* ── Add Item Row ── */}
{canCreate && (
{editMode && canCreate && (
<TableRow>
<TableCell>
<TextField size="small" placeholder="Bezeichnung" value={newItem.bezeichnung} onChange={(e) => setNewItem((f) => ({ ...f, bezeichnung: e.target.value }))} />
@@ -553,7 +566,7 @@ export default function BestellungDetail() {
<TableCell colSpan={5} align="right">
<Box sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.5 }}>
MwSt.
{canCreate ? (
{editMode && canCreate ? (
<TextField
size="small"
type="number"
@@ -715,38 +728,6 @@ export default function BestellungDetail() {
)}
</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 }}>
@@ -755,6 +736,42 @@ export default function BestellungDetail() {
</Paper>
)}
{/* ══════════════════════════════════════════════════════════════════════ */}
{/* Historie */}
{/* ══════════════════════════════════════════════════════════════════════ */}
<Accordion defaultExpanded={false} sx={{ mb: 3 }}>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<History />
<Typography variant="h6">Historie ({historie.length} Einträge)</Typography>
</Box>
</AccordionSummary>
<AccordionDetails>
{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>
)}
</AccordionDetails>
</Accordion>
{/* ══════════════════════════════════════════════════════════════════════ */}
{/* Dialogs */}
{/* ══════════════════════════════════════════════════════════════════════ */}

View File

@@ -21,7 +21,7 @@ import { useNotification } from '../contexts/NotificationContext';
import { bestellungApi } from '../services/bestellung';
import type { BestellungFormData, BestellpositionFormData, LieferantFormData, Lieferant } from '../types/bestellung.types';
const emptyOrderForm: BestellungFormData = { bezeichnung: '', lieferant_id: undefined, besteller_id: '', budget: undefined, notizen: '', positionen: [] };
const emptyOrderForm: BestellungFormData = { bezeichnung: '', lieferant_id: undefined, besteller_id: '', notizen: '', positionen: [] };
const emptyVendorForm: LieferantFormData = { name: '', kontakt_name: '', email: '', telefon: '', adresse: '', website: '', notizen: '' };
const emptyPosition: BestellpositionFormData = { bezeichnung: '', menge: 1, einheit: 'Stk' };
@@ -135,15 +135,6 @@ export default function BestellungNeu() {
renderInput={(params) => <TextField {...params} label="Besteller" />}
/>
<TextField
label="Budget"
type="number"
InputLabelProps={{ shrink: true }}
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

View File

@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useMemo } from 'react';
import {
Box,
Tab,
@@ -12,29 +12,24 @@ import {
TableRow,
Paper,
Chip,
IconButton,
Button,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
TextField,
MenuItem,
Select,
FormControl,
InputLabel,
Tooltip,
Checkbox,
FormControlLabel,
FormGroup,
Popover,
Badge,
LinearProgress,
Divider,
} 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 { Add as AddIcon, FilterList as FilterListIcon } from '@mui/icons-material';
import { useQuery } 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, LieferantFormData, Lieferant } from '../types/bestellung.types';
import type { BestellungStatus, Bestellung } from '../types/bestellung.types';
// ── Helpers ──
@@ -54,13 +49,26 @@ function TabPanel({ children, value, index }: TabPanelProps) {
const TAB_COUNT = 2;
// ── Status options for filter ──
// ── Status options ──
const ALL_STATUSES: BestellungStatus[] = ['entwurf', 'erstellt', 'bestellt', 'teillieferung', 'vollstaendig', 'abgeschlossen'];
const DEFAULT_EXCLUDED_STATUSES: BestellungStatus[] = ['abgeschlossen'];
// ── Empty form data ──
// ── Kennung formatter ──
const emptyVendorForm: LieferantFormData = { name: '', kontakt_name: '', email: '', telefon: '', adresse: '', website: '', notizen: '' };
function formatKennung(o: Bestellung): string {
if (o.laufende_nummer == null) return '';
const year = new Date(o.erstellt_am).getFullYear();
return `${year}/${o.laufende_nummer}`;
}
// ── Brutto calculator ──
function calcBrutto(o: Bestellung): number | undefined {
if (o.total_cost == null) return undefined;
const rate = (parseFloat(String(o.steuersatz)) || 20) / 100;
return o.total_cost * (1 + rate);
}
// ══════════════════════════════════════════════════════════════════════════════
// Component
@@ -69,8 +77,6 @@ const emptyVendorForm: LieferantFormData = { name: '', kontakt_name: '', email:
export default function Bestellungen() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const queryClient = useQueryClient();
const { showSuccess, showError } = useNotification();
const { hasPermission } = usePermissionContext();
// Tab from URL
@@ -83,19 +89,19 @@ export default function Bestellungen() {
if (t >= 0 && t < TAB_COUNT) setTab(t);
}, [searchParams]);
// ── State ──
const [statusFilter, setStatusFilter] = useState<string>('');
// ── Filter state ──
const [filterAnchor, setFilterAnchor] = useState<HTMLElement | null>(null);
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);
const [selectedVendors, setSelectedVendors] = useState<Set<string> | null>(null); // null = all
const [selectedOrderers, setSelectedOrderers] = useState<Set<string> | null>(null);
const [selectedStatuses, setSelectedStatuses] = useState<Set<BestellungStatus>>(
() => new Set(ALL_STATUSES.filter((s) => !DEFAULT_EXCLUDED_STATUSES.includes(s)))
);
// ── Queries ──
const { data: orders = [], isLoading: ordersLoading } = useQuery({
queryKey: ['bestellungen', statusFilter],
queryFn: () => bestellungApi.getOrders(statusFilter ? { status: statusFilter } : undefined),
queryKey: ['bestellungen'],
queryFn: () => bestellungApi.getOrders(),
});
const { data: vendors = [], isLoading: vendorsLoading } = useQuery({
@@ -103,58 +109,105 @@ export default function Bestellungen() {
queryFn: bestellungApi.getVendors,
});
// ── Mutations ──
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'),
});
// ── Derive unique filter values from data ──
const uniqueVendors = useMemo(() => {
const map = new Map<string, string>();
orders.forEach((o) => {
if (o.lieferant_name) map.set(String(o.lieferant_id ?? o.lieferant_name), o.lieferant_name);
});
return Array.from(map.entries()).sort((a, b) => a[1].localeCompare(b[1]));
}, [orders]);
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 uniqueOrderers = useMemo(() => {
const map = new Map<string, string>();
orders.forEach((o) => {
if (o.besteller_name) map.set(o.besteller_id ?? o.besteller_name, o.besteller_name);
});
return Array.from(map.entries()).sort((a, b) => a[1].localeCompare(b[1]));
}, [orders]);
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'),
});
// ── Filtered orders ──
const filteredOrders = useMemo(() => {
return orders.filter((o) => {
// Status filter
if (!selectedStatuses.has(o.status)) return false;
// Vendor filter (null = all selected)
if (selectedVendors !== null) {
const key = String(o.lieferant_id ?? o.lieferant_name ?? '');
if (!selectedVendors.has(key)) return false;
}
// Orderer filter (null = all selected)
if (selectedOrderers !== null) {
const key = o.besteller_id ?? o.besteller_name ?? '';
if (!selectedOrderers.has(key)) return false;
}
return true;
});
}, [orders, selectedStatuses, selectedVendors, selectedOrderers]);
// ── Dialog helpers ──
// ── Active filter count ──
const activeFilterCount = useMemo(() => {
let count = 0;
if (selectedStatuses.size !== ALL_STATUSES.length - DEFAULT_EXCLUDED_STATUSES.length) count++;
if (selectedVendors !== null) count++;
if (selectedOrderers !== null) count++;
return count;
}, [selectedStatuses, selectedVendors, selectedOrderers]);
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);
// ── Filter handlers ──
function resetFilters() {
setSelectedVendors(null);
setSelectedOrderers(null);
setSelectedStatuses(new Set(ALL_STATUSES.filter((s) => !DEFAULT_EXCLUDED_STATUSES.includes(s))));
}
function closeVendorDialog() {
setVendorDialogOpen(false);
setEditingVendor(null);
setVendorForm({ ...emptyVendorForm });
function toggleStatus(s: BestellungStatus) {
setSelectedStatuses((prev) => {
const next = new Set(prev);
if (next.has(s)) next.delete(s);
else next.add(s);
return next;
});
}
function handleVendorSave() {
if (!vendorForm.name.trim()) return;
if (editingVendor) {
updateVendor.mutate({ id: editingVendor.id, data: vendorForm });
} else {
createVendor.mutate(vendorForm);
}
function toggleVendor(key: string) {
setSelectedVendors((prev) => {
if (prev === null) {
// was "all selected" → deselect this one
const allKeys = new Set(uniqueVendors.map(([k]) => k));
allKeys.delete(key);
return allKeys;
}
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
// if all are selected again, go back to null
if (next.size === uniqueVendors.length) return null;
return next;
});
}
function toggleOrderer(key: string) {
setSelectedOrderers((prev) => {
if (prev === null) {
const allKeys = new Set(uniqueOrderers.map(([k]) => k));
allKeys.delete(key);
return allKeys;
}
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
if (next.size === uniqueOrderers.length) return null;
return next;
});
}
function isVendorSelected(key: string) {
return selectedVendors === null || selectedVendors.has(key);
}
function isOrdererSelected(key: string) {
return selectedOrderers === null || selectedOrderers.has(key);
}
// ── Render ──
@@ -173,62 +226,153 @@ export default function Bestellungen() {
{/* ── 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)}
<Badge badgeContent={activeFilterCount} color="primary">
<Button
variant="outlined"
size="small"
startIcon={<FilterListIcon />}
onClick={(e) => setFilterAnchor(e.currentTarget)}
>
<MenuItem value="">Alle</MenuItem>
{ALL_STATUSES.map((s) => (
<MenuItem key={s} value={s}>{BESTELLUNG_STATUS_LABELS[s]}</MenuItem>
))}
</Select>
</FormControl>
Filter
</Button>
</Badge>
{activeFilterCount > 0 && (
<Button size="small" onClick={resetFilters}>Zurücksetzen</Button>
)}
<Typography variant="body2" color="text.secondary">
{filteredOrders.length} von {orders.length} Bestellungen
</Typography>
</Box>
{/* Filter Popover */}
<Popover
open={!!filterAnchor}
anchorEl={filterAnchor}
onClose={() => setFilterAnchor(null)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
transformOrigin={{ vertical: 'top', horizontal: 'left' }}
slotProps={{ paper: { sx: { p: 2, maxWidth: 480, maxHeight: '70vh', overflow: 'auto' } } }}
>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{/* Status */}
<Box>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>Status</Typography>
<FormGroup row>
{ALL_STATUSES.map((s) => (
<FormControlLabel
key={s}
control={<Checkbox size="small" checked={selectedStatuses.has(s)} onChange={() => toggleStatus(s)} />}
label={BESTELLUNG_STATUS_LABELS[s]}
/>
))}
</FormGroup>
</Box>
<Divider />
{/* Vendor */}
{uniqueVendors.length > 0 && (
<Box>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>Lieferant</Typography>
<FormGroup>
{uniqueVendors.map(([key, label]) => (
<FormControlLabel
key={key}
control={<Checkbox size="small" checked={isVendorSelected(key)} onChange={() => toggleVendor(key)} />}
label={label}
/>
))}
</FormGroup>
</Box>
)}
{uniqueVendors.length > 0 && <Divider />}
{/* Orderer */}
{uniqueOrderers.length > 0 && (
<Box>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>Besteller</Typography>
<FormGroup>
{uniqueOrderers.map(([key, label]) => (
<FormControlLabel
key={key}
control={<Checkbox size="small" checked={isOrdererSelected(key)} onChange={() => toggleOrderer(key)} />}
label={label}
/>
))}
</FormGroup>
</Box>
)}
<Divider />
<Button size="small" onClick={resetFilters}>Zurücksetzen</Button>
</Box>
</Popover>
<TableContainer component={Paper}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Kennung</TableCell>
<TableCell>Bezeichnung</TableCell>
<TableCell>Lieferant</TableCell>
<TableCell>Besteller</TableCell>
<TableCell>Status</TableCell>
<TableCell align="right">Positionen</TableCell>
<TableCell align="right">Gesamtpreis</TableCell>
<TableCell align="right">Gesamtpreis (brutto)</TableCell>
<TableCell>Lieferung</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>
<TableRow><TableCell colSpan={9} align="center">Laden...</TableCell></TableRow>
) : filteredOrders.length === 0 ? (
<TableRow><TableCell colSpan={9} 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>
))
filteredOrders.map((o) => {
const brutto = calcBrutto(o);
const totalOrdered = o.total_ordered ?? 0;
const totalReceived = o.total_received ?? 0;
const deliveryPct = totalOrdered > 0 ? (totalReceived / totalOrdered) * 100 : 0;
return (
<TableRow
key={o.id}
hover
sx={{ cursor: 'pointer' }}
onClick={() => navigate(`/bestellungen/${o.id}`)}
>
<TableCell sx={{ whiteSpace: 'nowrap', fontFamily: 'monospace', fontSize: '0.85rem' }}>
{formatKennung(o)}
</TableCell>
<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(brutto)}</TableCell>
<TableCell sx={{ minWidth: 100 }}>
{totalOrdered > 0 ? (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<LinearProgress
variant="determinate"
value={deliveryPct}
sx={{ flexGrow: 1, height: 6, borderRadius: 3 }}
/>
<Typography variant="caption" sx={{ whiteSpace: 'nowrap' }}>
{totalReceived}/{totalOrdered}
</Typography>
</Box>
) : ''}
</TableCell>
<TableCell>{formatDate(o.erstellt_am)}</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
@@ -252,34 +396,30 @@ export default function Bestellungen() {
<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>
<TableRow><TableCell colSpan={5} align="center">Laden...</TableCell></TableRow>
) : vendors.length === 0 ? (
<TableRow><TableCell colSpan={6} align="center">Keine Lieferanten vorhanden</TableCell></TableRow>
<TableRow><TableCell colSpan={5} align="center">Keine Lieferanten vorhanden</TableCell></TableRow>
) : (
vendors.map((v) => (
<TableRow key={v.id}>
<TableRow
key={v.id}
hover
sx={{ cursor: 'pointer' }}
onClick={() => navigate(`/bestellungen/lieferanten/${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.email ? <a href={`mailto:${v.email}`} onClick={(e) => e.stopPropagation()}>{v.email}</a> : ''}</TableCell>
<TableCell>{v.telefon || ''}</TableCell>
<TableCell>
{v.website ? (
<a href={v.website} target="_blank" rel="noopener noreferrer">{v.website}</a>
<a href={v.website} target="_blank" rel="noopener noreferrer" onClick={(e) => e.stopPropagation()}>{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>
))
)}
@@ -288,79 +428,11 @@ export default function Bestellungen() {
</TableContainer>
{hasPermission('bestellungen:manage_vendors') && (
<ChatAwareFab onClick={() => setVendorDialogOpen(true)} aria-label="Lieferant hinzufügen">
<ChatAwareFab onClick={() => navigate('/bestellungen/lieferanten/neu')} aria-label="Lieferant hinzufügen">
<AddIcon />
</ChatAwareFab>
)}
</TabPanel>
{/* ── 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

@@ -0,0 +1,306 @@
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Paper,
Button,
TextField,
IconButton,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Grid,
Card,
CardContent,
Skeleton,
} from '@mui/material';
import { ArrowBack, Edit as EditIcon, Delete as DeleteIcon, Save as SaveIcon, Close as CloseIcon } 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 type { LieferantFormData } from '../types/bestellung.types';
const emptyForm: LieferantFormData = { name: '', kontakt_name: '', email: '', telefon: '', adresse: '', website: '', notizen: '' };
export default function LieferantDetail() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { showSuccess, showError } = useNotification();
const { hasPermission } = usePermissionContext();
const isNew = id === 'neu';
const vendorId = isNew ? 0 : Number(id);
const canManage = hasPermission('bestellungen:manage_vendors');
const [editMode, setEditMode] = useState(isNew);
const [form, setForm] = useState<LieferantFormData>({ ...emptyForm });
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
// ── Query ──
const { data: vendor, isLoading, isError } = useQuery({
queryKey: ['lieferant', vendorId],
queryFn: () => bestellungApi.getVendor(vendorId),
enabled: !isNew && !!vendorId,
});
// Sync form with loaded vendor data
useEffect(() => {
if (vendor) {
setForm({
name: vendor.name,
kontakt_name: vendor.kontakt_name || '',
email: vendor.email || '',
telefon: vendor.telefon || '',
adresse: vendor.adresse || '',
website: vendor.website || '',
notizen: vendor.notizen || '',
});
}
}, [vendor]);
// ── Mutations ──
const createVendor = useMutation({
mutationFn: (data: LieferantFormData) => bestellungApi.createVendor(data),
onSuccess: (created) => {
queryClient.invalidateQueries({ queryKey: ['lieferanten'] });
showSuccess('Lieferant erstellt');
navigate(`/bestellungen/lieferanten/${created.id}`, { replace: true });
},
onError: () => showError('Fehler beim Erstellen des Lieferanten'),
});
const updateVendor = useMutation({
mutationFn: (data: LieferantFormData) => bestellungApi.updateVendor(vendorId, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['lieferant', vendorId] });
queryClient.invalidateQueries({ queryKey: ['lieferanten'] });
showSuccess('Lieferant aktualisiert');
setEditMode(false);
},
onError: () => showError('Fehler beim Aktualisieren des Lieferanten'),
});
const deleteVendor = useMutation({
mutationFn: () => bestellungApi.deleteVendor(vendorId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['lieferanten'] });
showSuccess('Lieferant gelöscht');
navigate('/bestellungen?tab=1');
},
onError: () => showError('Fehler beim Löschen des Lieferanten'),
});
function handleSave() {
if (!form.name.trim()) return;
if (isNew) {
createVendor.mutate(form);
} else {
updateVendor.mutate(form);
}
}
function handleCancel() {
if (isNew) {
navigate('/bestellungen?tab=1');
} else if (vendor) {
setForm({
name: vendor.name,
kontakt_name: vendor.kontakt_name || '',
email: vendor.email || '',
telefon: vendor.telefon || '',
adresse: vendor.adresse || '',
website: vendor.website || '',
notizen: vendor.notizen || '',
});
setEditMode(false);
}
}
// ── Loading / Error ──
if (!isNew && isLoading) {
return (
<DashboardLayout>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
<IconButton onClick={() => navigate('/bestellungen?tab=1')}><ArrowBack /></IconButton>
<Skeleton width={300} height={40} />
</Box>
<Paper sx={{ p: 3 }}>
<Skeleton height={40} />
<Skeleton height={40} />
<Skeleton height={40} />
</Paper>
</DashboardLayout>
);
}
if (!isNew && (isError || !vendor)) {
return (
<DashboardLayout>
<Box sx={{ p: 4, textAlign: 'center' }}>
<Typography color="error">Lieferant nicht gefunden.</Typography>
<Button sx={{ mt: 2 }} onClick={() => navigate('/bestellungen?tab=1')}>Zurück</Button>
</Box>
</DashboardLayout>
);
}
const isSaving = createVendor.isPending || updateVendor.isPending;
return (
<DashboardLayout>
{/* ── Header ── */}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
<IconButton onClick={() => navigate('/bestellungen?tab=1')}>
<ArrowBack />
</IconButton>
<Typography variant="h4" sx={{ flexGrow: 1 }}>
{isNew ? 'Neuer Lieferant' : vendor!.name}
</Typography>
{!isNew && canManage && !editMode && (
<>
<Button startIcon={<EditIcon />} onClick={() => setEditMode(true)}>
Bearbeiten
</Button>
<Button startIcon={<DeleteIcon />} color="error" onClick={() => setDeleteDialogOpen(true)}>
Löschen
</Button>
</>
)}
{editMode && (
<>
<Button
variant="contained"
startIcon={<SaveIcon />}
onClick={handleSave}
disabled={!form.name.trim() || isSaving}
>
Speichern
</Button>
<Button startIcon={<CloseIcon />} onClick={handleCancel}>
Abbrechen
</Button>
</>
)}
</Box>
{/* ── Content ── */}
{editMode ? (
<Paper sx={{ p: 3 }}>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<TextField
label="Name"
required
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
/>
<TextField
label="Kontakt-Name"
value={form.kontakt_name || ''}
onChange={(e) => setForm((f) => ({ ...f, kontakt_name: e.target.value }))}
/>
<TextField
label="E-Mail"
type="email"
value={form.email || ''}
onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
/>
<TextField
label="Telefon"
value={form.telefon || ''}
onChange={(e) => setForm((f) => ({ ...f, telefon: e.target.value }))}
/>
<TextField
label="Adresse"
value={form.adresse || ''}
onChange={(e) => setForm((f) => ({ ...f, adresse: e.target.value }))}
/>
<TextField
label="Website"
value={form.website || ''}
onChange={(e) => setForm((f) => ({ ...f, website: e.target.value }))}
/>
<TextField
label="Notizen"
multiline
rows={4}
value={form.notizen || ''}
onChange={(e) => setForm((f) => ({ ...f, notizen: e.target.value }))}
/>
</Box>
</Paper>
) : (
<Grid container spacing={2}>
<Grid item xs={12} sm={6} md={4}>
<Card variant="outlined"><CardContent>
<Typography variant="caption" color="text.secondary">Name</Typography>
<Typography>{vendor!.name}</Typography>
</CardContent></Card>
</Grid>
<Grid item xs={12} sm={6} md={4}>
<Card variant="outlined"><CardContent>
<Typography variant="caption" color="text.secondary">Kontakt</Typography>
<Typography>{vendor!.kontakt_name || ''}</Typography>
</CardContent></Card>
</Grid>
<Grid item xs={12} sm={6} md={4}>
<Card variant="outlined"><CardContent>
<Typography variant="caption" color="text.secondary">E-Mail</Typography>
<Typography>
{vendor!.email ? <a href={`mailto:${vendor!.email}`}>{vendor!.email}</a> : ''}
</Typography>
</CardContent></Card>
</Grid>
<Grid item xs={12} sm={6} md={4}>
<Card variant="outlined"><CardContent>
<Typography variant="caption" color="text.secondary">Telefon</Typography>
<Typography>{vendor!.telefon || ''}</Typography>
</CardContent></Card>
</Grid>
<Grid item xs={12} sm={6} md={4}>
<Card variant="outlined"><CardContent>
<Typography variant="caption" color="text.secondary">Website</Typography>
<Typography>
{vendor!.website ? <a href={vendor!.website} target="_blank" rel="noopener noreferrer">{vendor!.website}</a> : ''}
</Typography>
</CardContent></Card>
</Grid>
<Grid item xs={12} sm={6} md={4}>
<Card variant="outlined"><CardContent>
<Typography variant="caption" color="text.secondary">Adresse</Typography>
<Typography>{vendor!.adresse || ''}</Typography>
</CardContent></Card>
</Grid>
{vendor!.notizen && (
<Grid item xs={12}>
<Card variant="outlined"><CardContent>
<Typography variant="caption" color="text.secondary">Notizen</Typography>
<Typography sx={{ whiteSpace: 'pre-wrap' }}>{vendor!.notizen}</Typography>
</CardContent></Card>
</Grid>
)}
</Grid>
)}
{/* ── Delete Dialog ── */}
<Dialog open={deleteDialogOpen} onClose={() => setDeleteDialogOpen(false)}>
<DialogTitle>Lieferant löschen</DialogTitle>
<DialogContent>
<Typography>
Soll der Lieferant <strong>{vendor?.name}</strong> wirklich gelöscht werden?
</Typography>
</DialogContent>
<DialogActions>
<Button onClick={() => setDeleteDialogOpen(false)}>Abbrechen</Button>
<Button color="error" variant="contained" onClick={() => deleteVendor.mutate()} disabled={deleteVendor.isPending}>
Löschen
</Button>
</DialogActions>
</Dialog>
</DashboardLayout>
);
}

View File

@@ -67,6 +67,9 @@ export interface Bestellung {
// Computed
total_cost?: number;
items_count?: number;
total_received?: number;
total_ordered?: number;
laufende_nummer?: number;
}
export interface BestellungFormData {