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

@@ -26,6 +26,9 @@ import UebungDetail from './pages/UebungDetail';
import Veranstaltungen from './pages/Veranstaltungen';
import VeranstaltungKategorien from './pages/VeranstaltungKategorien';
import Wissen from './pages/Wissen';
import Bestellungen from './pages/Bestellungen';
import BestellungDetail from './pages/BestellungDetail';
import Shop from './pages/Shop';
import AdminDashboard from './pages/AdminDashboard';
import AdminSettings from './pages/AdminSettings';
import NotFound from './pages/NotFound';
@@ -216,6 +219,30 @@ function App() {
</ProtectedRoute>
}
/>
<Route
path="/bestellungen"
element={
<ProtectedRoute>
<Bestellungen />
</ProtectedRoute>
}
/>
<Route
path="/bestellungen/:id"
element={
<ProtectedRoute>
<BestellungDetail />
</ProtectedRoute>
}
/>
<Route
path="/shop"
element={
<ProtectedRoute>
<Shop />
</ProtectedRoute>
}
/>
<Route
path="/admin"
element={

View File

@@ -0,0 +1,167 @@
import { useState } from 'react';
import {
Box,
Typography,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Chip,
FormControl,
InputLabel,
Select,
MenuItem,
CircularProgress,
} from '@mui/material';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { bestellungApi } from '../../services/bestellung';
import { shopApi } from '../../services/shop';
import { BESTELLUNG_STATUS_LABELS, BESTELLUNG_STATUS_COLORS } from '../../types/bestellung.types';
import { SHOP_STATUS_LABELS, SHOP_STATUS_COLORS } from '../../types/shop.types';
import type { BestellungStatus } from '../../types/bestellung.types';
import type { ShopAnfrageStatus } from '../../types/shop.types';
function BestellungenTab() {
const navigate = useNavigate();
const [statusFilter, setStatusFilter] = useState<string>('');
const { data: orders, isLoading: ordersLoading } = useQuery({
queryKey: ['admin-bestellungen', statusFilter],
queryFn: () => bestellungApi.getOrders(statusFilter ? { status: statusFilter } : undefined),
});
const { data: requests, isLoading: requestsLoading } = useQuery({
queryKey: ['admin-shop-requests'],
queryFn: () => shopApi.getRequests({ status: 'offen' }),
});
const formatCurrency = (value?: number) =>
value != null ? new Intl.NumberFormat('de-AT', { style: 'currency', currency: 'EUR' }).format(value) : '';
return (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
{/* Pending Shop Requests */}
{(requests?.length ?? 0) > 0 && (
<Paper sx={{ p: 2 }}>
<Typography variant="h6" gutterBottom>
Offene Shop-Anfragen ({requests?.length})
</Typography>
{requestsLoading ? (
<CircularProgress size={24} />
) : (
<TableContainer>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>#</TableCell>
<TableCell>Anfrager</TableCell>
<TableCell>Status</TableCell>
<TableCell>Erstellt am</TableCell>
</TableRow>
</TableHead>
<TableBody>
{(requests ?? []).map((req) => (
<TableRow
key={req.id}
hover
sx={{ cursor: 'pointer' }}
onClick={() => navigate('/shop?tab=2')}
>
<TableCell>{req.id}</TableCell>
<TableCell>{req.anfrager_name || ''}</TableCell>
<TableCell>
<Chip
label={SHOP_STATUS_LABELS[req.status as ShopAnfrageStatus]}
color={SHOP_STATUS_COLORS[req.status as ShopAnfrageStatus]}
size="small"
/>
</TableCell>
<TableCell>{new Date(req.erstellt_am).toLocaleDateString('de-AT')}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
</Paper>
)}
{/* Orders Overview */}
<Paper sx={{ p: 2 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
<Typography variant="h6">Bestellungen</Typography>
<FormControl size="small" sx={{ minWidth: 180 }}>
<InputLabel>Status</InputLabel>
<Select
value={statusFilter}
label="Status"
onChange={(e) => setStatusFilter(e.target.value)}
>
<MenuItem value="">Alle</MenuItem>
{Object.entries(BESTELLUNG_STATUS_LABELS).map(([key, label]) => (
<MenuItem key={key} value={key}>{label}</MenuItem>
))}
</Select>
</FormControl>
</Box>
{ordersLoading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>
<CircularProgress />
</Box>
) : (
<TableContainer>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Bezeichnung</TableCell>
<TableCell>Lieferant</TableCell>
<TableCell>Status</TableCell>
<TableCell align="right">Positionen</TableCell>
<TableCell align="right">Gesamt</TableCell>
<TableCell>Erstellt am</TableCell>
</TableRow>
</TableHead>
<TableBody>
{(orders ?? []).length === 0 ? (
<TableRow>
<TableCell colSpan={6} align="center">
<Typography variant="body2" color="text.secondary">Keine Bestellungen</Typography>
</TableCell>
</TableRow>
) : (
(orders ?? []).map((order) => (
<TableRow
key={order.id}
hover
sx={{ cursor: 'pointer' }}
onClick={() => navigate(`/bestellungen/${order.id}`)}
>
<TableCell>{order.bezeichnung}</TableCell>
<TableCell>{order.lieferant_name || ''}</TableCell>
<TableCell>
<Chip
label={BESTELLUNG_STATUS_LABELS[order.status as BestellungStatus]}
color={BESTELLUNG_STATUS_COLORS[order.status as BestellungStatus]}
size="small"
/>
</TableCell>
<TableCell align="right">{order.items_count ?? 0}</TableCell>
<TableCell align="right">{formatCurrency(order.total_cost)}</TableCell>
<TableCell>{new Date(order.erstellt_am).toLocaleDateString('de-AT')}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableContainer>
)}
</Paper>
</Box>
);
}
export default BestellungenTab;

View File

@@ -124,8 +124,6 @@ function NotificationBroadcastTab() {
setTargetDienstgrad(typeof value === 'string' ? value.split(',') : value);
};
const filtersActive = !alleBenutzer && (targetGroup.trim() || targetDienstgrad.length > 0);
const filterDescription = (() => {
if (alleBenutzer) return 'alle aktiven Benutzer';
const parts: string[] = [];

View File

@@ -86,6 +86,38 @@ function buildReverseHierarchy(hierarchy: Record<string, string[]>): Record<stri
return reverse;
}
// ── Visual sub-groups for permission matrix ──
// Maps feature_group → { subGroupLabel: actionSuffix[] }
// Actions not listed get placed in a default group.
const PERMISSION_SUB_GROUPS: Record<string, Record<string, string[]>> = {
kalender: {
'Termine': ['view', 'create'],
'Buchungen': ['view_bookings', 'manage_bookings'],
},
bestellungen: {
'Bestellungen': ['view', 'create', 'delete', 'export'],
'Lieferanten': ['manage_vendors'],
'Erinnerungen': ['manage_reminders'],
'Widget': ['widget'],
},
shop: {
'Katalog': ['view', 'manage_catalog'],
'Anfragen': ['create_request', 'approve_requests', 'link_orders'],
'Widget': ['widget'],
},
};
function getSubGroupLabel(featureGroupId: string, permId: string): string | null {
const subGroups = PERMISSION_SUB_GROUPS[featureGroupId];
if (!subGroups) return null;
const action = permId.includes(':') ? permId.split(':')[1] : permId;
for (const [label, actions] of Object.entries(subGroups)) {
if (actions.includes(action)) return label;
}
return null;
}
// ── Component ──
function PermissionMatrixTab() {
@@ -412,11 +444,29 @@ function PermissionMatrixTab() {
<Collapse in={isExpanded} timeout="auto" unmountOnExit>
<Table size="small">
<TableBody>
{fgPerms.map((perm: Permission) => {
const depTooltip = getDepTooltip(perm.id);
const tooltipText = [perm.description, depTooltip].filter(Boolean).join('\n');
return (
<TableRow key={perm.id} hover>
{(() => {
let lastSubGroup: string | null | undefined = undefined;
return fgPerms.map((perm: Permission) => {
const depTooltip = getDepTooltip(perm.id);
const tooltipText = [perm.description, depTooltip].filter(Boolean).join('\n');
const subGroup = getSubGroupLabel(fg.id, perm.id);
const showSubGroupHeader = subGroup !== lastSubGroup && subGroup !== null;
lastSubGroup = subGroup;
return (
<React.Fragment key={perm.id}>
{showSubGroupHeader && (
<TableRow>
<TableCell
colSpan={2 + nonAdminGroups.length}
sx={{ pl: 5, py: 0.5, bgcolor: 'action.selected', position: 'sticky', left: 0, zIndex: 1 }}
>
<Typography variant="caption" sx={{ fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, color: 'text.secondary' }}>
{subGroup}
</Typography>
</TableCell>
</TableRow>
)}
<TableRow hover>
<TableCell sx={{ pl: 6, minWidth: 250, position: 'sticky', left: 0, zIndex: 1, bgcolor: 'background.paper' }}>
<Tooltip title={tooltipText || ''} placement="right"><span>{perm.label}</span></Tooltip>
</TableCell>
@@ -441,8 +491,10 @@ function PermissionMatrixTab() {
);
})}
</TableRow>
);
})}
</React.Fragment>
);
});
})()}
</TableBody>
</Table>
</Collapse>

View File

@@ -60,7 +60,7 @@ const ContentOverlay: React.FC<ContentOverlayProps> = ({ open, onClose, mode, co
onClose={onClose}
maxWidth="lg"
fullWidth
slotProps={{ paper: { sx: { bgcolor: mode === 'image' ? 'black' : 'background.paper', m: 1 } } }}
PaperProps={{ sx: { bgcolor: mode === 'image' ? 'black' : 'background.paper', m: 1 } }}
>
<DialogContent sx={{ p: 0, position: 'relative', display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 200 }}>
{mode === 'image' && (

View File

@@ -0,0 +1,109 @@
import { Card, CardContent, Typography, Box, Chip, List, ListItem, ListItemText, Divider, Skeleton } from '@mui/material';
import { LocalShipping } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { bestellungApi } from '../../services/bestellung';
import { BESTELLUNG_STATUS_LABELS, BESTELLUNG_STATUS_COLORS } from '../../types/bestellung.types';
import type { BestellungStatus } from '../../types/bestellung.types';
function BestellungenWidget() {
const navigate = useNavigate();
const { data: orders, isLoading, isError } = useQuery({
queryKey: ['bestellungen-widget'],
queryFn: () => bestellungApi.getOrders(),
refetchInterval: 5 * 60 * 1000,
retry: 1,
});
const openOrders = (orders ?? []).filter(
(o) => !['abgeschlossen'].includes(o.status)
);
if (isLoading) {
return (
<Card>
<CardContent>
<Typography variant="h6" gutterBottom>Bestellungen</Typography>
<Skeleton variant="rectangular" height={60} />
<Skeleton variant="rectangular" height={60} sx={{ mt: 1 }} />
</CardContent>
</Card>
);
}
if (isError) {
return (
<Card>
<CardContent>
<Typography variant="h6" gutterBottom>Bestellungen</Typography>
<Typography variant="body2" color="text.secondary">
Bestellungen konnten nicht geladen werden.
</Typography>
</CardContent>
</Card>
);
}
if (openOrders.length === 0) {
return (
<Card>
<CardContent>
<Typography variant="h6" gutterBottom>Bestellungen</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: 'text.secondary' }}>
<LocalShipping fontSize="small" />
<Typography variant="body2">Keine offenen Bestellungen</Typography>
</Box>
</CardContent>
</Card>
);
}
return (
<Card>
<CardContent>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
<Typography variant="h6">Bestellungen</Typography>
<Chip label={`${openOrders.length} offen`} size="small" color="primary" />
</Box>
<List dense disablePadding>
{openOrders.slice(0, 5).map((order, idx) => (
<Box key={order.id}>
{idx > 0 && <Divider />}
<ListItem
disablePadding
sx={{ cursor: 'pointer', py: 0.5, '&:hover': { bgcolor: 'action.hover' } }}
onClick={() => navigate(`/bestellungen/${order.id}`)}
>
<ListItemText
primary={order.bezeichnung}
secondary={order.lieferant_name || 'Kein Lieferant'}
primaryTypographyProps={{ variant: 'body2', noWrap: true }}
secondaryTypographyProps={{ variant: 'caption' }}
/>
<Chip
label={BESTELLUNG_STATUS_LABELS[order.status as BestellungStatus]}
color={BESTELLUNG_STATUS_COLORS[order.status as BestellungStatus]}
size="small"
sx={{ ml: 1 }}
/>
</ListItem>
</Box>
))}
</List>
{openOrders.length > 5 && (
<Typography
variant="caption"
color="primary"
sx={{ cursor: 'pointer', mt: 1, display: 'block' }}
onClick={() => navigate('/bestellungen')}
>
Alle {openOrders.length} Bestellungen anzeigen
</Typography>
)}
</CardContent>
</Card>
);
}
export default BestellungenWidget;

View File

@@ -0,0 +1,106 @@
import { Card, CardContent, Typography, Box, Chip, List, ListItem, ListItemText, Divider, Skeleton } from '@mui/material';
import { Store } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { shopApi } from '../../services/shop';
import { SHOP_STATUS_LABELS, SHOP_STATUS_COLORS } from '../../types/shop.types';
import type { ShopAnfrageStatus } from '../../types/shop.types';
function ShopWidget() {
const navigate = useNavigate();
const { data: requests, isLoading, isError } = useQuery({
queryKey: ['shop-widget-requests'],
queryFn: () => shopApi.getRequests({ status: 'offen' }),
refetchInterval: 5 * 60 * 1000,
retry: 1,
});
if (isLoading) {
return (
<Card>
<CardContent>
<Typography variant="h6" gutterBottom>Shop-Anfragen</Typography>
<Skeleton variant="rectangular" height={60} />
</CardContent>
</Card>
);
}
if (isError) {
return (
<Card>
<CardContent>
<Typography variant="h6" gutterBottom>Shop-Anfragen</Typography>
<Typography variant="body2" color="text.secondary">
Anfragen konnten nicht geladen werden.
</Typography>
</CardContent>
</Card>
);
}
const pendingCount = requests?.length ?? 0;
if (pendingCount === 0) {
return (
<Card>
<CardContent>
<Typography variant="h6" gutterBottom>Shop-Anfragen</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: 'text.secondary' }}>
<Store fontSize="small" />
<Typography variant="body2">Keine offenen Anfragen</Typography>
</Box>
</CardContent>
</Card>
);
}
return (
<Card>
<CardContent>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
<Typography variant="h6">Shop-Anfragen</Typography>
<Chip label={`${pendingCount} offen`} size="small" color="warning" />
</Box>
<List dense disablePadding>
{(requests ?? []).slice(0, 5).map((req, idx) => (
<Box key={req.id}>
{idx > 0 && <Divider />}
<ListItem
disablePadding
sx={{ cursor: 'pointer', py: 0.5, '&:hover': { bgcolor: 'action.hover' } }}
onClick={() => navigate('/shop?tab=2')}
>
<ListItemText
primary={`Anfrage #${req.id}`}
secondary={req.anfrager_name || 'Unbekannt'}
primaryTypographyProps={{ variant: 'body2' }}
secondaryTypographyProps={{ variant: 'caption' }}
/>
<Chip
label={SHOP_STATUS_LABELS[req.status as ShopAnfrageStatus]}
color={SHOP_STATUS_COLORS[req.status as ShopAnfrageStatus]}
size="small"
sx={{ ml: 1 }}
/>
</ListItem>
</Box>
))}
</List>
{pendingCount > 5 && (
<Typography
variant="caption"
color="primary"
sx={{ cursor: 'pointer', mt: 1, display: 'block' }}
onClick={() => navigate('/shop?tab=2')}
>
Alle {pendingCount} Anfragen anzeigen
</Typography>
)}
</CardContent>
</Card>
);
}
export default ShopWidget;

View File

@@ -18,3 +18,5 @@ export { default as AnnouncementBanner } from './AnnouncementBanner';
export { default as BannerWidget } from './BannerWidget';
export { default as LinksWidget } from './LinksWidget';
export { default as WidgetGroup } from './WidgetGroup';
export { default as BestellungenWidget } from './BestellungenWidget';
export { default as ShopWidget } from './ShopWidget';

View File

@@ -25,6 +25,8 @@ import {
Menu as MenuIcon,
ExpandMore,
ExpandLess,
LocalShipping,
Store,
} from '@mui/icons-material';
import { useNavigate, useLocation } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
@@ -61,6 +63,7 @@ const adminSubItems: SubItem[] = [
{ text: 'Wartung', path: '/admin?tab=5' },
{ text: 'FDISK Sync', path: '/admin?tab=6' },
{ text: 'Berechtigungen', path: '/admin?tab=7' },
{ text: 'Bestellungen', path: '/admin?tab=8' },
];
const baseNavigationItems: NavigationItem[] = [
@@ -106,6 +109,22 @@ const baseNavigationItems: NavigationItem[] = [
path: '/wissen',
permission: 'wissen:view',
},
{
text: 'Bestellungen',
icon: <LocalShipping />,
path: '/bestellungen',
subItems: [
{ text: 'Übersicht', path: '/bestellungen?tab=0' },
{ text: 'Lieferanten', path: '/bestellungen?tab=1' },
],
permission: 'bestellungen:view',
},
{
text: 'Shop',
icon: <Store />,
path: '/shop',
permission: 'shop:view',
},
];
const adminItem: NavigationItem = {

View File

@@ -13,6 +13,8 @@ export const WIDGETS = [
{ key: 'eventQuickAdd', label: 'Termin erstellen', defaultVisible: true },
{ key: 'adminStatus', label: 'Admin Status', defaultVisible: true },
{ key: 'links', label: 'Links', defaultVisible: true },
{ key: 'bestellungen', label: 'Bestellungen', defaultVisible: true },
{ key: 'shopRequests', label: 'Shop-Anfragen', defaultVisible: true },
] as const;
export type WidgetKey = typeof WIDGETS[number]['key'];

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

View File

@@ -0,0 +1,117 @@
import { api } from './api';
import type {
Lieferant,
LieferantFormData,
Bestellung,
BestellungFormData,
BestellungDetailResponse,
Bestellposition,
BestellpositionFormData,
BestellungDatei,
BestellungErinnerung,
ErinnerungFormData,
BestellungHistorie,
} from '../types/bestellung.types';
export const bestellungApi = {
// ── Vendors ──
getVendors: async (): Promise<Lieferant[]> => {
const r = await api.get('/api/bestellungen/vendors');
return r.data.data;
},
getVendor: async (id: number): Promise<Lieferant> => {
const r = await api.get(`/api/bestellungen/vendors/${id}`);
return r.data.data;
},
createVendor: async (data: LieferantFormData): Promise<Lieferant> => {
const r = await api.post('/api/bestellungen/vendors', data);
return r.data.data;
},
updateVendor: async (id: number, data: LieferantFormData): Promise<Lieferant> => {
const r = await api.patch(`/api/bestellungen/vendors/${id}`, data);
return r.data.data;
},
deleteVendor: async (id: number): Promise<void> => {
await api.delete(`/api/bestellungen/vendors/${id}`);
},
// ── Orders ──
getOrders: async (filters?: { status?: string; lieferant_id?: number }): Promise<Bestellung[]> => {
const params = new URLSearchParams();
if (filters?.status) params.set('status', filters.status);
if (filters?.lieferant_id) params.set('lieferant_id', String(filters.lieferant_id));
const r = await api.get(`/api/bestellungen?${params.toString()}`);
return r.data.data;
},
getOrder: async (id: number): Promise<BestellungDetailResponse> => {
const r = await api.get(`/api/bestellungen/${id}`);
return r.data.data;
},
createOrder: async (data: BestellungFormData): Promise<Bestellung> => {
const r = await api.post('/api/bestellungen', data);
return r.data.data;
},
updateOrder: async (id: number, data: Partial<BestellungFormData>): Promise<Bestellung> => {
const r = await api.patch(`/api/bestellungen/${id}`, data);
return r.data.data;
},
deleteOrder: async (id: number): Promise<void> => {
await api.delete(`/api/bestellungen/${id}`);
},
updateStatus: async (id: number, status: string): Promise<Bestellung> => {
const r = await api.patch(`/api/bestellungen/${id}/status`, { status });
return r.data.data;
},
// ── Line Items ──
addLineItem: async (orderId: number, data: BestellpositionFormData): Promise<Bestellposition> => {
const r = await api.post(`/api/bestellungen/${orderId}/items`, data);
return r.data.data;
},
updateLineItem: async (itemId: number, data: Partial<BestellpositionFormData>): Promise<Bestellposition> => {
const r = await api.patch(`/api/bestellungen/items/${itemId}`, data);
return r.data.data;
},
deleteLineItem: async (itemId: number): Promise<void> => {
await api.delete(`/api/bestellungen/items/${itemId}`);
},
updateReceivedQty: async (itemId: number, menge: number): Promise<Bestellposition> => {
const r = await api.patch(`/api/bestellungen/items/${itemId}/received`, { erhalten_menge: menge });
return r.data.data;
},
// ── Files ──
uploadFile: async (orderId: number, file: File): Promise<BestellungDatei> => {
const formData = new FormData();
formData.append('datei', file);
const r = await api.post(`/api/bestellungen/${orderId}/files`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return r.data.data;
},
deleteFile: async (fileId: number): Promise<void> => {
await api.delete(`/api/bestellungen/files/${fileId}`);
},
getFiles: async (orderId: number): Promise<BestellungDatei[]> => {
const r = await api.get(`/api/bestellungen/${orderId}/files`);
return r.data.data;
},
// ── Reminders ──
addReminder: async (orderId: number, data: ErinnerungFormData): Promise<BestellungErinnerung> => {
const r = await api.post(`/api/bestellungen/${orderId}/reminders`, data);
return r.data.data;
},
markReminderDone: async (reminderId: number): Promise<void> => {
await api.patch(`/api/bestellungen/reminders/${reminderId}`, { erledigt: true });
},
deleteReminder: async (reminderId: number): Promise<void> => {
await api.delete(`/api/bestellungen/reminders/${reminderId}`);
},
// ── History ──
getHistory: async (orderId: number): Promise<BestellungHistorie[]> => {
const r = await api.get(`/api/bestellungen/${orderId}/history`);
return r.data.data;
},
};

View File

@@ -0,0 +1,73 @@
import { api } from './api';
import type {
ShopArtikel,
ShopArtikelFormData,
ShopAnfrage,
ShopAnfrageDetailResponse,
ShopAnfrageFormItem,
} from '../types/shop.types';
export const shopApi = {
// ── Catalog Items ──
getItems: async (filters?: { kategorie?: string; aktiv?: boolean }): Promise<ShopArtikel[]> => {
const params = new URLSearchParams();
if (filters?.kategorie) params.set('kategorie', filters.kategorie);
if (filters?.aktiv !== undefined) params.set('aktiv', String(filters.aktiv));
const r = await api.get(`/api/shop/items?${params.toString()}`);
return r.data.data;
},
getItem: async (id: number): Promise<ShopArtikel> => {
const r = await api.get(`/api/shop/items/${id}`);
return r.data.data;
},
createItem: async (data: ShopArtikelFormData): Promise<ShopArtikel> => {
const r = await api.post('/api/shop/items', data);
return r.data.data;
},
updateItem: async (id: number, data: Partial<ShopArtikelFormData>): Promise<ShopArtikel> => {
const r = await api.patch(`/api/shop/items/${id}`, data);
return r.data.data;
},
deleteItem: async (id: number): Promise<void> => {
await api.delete(`/api/shop/items/${id}`);
},
getCategories: async (): Promise<string[]> => {
const r = await api.get('/api/shop/categories');
return r.data.data;
},
// ── Requests ──
getRequests: async (filters?: { status?: string }): Promise<ShopAnfrage[]> => {
const params = new URLSearchParams();
if (filters?.status) params.set('status', filters.status);
const r = await api.get(`/api/shop/requests?${params.toString()}`);
return r.data.data;
},
getMyRequests: async (): Promise<ShopAnfrage[]> => {
const r = await api.get('/api/shop/requests/my');
return r.data.data;
},
getRequest: async (id: number): Promise<ShopAnfrageDetailResponse> => {
const r = await api.get(`/api/shop/requests/${id}`);
return r.data.data;
},
createRequest: async (items: ShopAnfrageFormItem[], notizen?: string): Promise<ShopAnfrage> => {
const r = await api.post('/api/shop/requests', { items, notizen });
return r.data.data;
},
updateRequestStatus: async (id: number, status: string, admin_notizen?: string): Promise<ShopAnfrage> => {
const r = await api.patch(`/api/shop/requests/${id}/status`, { status, admin_notizen });
return r.data.data;
},
deleteRequest: async (id: number): Promise<void> => {
await api.delete(`/api/shop/requests/${id}`);
},
// ── Linking ──
linkToOrder: async (anfrageId: number, bestellungId: number): Promise<void> => {
await api.post(`/api/shop/requests/${anfrageId}/link`, { bestellung_id: bestellungId });
},
unlinkFromOrder: async (anfrageId: number, bestellungId: number): Promise<void> => {
await api.delete(`/api/shop/requests/${anfrageId}/link/${bestellungId}`);
},
};

View File

@@ -0,0 +1,156 @@
// Bestellungen (Vendor Orders) types
// ── Vendors ──
export interface Lieferant {
id: number;
name: string;
kontakt_name?: string;
email?: string;
telefon?: string;
adresse?: string;
website?: string;
notizen?: string;
erstellt_von?: string;
erstellt_am: string;
aktualisiert_am: string;
}
export interface LieferantFormData {
name: string;
kontakt_name?: string;
email?: string;
telefon?: string;
adresse?: string;
website?: string;
notizen?: string;
}
// ── Orders ──
export type BestellungStatus = 'entwurf' | 'erstellt' | 'bestellt' | 'teillieferung' | 'vollstaendig' | 'abgeschlossen';
export const BESTELLUNG_STATUS_LABELS: Record<BestellungStatus, string> = {
entwurf: 'Entwurf',
erstellt: 'Erstellt',
bestellt: 'Bestellt',
teillieferung: 'Teillieferung',
vollstaendig: 'Vollständig',
abgeschlossen: 'Abgeschlossen',
};
export const BESTELLUNG_STATUS_COLORS: Record<BestellungStatus, 'default' | 'info' | 'primary' | 'warning' | 'success'> = {
entwurf: 'default',
erstellt: 'info',
bestellt: 'primary',
teillieferung: 'warning',
vollstaendig: 'success',
abgeschlossen: 'success',
};
export interface Bestellung {
id: number;
bezeichnung: string;
lieferant_id?: number;
lieferant_name?: string;
besteller_id?: string;
besteller_name?: string;
status: BestellungStatus;
budget?: number;
notizen?: string;
erstellt_von?: string;
erstellt_am: string;
aktualisiert_am: string;
bestellt_am?: string;
abgeschlossen_am?: string;
// Computed
total_cost?: number;
items_count?: number;
}
export interface BestellungFormData {
bezeichnung: string;
lieferant_id?: number;
besteller_id?: string;
status?: BestellungStatus;
budget?: number;
notizen?: string;
}
// ── Line Items ──
export interface Bestellposition {
id: number;
bestellung_id: number;
bezeichnung: string;
artikelnummer?: string;
menge: number;
einheit: string;
einzelpreis?: number;
erhalten_menge: number;
notizen?: string;
erstellt_am: string;
aktualisiert_am: string;
}
export interface BestellpositionFormData {
bezeichnung: string;
artikelnummer?: string;
menge: number;
einheit?: string;
einzelpreis?: number;
notizen?: string;
}
// ── File Attachments ──
export interface BestellungDatei {
id: number;
bestellung_id: number;
dateiname: string;
dateipfad: string;
dateityp: string;
dateigroesse?: number;
thumbnail_pfad?: string;
hochgeladen_von?: string;
hochgeladen_am: string;
}
// ── Reminders ──
export interface BestellungErinnerung {
id: number;
bestellung_id: number;
faellig_am: string;
nachricht?: string;
erledigt: boolean;
erstellt_von?: string;
erstellt_am: string;
}
export interface ErinnerungFormData {
faellig_am: string;
nachricht?: string;
}
// ── Audit Trail ──
export interface BestellungHistorie {
id: number;
bestellung_id: number;
aktion: string;
details?: Record<string, unknown>;
erstellt_von?: string;
erstellt_von_name?: string;
erstellt_am: string;
}
// ── API Response Types ──
export interface BestellungDetailResponse {
bestellung: Bestellung;
positionen: Bestellposition[];
dateien: BestellungDatei[];
erinnerungen: BestellungErinnerung[];
historie: BestellungHistorie[];
}

View File

@@ -0,0 +1,83 @@
// Shop (Internal Ordering) types
// ── Catalog Items ──
export interface ShopArtikel {
id: number;
bezeichnung: string;
beschreibung?: string;
kategorie?: string;
bild_pfad?: string;
geschaetzter_preis?: number;
aktiv: boolean;
erstellt_von?: string;
erstellt_am: string;
aktualisiert_am: string;
}
export interface ShopArtikelFormData {
bezeichnung: string;
beschreibung?: string;
kategorie?: string;
geschaetzter_preis?: number;
aktiv?: boolean;
}
// ── Requests ──
export type ShopAnfrageStatus = 'offen' | 'genehmigt' | 'abgelehnt' | 'bestellt' | 'erledigt';
export const SHOP_STATUS_LABELS: Record<ShopAnfrageStatus, string> = {
offen: 'Offen',
genehmigt: 'Genehmigt',
abgelehnt: 'Abgelehnt',
bestellt: 'Bestellt',
erledigt: 'Erledigt',
};
export const SHOP_STATUS_COLORS: Record<ShopAnfrageStatus, 'default' | 'info' | 'error' | 'primary' | 'success'> = {
offen: 'default',
genehmigt: 'info',
abgelehnt: 'error',
bestellt: 'primary',
erledigt: 'success',
};
export interface ShopAnfrage {
id: number;
anfrager_id: string;
anfrager_name?: string;
status: ShopAnfrageStatus;
notizen?: string;
admin_notizen?: string;
bearbeitet_von?: string;
bearbeitet_von_name?: string;
erstellt_am: string;
aktualisiert_am: string;
items_count?: number;
}
export interface ShopAnfragePosition {
id: number;
anfrage_id: number;
artikel_id?: number;
bezeichnung: string;
menge: number;
notizen?: string;
erstellt_am: string;
}
export interface ShopAnfrageFormItem {
artikel_id?: number;
bezeichnung: string;
menge: number;
notizen?: string;
}
// ── API Response Types ──
export interface ShopAnfrageDetailResponse {
anfrage: ShopAnfrage;
positionen: ShopAnfragePosition[];
linked_bestellungen?: { id: number; bezeichnung: string; status: string }[];
}