Files
dashboard/frontend/src/pages/AusruestungsanfrageDetail.tsx

545 lines
24 KiB
TypeScript

import { useState, useCallback } from 'react';
import {
Box, Typography, Paper, Button, Chip, IconButton,
Table, TableBody, TableCell, TableHead, TableRow,
Dialog, DialogTitle, DialogContent, DialogActions, TextField,
MenuItem, Select, FormControl, InputLabel, Autocomplete,
Checkbox, LinearProgress, Switch, FormControlLabel, Alert,
} from '@mui/material';
import {
ArrowBack, Add as AddIcon, Delete as DeleteIcon, Edit as EditIcon,
Check as CheckIcon, Close as CloseIcon, ShoppingCart as ShoppingCartIcon,
} 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 { useAuth } from '../contexts/AuthContext';
import { ausruestungsanfrageApi } from '../services/ausruestungsanfrage';
import { AUSRUESTUNG_STATUS_LABELS, AUSRUESTUNG_STATUS_COLORS } from '../types/ausruestungsanfrage.types';
import type {
AusruestungAnfrage, AusruestungAnfrageDetailResponse,
AusruestungAnfrageFormItem, AusruestungAnfrageStatus,
AusruestungEigenschaft,
} from '../types/ausruestungsanfrage.types';
// ── Helpers ──
function formatOrderId(r: AusruestungAnfrage): string {
if (r.bestell_jahr && r.bestell_nummer) {
return `${r.bestell_jahr}/${String(r.bestell_nummer).padStart(3, '0')}`;
}
return `#${r.id}`;
}
// ══════════════════════════════════════════════════════════════════════════════
// Component
// ══════════════════════════════════════════════════════════════════════════════
export default function AusruestungsanfrageDetail() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { showSuccess, showError } = useNotification();
const { hasPermission } = usePermissionContext();
const { user } = useAuth();
const requestId = Number(id);
// ── State ──
const [editing, setEditing] = useState(false);
const [editBezeichnung, setEditBezeichnung] = useState('');
const [editNotizen, setEditNotizen] = useState('');
const [editItems, setEditItems] = useState<AusruestungAnfrageFormItem[]>([]);
// Admin action state
const [actionDialog, setActionDialog] = useState<{ action: 'genehmigt' | 'abgelehnt' } | null>(null);
const [adminNotizen, setAdminNotizen] = useState('');
const [statusChangeValue, setStatusChangeValue] = useState('');
// Eigenschaften state for edit mode
const [editItemEigenschaften, setEditItemEigenschaften] = useState<Record<number, AusruestungEigenschaft[]>>({});
const [editItemEigenschaftValues, setEditItemEigenschaftValues] = useState<Record<number, Record<number, string>>>({});
// Permissions
const showAdminActions = hasPermission('ausruestungsanfrage:approve');
const canEditAny = hasPermission('ausruestungsanfrage:edit');
const canLink = hasPermission('ausruestungsanfrage:link_orders');
// ── Queries ──
const { data: detail, isLoading, isError } = useQuery<AusruestungAnfrageDetailResponse>({
queryKey: ['ausruestungsanfrage', 'request', requestId],
queryFn: () => ausruestungsanfrageApi.getRequest(requestId),
enabled: !isNaN(requestId),
retry: 1,
});
const { data: catalogItems = [] } = useQuery({
queryKey: ['ausruestungsanfrage', 'items-for-edit'],
queryFn: () => ausruestungsanfrageApi.getItems({ aktiv: true }),
staleTime: 5 * 60 * 1000,
});
const loadEigenschaftenForItem = useCallback(async (artikelId: number) => {
if (editItemEigenschaften[artikelId]) return;
try {
const eigs = await ausruestungsanfrageApi.getArtikelEigenschaften(artikelId);
if (eigs?.length > 0) setEditItemEigenschaften(prev => ({ ...prev, [artikelId]: eigs }));
} catch { /* ignore */ }
}, [editItemEigenschaften]);
// ── Mutations ──
const updateMut = useMutation({
mutationFn: (data: { bezeichnung?: string; notizen?: string; items?: AusruestungAnfrageFormItem[] }) =>
ausruestungsanfrageApi.updateRequest(requestId, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['ausruestungsanfrage'] });
showSuccess('Anfrage aktualisiert');
setEditing(false);
},
onError: () => showError('Fehler beim Aktualisieren'),
});
const statusMut = useMutation({
mutationFn: ({ status, notes }: { status: string; notes?: string }) =>
ausruestungsanfrageApi.updateRequestStatus(requestId, status, notes),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['ausruestungsanfrage'] });
showSuccess('Status aktualisiert');
setActionDialog(null);
setAdminNotizen('');
setStatusChangeValue('');
},
onError: () => showError('Fehler beim Aktualisieren'),
});
const geliefertMut = useMutation({
mutationFn: ({ positionId, geliefert }: { positionId: number; geliefert: boolean }) =>
ausruestungsanfrageApi.updatePositionGeliefert(positionId, geliefert),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['ausruestungsanfrage'] });
},
onError: () => showError('Fehler beim Aktualisieren'),
});
const zurueckgegebenMut = useMutation({
mutationFn: ({ positionId, zurueckgegeben }: { positionId: number; zurueckgegeben: boolean }) =>
ausruestungsanfrageApi.updatePositionZurueckgegeben(positionId, zurueckgegeben),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['ausruestungsanfrage'] });
},
onError: () => showError('Fehler beim Aktualisieren'),
});
// ── Edit helpers ──
const startEditing = () => {
if (!detail) return;
setEditBezeichnung(detail.anfrage.bezeichnung || '');
setEditNotizen(detail.anfrage.notizen || '');
setEditItems(detail.positionen.map(p => ({
artikel_id: p.artikel_id,
bezeichnung: p.bezeichnung,
menge: p.menge,
notizen: p.notizen,
eigenschaften: p.eigenschaften?.map(e => ({ eigenschaft_id: e.eigenschaft_id, wert: e.wert })),
ist_ersatz: p.ist_ersatz || false,
})));
const initVals: Record<number, Record<number, string>> = {};
detail.positionen.forEach((p, idx) => {
if (p.artikel_id) loadEigenschaftenForItem(p.artikel_id);
if (p.eigenschaften?.length) {
initVals[idx] = {};
p.eigenschaften.forEach(e => { initVals[idx][e.eigenschaft_id] = e.wert; });
}
});
setEditItemEigenschaftValues(initVals);
setEditing(true);
};
const handleSaveEdit = () => {
if (editItems.length === 0) return;
const items = editItems.map((item, idx) => {
const vals = editItemEigenschaftValues[idx] || {};
const eigenschaften = Object.entries(vals)
.filter(([, wert]) => wert.trim())
.map(([eid, wert]) => ({ eigenschaft_id: Number(eid), wert }));
return { ...item, eigenschaften: eigenschaften.length > 0 ? eigenschaften : undefined };
});
updateMut.mutate({
bezeichnung: editBezeichnung || undefined,
notizen: editNotizen || undefined,
items,
});
};
const addEditItem = () => {
setEditItems(prev => [...prev, { bezeichnung: '', menge: 1 }]);
};
const removeEditItem = (idx: number) => {
setEditItems(prev => prev.filter((_, i) => i !== idx));
};
const updateEditItem = (idx: number, field: string, value: unknown) => {
setEditItems(prev => prev.map((item, i) => i === idx ? { ...item, [field]: value } : item));
};
const anfrage = detail?.anfrage;
const canEdit = anfrage && (
canEditAny ||
(anfrage.anfrager_id === user?.id && anfrage.status === 'offen')
);
return (
<DashboardLayout>
{/* Header */}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
<IconButton onClick={() => navigate('/ausruestungsanfrage')}>
<ArrowBack />
</IconButton>
<Typography variant="h5" sx={{ flexGrow: 1 }}>
Anfrage {anfrage ? formatOrderId(anfrage) : '...'}
{anfrage?.bezeichnung && `${anfrage.bezeichnung}`}
</Typography>
{anfrage && (
<Chip
label={AUSRUESTUNG_STATUS_LABELS[anfrage.status]}
color={AUSRUESTUNG_STATUS_COLORS[anfrage.status]}
/>
)}
</Box>
{isLoading ? (
<LinearProgress />
) : isError ? (
<Typography color="error">Fehler beim Laden der Anfrage.</Typography>
) : !detail ? (
<Typography color="text.secondary">Anfrage nicht gefunden.</Typography>
) : editing ? (
/* ── Edit Mode ── */
<Paper sx={{ p: 3 }}>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<TextField
label="Bezeichnung (optional)"
value={editBezeichnung}
onChange={e => setEditBezeichnung(e.target.value)}
fullWidth
/>
<TextField
label="Notizen (optional)"
value={editNotizen}
onChange={e => setEditNotizen(e.target.value)}
multiline
rows={2}
fullWidth
/>
<Typography variant="subtitle2" sx={{ mt: 1 }}>Positionen</Typography>
{editItems.map((item, idx) => (
<Box key={idx} sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
<Autocomplete
freeSolo
options={catalogItems}
getOptionLabel={o => typeof o === 'string' ? o : o.bezeichnung}
value={item.artikel_id ? catalogItems.find(c => c.id === item.artikel_id) || item.bezeichnung : item.bezeichnung}
onChange={(_, v) => {
if (typeof v === 'string') {
updateEditItem(idx, 'bezeichnung', v);
updateEditItem(idx, 'artikel_id', undefined);
} else if (v) {
setEditItems(prev => prev.map((it, i) => i === idx ? { ...it, artikel_id: v.id, bezeichnung: v.bezeichnung } : it));
loadEigenschaftenForItem(v.id);
setEditItemEigenschaftValues(prev => { const n = { ...prev }; delete n[idx]; return n; });
}
}}
onInputChange={(_, val, reason) => {
if (reason === 'input') {
setEditItems(prev => prev.map((it, i) => i === idx ? { ...it, bezeichnung: val, artikel_id: undefined } : it));
}
}}
renderInput={params => <TextField {...params} label="Artikel" size="small" />}
sx={{ flexGrow: 1 }}
/>
<TextField
size="small"
type="number"
label="Menge"
value={item.menge}
onChange={e => updateEditItem(idx, 'menge', Math.max(1, Number(e.target.value)))}
sx={{ width: 90 }}
inputProps={{ min: 1 }}
/>
<IconButton size="small" onClick={() => removeEditItem(idx)}>
<DeleteIcon fontSize="small" />
</IconButton>
</Box>
{item.artikel_id && editItemEigenschaften[item.artikel_id]?.length > 0 && (
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, ml: 1, pl: 1.5, borderLeft: '2px solid', borderColor: 'divider' }}>
{editItemEigenschaften[item.artikel_id].map(e => (
e.typ === 'options' && e.optionen?.length ? (
<TextField key={e.id} select size="small" label={e.name} required={e.pflicht}
value={editItemEigenschaftValues[idx]?.[e.id] || ''}
onChange={ev => setEditItemEigenschaftValues(prev => ({
...prev, [idx]: { ...(prev[idx] || {}), [e.id]: ev.target.value }
}))}
sx={{ minWidth: 140 }}
>
<MenuItem value=""></MenuItem>
{e.optionen.map(opt => <MenuItem key={opt} value={opt}>{opt}</MenuItem>)}
</TextField>
) : (
<TextField key={e.id} size="small" label={e.name} required={e.pflicht}
value={editItemEigenschaftValues[idx]?.[e.id] || ''}
onChange={ev => setEditItemEigenschaftValues(prev => ({
...prev, [idx]: { ...(prev[idx] || {}), [e.id]: ev.target.value }
}))}
sx={{ minWidth: 160 }}
/>
)
))}
</Box>
)}
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5, ml: 1 }}>
<FormControlLabel
control={
<Switch
size="small"
checked={item.ist_ersatz || false}
onChange={(e) => updateEditItem(idx, 'ist_ersatz', e.target.checked)}
/>
}
label="Ersatzbeschaffung"
/>
{item.ist_ersatz && (
<Alert severity="info" sx={{ py: 0, fontSize: '0.8rem' }}>
Altes Gerät muss zurückgegeben werden
</Alert>
)}
</Box>
</Box>
))}
<Button size="small" startIcon={<AddIcon />} onClick={addEditItem}>
Position hinzufügen
</Button>
<Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end', mt: 2 }}>
<Button onClick={() => setEditing(false)}>Abbrechen</Button>
<Button
variant="contained"
onClick={handleSaveEdit}
disabled={updateMut.isPending || editItems.length === 0 || editItems.some(i => !i.bezeichnung.trim())}
>
Speichern
</Button>
</Box>
</Box>
</Paper>
) : (
/* ── View Mode ── */
<>
<Paper sx={{ p: 3, mb: 3 }}>
{/* Meta info */}
<Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1.5, mb: 2 }}>
{(anfrage!.anfrager_name || anfrage!.fuer_benutzer_name) && (
<Box>
<Typography variant="caption" color="text.secondary">Anfrage für</Typography>
<Typography variant="body2" fontWeight={500}>
{anfrage!.fuer_benutzer_name
? `${anfrage!.fuer_benutzer_name} (erstellt von ${anfrage!.anfrager_name || 'Unbekannt'})`
: anfrage!.anfrager_name}
</Typography>
</Box>
)}
<Box>
<Typography variant="caption" color="text.secondary">Erstellt am</Typography>
<Typography variant="body2" fontWeight={500}>{new Date(anfrage!.erstellt_am).toLocaleDateString('de-AT')}</Typography>
</Box>
{anfrage!.bearbeitet_von_name && (
<Box>
<Typography variant="caption" color="text.secondary">Bearbeitet von</Typography>
<Typography variant="body2" fontWeight={500}>{anfrage!.bearbeitet_von_name}</Typography>
</Box>
)}
</Box>
{anfrage!.notizen && (
<Paper variant="outlined" sx={{ p: 1.5, bgcolor: 'action.hover', mb: 1.5 }}>
<Typography variant="caption" color="text.secondary" display="block" sx={{ mb: 0.5 }}>Notizen</Typography>
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>{anfrage!.notizen}</Typography>
</Paper>
)}
{anfrage!.admin_notizen && (
<Paper variant="outlined" sx={{ p: 1.5, bgcolor: 'warning.main', color: 'warning.contrastText', borderColor: 'warning.dark', mb: 1.5 }}>
<Typography variant="caption" display="block" sx={{ mb: 0.5, opacity: 0.8 }}>Admin Notizen</Typography>
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>{anfrage!.admin_notizen}</Typography>
</Paper>
)}
</Paper>
{/* Positionen */}
<Paper sx={{ p: 3, mb: 3 }}>
<Typography variant="subtitle2" sx={{ mb: 1 }}>Positionen ({detail.positionen.length})</Typography>
<Table size="small">
<TableHead>
<TableRow>
{showAdminActions && <TableCell padding="checkbox">Geliefert</TableCell>}
<TableCell>Artikel</TableCell>
<TableCell align="right">Menge</TableCell>
<TableCell>Details</TableCell>
</TableRow>
</TableHead>
<TableBody>
{detail.positionen.map(p => (
<TableRow key={p.id} sx={p.geliefert ? { opacity: 0.5 } : undefined}>
{showAdminActions && (
<TableCell padding="checkbox">
<Checkbox
size="small"
checked={p.geliefert}
disabled={geliefertMut.isPending}
onChange={(_, checked) => geliefertMut.mutate({ positionId: p.id, geliefert: checked })}
/>
</TableCell>
)}
<TableCell>
<Typography variant="body2" fontWeight={500} sx={p.geliefert ? { textDecoration: 'line-through' } : undefined}>{p.bezeichnung}</Typography>
<Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', mt: 0.5 }}>
{p.ist_ersatz && (
<Chip label="Ersatzbeschaffung" size="small" color="warning" variant="outlined" />
)}
{p.eigenschaften && p.eigenschaften.length > 0 && p.eigenschaften.map(e => (
<Chip key={e.eigenschaft_id} label={`${e.eigenschaft_name}: ${e.wert}`} size="small" variant="outlined" />
))}
</Box>
</TableCell>
<TableCell align="right">
<Typography variant="body2" fontWeight={600}>{p.menge}x</Typography>
</TableCell>
<TableCell>
{p.notizen && <Typography variant="caption" color="text.secondary" display="block">{p.notizen}</Typography>}
{p.ist_ersatz && (
<FormControlLabel
control={
<Checkbox
size="small"
checked={p.altes_geraet_zurueckgegeben}
disabled={!showAdminActions || zurueckgegebenMut.isPending}
onChange={(_, checked) => zurueckgegebenMut.mutate({ positionId: p.id, zurueckgegeben: checked })}
/>
}
label={<Typography variant="caption">Altes Gerät zurückgegeben</Typography>}
/>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
{/* Linked Bestellungen */}
{detail.linked_bestellungen && detail.linked_bestellungen.length > 0 && (
<Paper sx={{ p: 3, mb: 3 }}>
<Typography variant="subtitle2" sx={{ mb: 1 }}>Verknüpfte Bestellungen</Typography>
<Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
{detail.linked_bestellungen.map(b => (
<Chip key={b.id} label={`#${b.id} ${b.bezeichnung}`} size="small" />
))}
</Box>
</Paper>
)}
{/* Action buttons */}
<Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
{showAdminActions && anfrage && anfrage.status === 'offen' && (
<>
<Button
color="success"
variant="outlined"
startIcon={<CheckIcon />}
onClick={() => { setActionDialog({ action: 'genehmigt' }); setAdminNotizen(''); }}
>
Genehmigen
</Button>
<Button
color="error"
variant="outlined"
startIcon={<CloseIcon />}
onClick={() => { setActionDialog({ action: 'abgelehnt' }); setAdminNotizen(''); }}
>
Ablehnen
</Button>
</>
)}
{showAdminActions && anfrage && (
<FormControl size="small" sx={{ minWidth: 140 }}>
<InputLabel>Status ändern</InputLabel>
<Select
value={statusChangeValue}
label="Status ändern"
onChange={e => {
const val = e.target.value;
setStatusChangeValue(val);
if (val) statusMut.mutate({ status: val });
}}
>
{(Object.keys(AUSRUESTUNG_STATUS_LABELS) as AusruestungAnfrageStatus[])
.filter(s => s !== anfrage.status)
.map(s => (
<MenuItem key={s} value={s}>{AUSRUESTUNG_STATUS_LABELS[s]}</MenuItem>
))}
</Select>
</FormControl>
)}
{showAdminActions && anfrage && anfrage.status === 'genehmigt' && canLink && (
<Button
variant="contained"
color="primary"
startIcon={<ShoppingCartIcon />}
onClick={() => navigate(`/ausruestungsanfragen/${requestId}/bestellen`)}
>
Bestellungen erstellen
</Button>
)}
{canEdit && !editing && (
<Button startIcon={<EditIcon />} onClick={startEditing}>
Bearbeiten
</Button>
)}
</Box>
</>
)}
{/* Approve/Reject sub-dialog */}
<Dialog open={actionDialog != null} onClose={() => setActionDialog(null)} maxWidth="sm" fullWidth>
<DialogTitle>{actionDialog?.action === 'genehmigt' ? 'Anfrage genehmigen' : 'Anfrage ablehnen'}</DialogTitle>
<DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '20px !important' }}>
<TextField
fullWidth
label="Admin Notizen (optional)"
value={adminNotizen}
onChange={e => setAdminNotizen(e.target.value)}
multiline
rows={2}
/>
</DialogContent>
<DialogActions>
<Button onClick={() => setActionDialog(null)}>Abbrechen</Button>
<Button
variant="contained"
color={actionDialog?.action === 'genehmigt' ? 'success' : 'error'}
onClick={() => {
if (!actionDialog) return;
statusMut.mutate({ status: actionDialog.action, notes: adminNotizen || undefined });
}}
disabled={statusMut.isPending}
>
{actionDialog?.action === 'genehmigt' ? 'Genehmigen' : 'Ablehnen'}
</Button>
</DialogActions>
</Dialog>
</DashboardLayout>
);
}