This commit is contained in:
seb
2026-10-12 21:41:44 +02:00
parent df22f77369
commit 1ad9b14aa6
2 changed files with 942 additions and 1230 deletions

View File

@@ -4,27 +4,26 @@ import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip'; import Chip from '@mui/material/Chip';
import CircularProgress from '@mui/material/CircularProgress'; import CircularProgress from '@mui/material/CircularProgress';
import Divider from '@mui/material/Divider'; import Divider from '@mui/material/Divider';
import FormControlLabel from '@mui/material/FormControlLabel';
import IconButton from '@mui/material/IconButton'; import IconButton from '@mui/material/IconButton';
import ListItemButton from '@mui/material/ListItemButton'; import ListItemButton from '@mui/material/ListItemButton';
import Switch from '@mui/material/Switch';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import MenuItem from '@mui/material/MenuItem'; import MenuItem from '@mui/material/MenuItem';
import PaymentsIcon from '@mui/icons-material/Payments'; import PaymentsIcon from '@mui/icons-material/Payments';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import PointOfSaleIcon from '@mui/icons-material/PointOfSale';
import CreditCardIcon from '@mui/icons-material/CreditCard';
import AddIcon from '@mui/icons-material/Add'; import AddIcon from '@mui/icons-material/Add';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined'; import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import CloseIcon from '@mui/icons-material/Close'; import CloseIcon from '@mui/icons-material/Close';
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos'; import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
import { enqueueSnackbar } from 'notistack'; import { enqueueSnackbar } from 'notistack';
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit'; import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
import FillSpace from 'dashgui/FillSpace'; import FillSpace from 'dashgui/FillSpace';
import { PanelTile, PanelTileGrid } from 'dashgui/panels'; import { PanelTile, PanelTileGrid } from 'dashgui/panels';
import BackendError from '../BackendError'; import BackendError from '../BackendError';
import AppDialog from '../AppDialog'; import AppDialog from '../AppDialog';
import orderAutomat, { import orderAutomat from '../../automats/orderAutomat';
isOrderPaid,
} from '../../automats/orderAutomat';
import accountAutomat from '../../automats/accountAutomat'; import accountAutomat from '../../automats/accountAutomat';
import { payment as paymentApi } from '../../api'; import { payment as paymentApi } from '../../api';
import { backendErrorFrom } from '../../utils/backendError'; import { backendErrorFrom } from '../../utils/backendError';
@@ -35,12 +34,10 @@ import {
formatDate, formatDate,
loadParties, loadParties,
manifestConfig, manifestConfig,
numberDisplay,
partyDisplayName, partyDisplayName,
} from './manifestConfig'; } from './manifestConfig';
import { import {
YELLOW_PANEL, YELLOW_PANEL,
SURFACE_BASE,
SURFACE_RAISED, SURFACE_RAISED,
WHITE, WHITE,
} from '../../colors'; } from '../../colors';
@@ -48,46 +45,31 @@ import {
const cfg = manifestConfig('order'); const cfg = manifestConfig('order');
const PAYMENT_TYPES = [ const PAYMENT_TYPES = [
{ value: 'transfer', label: 'Banküberweisung' }, { value: 'transfer', label: 'Banküberweisung', icon: AccountBalanceIcon },
{ value: 'cash', label: 'Barzahlung' }, { value: 'cash', label: 'Barzahlung', icon: PointOfSaleIcon },
{ value: 'card', label: 'EC- / Kreditkarte' }, { value: 'card', label: 'EC- / Kreditkarte', icon: CreditCardIcon },
{ value: 'paypal', label: 'PayPal' }, { value: 'paypal', label: 'PayPal', icon: PaymentsIcon },
{ value: 'sepa', label: 'SEPA-Lastschrift' }, { value: 'sepa', label: 'SEPA-Lastschrift', icon: AccountBalanceIcon },
{ value: 'invoice', label: 'Auf Rechnung' }, { value: 'invoice', label: 'Auf Rechnung', icon: PaymentsIcon },
{ value: 'other', label: 'Sonstige' }, { value: 'other', label: 'Sonstige', icon: PaymentsIcon },
]; ];
function getOrderFinancials(order) { function typeLabel(val) {
const lines = Array.isArray(order?.lines) ? order.lines : []; const match = PAYMENT_TYPES.find((t) => t.value === val);
let total = Number(order?.orderTotal) || 0; return match?.label || val || 'Zahlung';
if (!total && lines.length > 0) {
total = lines.reduce((acc, line) => {
const net = (Number(line.amount) || 0) * (Number(line.net) || 0) * (1 - (Number(line.rebate) || 0) / 100);
return acc + net * (1 + (Number(line.taxrate) || 0) / 100);
}, 0);
} }
total = Math.round(total * 100) / 100;
const payments = Array.isArray(order?.payments) ? order.payments : []; function typeIcon(val) {
let paid = Number(order?.paidTotal) || 0; const match = PAYMENT_TYPES.find((t) => t.value === val);
if (!paid && payments.length > 0) { const IconComp = match?.icon || PaymentsIcon;
paid = payments.reduce((acc, p) => acc + (Number(p.amount) || 0), 0); return <IconComp sx={{ fontSize: 18 }} />;
}
paid = Math.round(paid * 100) / 100;
const remaining = Math.max(0, Math.round((total - paid) * 100) / 100);
return {
total,
paid,
remaining,
};
} }
const rowSx = { const rowSx = {
alignItems: 'center', alignItems: 'center',
height: 64, height: 56,
minHeight: 64, minHeight: 56,
maxHeight: 64, maxHeight: 56,
boxSizing: 'border-box', boxSizing: 'border-box',
py: 0, py: 0,
gap: 1.5, gap: 1.5,
@@ -95,23 +77,20 @@ const rowSx = {
const ellipsisSx = { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; const ellipsisSx = { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
const rowContext = { const paymentRowContext = {
partiesById: {}, partiesById: {},
onOpen: null, accountsById: {},
busyId: null,
onDelete: null,
onNavigateOrder: null,
}; };
// MARK: <OrderPaymentRow/> // MARK: <PaymentTableRow/>
class OrderPaymentRow extends PureComponent { class PaymentTableRow extends PureComponent {
partyName(partyId) {
if (partyId == null) return '–';
const party = rowContext.partiesById[partyId];
return partyDisplayName('order', party) || `Kunde #${partyId}`;
}
render() { render() {
const { item: order } = this.props; const { item: payment } = this.props;
if (!order) { if (!payment) {
return ( return (
<ListItemButton disabled divider sx={{ ...rowSx, opacity: 0, pointerEvents: 'none' }}> <ListItemButton disabled divider sx={{ ...rowSx, opacity: 0, pointerEvents: 'none' }}>
<Typography variant="body2">&nbsp;</Typography> <Typography variant="body2">&nbsp;</Typography>
@@ -119,131 +98,135 @@ class OrderPaymentRow extends PureComponent {
); );
} }
const { onOpen } = rowContext; const { partiesById, accountsById, busyId, onDelete, onNavigateOrder } = paymentRowContext;
const { total, paid, remaining } = getOrderFinancials(order); const party = partiesById[payment.entityId];
const isPaid = isOrderPaid(order) || (total > 0 && Math.abs(paid - total) < 0.01); const customerName = partyDisplayName('order', party) || (payment.entityId ? `Kunde #${payment.entityId}` : '–');
const isPartial = paid > 0 && !isPaid; const accountName = accountsById[payment.accountId] || `Konto #${payment.accountId}`;
const paymentsCount = Array.isArray(order.payments) ? order.payments.length : 0; const isBusy = busyId === payment.id;
return ( return (
<ListItemButton divider sx={rowSx} onClick={() => onOpen?.(order)}> <ListItemButton divider sx={rowSx} onClick={() => onNavigateOrder?.(payment.orderId)}>
<Box sx={{ width: 130, flexShrink: 0, minWidth: 0 }}> {/* Payment ID from payment table */}
<Typography variant="body1" sx={{ fontWeight: 600, ...ellipsisSx }}> <Box sx={{ width: 80, flexShrink: 0 }}>
{order.number} <Chip size="small" label={`#${payment.id}`} sx={{ fontWeight: 700, fontVariantNumeric: 'tabular-nums' }} />
</Typography> </Box>
<Typography variant="body2" color="text.secondary" sx={ellipsisSx}>
{numberDisplay(order.externalNumber)} {/* Amount */}
<Box sx={{ width: 130, flexShrink: 0, textAlign: 'right' }}>
<Typography variant="body1" sx={{ fontWeight: 700, color: 'success.main', fontVariantNumeric: 'tabular-nums' }}>
+{formatPrice(payment.amount)}
</Typography> </Typography>
</Box> </Box>
<Box sx={{ width: 100, flexShrink: 0, minWidth: 0 }}> {/* Payment Type */}
<Typography variant="body2" color="text.secondary" sx={ellipsisSx}> <Box sx={{ width: 160, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 1 }}>
{order.date ? formatDate(order.date) : '–'} {typeIcon(payment.type)}
<Typography variant="body2" sx={{ fontWeight: 600, ...ellipsisSx }}>
{typeLabel(payment.type)}
</Typography> </Typography>
</Box> </Box>
{/* Account from account table */}
<Box sx={{ width: 150, flexShrink: 0 }}>
<Typography variant="body2" color="text.secondary" sx={ellipsisSx}>
{accountName}
</Typography>
</Box>
{/* Linked Manifest (Auftrag) */}
<Box sx={{ width: 120, flexShrink: 0 }}>
<Typography variant="body2" sx={{ fontWeight: 600, color: 'primary.main', ...ellipsisSx }}>
{payment.orderNumber}
</Typography>
</Box>
{/* Customer Name */}
<Box sx={{ flex: 1, minWidth: 0 }}> <Box sx={{ flex: 1, minWidth: 0 }}>
<Typography variant="body1" sx={{ fontWeight: 500, ...ellipsisSx }}> <Typography variant="body2" sx={{ fontWeight: 500, ...ellipsisSx }}>
{this.partyName(order.entityId)} {customerName}
</Typography> </Typography>
</Box> </Box>
{/* Amounts */} {/* Action: Delete payment */}
<Box sx={{ width: 100, flexShrink: 0, textAlign: 'right' }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
{total > 0 ? formatPrice(total) : '—'}
</Typography>
</Box>
<Box sx={{ width: 100, flexShrink: 0, textAlign: 'right' }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontVariantNumeric: 'tabular-nums', color: paid > 0 ? 'success.main' : 'text.disabled' }}>
{paid > 0 ? formatPrice(paid) : '0,00 €'}
</Typography>
</Box>
<Box sx={{ width: 100, flexShrink: 0, textAlign: 'right' }}>
<Typography variant="body2" sx={{ fontWeight: 700, fontVariantNumeric: 'tabular-nums', color: remaining > 0 ? 'error.main' : 'text.secondary' }}>
{remaining > 0 ? formatPrice(remaining) : '0,00 €'}
</Typography>
</Box>
{/* Status chip */}
<Box sx={{ width: 110, flexShrink: 0, display: 'flex', justifyContent: 'center' }}>
{isPaid ? (
<Chip size="small" color="success" label="Bezahlt" sx={{ height: 22, fontWeight: 600, fontSize: '0.75rem' }} />
) : isPartial ? (
<Chip size="small" color="warning" label="Teilbezahlt" sx={{ height: 22, fontWeight: 600, fontSize: '0.75rem' }} />
) : (
<Chip size="small" color="error" variant="outlined" label="Offen" sx={{ height: 22, fontWeight: 600, fontSize: '0.75rem' }} />
)}
</Box>
{/* Payments count */}
<Box sx={{ width: 80, flexShrink: 0, textAlign: 'center' }}>
<Chip
size="small"
label={`${paymentsCount} ${paymentsCount === 1 ? 'Zahlung' : 'Zahlungen'}`}
sx={{
height: 22,
fontSize: '0.7rem',
fontWeight: 500,
bgcolor: paymentsCount > 0 ? 'action.selected' : 'action.hover',
}}
/>
</Box>
<IconButton <IconButton
size="small" size="small"
color="error"
disabled={isBusy}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
onOpen?.(order); onDelete?.(payment);
}} }}
aria-label={`Zahlung #${payment.id} löschen`}
sx={{ width: 36, height: 36, flexShrink: 0 }} sx={{ width: 36, height: 36, flexShrink: 0 }}
> >
<ArrowForwardIosIcon sx={{ fontSize: 16 }} /> <DeleteOutlinedIcon fontSize="small" />
</IconButton> </IconButton>
</ListItemButton> </ListItemButton>
); );
} }
} }
// MARK: <AddPaymentDialog/> // MARK: <RecordPaymentDialog/>
class AddPaymentDialog extends PureComponent { class RecordPaymentDialog extends PureComponent {
constructor(props) { constructor(props) {
super(props); super(props);
const { order } = props; const orders = props.orders || [];
const { remaining } = getOrderFinancials(order); // Prefer unpaid orders
const unpaidOrders = orders.filter((o) => {
const tot = Number(o.orderTotal) || 0;
const pd = Number(o.paidTotal) || 0;
return tot === 0 || pd < tot;
});
const selectedOrder = unpaidOrders[0] || orders[0] || null;
const remaining = selectedOrder ? Math.max(0, Math.round(((Number(selectedOrder.orderTotal) || 0) - (Number(selectedOrder.paidTotal) || 0)) * 100) / 100) : 0;
const accounts = accountAutomat.state.items || []; const accounts = accountAutomat.state.items || [];
const defaultAccount = accounts[0]?.id || 1; const defaultAccountId = accounts[0]?.id || 1;
this.state = { this.state = {
accountId: defaultAccount, orderId: selectedOrder?.id || '',
accountId: defaultAccountId,
type: 'transfer', type: 'transfer',
amount: remaining > 0 ? String(remaining) : '', amount: remaining > 0 ? String(remaining) : '',
saving: false, saving: false,
}; };
this.handleOrderChange = this.handleOrderChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this); this.handleSubmit = this.handleSubmit.bind(this);
} }
handleOrderChange(newOrderId) {
const order = this.props.orders.find((o) => o.id === Number(newOrderId));
const remaining = order ? Math.max(0, Math.round(((Number(order.orderTotal) || 0) - (Number(order.paidTotal) || 0)) * 100) / 100) : 0;
this.setState({
orderId: newOrderId,
amount: remaining > 0 ? String(remaining) : '',
});
}
async handleSubmit() { async handleSubmit() {
const { order, onClose, onSuccess } = this.props; const { onClose, onSuccess } = this.props;
const { accountId, type, amount } = this.state; const { orderId, accountId, type, amount } = this.state;
const numAmount = Number(String(amount).replace(',', '.')); const numAmount = Number(String(amount).replace(',', '.'));
if (!orderId) {
enqueueSnackbar('Bitte einen Auftrag auswählen.', { variant: 'warning' });
return;
}
if (!Number.isFinite(numAmount) || numAmount <= 0) { if (!Number.isFinite(numAmount) || numAmount <= 0) {
enqueueSnackbar('Bitte einen gültigen Zahlungsbetrag größer 0 eingeben.', { variant: 'warning' }); enqueueSnackbar('Bitte einen gültigen Betrag größer 0 eingeben.', { variant: 'warning' });
return; return;
} }
this.setState({ saving: true }); this.setState({ saving: true });
try { try {
await paymentApi.create(order.id, { await paymentApi.create(orderId, {
accountId: Number(accountId), accountId: Number(accountId),
type, type,
amount: numAmount, amount: numAmount,
}); });
enqueueSnackbar('Zahlung erfolgreich verbucht!', { variant: 'success' }); enqueueSnackbar('Zahlungseingang erfolgreich verbucht!', { variant: 'success' });
await orderAutomat.actions.reload(); await orderAutomat.actions.reload();
onSuccess?.(); onSuccess?.();
onClose(); onClose();
@@ -254,29 +237,51 @@ class AddPaymentDialog extends PureComponent {
} }
render() { render() {
const { open, onClose, order } = this.props; const { open, onClose, orders, partiesById } = this.props;
const { accountId, type, amount, saving } = this.state; const { orderId, accountId, type, amount, saving } = this.state;
const accounts = accountAutomat.state.items || []; const accounts = accountAutomat.state.items || [];
return ( return (
<AppDialog open={open} onClose={onClose} maxWidth="xs" fullWidth> <AppDialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<Box sx={{ p: 2.5 }}> <Box sx={{ p: 2.5 }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', pb: 2 }}> <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', pb: 2 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<PaymentsIcon color="primary" />
<Typography variant="h6" sx={{ fontWeight: 600 }}> <Typography variant="h6" sx={{ fontWeight: 600 }}>
Zahlung erfassen Zahlungseingang erfassen
</Typography> </Typography>
</Box>
<IconButton onClick={onClose} size="small"> <IconButton onClick={onClose} size="small">
<CloseIcon /> <CloseIcon />
</IconButton> </IconButton>
</Box> </Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Auftrag: <strong>{order?.number}</strong>
</Typography>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mb: 3 }}> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mb: 3 }}>
<TextField <TextField
select select
label="Konto / Kasse" label="Auftrag (Manifest)"
size="small"
value={orderId}
onChange={(e) => this.handleOrderChange(e.target.value)}
fullWidth
>
{orders.map((o) => {
const party = partiesById[o.entityId];
const partyName = partyDisplayName('order', party) || `Kunde #${o.entityId}`;
const tot = Number(o.orderTotal) || 0;
const pd = Number(o.paidTotal) || 0;
const rem = Math.max(0, tot - pd);
return (
<MenuItem key={o.id} value={o.id}>
{o.number} — {partyName} (Offen: {formatPrice(rem)})
</MenuItem>
);
})}
</TextField>
<TextField
select
label="Konto / Kasse (account)"
size="small" size="small"
value={accountId} value={accountId}
onChange={(e) => this.setState({ accountId: e.target.value })} onChange={(e) => this.setState({ accountId: e.target.value })}
@@ -288,13 +293,13 @@ class AddPaymentDialog extends PureComponent {
</MenuItem> </MenuItem>
)) ))
) : ( ) : (
<MenuItem value={1}>Standard-Bankkonto</MenuItem> <MenuItem value={1}>Standardkonto</MenuItem>
)} )}
</TextField> </TextField>
<TextField <TextField
select select
label="Zahlungsart" label="Zahlungsart (type)"
size="small" size="small"
value={type} value={type}
onChange={(e) => this.setState({ type: e.target.value })} onChange={(e) => this.setState({ type: e.target.value })}
@@ -307,7 +312,7 @@ class AddPaymentDialog extends PureComponent {
</TextField> </TextField>
<TextField <TextField
label="Betrag (€)" label="Zahlungsbetrag (€)"
size="small" size="small"
type="number" type="number"
value={amount} value={amount}
@@ -330,195 +335,6 @@ class AddPaymentDialog extends PureComponent {
} }
} }
// MARK: <OrderPaymentDetailDialog/>
class OrderPaymentDetailDialog extends PureComponent {
constructor(props) {
super(props);
this.state = {
addPaymentOpen: false,
busyAction: false,
};
this.handleDeletePayment = this.handleDeletePayment.bind(this);
}
async handleDeletePayment(pay) {
if (!window.confirm(`Zahlung über ${formatPrice(pay.amount)} wirklich löschen?`)) return;
this.setState({ busyAction: true });
try {
await paymentApi.delete(pay.id);
enqueueSnackbar('Zahlung gelöscht.', { variant: 'success' });
await orderAutomat.actions.reload();
} catch (err) {
notifyError(err);
} finally {
this.setState({ busyAction: false });
}
}
render() {
const { open, onClose, orderId, partiesById } = this.props;
const { addPaymentOpen, busyAction } = this.state;
const order = orderAutomat.state.items?.find((o) => o.id === orderId);
if (!order) return null;
const party = partiesById[order.entityId];
const customerName = partyDisplayName('order', party) || `Kunde #${order.entityId}`;
const { total, paid, remaining } = getOrderFinancials(order);
const payments = Array.isArray(order.payments) ? order.payments : [];
const accounts = accountAutomat.state.items || [];
const accountsById = Object.fromEntries(accounts.map((a) => [a.id, a.name]));
return (
<AppDialog open={open} onClose={onClose} maxWidth="md" fullWidth>
<Box sx={{ p: 3 }}>
{/* Header */}
<Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', pb: 2, borderBottom: '1px solid', borderColor: 'divider' }}>
<Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
<Typography variant="h5" sx={{ fontWeight: 700 }}>
Zahlungen: {order.number}
</Typography>
{remaining === 0 ? (
<Chip size="small" color="success" label="Vollständig bezahlt" sx={{ fontWeight: 600 }} />
) : paid > 0 ? (
<Chip size="small" color="warning" label={`Teilbezahlt (${formatPrice(paid)})`} sx={{ fontWeight: 600 }} />
) : (
<Chip size="small" color="error" variant="outlined" label="Unbezahlt" sx={{ fontWeight: 600 }} />
)}
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
Kunde: <strong>{customerName}</strong> • Datum: {order.date ? formatDate(order.date) : '–'}
</Typography>
</Box>
<IconButton onClick={onClose} size="small">
<CloseIcon />
</IconButton>
</Box>
{/* Quick Metrics Bar */}
<Box sx={{ display: 'flex', gap: 3, my: 2.5, p: 2, bgcolor: SURFACE_RAISED, borderRadius: 2 }}>
<Box>
<Typography variant="caption" color="text.secondary">Auftrags-Gesamtbetrag (Brutto)</Typography>
<Typography variant="h6" sx={{ fontWeight: 700 }}>{formatPrice(total)}</Typography>
</Box>
<Divider orientation="vertical" flexItem />
<Box>
<Typography variant="caption" color="text.secondary">Bereits bezahlt</Typography>
<Typography variant="h6" sx={{ fontWeight: 700, color: paid > 0 ? 'success.main' : 'text.primary' }}>
{formatPrice(paid)}
</Typography>
</Box>
<Divider orientation="vertical" flexItem />
<Box>
<Typography variant="caption" color="text.secondary">Offener Saldo</Typography>
<Typography variant="h6" sx={{ fontWeight: 700, color: remaining > 0 ? 'error.main' : 'text.secondary' }}>
{formatPrice(remaining)}
</Typography>
</Box>
<Box sx={{ flex: 1 }} />
<Button
variant="contained"
startIcon={<AddIcon />}
onClick={() => this.setState({ addPaymentOpen: true })}
disabled={busyAction}
sx={{ alignSelf: 'center', height: 40 }}
>
Zahlung buchen
</Button>
</Box>
{/* Payments list */}
<Typography variant="h6" sx={{ fontWeight: 600, mb: 1.5 }}>
Gebuchte Zahlungseingänge ({payments.length})
</Typography>
{payments.length === 0 ? (
<Box sx={{ p: 4, textAlign: 'center', bgcolor: SURFACE_BASE, borderRadius: 2, border: '1px dashed', borderColor: 'divider', mb: 3 }}>
<Typography variant="body1" color="text.secondary" sx={{ mb: 1.5 }}>
Bisher keine Zahlungen für diesen Auftrag erfasst.
</Typography>
<Button
variant="outlined"
startIcon={<AddIcon />}
onClick={() => this.setState({ addPaymentOpen: true })}
>
Erste Zahlung buchen
</Button>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, mb: 3 }}>
{payments.map((p) => {
const typeObj = PAYMENT_TYPES.find((pt) => pt.value === p.type);
const typeLabel = typeObj?.label || p.type;
const accountName = accountsById[p.accountId] || `Konto #${p.accountId}`;
return (
<Box
key={p.id}
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
p: 2,
bgcolor: WHITE,
borderRadius: 1.5,
border: '1px solid',
borderColor: 'divider',
boxShadow: 1,
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<PaymentsIcon color="primary" />
<Box>
<Typography variant="subtitle2" sx={{ fontWeight: 600 }}>
{typeLabel}
</Typography>
<Typography variant="caption" color="text.secondary">
{accountName}
</Typography>
</Box>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Typography variant="h6" sx={{ fontWeight: 700, fontVariantNumeric: 'tabular-nums', color: 'success.main' }}>
+{formatPrice(p.amount)}
</Typography>
<IconButton
size="small"
color="error"
disabled={busyAction}
onClick={() => this.handleDeletePayment(p)}
aria-label="Zahlung löschen"
>
<DeleteOutlinedIcon fontSize="small" />
</IconButton>
</Box>
</Box>
);
})}
</Box>
)}
<Box sx={{ display: 'flex', justifyContent: 'flex-end', pt: 2, borderTop: '1px solid', borderColor: 'divider' }}>
<Button variant="outlined" onClick={onClose}>
Schließen
</Button>
</Box>
</Box>
{addPaymentOpen && (
<AddPaymentDialog
open={addPaymentOpen}
order={order}
onClose={() => this.setState({ addPaymentOpen: false })}
/>
)}
</AppDialog>
);
}
}
// MARK: <OrderPaymentList/> // MARK: <OrderPaymentList/>
export class OrderPaymentList extends PureComponent { export class OrderPaymentList extends PureComponent {
constructor(props) { constructor(props) {
@@ -528,25 +344,29 @@ export class OrderPaymentList extends PureComponent {
status: s.status === 'ready' ? 'ready' : 'loading', status: s.status === 'ready' ? 'ready' : 'loading',
error: s.error ? backendErrorFrom(s.error) : null, error: s.error ? backendErrorFrom(s.error) : null,
items: s.items ?? [], items: s.items ?? [],
total: s.total ?? 0,
filter: '', filter: '',
onlyUnpaid: true, // Default to unpaid
partiesById: {}, partiesById: {},
selectedOrderId: null, accountsById: {},
busyId: null,
recordDialogOpen: false,
}; };
this._cancelled = false; this._cancelled = false;
this.handleRetry = this.handleRetry.bind(this); this.handleRetry = this.handleRetry.bind(this);
this.handleOpenOrder = this.handleOpenOrder.bind(this); this.handleDeletePayment = this.handleDeletePayment.bind(this);
this.handleNavigateOrder = this.handleNavigateOrder.bind(this);
} }
componentDidMount() { componentDidMount() {
this._cancelled = false; this._cancelled = false;
this.unsub = orderAutomat.subscribe(this, (state) => ({ this.unsub = orderAutomat.subscribe(this, (state) => ({
items: state.items ?? [], items: state.items ?? [],
total: state.total ?? 0,
status: state.status, status: state.status,
error: state.error ? backendErrorFrom(state.error) : null, error: state.error ? backendErrorFrom(state.error) : null,
})); }));
this.unsubAccount = accountAutomat.subscribe(this, (state) => ({
accountsById: Object.fromEntries((state.items || []).map((a) => [a.id, a.name])),
}));
if (orderAutomat.state.status === 'idle') { if (orderAutomat.state.status === 'idle') {
void orderAutomat.actions.load().catch(() => {}); void orderAutomat.actions.load().catch(() => {});
} }
@@ -557,6 +377,7 @@ export class OrderPaymentList extends PureComponent {
componentWillUnmount() { componentWillUnmount() {
this._cancelled = true; this._cancelled = true;
this.unsub?.(); this.unsub?.();
this.unsubAccount?.();
} }
async loadPartiesData() { async loadPartiesData() {
@@ -574,32 +395,73 @@ export class OrderPaymentList extends PureComponent {
void orderAutomat.actions.load().catch(() => {}); void orderAutomat.actions.load().catch(() => {});
} }
handleOpenOrder(order) { extractAllPayments(orders = this.state.items) {
this.setState({ selectedOrderId: order.id }); const list = [];
for (const order of orders) {
if (!Array.isArray(order.payments)) continue;
for (const pay of order.payments) {
list.push({
...pay,
orderId: order.id,
orderNumber: order.number,
orderDate: order.date,
entityId: order.entityId,
orderTotal: order.orderTotal,
paidTotal: order.paidTotal,
});
}
}
// Sort descending by payment id
return list.sort((a, b) => Number(b.id || 0) - Number(a.id || 0));
} }
getFilteredOrders() { async handleDeletePayment(payment) {
const { items, filter, onlyUnpaid, partiesById } = this.state; if (!window.confirm(`Zahlung #${payment.id} über ${formatPrice(payment.amount)} wirklich löschen?`)) return;
const q = filter.trim().toLowerCase(); this.setState({ busyId: payment.id });
try {
return items.filter((order) => { await paymentApi.delete(payment.id);
const { total, paid } = getOrderFinancials(order); enqueueSnackbar(`Zahlung #${payment.id} gelöscht.`, { variant: 'success' });
const isPaid = isOrderPaid(order) || (total > 0 && Math.abs(paid - total) < 0.01); await orderAutomat.actions.reload();
if (onlyUnpaid && isPaid) return false; } catch (err) {
notifyError(err);
if (q) { } finally {
const party = partiesById[order.entityId]; if (!this._cancelled) {
const partyName = partyDisplayName('order', party); this.setState({ busyId: null });
const matches = [order.number, order.externalNumber, partyName]
.some((val) => String(val || '').toLowerCase().includes(q));
if (!matches) return false;
} }
return true; }
}
handleNavigateOrder(orderId) {
if (orderId) {
this.props.navigate(`/auftrag/bestellung/${orderId}`);
}
}
getFilteredPayments() {
const all = this.extractAllPayments();
const q = this.state.filter.trim().toLowerCase();
if (!q) return all;
const { partiesById, accountsById } = this.state;
return all.filter((pay) => {
const party = partiesById[pay.entityId];
const customerName = partyDisplayName('order', party);
const accountName = accountsById[pay.accountId];
const typeStr = typeLabel(pay.type);
return [
String(pay.id),
pay.orderNumber,
customerName,
accountName,
typeStr,
pay.type,
].some((val) => String(val || '').toLowerCase().includes(q));
}); });
} }
render() { render() {
const { status, error, filter, onlyUnpaid, partiesById, selectedOrderId } = this.state; const { status, error, filter, partiesById, accountsById, busyId, recordDialogOpen, items } = this.state;
if (status === 'loading' || status === 'idle') { if (status === 'loading' || status === 'idle') {
return ( return (
@@ -613,72 +475,84 @@ export class OrderPaymentList extends PureComponent {
return <BackendError error={error} onRetry={this.handleRetry} />; return <BackendError error={error} onRetry={this.handleRetry} />;
} }
const filtered = this.getFilteredOrders(); const filtered = this.getFilteredPayments();
rowContext.partiesById = partiesById; const allPayments = this.extractAllPayments();
rowContext.onOpen = this.handleOpenOrder; const totalAmount = allPayments.reduce((sum, p) => sum + (Number(p.amount) || 0), 0);
paymentRowContext.partiesById = partiesById;
paymentRowContext.accountsById = accountsById;
paymentRowContext.busyId = busyId;
paymentRowContext.onDelete = this.handleDeletePayment;
paymentRowContext.onNavigateOrder = this.handleNavigateOrder;
return ( return (
<> <>
{/* Metrics Banner */}
<PanelTileGrid> <PanelTileGrid>
<Box <Box
sx={{ sx={{
gridColumn: { xs: '1 / -1', sm: 'span 2', md: 'span 2' }, gridColumn: { xs: '1 / -1', sm: 'span 2', md: 'span 2' },
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
gap: 1.25, gap: 2,
pb: 2, pb: 2,
}} }}
> >
<Box
sx={{
display: 'flex',
alignItems: 'center',
gap: 3,
p: 2,
bgcolor: SURFACE_RAISED,
borderRadius: 2,
flexWrap: 'wrap',
}}
>
<Box>
<Typography variant="caption" color="text.secondary">
Gesamtsumme aller Zahlungen
</Typography>
<Typography variant="h5" sx={{ fontWeight: 700, color: 'success.main', fontVariantNumeric: 'tabular-nums' }}>
{formatPrice(totalAmount)}
</Typography>
</Box>
<Divider orientation="vertical" flexItem />
<Box>
<Typography variant="caption" color="text.secondary">
Anzahl Zahlungseinträge (Tabelle payment)
</Typography>
<Typography variant="h5" sx={{ fontWeight: 700 }}>
{allPayments.length}
</Typography>
</Box>
<Box sx={{ flex: 1 }} />
<Button
variant="contained"
startIcon={<AddIcon />}
onClick={() => this.setState({ recordDialogOpen: true })}
sx={{ height: 40 }}
>
Zahlungseingang erfassen
</Button>
</Box>
{/* Search Bar */}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<SingleLineTextEdit <SingleLineTextEdit
sx={{ flex: 1 }} sx={{ flex: 1 }}
size="small" size="small"
search search
clear clear
placeholder="Auftrag oder Kunde suchen…" placeholder="Zahlungs-ID, Auftrag, Kunde, Konto oder Zahlungsart suchen…"
value={filter} value={filter}
onChange={(next) => this.setState({ filter: next })} onChange={(next) => this.setState({ filter: next })}
/> />
</Box> </Box>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<Box
sx={{
display: 'inline-flex',
alignItems: 'center',
gap: 1.5,
px: 1.5,
py: 0.25,
borderRadius: 2,
bgcolor: 'background.paper',
boxShadow: 1,
}}
>
<FormControlLabel
control={
<Switch
size="small"
color="warning"
checked={onlyUnpaid}
onChange={(e) => this.setState({ onlyUnpaid: e.target.checked })}
/>
}
label={
<Typography variant="body2" sx={{ fontWeight: onlyUnpaid ? 600 : 400, userSelect: 'none' }}>
Nur unbezahlte Aufträge
</Typography>
}
sx={{ m: 0 }}
/>
</Box>
<Typography variant="caption" color="text.secondary">
{filtered.length} Auftrag / Aufträge zur Zahlungsüberwachung
</Typography>
</Box>
</Box> </Box>
</PanelTileGrid> </PanelTileGrid>
{/* Payments Table (connected directly to payment records) */}
<PanelTileGrid> <PanelTileGrid>
<PanelTile wide={3} minHeight={0} color={YELLOW_PANEL} sx={{ pb: 0 }}> <PanelTile wide={3} minHeight={0} color={YELLOW_PANEL} sx={{ pb: 0 }}>
<FillSpace <FillSpace
@@ -687,7 +561,7 @@ export class OrderPaymentList extends PureComponent {
minHeight={0} minHeight={0}
items={filtered} items={filtered}
totalCount={filtered.length} totalCount={filtered.length}
renderItem={OrderPaymentRow} renderItem={PaymentTableRow}
virtualScrollbar virtualScrollbar
header={ header={
<Box <Box
@@ -708,14 +582,12 @@ export class OrderPaymentList extends PureComponent {
userSelect: 'none', userSelect: 'none',
}} }}
> >
<Box sx={{ width: 130, flexShrink: 0 }}>Auftragsnr.</Box> <Box sx={{ width: 80, flexShrink: 0 }}>ID</Box>
<Box sx={{ width: 100, flexShrink: 0 }}>Datum</Box> <Box sx={{ width: 130, flexShrink: 0, textAlign: 'right' }}>Betrag</Box>
<Box sx={{ width: 160, flexShrink: 0 }}>Zahlungsart</Box>
<Box sx={{ width: 150, flexShrink: 0 }}>Konto</Box>
<Box sx={{ width: 120, flexShrink: 0 }}>Auftrag</Box>
<Box sx={{ flex: 1, minWidth: 0 }}>Kunde</Box> <Box sx={{ flex: 1, minWidth: 0 }}>Kunde</Box>
<Box sx={{ width: 100, flexShrink: 0, textAlign: 'right' }}>Gesamt</Box>
<Box sx={{ width: 100, flexShrink: 0, textAlign: 'right' }}>Bezahlt</Box>
<Box sx={{ width: 100, flexShrink: 0, textAlign: 'right' }}>Offen</Box>
<Box sx={{ width: 110, flexShrink: 0, textAlign: 'center' }}>Status</Box>
<Box sx={{ width: 80, flexShrink: 0, textAlign: 'center' }}>Zahlungen</Box>
<Box sx={{ width: 36, flexShrink: 0 }} /> <Box sx={{ width: 36, flexShrink: 0 }} />
</Box> </Box>
} }
@@ -723,12 +595,12 @@ export class OrderPaymentList extends PureComponent {
</PanelTile> </PanelTile>
</PanelTileGrid> </PanelTileGrid>
{selectedOrderId != null && ( {recordDialogOpen && (
<OrderPaymentDetailDialog <RecordPaymentDialog
open={selectedOrderId != null} open={recordDialogOpen}
orderId={selectedOrderId} orders={items}
partiesById={partiesById} partiesById={partiesById}
onClose={() => this.setState({ selectedOrderId: null })} onClose={() => this.setState({ recordDialogOpen: false })}
/> />
)} )}
</> </>

File diff suppressed because it is too large Load Diff