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:
321
src/components/manifest/ManifestForm.jsx
Normal file
321
src/components/manifest/ManifestForm.jsx
Normal file
@@ -0,0 +1,321 @@
|
||||
import { PureComponent } from 'react';
|
||||
import Box from '@mui/material/Box';
|
||||
import CircularProgress from '@mui/material/CircularProgress';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import { enqueueSnackbar } from 'notistack';
|
||||
import BackendError from '../BackendError';
|
||||
import { PanelTile, PanelTileGrid } from '../panels';
|
||||
import { StorageManagerContext } from '../../api/storageManagerContext';
|
||||
import { router } from '../../appRouter';
|
||||
import { requireArray, requireDefined, requireObject } from '../../utils/apiShape';
|
||||
import { backendErrorFrom } from '../../utils/backendError';
|
||||
import { notifyError } from '../../utils/notify';
|
||||
import ManifestHeader from './ManifestHeader';
|
||||
import ManifestLines from './ManifestLines';
|
||||
import {
|
||||
buildManifestBody,
|
||||
dateInputValue,
|
||||
emptyLine,
|
||||
lineFromApi,
|
||||
loadParties,
|
||||
manifestConfig,
|
||||
} from './manifestConfig';
|
||||
|
||||
class ManifestForm extends PureComponent {
|
||||
static contextType = StorageManagerContext;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.cfg = manifestConfig(props.kind);
|
||||
this.state = {
|
||||
status: props.mode === 'edit' ? 'loading' : 'loadingParties',
|
||||
error: null,
|
||||
parties: [],
|
||||
partiesLoading: true,
|
||||
date: '',
|
||||
partyId: null,
|
||||
number: '',
|
||||
lines: [emptyLine()],
|
||||
saving: false,
|
||||
};
|
||||
this._cancelled = false;
|
||||
this.handleRetry = this.handleRetry.bind(this);
|
||||
this.handlePartyChange = this.handlePartyChange.bind(this);
|
||||
this.handleDateChange = this.handleDateChange.bind(this);
|
||||
this.handleNumberChange = this.handleNumberChange.bind(this);
|
||||
this.handleLineChange = this.handleLineChange.bind(this);
|
||||
this.handleAddLine = this.handleAddLine.bind(this);
|
||||
this.handleRemoveLine = this.handleRemoveLine.bind(this);
|
||||
this.handleSave = this.handleSave.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this._cancelled = false;
|
||||
if (this.props.mode === 'edit') void this.loadEdit();
|
||||
else void this.loadPartiesOnly();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (
|
||||
this.props.mode === 'edit' &&
|
||||
prevProps.docId !== this.props.docId
|
||||
) {
|
||||
void this.loadEdit();
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this._cancelled = true;
|
||||
}
|
||||
|
||||
async loadPartiesOnly() {
|
||||
this.setState({ status: 'loadingParties', error: null, partiesLoading: true });
|
||||
try {
|
||||
const parties = await loadParties(this.props.kind, this.context);
|
||||
if (this._cancelled) return;
|
||||
this.setState({
|
||||
status: 'ready',
|
||||
parties,
|
||||
partiesLoading: false,
|
||||
});
|
||||
} catch (err) {
|
||||
if (this._cancelled) return;
|
||||
this.setState({
|
||||
status: 'failed',
|
||||
error: backendErrorFrom(err),
|
||||
partiesLoading: false,
|
||||
});
|
||||
notifyError(err);
|
||||
}
|
||||
}
|
||||
|
||||
async loadEdit() {
|
||||
const { docId, kind } = this.props;
|
||||
const cfg = this.cfg;
|
||||
if (docId == null) {
|
||||
this.setState({
|
||||
status: 'failed',
|
||||
error: backendErrorFrom(new Error(cfg.invalidId)),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.setState({ status: 'loading', error: null, partiesLoading: true });
|
||||
try {
|
||||
const [docRes, parties] = await Promise.all([
|
||||
this.context[cfg.api].get(docId),
|
||||
loadParties(kind, this.context),
|
||||
]);
|
||||
if (this._cancelled) return;
|
||||
|
||||
requireObject(docRes, cfg.getPathLabel);
|
||||
requireObject(docRes[cfg.docField], cfg.docField);
|
||||
const doc = docRes[cfg.docField];
|
||||
const apiLines = requireArray(doc.lines, `${cfg.docField}.lines`);
|
||||
const lines =
|
||||
apiLines.length > 0 ? apiLines.map(lineFromApi) : [emptyLine()];
|
||||
|
||||
this.setState({
|
||||
status: 'ready',
|
||||
parties,
|
||||
partiesLoading: false,
|
||||
date: dateInputValue(doc.date),
|
||||
partyId: doc[cfg.partyField],
|
||||
number: doc.number ?? '',
|
||||
lines,
|
||||
});
|
||||
} catch (err) {
|
||||
if (this._cancelled) return;
|
||||
this.setState({
|
||||
status: 'failed',
|
||||
error: backendErrorFrom(err),
|
||||
partiesLoading: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
handleRetry() {
|
||||
if (this.props.mode === 'edit') void this.loadEdit();
|
||||
else void this.loadPartiesOnly();
|
||||
}
|
||||
|
||||
handlePartyChange(partyId) {
|
||||
const { mode } = this.props;
|
||||
const { requirePartyBeforeLines } = this.cfg;
|
||||
if (mode === 'create' && requirePartyBeforeLines && partyId == null) {
|
||||
this.setState({ partyId: null, lines: [emptyLine()] });
|
||||
return;
|
||||
}
|
||||
this.setState({ partyId });
|
||||
}
|
||||
|
||||
handleDateChange(date) {
|
||||
this.setState({ date });
|
||||
}
|
||||
|
||||
handleNumberChange(number) {
|
||||
this.setState({ number });
|
||||
}
|
||||
|
||||
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() {
|
||||
const { mode, docId } = this.props;
|
||||
const cfg = this.cfg;
|
||||
if (this.state.saving) return;
|
||||
if (mode === 'edit' && docId == null) return;
|
||||
|
||||
const requireAtLeastOne = mode === 'create';
|
||||
let body;
|
||||
try {
|
||||
body = buildManifestBody(
|
||||
{
|
||||
number: this.state.number,
|
||||
date: this.state.date,
|
||||
partyId: this.state.partyId,
|
||||
lines: this.state.lines,
|
||||
},
|
||||
{ partyField: cfg.partyField, requireAtLeastOne },
|
||||
);
|
||||
} catch (err) {
|
||||
notifyError(err);
|
||||
return;
|
||||
}
|
||||
|
||||
this.setState({ saving: true });
|
||||
try {
|
||||
if (mode === 'create') {
|
||||
const data = await this.context[cfg.api].create(body);
|
||||
requireObject(data, cfg.postPathLabel);
|
||||
requireObject(data[cfg.docField], cfg.docField);
|
||||
requireDefined(data[cfg.docField].id, `${cfg.docField}.id`);
|
||||
await this.context[cfg.updateCache]();
|
||||
if (this._cancelled) return;
|
||||
enqueueSnackbar(cfg.createdMsg, { variant: 'success' });
|
||||
void router.navigate(cfg.editPath(data[cfg.docField].id));
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await this.context[cfg.api].update(docId, body);
|
||||
requireObject(data, cfg.patchPathLabel);
|
||||
requireObject(data[cfg.docField], cfg.docField);
|
||||
requireDefined(data[cfg.docField].id, `${cfg.docField}.id`);
|
||||
await this.context[cfg.updateCache]();
|
||||
if (this._cancelled) return;
|
||||
const doc = data[cfg.docField];
|
||||
const apiLines = requireArray(doc.lines, `${cfg.docField}.lines`);
|
||||
this.setState({
|
||||
date: dateInputValue(doc.date),
|
||||
partyId: doc[cfg.partyField],
|
||||
number: doc.number ?? '',
|
||||
lines:
|
||||
apiLines.length > 0 ? apiLines.map(lineFromApi) : [emptyLine()],
|
||||
saving: false,
|
||||
});
|
||||
enqueueSnackbar(cfg.savedMsg, { variant: 'success' });
|
||||
} catch (err) {
|
||||
if (this._cancelled) return;
|
||||
notifyError(err);
|
||||
this.setState({ saving: false });
|
||||
}
|
||||
}
|
||||
|
||||
renderArticles() {
|
||||
const { mode } = this.props;
|
||||
const cfg = this.cfg;
|
||||
const { partyId, lines, saving } = this.state;
|
||||
|
||||
if (
|
||||
cfg.requirePartyBeforeLines &&
|
||||
mode === 'create' &&
|
||||
partyId == null
|
||||
) {
|
||||
return (
|
||||
<PanelTile wide={3} minHeight={160} color="#e2e8f0">
|
||||
<Typography color="text.secondary">
|
||||
{cfg.partyGateMessage}
|
||||
</Typography>
|
||||
</PanelTile>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ManifestLines
|
||||
lines={lines}
|
||||
saving={saving}
|
||||
linesColor={cfg.linesColor}
|
||||
onLineChange={this.handleLineChange}
|
||||
onAddLine={this.handleAddLine}
|
||||
onRemoveLine={this.handleRemoveLine}
|
||||
onSave={() => void this.handleSave()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const { kind, mode } = this.props;
|
||||
const cfg = this.cfg;
|
||||
const {
|
||||
status,
|
||||
error,
|
||||
parties,
|
||||
partiesLoading,
|
||||
date,
|
||||
partyId,
|
||||
number,
|
||||
saving,
|
||||
} = this.state;
|
||||
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 'failed') {
|
||||
return <BackendError error={error} onRetry={this.handleRetry} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<PanelTileGrid>
|
||||
<ManifestHeader
|
||||
kind={kind}
|
||||
headerColor={cfg.headerColor}
|
||||
dateLabel={cfg.dateLabel}
|
||||
partyLabel={cfg.partyLabel}
|
||||
parties={parties}
|
||||
partiesLoading={partiesLoading || status === 'loadingParties'}
|
||||
partyId={partyId}
|
||||
date={date}
|
||||
number={number}
|
||||
saving={saving}
|
||||
onPartyChange={this.handlePartyChange}
|
||||
onDateChange={this.handleDateChange}
|
||||
onNumberChange={this.handleNumberChange}
|
||||
/>
|
||||
{status === 'ready' ? this.renderArticles() : null}
|
||||
</PanelTileGrid>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default ManifestForm;
|
||||
83
src/components/manifest/ManifestFormLine.jsx
Normal file
83
src/components/manifest/ManifestFormLine.jsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import { PureComponent } from 'react';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import TableCell from '@mui/material/TableCell';
|
||||
import TableRow from '@mui/material/TableRow';
|
||||
import TextField from '@mui/material/TextField';
|
||||
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
|
||||
import { LINE_COLUMNS } from './manifestConfig';
|
||||
|
||||
class ManifestFormLine extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.handleRemove = this.handleRemove.bind(this);
|
||||
}
|
||||
|
||||
handleRemove() {
|
||||
this.props.onRemove(this.props.line.key);
|
||||
}
|
||||
|
||||
renderField(column) {
|
||||
const { id, align, type } = column;
|
||||
const { line, saving, onChange } = this.props;
|
||||
return (
|
||||
<TextField
|
||||
size="small"
|
||||
fullWidth
|
||||
type={type}
|
||||
value={line[id]}
|
||||
disabled={saving}
|
||||
autoComplete="off"
|
||||
onChange={(e) => onChange(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,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const { columns = LINE_COLUMNS, saving } = this.props;
|
||||
|
||||
return (
|
||||
<TableRow>
|
||||
{columns.map((col) => (
|
||||
<TableCell
|
||||
key={col.id}
|
||||
align={col.align}
|
||||
sx={{ py: 0.75, verticalAlign: 'middle' }}
|
||||
>
|
||||
{this.renderField(col)}
|
||||
</TableCell>
|
||||
))}
|
||||
<TableCell padding="checkbox" sx={{ py: 0.75 }}>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label="Zeile entfernen"
|
||||
disabled={saving}
|
||||
onClick={this.handleRemove}
|
||||
>
|
||||
<DeleteOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default ManifestFormLine;
|
||||
93
src/components/manifest/ManifestHeader.jsx
Normal file
93
src/components/manifest/ManifestHeader.jsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import { PureComponent } from 'react';
|
||||
import Autocomplete from '@mui/material/Autocomplete';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import TextField from '@mui/material/TextField';
|
||||
import SingleLineTextEdit from '../SingleLineTextEdit';
|
||||
import { PanelTile } from '../panels';
|
||||
import { partyDisplayName } from './manifestConfig';
|
||||
|
||||
class ManifestHeader extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.handlePartyChange = this.handlePartyChange.bind(this);
|
||||
}
|
||||
|
||||
handlePartyChange(_event, option) {
|
||||
this.props.onPartyChange(option?.id ?? null);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
kind,
|
||||
headerColor,
|
||||
dateLabel,
|
||||
partyLabel,
|
||||
parties,
|
||||
partiesLoading,
|
||||
partyId,
|
||||
date,
|
||||
number,
|
||||
saving,
|
||||
onDateChange,
|
||||
onNumberChange,
|
||||
} = this.props;
|
||||
|
||||
const selected = parties.find((row) => row.id === partyId) ?? null;
|
||||
|
||||
return (
|
||||
<PanelTile wide={3} minHeight={160} color={headerColor} title="Kopfdaten">
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
|
||||
<TextField
|
||||
size="small"
|
||||
type="date"
|
||||
label={dateLabel}
|
||||
value={date}
|
||||
disabled={saving}
|
||||
onChange={(e) => onDateChange(e.target.value)}
|
||||
autoComplete="off"
|
||||
slotProps={{
|
||||
inputLabel: { shrink: true },
|
||||
htmlInput: { spellCheck: false },
|
||||
}}
|
||||
sx={{ minWidth: 220 }}
|
||||
/>
|
||||
<Autocomplete
|
||||
size="small"
|
||||
options={parties}
|
||||
value={selected}
|
||||
loading={Boolean(partiesLoading)}
|
||||
disabled={saving}
|
||||
getOptionLabel={(option) => partyDisplayName(kind, option)}
|
||||
isOptionEqualToValue={(option, value) => option.id === value.id}
|
||||
onChange={this.handlePartyChange}
|
||||
sx={{ flex: 1, minWidth: 220 }}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
label={partyLabel}
|
||||
slotProps={{
|
||||
...params.slotProps,
|
||||
htmlInput: {
|
||||
...params.slotProps?.htmlInput,
|
||||
spellCheck: false,
|
||||
autoComplete: 'off',
|
||||
},
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<SingleLineTextEdit
|
||||
size="small"
|
||||
label="Nummer"
|
||||
value={number}
|
||||
disabled={saving}
|
||||
onChange={onNumberChange}
|
||||
sx={{ minWidth: 180, flex: 1 }}
|
||||
/>
|
||||
</Stack>
|
||||
</PanelTile>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default ManifestHeader;
|
||||
91
src/components/manifest/ManifestLines.jsx
Normal file
91
src/components/manifest/ManifestLines.jsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import { PureComponent } from 'react';
|
||||
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 AddIcon from '@mui/icons-material/Add';
|
||||
import { PanelTile } from '../panels';
|
||||
import { LINE_COLUMNS } from './manifestConfig';
|
||||
import ManifestFormLine from './ManifestFormLine';
|
||||
|
||||
class ManifestLines extends PureComponent {
|
||||
render() {
|
||||
const {
|
||||
lines,
|
||||
saving,
|
||||
linesColor,
|
||||
onLineChange,
|
||||
onAddLine,
|
||||
onRemoveLine,
|
||||
onSave,
|
||||
columns = LINE_COLUMNS,
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<PanelTile wide={3} minHeight={280} color={linesColor} 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: linesColor,
|
||||
}}
|
||||
>
|
||||
{col.label}
|
||||
</TableCell>
|
||||
))}
|
||||
<TableCell padding="checkbox" sx={{ bgcolor: linesColor }} />
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{lines.map((line) => (
|
||||
<ManifestFormLine
|
||||
key={line.key}
|
||||
line={line}
|
||||
columns={columns}
|
||||
saving={saving}
|
||||
onChange={onLineChange}
|
||||
onRemove={onRemoveLine}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
|
||||
<Button
|
||||
size="small"
|
||||
startIcon={<AddIcon />}
|
||||
disabled={saving}
|
||||
onClick={onAddLine}
|
||||
>
|
||||
Zeile hinzufügen
|
||||
</Button>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<Button
|
||||
variant="contained"
|
||||
size="small"
|
||||
disabled={saving}
|
||||
onClick={onSave}
|
||||
>
|
||||
{saving ? 'Speichern…' : 'Speichern'}
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
</PanelTile>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default ManifestLines;
|
||||
206
src/components/manifest/ManifestList.jsx
Normal file
206
src/components/manifest/ManifestList.jsx
Normal file
@@ -0,0 +1,206 @@
|
||||
import { PureComponent } from 'react';
|
||||
import Box from '@mui/material/Box';
|
||||
import Button from '@mui/material/Button';
|
||||
import CircularProgress from '@mui/material/CircularProgress';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
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 Typography from '@mui/material/Typography';
|
||||
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
|
||||
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
|
||||
import { enqueueSnackbar } from 'notistack';
|
||||
import BackendError from '../BackendError';
|
||||
import { PanelTile, PanelTileGrid } from '../panels';
|
||||
import { StorageManagerContext } from '../../api/storageManagerContext';
|
||||
import { router } from '../../appRouter';
|
||||
import { backendErrorFrom } from '../../utils/backendError';
|
||||
import { notifyError } from '../../utils/notify';
|
||||
import {
|
||||
formatDate,
|
||||
loadParties,
|
||||
manifestConfig,
|
||||
partyDisplayName,
|
||||
sortDocs,
|
||||
} from './manifestConfig';
|
||||
|
||||
class ManifestList extends PureComponent {
|
||||
static contextType = StorageManagerContext;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.cfg = manifestConfig(props.kind);
|
||||
this.state = {
|
||||
status: 'loading',
|
||||
error: null,
|
||||
docs: [],
|
||||
partiesById: {},
|
||||
busyId: null,
|
||||
};
|
||||
this._cancelled = false;
|
||||
this.handleRetry = this.handleRetry.bind(this);
|
||||
this.handleCreate = this.handleCreate.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this._cancelled = false;
|
||||
void this.load();
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this._cancelled = true;
|
||||
}
|
||||
|
||||
async load() {
|
||||
const cfg = this.cfg;
|
||||
this.setState({ status: 'loading', error: null });
|
||||
try {
|
||||
const [docs, parties] = await Promise.all([
|
||||
cfg.listPromise(this.context),
|
||||
loadParties(this.props.kind, this.context),
|
||||
]);
|
||||
if (this._cancelled) return;
|
||||
this.setState({
|
||||
status: 'ready',
|
||||
docs: sortDocs(docs),
|
||||
partiesById: cfg.partiesByIdFromList(parties),
|
||||
});
|
||||
} catch (err) {
|
||||
if (this._cancelled) return;
|
||||
this.setState({ status: 'failed', error: backendErrorFrom(err) });
|
||||
}
|
||||
}
|
||||
|
||||
handleRetry() {
|
||||
void this.load();
|
||||
}
|
||||
|
||||
handleCreate() {
|
||||
void router.navigate(this.cfg.createPath);
|
||||
}
|
||||
|
||||
handleEdit(doc) {
|
||||
void router.navigate(this.cfg.editPath(doc.id));
|
||||
}
|
||||
|
||||
async handleDelete(doc) {
|
||||
if (this.state.busyId != null) return;
|
||||
if (!window.confirm(this.cfg.confirmDelete(doc.number))) return;
|
||||
|
||||
const cfg = this.cfg;
|
||||
this.setState({ busyId: doc.id });
|
||||
try {
|
||||
await this.context[cfg.api].delete(doc.id);
|
||||
const list = await this.context[cfg.updateCache]();
|
||||
if (this._cancelled) return;
|
||||
this.setState({
|
||||
docs: sortDocs(list),
|
||||
busyId: null,
|
||||
});
|
||||
enqueueSnackbar(cfg.deletedMsg, { variant: 'success' });
|
||||
} catch (err) {
|
||||
if (this._cancelled) return;
|
||||
notifyError(err);
|
||||
this.setState({ busyId: null });
|
||||
}
|
||||
}
|
||||
|
||||
partyName(partyId) {
|
||||
if (partyId == null) return null;
|
||||
return partyDisplayName(
|
||||
this.props.kind,
|
||||
this.state.partiesById[partyId],
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const { status, error, docs, busyId } = this.state;
|
||||
const cfg = this.cfg;
|
||||
const partyField = cfg.partyField;
|
||||
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 'failed') {
|
||||
return <BackendError error={error} onRetry={this.handleRetry} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<PanelTileGrid>
|
||||
<PanelTile wide={3} minHeight={240} color={cfg.listColor}>
|
||||
<Stack spacing={2}>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<Button variant="contained" size="small" onClick={this.handleCreate}>
|
||||
{cfg.createButton}
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{docs.length === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{cfg.emptyList}
|
||||
</Typography>
|
||||
) : (
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Nummer</TableCell>
|
||||
<TableCell>{cfg.dateLabel}</TableCell>
|
||||
<TableCell>{cfg.partyLabel}</TableCell>
|
||||
<TableCell padding="checkbox" />
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{docs.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
hover
|
||||
sx={{ cursor: 'pointer' }}
|
||||
onClick={() => this.handleEdit(row)}
|
||||
>
|
||||
<TableCell>{row.number}</TableCell>
|
||||
<TableCell>{formatDate(row.date)}</TableCell>
|
||||
<TableCell>{this.partyName(row[partyField])}</TableCell>
|
||||
<TableCell
|
||||
padding="checkbox"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`„${row.number}“ bearbeiten`}
|
||||
onClick={() => this.handleEdit(row)}
|
||||
>
|
||||
<EditOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`„${row.number}“ löschen`}
|
||||
disabled={busyId != null}
|
||||
onClick={() => void this.handleDelete(row)}
|
||||
>
|
||||
<DeleteOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)}
|
||||
</Stack>
|
||||
</PanelTile>
|
||||
</PanelTileGrid>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default ManifestList;
|
||||
13
src/components/manifest/index.js
Normal file
13
src/components/manifest/index.js
Normal file
@@ -0,0 +1,13 @@
|
||||
export { default as ManifestList } from './ManifestList';
|
||||
export { default as ManifestForm } from './ManifestForm';
|
||||
export { default as ManifestHeader } from './ManifestHeader';
|
||||
export { default as ManifestLines } from './ManifestLines';
|
||||
export { default as ManifestFormLine } from './ManifestFormLine';
|
||||
export { withManifestId } from './withManifestId';
|
||||
export {
|
||||
manifestConfig,
|
||||
LINE_COLUMNS,
|
||||
emptyLine,
|
||||
lineFromApi,
|
||||
buildManifestBody,
|
||||
} from './manifestConfig';
|
||||
264
src/components/manifest/manifestConfig.js
Normal file
264
src/components/manifest/manifestConfig.js
Normal file
@@ -0,0 +1,264 @@
|
||||
/** Groups that are not sales customers (filter client-side). */
|
||||
export const EXCLUDED_CUSTOMER_GROUP_NAMES = new Set(['Lieferanten', 'POS']);
|
||||
|
||||
export function entityDisplayName(entity) {
|
||||
if (!entity) return '';
|
||||
return [entity.firstName, entity.name].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
export function sortEntities(entities) {
|
||||
return [...entities].sort((a, b) => {
|
||||
const byName = String(a.name).localeCompare(String(b.name), 'de');
|
||||
if (byName !== 0) return byName;
|
||||
return String(a.firstName ?? '').localeCompare(String(b.firstName ?? ''), 'de');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Customers = entities whose customergroup.name is not Lieferanten/POS.
|
||||
*/
|
||||
export function filterCustomerEntities(entities, groups) {
|
||||
const excludedIds = new Set(
|
||||
groups
|
||||
.filter((g) => EXCLUDED_CUSTOMER_GROUP_NAMES.has(g.name))
|
||||
.map((g) => g.id),
|
||||
);
|
||||
return sortEntities(
|
||||
entities.filter((e) => !excludedIds.has(e.customergroupId)),
|
||||
);
|
||||
}
|
||||
|
||||
export function sortSuppliers(suppliers) {
|
||||
return [...suppliers].sort((a, b) =>
|
||||
String(a.name).localeCompare(String(b.name), 'de'),
|
||||
);
|
||||
}
|
||||
|
||||
export function sortDocs(docs) {
|
||||
return [...docs].sort((a, b) => String(b.date).localeCompare(String(a.date)));
|
||||
}
|
||||
|
||||
export function formatDate(iso) {
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleDateString('de-DE');
|
||||
}
|
||||
|
||||
export function dateInputValue(iso) {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return String(iso).slice(0, 10);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function emptyLine() {
|
||||
return {
|
||||
key: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
amount: '',
|
||||
sku: '',
|
||||
tax: '',
|
||||
rebate: '',
|
||||
net: '',
|
||||
};
|
||||
}
|
||||
|
||||
export function lineFromApi(row) {
|
||||
return {
|
||||
key: `line-${row.id}`,
|
||||
amount: row.amount == null ? '' : String(row.amount),
|
||||
sku: row.sku ?? '',
|
||||
tax: row.tax == null ? '' : String(row.tax),
|
||||
rebate: row.rebate == null ? '' : String(row.rebate),
|
||||
net: row.net == null ? '' : String(row.net),
|
||||
};
|
||||
}
|
||||
|
||||
function parseNum(value) {
|
||||
if (value == null || value === '') return null;
|
||||
const n = Number(String(value).trim().replace(',', '.'));
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/** Build create/update line array. Throws Error on client validation. */
|
||||
export function buildLines(lines, { requireAtLeastOne }) {
|
||||
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 (requireAtLeastOne && outLines.length === 0) {
|
||||
throw new Error('Mindestens eine Artikelzeile nötig.');
|
||||
}
|
||||
return outLines;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ number: string, date: string, partyId: number|null, lines: object[] }} form
|
||||
* @param {{ partyField: 'supplierId'|'entityId', requireAtLeastOne: boolean }} opts
|
||||
*/
|
||||
export function buildManifestBody(form, { partyField, requireAtLeastOne }) {
|
||||
const number = String(form.number ?? '').trim();
|
||||
const date = form.date;
|
||||
if (!number) throw new Error('Nummer fehlt.');
|
||||
if (!date) throw new Error('Datum fehlt.');
|
||||
|
||||
const body = {
|
||||
number,
|
||||
date,
|
||||
lines: buildLines(form.lines, { requireAtLeastOne }),
|
||||
};
|
||||
if (form.partyId != null) body[partyField] = form.partyId;
|
||||
else if (!requireAtLeastOne) body[partyField] = null;
|
||||
return body;
|
||||
}
|
||||
|
||||
export const LINE_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' },
|
||||
];
|
||||
|
||||
/** @typedef {'delivery'|'quote'|'order'} ManifestKind */
|
||||
|
||||
/**
|
||||
* Load party options for Autocomplete / list name lookup.
|
||||
* @param {ManifestKind} kind
|
||||
* @param {object} ctx StorageManager instance
|
||||
*/
|
||||
export async function loadParties(kind, ctx) {
|
||||
if (kind === 'delivery') {
|
||||
const list = ctx.suppliers ?? (await ctx.supplierPromise);
|
||||
return sortSuppliers(list);
|
||||
}
|
||||
const [entities, groups] = await Promise.all([
|
||||
ctx.entities ?? ctx.entityPromise,
|
||||
ctx.customergroups ?? ctx.customergroupPromise,
|
||||
]);
|
||||
return filterCustomerEntities(entities, groups);
|
||||
}
|
||||
|
||||
export function partyDisplayName(kind, party) {
|
||||
if (!party) return '';
|
||||
if (kind === 'delivery') return String(party.name ?? '');
|
||||
return entityDisplayName(party);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ManifestKind} kind
|
||||
*/
|
||||
export function manifestConfig(kind) {
|
||||
if (kind === 'delivery') {
|
||||
return {
|
||||
kind: 'delivery',
|
||||
api: 'delivery',
|
||||
listField: 'deliveries',
|
||||
docField: 'delivery',
|
||||
partyField: 'supplierId',
|
||||
listPath: '/lieferung',
|
||||
createPath: '/lieferung/neu',
|
||||
editPath: (id) => `/lieferung/${id}`,
|
||||
dateLabel: 'Lieferdatum',
|
||||
partyLabel: 'Lieferant',
|
||||
emptyList: 'Noch keine Lieferungen.',
|
||||
createButton: 'Neue Lieferung',
|
||||
createdMsg: 'Lieferung angelegt.',
|
||||
savedMsg: 'Lieferung gespeichert.',
|
||||
deletedMsg: 'Lieferung gelöscht.',
|
||||
confirmDelete: (number) => `Lieferung „${number}“ wirklich löschen?`,
|
||||
invalidId: 'Ungültige Lieferungs-ID.',
|
||||
partyGateMessage: 'Lieferant wählen, um Artikel zu erfassen.',
|
||||
getPathLabel: 'GET /api/delivery/:id',
|
||||
postPathLabel: 'POST /api/delivery',
|
||||
patchPathLabel: 'PATCH /api/delivery/:id',
|
||||
listColor: '#fed7aa',
|
||||
headerColor: '#fed7aa',
|
||||
linesColor: '#bbf7d0',
|
||||
requirePartyBeforeLines: true,
|
||||
updateCache: 'updateDelivery',
|
||||
listPromise: (ctx) => ctx.deliveries ?? ctx.deliveryPromise,
|
||||
partiesByIdFromList: (parties) =>
|
||||
Object.fromEntries(parties.map((row) => [row.id, row])),
|
||||
};
|
||||
}
|
||||
if (kind === 'quote') {
|
||||
return {
|
||||
kind: 'quote',
|
||||
api: 'quote',
|
||||
listField: 'quotes',
|
||||
docField: 'quote',
|
||||
partyField: 'entityId',
|
||||
listPath: '/auftrag',
|
||||
createPath: '/auftrag/neu',
|
||||
editPath: (id) => `/auftrag/${id}`,
|
||||
dateLabel: 'Gültig bis',
|
||||
partyLabel: 'Kunde',
|
||||
emptyList: 'Noch keine Angebote.',
|
||||
createButton: 'Neues Angebot',
|
||||
createdMsg: 'Angebot angelegt.',
|
||||
savedMsg: 'Angebot gespeichert.',
|
||||
deletedMsg: 'Angebot gelöscht.',
|
||||
confirmDelete: (number) => `Angebot „${number}“ wirklich löschen?`,
|
||||
invalidId: 'Ungültige Angebots-ID.',
|
||||
partyGateMessage: null,
|
||||
getPathLabel: 'GET /api/quote/:id',
|
||||
postPathLabel: 'POST /api/quote',
|
||||
patchPathLabel: 'PATCH /api/quote/:id',
|
||||
listColor: '#fde68a',
|
||||
headerColor: '#fde68a',
|
||||
linesColor: '#bbf7d0',
|
||||
requirePartyBeforeLines: false,
|
||||
updateCache: 'updateQuote',
|
||||
listPromise: (ctx) => ctx.quotes ?? ctx.quotePromise,
|
||||
partiesByIdFromList: (parties) =>
|
||||
Object.fromEntries(parties.map((row) => [row.id, row])),
|
||||
};
|
||||
}
|
||||
if (kind === 'order') {
|
||||
return {
|
||||
kind: 'order',
|
||||
api: 'order',
|
||||
listField: 'orders',
|
||||
docField: 'order',
|
||||
partyField: 'entityId',
|
||||
listPath: '/auftrag/bestellung',
|
||||
createPath: '/auftrag/bestellung/neu',
|
||||
editPath: (id) => `/auftrag/bestellung/${id}`,
|
||||
dateLabel: 'Lieferdatum',
|
||||
partyLabel: 'Kunde',
|
||||
emptyList: 'Noch keine Bestellungen.',
|
||||
createButton: 'Neue Bestellung',
|
||||
createdMsg: 'Bestellung angelegt.',
|
||||
savedMsg: 'Bestellung gespeichert.',
|
||||
deletedMsg: 'Bestellung gelöscht.',
|
||||
confirmDelete: (number) => `Bestellung „${number}“ wirklich löschen?`,
|
||||
invalidId: 'Ungültige Bestellungs-ID.',
|
||||
partyGateMessage: null,
|
||||
getPathLabel: 'GET /api/order/:id',
|
||||
postPathLabel: 'POST /api/order',
|
||||
patchPathLabel: 'PATCH /api/order/:id',
|
||||
listColor: '#c4b5fd',
|
||||
headerColor: '#c4b5fd',
|
||||
linesColor: '#bbf7d0',
|
||||
requirePartyBeforeLines: false,
|
||||
updateCache: 'updateOrder',
|
||||
listPromise: (ctx) => ctx.orders ?? ctx.orderPromise,
|
||||
partiesByIdFromList: (parties) =>
|
||||
Object.fromEntries(parties.map((row) => [row.id, row])),
|
||||
};
|
||||
}
|
||||
throw new Error(`Unknown manifest kind: ${kind}`);
|
||||
}
|
||||
20
src/components/manifest/withManifestId.jsx
Normal file
20
src/components/manifest/withManifestId.jsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
/**
|
||||
* Router glue only: maps a path param to `docId` (integer or null).
|
||||
* Function component is intentional — useParams has no class equivalent.
|
||||
*/
|
||||
export function withManifestId(paramName, Wrapped) {
|
||||
function ManifestIdWrapper(props) {
|
||||
const params = useParams();
|
||||
const raw = params[paramName];
|
||||
const docId = Number(raw);
|
||||
return (
|
||||
<Wrapped
|
||||
{...props}
|
||||
docId={Number.isInteger(docId) ? docId : null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return ManifestIdWrapper;
|
||||
}
|
||||
Reference in New Issue
Block a user