Add shared Manifest UI for delivery, quote, and order.

Wire quote/order API clients and routes, then unify list/create/edit behind ManifestList/Form tiles so Lieferungen and Auftrag share one stack.
This commit is contained in:
seb
2026-08-06 20:08:56 +02:00
parent 8d50d083f5
commit 4896b1dc36
26 changed files with 1356 additions and 1103 deletions

View File

@@ -1,412 +1,9 @@
import { PureComponent } from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import AddIcon from '@mui/icons-material/Add';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import IconButton from '@mui/material/IconButton';
import { enqueueSnackbar } from 'notistack';
import BackendError from '../../components/BackendError';
import SingleLineTextEdit from '../../components/SingleLineTextEdit';
import { PanelTile, PanelTileGrid } from '../../components/panels';
import { StorageManagerContext } from '../../api/storageManagerContext';
import { router } from '../../appRouter';
import { requireDefined, requireObject } from '../../utils/apiShape';
import { backendErrorFrom } from '../../utils/backendError';
import { notifyError } from '../../utils/notify';
function sortSuppliers(suppliers) {
return [...suppliers].sort((a, b) =>
String(a.name).localeCompare(String(b.name), 'de'),
);
}
function emptyLine() {
return {
key: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
amount: '',
sku: '',
tax: '',
rebate: '',
net: '',
};
}
function parseNum(value) {
if (value == null || value === '') return null;
const n = Number(String(value).trim().replace(',', '.'));
return Number.isFinite(n) ? n : null;
}
/** Build POST /api/delivery body from form state. Throws Error on client validation. */
function buildCreateBody({ shippingNumber, estimatedDeliveryDate, supplierId, lines }) {
const number = shippingNumber.trim();
const date = estimatedDeliveryDate;
if (!number) throw new Error('Sendungsnummer fehlt.');
if (!date) throw new Error('Lieferdatum fehlt.');
const outLines = [];
for (const line of lines) {
const sku = String(line.sku ?? '').trim();
const amount = parseNum(line.amount);
const net = parseNum(line.net);
const tax = parseNum(line.tax);
const rebate = parseNum(line.rebate);
const blank =
!sku && amount == null && net == null && tax == null && rebate == null;
if (blank) continue;
if (!sku || amount == null || net == null || tax == null) {
throw new Error('Jede Zeile braucht SKU, Amount, Net und Tax.');
}
const row = { sku, amount, net, tax };
if (rebate != null) row.rebate = rebate;
outLines.push(row);
}
if (outLines.length === 0) {
throw new Error('Mindestens eine Artikelzeile nötig.');
}
const body = { number, date, lines: outLines };
if (supplierId != null) body.supplierId = supplierId;
return body;
}
const COLUMNS = [
{ id: 'amount', label: 'Amount', width: 88, align: 'right', type: 'number' },
{ id: 'sku', label: 'SKU', width: 140, align: 'left', type: 'text' },
{ id: 'tax', label: 'Tax', width: 80, align: 'right', type: 'number' },
{ id: 'rebate', label: 'Rebate', width: 88, align: 'right', type: 'number' },
{ id: 'net', label: 'Net', width: 104, align: 'right', type: 'number' },
];
import { ManifestForm } from '../../components/manifest';
class LieferungNeuPage extends PureComponent {
static contextType = StorageManagerContext;
constructor(props) {
super(props);
this.state = {
suppliersStatus: 'loading',
suppliersError: null,
suppliers: [],
estimatedDeliveryDate: '',
supplierId: null,
shippingNumber: '',
lines: [emptyLine()],
saving: false,
};
this._cancelled = false;
this.handleRetrySuppliers = this.handleRetrySuppliers.bind(this);
this.handleAddLine = this.handleAddLine.bind(this);
this.handleSupplierChange = this.handleSupplierChange.bind(this);
this.handleSave = this.handleSave.bind(this);
}
componentDidMount() {
this._cancelled = false;
void this.loadSuppliers();
}
componentWillUnmount() {
this._cancelled = true;
}
async loadSuppliers() {
this.setState({ suppliersStatus: 'loading', suppliersError: null });
try {
const list = this.context.suppliers ?? (await this.context.supplierPromise);
if (this._cancelled) return;
this.setState({
suppliersStatus: 'ready',
suppliers: sortSuppliers(list),
});
} catch (err) {
if (this._cancelled) return;
this.setState({
suppliersStatus: 'failed',
suppliersError: backendErrorFrom(err),
});
notifyError(err);
}
}
handleRetrySuppliers() {
void this.loadSuppliers();
}
handleSupplierChange(_event, option) {
this.setState({
supplierId: option?.id ?? null,
lines: option ? this.state.lines : [emptyLine()],
});
}
handleLineChange(key, field, value) {
this.setState((prev) => ({
lines: prev.lines.map((line) =>
line.key === key ? { ...line, [field]: value } : line,
),
}));
}
handleAddLine() {
this.setState((prev) => ({ lines: [...prev.lines, emptyLine()] }));
}
handleRemoveLine(key) {
this.setState((prev) => {
const next = prev.lines.filter((line) => line.key !== key);
return { lines: next.length > 0 ? next : [emptyLine()] };
});
}
async handleSave() {
if (this.state.saving) return;
let body;
try {
body = buildCreateBody(this.state);
} catch (err) {
notifyError(err);
return;
}
this.setState({ saving: true });
try {
const data = await this.context.delivery.create(body);
requireObject(data, 'POST /api/delivery');
requireObject(data.delivery, 'delivery');
requireDefined(data.delivery.id, 'delivery.id');
await this.context.updateDelivery();
if (this._cancelled) return;
enqueueSnackbar('Lieferung angelegt.', { variant: 'success' });
void router.navigate(`/lieferung/${data.delivery.id}`);
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ saving: false });
}
}
renderHeader() {
const {
suppliersStatus,
suppliers,
estimatedDeliveryDate,
supplierId,
shippingNumber,
saving,
} = this.state;
const selected =
suppliers.find((row) => row.id === supplierId) ?? null;
return (
<PanelTile wide={3} minHeight={160} color="#fed7aa" title="Kopfdaten">
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
<TextField
size="small"
type="date"
label="Lieferdatum"
value={estimatedDeliveryDate}
disabled={saving}
onChange={(e) =>
this.setState({ estimatedDeliveryDate: e.target.value })
}
autoComplete="off"
slotProps={{
inputLabel: { shrink: true },
htmlInput: { spellCheck: false },
}}
sx={{ minWidth: 220 }}
/>
<Autocomplete
size="small"
options={suppliers}
value={selected}
loading={suppliersStatus === 'loading'}
disabled={saving}
getOptionLabel={(option) => String(option.name ?? '')}
isOptionEqualToValue={(option, value) => option.id === value.id}
onChange={this.handleSupplierChange}
sx={{ flex: 1, minWidth: 220 }}
renderInput={(params) => {
const { InputProps, inputProps, ...other } = params;
return (
<TextField
{...other}
label="Lieferant"
autoComplete="off"
slotProps={{
input: InputProps,
htmlInput: {
...inputProps,
spellCheck: false,
autoComplete: 'off',
},
}}
/>
);
}}
/>
<SingleLineTextEdit
size="small"
label="Nummer"
value={shippingNumber}
disabled={saving}
onChange={(next) => this.setState({ shippingNumber: next })}
sx={{ minWidth: 180, flex: 1 }}
/>
</Stack>
</PanelTile>
);
}
renderLineField(line, column) {
const { id, align, type } = column;
const { saving } = this.state;
return (
<TextField
size="small"
fullWidth
type={type}
value={line[id]}
disabled={saving}
autoComplete="off"
onChange={(e) => this.handleLineChange(line.key, id, e.target.value)}
slotProps={{
htmlInput: {
inputMode: type === 'number' ? 'decimal' : 'text',
style: { textAlign: align },
spellCheck: false,
autoComplete: 'off',
step: type === 'number' ? 'any' : undefined,
},
}}
sx={{
'& input[type=number]': {
MozAppearance: 'textfield',
},
'& input[type=number]::-webkit-outer-spin-button, & input[type=number]::-webkit-inner-spin-button':
{
WebkitAppearance: 'none',
margin: 0,
},
}}
/>
);
}
renderArticles() {
const { supplierId, lines, saving } = this.state;
if (supplierId == null) {
return (
<PanelTile wide={3} minHeight={160} color="#e2e8f0">
<Typography color="text.secondary">
Lieferant wählen, um Artikel zu erfassen.
</Typography>
</PanelTile>
);
}
return (
<PanelTile wide={3} minHeight={280} color="#bbf7d0" title="Artikel">
<Stack spacing={1.5}>
<TableContainer>
<Table size="small" stickyHeader>
<TableHead>
<TableRow>
{COLUMNS.map((col) => (
<TableCell
key={col.id}
align={col.align}
sx={{
width: col.width,
whiteSpace: 'nowrap',
bgcolor: '#bbf7d0',
}}
>
{col.label}
</TableCell>
))}
<TableCell padding="checkbox" sx={{ bgcolor: '#bbf7d0' }} />
</TableRow>
</TableHead>
<TableBody>
{lines.map((line) => (
<TableRow key={line.key}>
{COLUMNS.map((col) => (
<TableCell
key={col.id}
align={col.align}
sx={{ py: 0.75, verticalAlign: 'middle' }}
>
{this.renderLineField(line, col)}
</TableCell>
))}
<TableCell padding="checkbox" sx={{ py: 0.75 }}>
<IconButton
size="small"
aria-label="Zeile entfernen"
disabled={saving}
onClick={() => this.handleRemoveLine(line.key)}
>
<DeleteOutlinedIcon fontSize="small" />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
<Button
size="small"
startIcon={<AddIcon />}
disabled={saving}
onClick={this.handleAddLine}
>
Zeile hinzufügen
</Button>
<Box sx={{ flex: 1 }} />
<Button
variant="contained"
size="small"
disabled={saving}
onClick={() => void this.handleSave()}
>
{saving ? 'Speichern…' : 'Speichern'}
</Button>
</Box>
</Stack>
</PanelTile>
);
}
render() {
const { suppliersStatus, suppliersError } = this.state;
if (suppliersStatus === 'failed') {
return (
<BackendError
error={suppliersError}
onRetry={this.handleRetrySuppliers}
/>
);
}
return (
<PanelTileGrid>
{this.renderHeader()}
{this.renderArticles()}
</PanelTileGrid>
);
return <ManifestForm kind="delivery" mode="create" />;
}
}