This commit is contained in:
seb
2026-10-19 01:02:08 +02:00
parent 9b40d1db87
commit eb15bcb83b
3 changed files with 274 additions and 147 deletions

View File

@@ -54,4 +54,16 @@ export const shipment = {
return http(`/api/shipment/${id}/file/${fileId}`, { method: 'DELETE' });
},
// #endregion
// #region POST /api/shipment/:id/pdf — createPdf
createPdf(id) {
return http(`/api/shipment/${id}/pdf`, { method: 'POST' });
},
// #endregion
// #region GET /api/shipment/:id/file/:fileId — getFileUrl
getFileUrl(id, fileId) {
return `/api/shipment/${encodeURIComponent(id)}/file/${encodeURIComponent(fileId)}`;
},
// #endregion
};

View File

@@ -4,7 +4,6 @@ import IconButton from '@mui/material/IconButton';
import ListItem from '@mui/material/ListItem';
import Switch from '@mui/material/Switch';
import FormControlLabel from '@mui/material/FormControlLabel';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
@@ -158,43 +157,39 @@ class CarrierItem extends PureComponent {
/>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexShrink: 0 }}>
<Tooltip title="Paketverfolgung / Tracking für Sendungen aktivieren">
<FormControlLabel
control={
<Switch
size="small"
checked={hasPackages}
disabled={disabled || !item}
onChange={this.handleToggleHasPackages}
/>
}
label={
<Typography variant="caption" sx={{ userSelect: 'none', fontWeight: 500 }}>
Pakete
</Typography>
}
sx={{ m: 0, gap: 0.5 }}
/>
</Tooltip>
<FormControlLabel
control={
<Switch
size="small"
checked={hasPackages}
disabled={disabled || !item}
onChange={this.handleToggleHasPackages}
/>
}
label={
<Typography variant="caption" sx={{ userSelect: 'none', fontWeight: 500 }}>
Pakete
</Typography>
}
sx={{ m: 0, gap: 0.5 }}
/>
<Tooltip title="Für Retouren / Rücksendungen verwenden">
<FormControlLabel
control={
<Switch
size="small"
checked={isReverse}
disabled={disabled || !item}
onChange={this.handleToggleIsReverse}
/>
}
label={
<Typography variant="caption" sx={{ userSelect: 'none', fontWeight: 500 }}>
Retoure
</Typography>
}
sx={{ m: 0, gap: 0.5 }}
/>
</Tooltip>
<FormControlLabel
control={
<Switch
size="small"
checked={isReverse}
disabled={disabled || !item}
onChange={this.handleToggleIsReverse}
/>
}
label={
<Typography variant="caption" sx={{ userSelect: 'none', fontWeight: 500 }}>
Retoure
</Typography>
}
sx={{ m: 0, gap: 0.5 }}
/>
</Box>
<IconButton

View File

@@ -24,9 +24,10 @@ import AddIcon from '@mui/icons-material/Add';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import CheckCircleOutlineOutlinedIcon from '@mui/icons-material/CheckCircleOutlineOutlined';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
import { enqueueSnackbar } from 'notistack';
import AppDialog from '../AppDialog';
import { shipment as shipmentApi, shipping as shippingApi } from '../../api';
import { shipment as shipmentApi, shipping as shippingApi, stock as stockApi } from '../../api';
import { notifyError } from '../../utils/notify';
import { formatDate } from './manifestConfig';
import orderAutomat from '../../automats/orderAutomat';
@@ -38,13 +39,11 @@ import { SURFACE_RAISED, WHITE } from '../../colors';
class AddPackageDialog extends PureComponent {
constructor(props) {
super(props);
const carriers = carrierAutomat.state.carriers || [];
const carriers = (carrierAutomat.state.carriers || []).filter((c) => !c.isReverse);
this.state = {
carriers,
carrierId: carriers[0]?.id ?? '',
trackingCode: '',
type: 'parcel',
state: 'draft',
saving: false,
};
this.handleSubmit = this.handleSubmit.bind(this);
@@ -52,7 +51,7 @@ class AddPackageDialog extends PureComponent {
componentDidMount() {
this.unsub = carrierAutomat.subscribe(this, (state) => {
const carriers = state.carriers || [];
const carriers = (state.carriers || []).filter((c) => !c.isReverse);
const currentId = this.state.carrierId;
const valid = carriers.some((c) => c.id === currentId);
return {
@@ -61,7 +60,7 @@ class AddPackageDialog extends PureComponent {
};
});
if (carrierAutomat.state.status !== 'ready') {
void carrierAutomat.actions.load().catch(() => {});
void carrierAutomat.actions.load().catch(() => { });
}
}
@@ -71,18 +70,32 @@ class AddPackageDialog extends PureComponent {
async handleSubmit() {
const { shipment, onClose, onSuccess } = this.props;
const { carrierId, trackingCode, type, state } = this.state;
const { carriers, carrierId, trackingCode } = this.state;
if (!shipment?.id || !carrierId) return;
const selectedCarrier = carriers.find((c) => String(c.id) === String(carrierId));
const hasPackages = Boolean(selectedCarrier?.hasPackages);
const trimmedTracking = hasPackages && trackingCode ? trackingCode.trim() : undefined;
this.setState({ saving: true });
try {
await shippingApi.create(shipment.id, {
carrierId: Number(carrierId),
trackingCode: trackingCode.trim() || undefined,
type,
state,
trackingCode: trimmedTracking || undefined,
type: 'parcel',
state: 'draft',
});
enqueueSnackbar('Paket angelegt.', { variant: 'success' });
const oldPdf = (shipment.files || []).find(
(f) => f.mimetype === 'application/pdf' || f.name?.toLowerCase().endsWith('.pdf')
);
if (oldPdf?.id) {
try {
await shipmentApi.deleteFile(shipment.id, oldPdf.id);
} catch {
// ignore
}
}
enqueueSnackbar('Versandart angelegt.', { variant: 'success' });
await Promise.all([
orderAutomat.actions.reload(),
shipmentAutomat.actions.reload(),
@@ -97,15 +110,17 @@ class AddPackageDialog extends PureComponent {
render() {
const { open, onClose, shipment } = this.props;
const { carriers, carrierId, trackingCode, type, state, saving } = this.state;
const { carriers, carrierId, trackingCode, saving } = this.state;
const canSubmit = Boolean(carrierId) && !saving;
const selectedCarrier = carriers.find((c) => String(c.id) === String(carrierId));
const hasPackages = Boolean(selectedCarrier?.hasPackages);
return (
<AppDialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<Box sx={{ p: 2.5 }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', pb: 2 }}>
<Typography variant="h6" sx={{ fontWeight: 600 }}>
Paket zu Lieferschein hinzufügen
Versandart hinzufügen
</Typography>
<IconButton onClick={onClose} size="small">
<CloseIcon />
@@ -118,14 +133,14 @@ class AddPackageDialog extends PureComponent {
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mb: 3 }}>
<TextField
select
label="Versandart (Carrier)"
label="Versandart"
size="small"
value={carrierId}
onChange={(e) => this.setState({ carrierId: e.target.value })}
error={carriers.length === 0}
helperText={
carriers.length === 0
? 'Keine Versandarten eingerichtet (unter Auftrag → Versandarten anlegen)'
? 'Keine Versandarten eingerichtet'
: undefined
}
>
@@ -136,38 +151,15 @@ class AddPackageDialog extends PureComponent {
))}
</TextField>
<TextField
label="Tracking-Code / Sendungsnummer"
size="small"
value={trackingCode}
onChange={(e) => this.setState({ trackingCode: e.target.value })}
placeholder="z.B. 00340434234234234"
/>
<TextField
select
label="Paketart"
size="small"
value={type}
onChange={(e) => this.setState({ type: e.target.value })}
>
<MenuItem value="parcel">Paket (Parcel)</MenuItem>
<MenuItem value="pallet">Palette (Pallet)</MenuItem>
<MenuItem value="letter">Brief / Dokument</MenuItem>
</TextField>
<TextField
select
label="Status"
size="small"
value={state}
onChange={(e) => this.setState({ state: e.target.value })}
helperText={state === 'shipped' ? 'Bucht bei Auswahl direkt das Lager ab.' : undefined}
>
<MenuItem value="draft">Entwurf (draft)</MenuItem>
<MenuItem value="packed">Gepackt (packed)</MenuItem>
<MenuItem value="shipped">Versendet (shipped — Lagerabbuchung)</MenuItem>
</TextField>
{hasPackages && (
<TextField
label="Referenz"
size="small"
value={trackingCode}
onChange={(e) => this.setState({ trackingCode: e.target.value })}
placeholder="z.B. Sendungsnummer, Paket-ID oder Referenz"
/>
)}
</Box>
<Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 1.5 }}>
@@ -175,7 +167,7 @@ class AddPackageDialog extends PureComponent {
Abbrechen
</Button>
<Button variant="contained" onClick={this.handleSubmit} disabled={!canSubmit}>
{saving ? 'Wird gespeichert…' : 'Paket anlegen'}
{saving ? 'Wird gespeichert…' : 'Versandart hinzufügen'}
</Button>
</Box>
</Box>
@@ -196,11 +188,14 @@ export default class ShipmentDetailDialog extends PureComponent {
error: null,
addPackageDialogOpen: false,
busyAction: false,
pdfLoading: false,
};
this.handleRefresh = this.handleRefresh.bind(this);
this.handleDeletePackage = this.handleDeletePackage.bind(this);
this.handleMarkPackageShipped = this.handleMarkPackageShipped.bind(this);
this.handleStateChange = this.handleStateChange.bind(this);
this.handleDeleteShipment = this.handleDeleteShipment.bind(this);
this.handleOpenPdf = this.handleOpenPdf.bind(this);
}
componentDidMount() {
@@ -240,11 +235,21 @@ export default class ShipmentDetailDialog extends PureComponent {
// #endregion
async handleDeletePackage(pkg) {
if (!window.confirm(`Paket „#${pkg.number || pkg.id}“ wirklich löschen?`)) return;
if (!window.confirm(`Versandart „#${pkg.number || pkg.id}“ wirklich löschen?`)) return;
this.setState({ busyAction: true });
try {
await shippingApi.delete(pkg.id);
enqueueSnackbar('Paket gelöscht.', { variant: 'success' });
const oldPdf = (this.state.shipment?.files || []).find(
(f) => f.mimetype === 'application/pdf' || f.name?.toLowerCase().endsWith('.pdf')
);
if (oldPdf?.id) {
try {
await shipmentApi.deleteFile(this.state.shipment.id, oldPdf.id);
} catch {
// ignore
}
}
enqueueSnackbar('Versandart gelöscht.', { variant: 'success' });
await Promise.all([
orderAutomat.actions.reload(),
shipmentAutomat.actions.reload(),
@@ -282,6 +287,29 @@ export default class ShipmentDetailDialog extends PureComponent {
this.setState({ busyAction: true });
try {
if (newState === 'delivered') {
// 1. Mark any unshipped packages as shipped (triggers backend stock deduction for linked shippings)
const unshippedPackages = (this.state.shipment?.shippings || []).filter(
(p) => p.state !== 'shipped'
);
for (const pkg of unshippedPackages) {
try {
await shippingApi.update(pkg.id, { state: 'shipped' });
} catch (err) {
console.warn('Could not mark shipping as shipped:', err);
}
}
// 2. Ensure stock deduction is executed via stock.ship for the shipment lines
try {
await stockApi.ship({ shipmentId });
} catch (err) {
if (!err?.message?.toLowerCase().includes('already shipped')) {
console.warn('Stock ship warning:', err);
}
}
}
await shipmentApi.update(shipmentId, { state: newState });
this.setState((prev) => ({
shipment: { ...prev.shipment, state: newState },
@@ -293,6 +321,7 @@ export default class ShipmentDetailDialog extends PureComponent {
shipmentAutomat.actions.reload(),
]);
this.props.onChanged?.();
await this.handleRefresh();
} catch (err) {
notifyError(err);
} finally {
@@ -300,14 +329,78 @@ export default class ShipmentDetailDialog extends PureComponent {
}
}
// MARK: calls shipmentApi.delete
// #region DELETE /api/shipment/:id — delete shipment
async handleDeleteShipment() {
const { shipment } = this.state;
if (!shipment?.id) return;
const label = shipment.number || `Lieferschein #${shipment.id}`;
if (!window.confirm(`Möchten Sie den ${label} wirklich löschen?`)) {
return;
}
this.setState({ busyAction: true });
try {
await shipmentApi.delete(shipment.id);
enqueueSnackbar(`${label} gelöscht.`, { variant: 'success' });
await Promise.all([
orderAutomat.actions.reload(),
shipmentAutomat.actions.reload(),
]);
this.props.onChanged?.();
this.props.onClose();
} catch (err) {
notifyError(err);
this.setState({ busyAction: false });
}
}
// #endregion
// MARK: calls shipmentApi.createPdf and shipmentApi.getFileUrl
// #region POST /api/shipment/:id/pdf & GET file — open PDF
async handleOpenPdf() {
const { shipment } = this.state;
if (!shipment?.id) return;
this.setState({ pdfLoading: true });
try {
const existingPdf = (shipment.files || []).find(
(f) => f.mimetype === 'application/pdf' || f.name?.toLowerCase().endsWith('.pdf')
);
let targetUrl = null;
if (existingPdf) {
targetUrl = shipmentApi.getFileUrl(shipment.id, existingPdf.fileId || existingPdf.id);
} else {
const res = await shipmentApi.createPdf(shipment.id);
const rawUrl = res?.fileUrl || (res?.attachment ? shipmentApi.getFileUrl(shipment.id, res.attachment.fileId || res.attachment.id) : null);
targetUrl = rawUrl ? (rawUrl.startsWith('/api') ? rawUrl : `/api${rawUrl}`) : null;
await this.handleRefresh();
}
if (targetUrl) {
window.open(targetUrl, '_blank');
} else {
enqueueSnackbar('PDF-URL konnte nicht geladen werden.', { variant: 'error' });
}
} catch (err) {
notifyError(err);
} finally {
this.setState({ pdfLoading: false });
}
}
// #endregion
render() {
const { open, onClose } = this.props;
const { shipment, loading, error, addPackageDialogOpen, busyAction } = this.state;
const { shipment, loading, error, addPackageDialogOpen, busyAction, pdfLoading } = this.state;
if (!shipment) return null;
const shLines = Array.isArray(shipment.lines) ? shipment.lines : [];
const shPackages = Array.isArray(shipment.shippings) ? shipment.shippings : [];
const carriers = carrierAutomat.state.carriers || [];
return (
<AppDialog open={open} onClose={onClose} maxWidth="md" fullWidth>
@@ -386,7 +479,7 @@ export default class ShipmentDetailDialog extends PureComponent {
disabled={busyAction}
sx={{ textTransform: 'none', fontWeight: 600, height: 28, fontSize: '0.75rem' }}
>
Paket hinzufügen
Versand hinzufügen
</Button>
</Box>
@@ -394,6 +487,8 @@ export default class ShipmentDetailDialog extends PureComponent {
<Stack spacing={1}>
{shPackages.map((pkg) => {
const isShipped = pkg.state === 'shipped';
const carrierObj = carriers.find((c) => Number(c.id) === Number(pkg.carrierId));
const carrierHasPackages = carrierObj ? Boolean(carrierObj.hasPackages) : false;
return (
<Box
key={pkg.id}
@@ -412,7 +507,7 @@ export default class ShipmentDetailDialog extends PureComponent {
<Chip size="small" label={`#${pkg.number || pkg.id}`} sx={{ fontWeight: 700 }} />
<Box>
<Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
{pkg.carrier || 'DHL'} ({pkg.type === 'pallet' ? 'Palette' : 'Paket'})
{pkg.carrier || 'Versand'}
</Typography>
{pkg.trackingCode ? (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mt: 0.25 }}>
@@ -423,18 +518,14 @@ export default class ShipmentDetailDialog extends PureComponent {
size="small"
onClick={() => {
navigator.clipboard.writeText(pkg.trackingCode);
enqueueSnackbar('Tracking-Code kopiert!', { variant: 'info' });
enqueueSnackbar('Referenz kopiert!', { variant: 'info' });
}}
sx={{ p: 0.25 }}
>
<ContentCopyIcon sx={{ fontSize: 13 }} />
</IconButton>
</Box>
) : (
<Typography variant="caption" color="text.secondary">
Ohne Tracking
</Typography>
)}
) : null}
</Box>
</Box>
@@ -449,16 +540,18 @@ export default class ShipmentDetailDialog extends PureComponent {
/>
) : (
<>
<Button
size="small"
variant="contained"
color="success"
disabled={busyAction}
onClick={() => this.handleMarkPackageShipped(pkg)}
sx={{ textTransform: 'none', py: 0.25, px: 1, height: 26, fontSize: '0.75rem' }}
>
Als versendet buchen
</Button>
{carrierHasPackages && (
<Button
size="small"
variant="contained"
color="success"
disabled={busyAction}
onClick={() => this.handleMarkPackageShipped(pkg)}
sx={{ textTransform: 'none', py: 0.25, px: 1, height: 26, fontSize: '0.75rem' }}
>
Als versendet buchen
</Button>
)}
<IconButton
size="small"
color="error"
@@ -478,51 +571,78 @@ export default class ShipmentDetailDialog extends PureComponent {
</Box>
</DialogContent>
<DialogActions sx={{ p: 2, justifyContent: 'flex-end' }}>
{(!shipment.state || shipment.state === 'new') && (
<DialogActions sx={{ p: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Button
variant="outlined"
color="error"
startIcon={<DeleteOutlinedIcon />}
disabled={busyAction || shipment.state === 'delivered'}
onClick={this.handleDeleteShipment}
title={shipment.state === 'delivered' ? 'Bereits versendete Lieferscheine können nicht gelöscht werden' : 'Lieferschein löschen'}
sx={{ textTransform: 'none', fontWeight: 600 }}
>
Lieferschein löschen
</Button>
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center' }}>
<Button
variant="contained"
color="primary"
disabled={busyAction}
onClick={() => this.handleStateChange('delivered')}
sx={{ textTransform: 'none', fontWeight: 700 }}
>
{busyAction ? 'Wird versendet…' : 'Versenden'}
</Button>
)}
{shipment.state === 'delivered' && (
<Button
variant="contained"
color="warning"
disabled={busyAction}
onClick={() => this.handleStateChange('returned')}
sx={{ textTransform: 'none', fontWeight: 700 }}
>
{busyAction ? 'Wird gebucht…' : 'Retoure'}
</Button>
)}
{shipment.state === 'returned' && (
<Chip
label="Retoure"
color="error"
variant="outlined"
sx={{ fontWeight: 700, height: 28, fontSize: '0.8rem' }}
/>
)}
color="inherit"
startIcon={pdfLoading ? <CircularProgress size={16} color="inherit" /> : <PictureAsPdfIcon sx={{ color: 'error.main' }} />}
disabled={busyAction || pdfLoading}
onClick={this.handleOpenPdf}
sx={{ textTransform: 'none', fontWeight: 600 }}
>
{pdfLoading ? 'PDF wird geladen…' : 'PDF'}
</Button>
{(!shipment.state || shipment.state === 'new') && (
<Button
variant="contained"
color="primary"
disabled={busyAction}
onClick={() => this.handleStateChange('delivered')}
sx={{ textTransform: 'none', fontWeight: 700 }}
>
{busyAction ? 'Wird versendet…' : 'Versenden'}
</Button>
)}
{shipment.state === 'delivered' && (
<Button
variant="contained"
color="warning"
disabled={busyAction}
onClick={() => this.handleStateChange('returned')}
sx={{ textTransform: 'none', fontWeight: 700 }}
>
{busyAction ? 'Wird gebucht…' : 'Retoure'}
</Button>
)}
{shipment.state === 'returned' && (
<Chip
label="Retoure"
color="error"
variant="outlined"
sx={{ fontWeight: 700, height: 28, fontSize: '0.8rem' }}
/>
)}
</Stack>
</DialogActions>
{addPackageDialogOpen && (
<AddPackageDialog
open={addPackageDialogOpen}
shipment={shipment}
onClose={() => this.setState({ addPackageDialogOpen: false })}
onSuccess={async () => {
this.props.onChanged?.();
await this.handleRefresh();
}}
/>
)}
</AppDialog>
{
addPackageDialogOpen && (
<AddPackageDialog
open={addPackageDialogOpen}
shipment={shipment}
onClose={() => this.setState({ addPackageDialogOpen: false })}
onSuccess={async () => {
this.props.onChanged?.();
await this.handleRefresh();
}}
/>
)
}
</AppDialog >
);
}
}