Add Kunde CRUD with addresses/contacts, delivery edit, and Auftrag sub-nav.

Wire customergroup/entity APIs, Lieferungen detail editing, and Angebot/Bestellung/Ausliefern/Retoure placeholders.
This commit is contained in:
seb
2026-08-06 07:38:23 +02:00
parent 1ee29399ff
commit 27fd5d3e94
20 changed files with 2265 additions and 56 deletions

774
src/pages/kunde/edit.jsx Normal file
View File

@@ -0,0 +1,774 @@
import { PureComponent } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
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 { requireArray, requireDefined, requireObject } from '../../utils/apiShape';
import { backendErrorFrom } from '../../utils/backendError';
import { notifyError } from '../../utils/notify';
import withEntityRoute from './withEntityRoute';
const ADDRESS_FIELDS = [
'addressType',
'firstName',
'name',
'street',
'streetNumber',
'zip',
'city',
'county',
];
function emptyAddressDraft() {
return {
addressType: 'billing',
firstName: '',
name: '',
street: '',
streetNumber: '',
zip: '',
city: '',
county: '',
};
}
function addressDraftFrom(row) {
return {
addressType: row.addressType ?? '',
firstName: row.firstName ?? '',
name: row.name ?? '',
street: row.street ?? '',
streetNumber: row.streetNumber ?? '',
zip: row.zip ?? '',
city: row.city ?? '',
county: row.county ?? '',
};
}
function compactAddressBody(draft) {
const body = {};
for (const key of ADDRESS_FIELDS) {
const trimmed = String(draft[key] ?? '').trim();
if (key === 'addressType') {
body.addressType = trimmed;
continue;
}
body[key] = trimmed === '' ? null : trimmed;
}
return body;
}
function emptyContactDraft() {
return { contactType: 'email', contact: '' };
}
class KundeEditPage extends PureComponent {
static contextType = StorageManagerContext;
constructor(props) {
super(props);
this.state = {
status: 'loading',
error: null,
entity: null,
groupName: null,
name: '',
firstName: '',
savingEntity: false,
addresses: [],
addressDrafts: {},
newAddress: emptyAddressDraft(),
busyAddressKey: null,
contacts: [],
contactDrafts: {},
newContact: emptyContactDraft(),
busyContactKey: null,
};
this._cancelled = false;
this.handleRetry = this.handleRetry.bind(this);
this.handleSaveEntity = this.handleSaveEntity.bind(this);
this.handleAddAddress = this.handleAddAddress.bind(this);
this.handleAddContact = this.handleAddContact.bind(this);
}
componentDidMount() {
this._cancelled = false;
void this.load();
}
componentDidUpdate(prevProps) {
if (prevProps.entityId !== this.props.entityId) {
void this.load();
}
}
componentWillUnmount() {
this._cancelled = true;
}
async load() {
const { entityId } = this.props;
if (entityId == null) {
this.setState({
status: 'failed',
error: backendErrorFrom(new Error('Ungültige Kunden-ID.')),
});
return;
}
this.setState({ status: 'loading', error: null });
try {
const [entityRes, addressRes, contactRes, groups] = await Promise.all([
this.context.entity.get(entityId),
this.context.entity.listAddresses(entityId),
this.context.entity.listContacts(entityId),
this.context.customergroups ?? this.context.customergroupPromise,
]);
if (this._cancelled) return;
requireObject(entityRes, 'GET /api/entity/:id');
requireObject(entityRes.entity, 'entity');
requireObject(addressRes, 'GET /api/entity/:id/address');
requireObject(contactRes, 'GET /api/entity/:id/contact');
const addresses = requireArray(addressRes.addresses, 'addresses');
const contacts = requireArray(contactRes.contacts, 'contacts');
const entity = entityRes.entity;
const group = groups.find((g) => g.id === entity.customergroupId);
this.setState({
status: 'ready',
entity,
groupName: group?.name ?? null,
name: entity.name ?? '',
firstName: entity.firstName ?? '',
addresses,
addressDrafts: Object.fromEntries(
addresses.map((row) => [row.id, addressDraftFrom(row)]),
),
contacts,
contactDrafts: Object.fromEntries(
contacts.map((row) => [
row.id,
{ contactType: row.contactType, contact: row.contact },
]),
),
newAddress: emptyAddressDraft(),
newContact: emptyContactDraft(),
});
} catch (err) {
if (this._cancelled) return;
this.setState({ status: 'failed', error: backendErrorFrom(err) });
}
}
handleRetry() {
void this.load();
}
async handleSaveEntity() {
const { entityId } = this.props;
const { name, firstName, savingEntity } = this.state;
if (savingEntity || entityId == null) return;
const trimmedName = name.trim();
if (!trimmedName) {
notifyError(new Error('Name fehlt.'));
return;
}
this.setState({ savingEntity: true });
try {
const data = await this.context.entity.update(entityId, {
name: trimmedName,
firstName: firstName.trim() === '' ? null : firstName.trim(),
});
requireObject(data, 'PATCH /api/entity/:id');
requireObject(data.entity, 'entity');
requireDefined(data.entity.id, 'entity.id');
await this.context.updateEntity();
if (this._cancelled) return;
this.setState({
entity: data.entity,
name: data.entity.name ?? '',
firstName: data.entity.firstName ?? '',
savingEntity: false,
});
enqueueSnackbar('Kunde gespeichert.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ savingEntity: false });
}
}
setAddressDraft(id, field, value) {
this.setState((prev) => ({
addressDrafts: {
...prev.addressDrafts,
[id]: { ...prev.addressDrafts[id], [field]: value },
},
}));
}
async handleSaveAddress(address) {
const { entityId } = this.props;
const draft = this.state.addressDrafts[address.id];
if (!draft || this.state.busyAddressKey != null || entityId == null) return;
const body = compactAddressBody(draft);
if (!body.addressType) {
notifyError(new Error('Adresstyp fehlt.'));
return;
}
this.setState({ busyAddressKey: address.id });
try {
const data = await this.context.entity.updateAddress(
entityId,
address.id,
body,
);
requireObject(data, 'PATCH /api/entity/:id/address/:id');
requireObject(data.address, 'address');
const listRes = await this.context.entity.listAddresses(entityId);
requireObject(listRes, 'GET /api/entity/:id/address');
const addresses = requireArray(listRes.addresses, 'addresses');
if (this._cancelled) return;
this.setState({
addresses,
addressDrafts: Object.fromEntries(
addresses.map((row) => [row.id, addressDraftFrom(row)]),
),
busyAddressKey: null,
});
enqueueSnackbar('Adresse gespeichert.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyAddressKey: null });
}
}
async handleAddAddress() {
const { entityId } = this.props;
const { newAddress, busyAddressKey } = this.state;
if (busyAddressKey != null || entityId == null) return;
const body = compactAddressBody(newAddress);
if (!body.addressType) {
notifyError(new Error('Adresstyp fehlt.'));
return;
}
this.setState({ busyAddressKey: 'new' });
try {
const data = await this.context.entity.createAddress(entityId, body);
requireObject(data, 'POST /api/entity/:id/address');
requireObject(data.address, 'address');
requireDefined(data.address.id, 'address.id');
const listRes = await this.context.entity.listAddresses(entityId);
requireObject(listRes, 'GET /api/entity/:id/address');
const addresses = requireArray(listRes.addresses, 'addresses');
if (this._cancelled) return;
this.setState({
addresses,
addressDrafts: Object.fromEntries(
addresses.map((row) => [row.id, addressDraftFrom(row)]),
),
newAddress: emptyAddressDraft(),
busyAddressKey: null,
});
enqueueSnackbar('Adresse angelegt.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyAddressKey: null });
}
}
async handleDeleteAddress(address) {
const { entityId } = this.props;
if (this.state.busyAddressKey != null || entityId == null) return;
if (!window.confirm('Adresse wirklich löschen?')) return;
this.setState({ busyAddressKey: address.id });
try {
await this.context.entity.deleteAddress(entityId, address.id);
const listRes = await this.context.entity.listAddresses(entityId);
requireObject(listRes, 'GET /api/entity/:id/address');
const addresses = requireArray(listRes.addresses, 'addresses');
if (this._cancelled) return;
this.setState({
addresses,
addressDrafts: Object.fromEntries(
addresses.map((row) => [row.id, addressDraftFrom(row)]),
),
busyAddressKey: null,
});
enqueueSnackbar('Adresse gelöscht.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyAddressKey: null });
}
}
setContactDraft(id, field, value) {
this.setState((prev) => ({
contactDrafts: {
...prev.contactDrafts,
[id]: { ...prev.contactDrafts[id], [field]: value },
},
}));
}
async handleSaveContact(contact) {
const { entityId } = this.props;
const draft = this.state.contactDrafts[contact.id];
if (!draft || this.state.busyContactKey != null || entityId == null) return;
const contactType = String(draft.contactType ?? '').trim();
const value = String(draft.contact ?? '').trim();
if (!contactType || !value) {
notifyError(new Error('Kontakttyp und Wert nötig.'));
return;
}
this.setState({ busyContactKey: contact.id });
try {
const data = await this.context.entity.updateContact(entityId, contact.id, {
contactType,
contact: value,
});
requireObject(data, 'PATCH /api/entity/:id/contact/:id');
requireObject(data.contact, 'contact');
const listRes = await this.context.entity.listContacts(entityId);
requireObject(listRes, 'GET /api/entity/:id/contact');
const contacts = requireArray(listRes.contacts, 'contacts');
if (this._cancelled) return;
this.setState({
contacts,
contactDrafts: Object.fromEntries(
contacts.map((row) => [
row.id,
{ contactType: row.contactType, contact: row.contact },
]),
),
busyContactKey: null,
});
enqueueSnackbar('Kontakt gespeichert.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyContactKey: null });
}
}
async handleAddContact() {
const { entityId } = this.props;
const { newContact, busyContactKey } = this.state;
if (busyContactKey != null || entityId == null) return;
const contactType = String(newContact.contactType ?? '').trim();
const value = String(newContact.contact ?? '').trim();
if (!contactType || !value) {
notifyError(new Error('Kontakttyp und Wert nötig.'));
return;
}
this.setState({ busyContactKey: 'new' });
try {
const data = await this.context.entity.createContact(entityId, {
contactType,
contact: value,
});
requireObject(data, 'POST /api/entity/:id/contact');
requireObject(data.contact, 'contact');
requireDefined(data.contact.id, 'contact.id');
const listRes = await this.context.entity.listContacts(entityId);
requireObject(listRes, 'GET /api/entity/:id/contact');
const contacts = requireArray(listRes.contacts, 'contacts');
if (this._cancelled) return;
this.setState({
contacts,
contactDrafts: Object.fromEntries(
contacts.map((row) => [
row.id,
{ contactType: row.contactType, contact: row.contact },
]),
),
newContact: emptyContactDraft(),
busyContactKey: null,
});
enqueueSnackbar('Kontakt angelegt.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyContactKey: null });
}
}
async handleDeleteContact(contact) {
const { entityId } = this.props;
if (this.state.busyContactKey != null || entityId == null) return;
if (!window.confirm('Kontakt wirklich löschen?')) return;
this.setState({ busyContactKey: contact.id });
try {
await this.context.entity.deleteContact(entityId, contact.id);
const listRes = await this.context.entity.listContacts(entityId);
requireObject(listRes, 'GET /api/entity/:id/contact');
const contacts = requireArray(listRes.contacts, 'contacts');
if (this._cancelled) return;
this.setState({
contacts,
contactDrafts: Object.fromEntries(
contacts.map((row) => [
row.id,
{ contactType: row.contactType, contact: row.contact },
]),
),
busyContactKey: null,
});
enqueueSnackbar('Kontakt gelöscht.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyContactKey: null });
}
}
renderAddressFields(draft, onChange, disabled) {
return (
<Stack spacing={1.5}>
<SingleLineTextEdit
size="small"
label="Adresstyp"
required
value={draft.addressType}
disabled={disabled}
onChange={(next) => onChange('addressType', next)}
/>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5}>
<SingleLineTextEdit
size="small"
label="Name"
value={draft.name}
disabled={disabled}
onChange={(next) => onChange('name', next)}
/>
<SingleLineTextEdit
size="small"
label="Vorname"
value={draft.firstName}
disabled={disabled}
onChange={(next) => onChange('firstName', next)}
/>
</Stack>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5}>
<SingleLineTextEdit
size="small"
label="Straße"
value={draft.street}
disabled={disabled}
onChange={(next) => onChange('street', next)}
sx={{ flex: 2 }}
/>
<SingleLineTextEdit
size="small"
label="Nr."
value={draft.streetNumber}
disabled={disabled}
onChange={(next) => onChange('streetNumber', next)}
sx={{ flex: 1 }}
/>
</Stack>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5}>
<SingleLineTextEdit
size="small"
label="PLZ"
value={draft.zip}
disabled={disabled}
onChange={(next) => onChange('zip', next)}
sx={{ flex: 1 }}
/>
<SingleLineTextEdit
size="small"
label="Ort"
value={draft.city}
disabled={disabled}
onChange={(next) => onChange('city', next)}
sx={{ flex: 2 }}
/>
</Stack>
<SingleLineTextEdit
size="small"
label="Bundesland / County"
value={draft.county}
disabled={disabled}
onChange={(next) => onChange('county', next)}
/>
</Stack>
);
}
render() {
const {
status,
error,
groupName,
name,
firstName,
savingEntity,
addresses,
addressDrafts,
newAddress,
busyAddressKey,
contacts,
contactDrafts,
newContact,
busyContactKey,
} = 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} />;
}
const addressBusy = busyAddressKey != null;
const contactBusy = busyContactKey != null;
return (
<PanelTileGrid>
<PanelTile wide={2} minHeight={200} color="#bfdbfe" title="Stammdaten">
<Stack spacing={2}>
{groupName != null ? (
<Typography variant="body2" color="text.secondary">
Gruppe: {groupName}
</Typography>
) : null}
<SingleLineTextEdit
size="small"
label="Name"
required
value={name}
disabled={savingEntity}
onChange={(next) => this.setState({ name: next })}
/>
<SingleLineTextEdit
size="small"
label="Vorname"
value={firstName}
disabled={savingEntity}
onChange={(next) => this.setState({ firstName: next })}
/>
<Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button
variant="contained"
size="small"
disabled={savingEntity || !name.trim()}
onClick={() => void this.handleSaveEntity()}
>
{savingEntity ? 'Speichern…' : 'Speichern'}
</Button>
</Box>
</Stack>
</PanelTile>
<PanelTile wide={3} minHeight={240} color="#bbf7d0" title="Adressen">
<Stack spacing={2}>
{addresses.length === 0 ? (
<Typography variant="body2" color="text.secondary">
Noch keine Adressen.
</Typography>
) : (
addresses.map((address) => {
const draft = addressDrafts[address.id] ?? addressDraftFrom(address);
const busy = busyAddressKey === address.id;
return (
<Box key={address.id}>
{this.renderAddressFields(
draft,
(field, value) => this.setAddressDraft(address.id, field, value),
addressBusy,
)}
<Box
sx={{
mt: 1,
display: 'flex',
gap: 1,
justifyContent: 'flex-end',
}}
>
<IconButton
size="small"
aria-label="Adresse löschen"
disabled={addressBusy}
onClick={() => void this.handleDeleteAddress(address)}
>
<DeleteOutlinedIcon fontSize="small" />
</IconButton>
<Button
size="small"
variant="outlined"
disabled={addressBusy}
onClick={() => void this.handleSaveAddress(address)}
>
{busy ? '…' : 'Speichern'}
</Button>
</Box>
<Divider sx={{ mt: 2 }} />
</Box>
);
})
)}
<Typography variant="subtitle2">Neue Adresse</Typography>
{this.renderAddressFields(
newAddress,
(field, value) =>
this.setState((prev) => ({
newAddress: { ...prev.newAddress, [field]: value },
})),
addressBusy,
)}
<Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button
size="small"
variant="contained"
disabled={addressBusy || !newAddress.addressType.trim()}
onClick={() => void this.handleAddAddress()}
>
{busyAddressKey === 'new' ? '…' : 'Adresse hinzufügen'}
</Button>
</Box>
</Stack>
</PanelTile>
<PanelTile wide={3} minHeight={200} color="#fde68a" title="Kontakte">
<Stack spacing={2}>
{contacts.length === 0 ? (
<Typography variant="body2" color="text.secondary">
Noch keine Kontakte.
</Typography>
) : (
contacts.map((contact) => {
const draft =
contactDrafts[contact.id] ?? {
contactType: contact.contactType,
contact: contact.contact,
};
const busy = busyContactKey === contact.id;
return (
<Stack
key={contact.id}
direction={{ xs: 'column', sm: 'row' }}
spacing={1}
sx={{ alignItems: { sm: 'center' } }}
>
<SingleLineTextEdit
size="small"
label="Typ"
fullWidth={false}
value={draft.contactType}
disabled={contactBusy}
onChange={(next) =>
this.setContactDraft(contact.id, 'contactType', next)
}
sx={{ width: 120, flex: '0 0 auto' }}
/>
<SingleLineTextEdit
size="small"
label="Kontakt"
value={draft.contact}
disabled={contactBusy}
onChange={(next) =>
this.setContactDraft(contact.id, 'contact', next)
}
sx={{ flex: 1, minWidth: 0 }}
/>
<IconButton
size="small"
aria-label="Kontakt löschen"
disabled={contactBusy}
onClick={() => void this.handleDeleteContact(contact)}
>
<DeleteOutlinedIcon fontSize="small" />
</IconButton>
<Button
size="small"
variant="outlined"
disabled={contactBusy}
onClick={() => void this.handleSaveContact(contact)}
>
{busy ? '…' : 'Speichern'}
</Button>
</Stack>
);
})
)}
<Divider />
<Typography variant="subtitle2">Neuer Kontakt</Typography>
<Stack
direction={{ xs: 'column', sm: 'row' }}
spacing={1}
sx={{ alignItems: { sm: 'center' } }}
>
<SingleLineTextEdit
size="small"
label="Typ"
fullWidth={false}
value={newContact.contactType}
disabled={contactBusy}
onChange={(next) =>
this.setState((prev) => ({
newContact: { ...prev.newContact, contactType: next },
}))
}
sx={{ width: 120, flex: '0 0 auto' }}
/>
<SingleLineTextEdit
size="small"
label="Kontakt"
value={newContact.contact}
disabled={contactBusy}
onChange={(next) =>
this.setState((prev) => ({
newContact: { ...prev.newContact, contact: next },
}))
}
sx={{ flex: 1, minWidth: 0 }}
/>
<Button
size="small"
variant="contained"
disabled={
contactBusy ||
!newContact.contactType.trim() ||
!newContact.contact.trim()
}
onClick={() => void this.handleAddContact()}
>
{busyContactKey === 'new' ? '…' : 'Hinzufügen'}
</Button>
</Stack>
</Stack>
</PanelTile>
</PanelTileGrid>
);
}
}
export default withEntityRoute(KundeEditPage);

View File

@@ -1,7 +1,278 @@
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 List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import GroupsIcon from '@mui/icons-material/Groups';
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 { requireDefined, requireObject } from '../../utils/apiShape';
import { backendErrorFrom } from '../../utils/backendError';
import { notifyError } from '../../utils/notify';
export default function KundeGruppenPage() {
return (
<Typography color="text.secondary">Gruppen — Inhalt folgt.</Typography>
function sortGroups(groups) {
return [...groups].sort((a, b) =>
String(a.name).localeCompare(String(b.name), 'de'),
);
}
function draftsFrom(groups) {
return Object.fromEntries(groups.map((row) => [row.id, row.name]));
}
class KundeGruppenPage extends PureComponent {
static contextType = StorageManagerContext;
constructor(props) {
super(props);
this.state = {
status: 'loading',
error: null,
groups: [],
drafts: {},
newName: '',
busyKey: null,
};
this._cancelled = false;
this.handleCreate = this.handleCreate.bind(this);
this.handleRetry = this.handleRetry.bind(this);
}
componentDidMount() {
this._cancelled = false;
void this.load();
}
componentWillUnmount() {
this._cancelled = true;
}
applyGroups(groups) {
const sorted = sortGroups(groups);
this.setState({
status: 'ready',
error: null,
groups: sorted,
drafts: draftsFrom(sorted),
});
}
async load() {
this.setState({ status: 'loading', error: null });
try {
const list =
this.context.customergroups ??
(await this.context.customergroupPromise);
if (this._cancelled) return;
this.applyGroups(list);
} catch (err) {
if (this._cancelled) return;
this.setState({ status: 'failed', error: backendErrorFrom(err) });
}
}
handleRetry() {
void this.load();
}
async refreshFromServer() {
const list = await this.context.updateCustomergroup();
if (this._cancelled) return;
this.applyGroups(list);
}
async handleCreate() {
const name = this.state.newName.trim();
if (!name || this.state.busyKey != null) return;
this.setState({ busyKey: 'new' });
try {
const data = await this.context.customergroup.create({ name });
requireObject(data, 'POST /api/customergroup');
requireObject(data.customergroup, 'customergroup');
requireDefined(data.customergroup.id, 'customergroup.id');
await this.refreshFromServer();
if (this._cancelled) return;
this.setState({ newName: '', busyKey: null });
enqueueSnackbar('Kundengruppe angelegt.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyKey: null });
}
}
async handleRename(group) {
const draft = String(this.state.drafts[group.id] ?? '').trim();
if (!draft) {
this.setState((prev) => ({
drafts: { ...prev.drafts, [group.id]: group.name },
}));
return;
}
if (draft === group.name || this.state.busyKey != null) return;
this.setState({ busyKey: group.id });
try {
const data = await this.context.customergroup.update(group.id, {
name: draft,
});
requireObject(data, 'PATCH /api/customergroup/:id');
requireObject(data.customergroup, 'customergroup');
requireDefined(data.customergroup.id, 'customergroup.id');
await this.refreshFromServer();
if (this._cancelled) return;
this.setState({ busyKey: null });
enqueueSnackbar('Kundengruppe gespeichert.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState((prev) => ({
busyKey: null,
drafts: { ...prev.drafts, [group.id]: group.name },
}));
}
}
async handleDelete(group) {
if (this.state.busyKey != null) return;
if (!window.confirm(`Kundengruppe „${group.name}“ wirklich löschen?`)) {
return;
}
this.setState({ busyKey: group.id });
try {
await this.context.customergroup.delete(group.id);
await this.refreshFromServer();
if (this._cancelled) return;
this.setState({ busyKey: null });
enqueueSnackbar('Kundengruppe gelöscht.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyKey: null });
}
}
render() {
const { status, error, groups, drafts, newName, busyKey } = this.state;
const busy = busyKey != null;
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={2} minHeight={280} color="#e9d5ff">
<Stack spacing={2}>
<Typography variant="body2" color="text.secondary">
Kundengruppen der ausgewählten Firma.
</Typography>
<List dense disablePadding>
{groups.length === 0 ? (
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
Noch keine Kundengruppen.
</Typography>
) : (
groups.map((group) => (
<ListItem
key={group.id}
disableGutters
sx={{ gap: 1, py: 0.75, alignItems: 'center' }}
>
<GroupsIcon
sx={{ color: 'text.secondary', fontSize: 20, flexShrink: 0 }}
/>
<SingleLineTextEdit
size="small"
label=""
value={drafts[group.id] ?? ''}
disabled={busy}
onChange={(next) =>
this.setState((prev) => ({
drafts: { ...prev.drafts, [group.id]: next },
}))
}
onBlur={() => void this.handleRename(group)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
event.target.blur();
}
if (event.key === 'Escape') {
event.preventDefault();
this.setState((prev) => ({
drafts: {
...prev.drafts,
[group.id]: group.name,
},
}));
event.target.blur();
}
}}
sx={{ flex: 1 }}
/>
<IconButton
edge="end"
size="small"
aria-label={`„${group.name}“ löschen`}
disabled={busy}
onClick={() => void this.handleDelete(group)}
>
<DeleteOutlinedIcon fontSize="small" />
</IconButton>
</ListItem>
))
)}
</List>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<SingleLineTextEdit
size="small"
label="Neue Kundengruppe"
value={newName}
disabled={busy}
onChange={(next) => this.setState({ newName: next })}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
void this.handleCreate();
}
}}
sx={{ flex: 1 }}
/>
<Button
variant="contained"
size="small"
disabled={busy || !newName.trim()}
onClick={() => void this.handleCreate()}
>
{busyKey === 'new' ? '…' : 'Hinzufügen'}
</Button>
</Box>
</Stack>
</PanelTile>
</PanelTileGrid>
);
}
}
export default KundeGruppenPage;

View File

@@ -1,7 +1,197 @@
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 '../../components/BackendError';
import { PanelTile, PanelTileGrid } from '../../components/panels';
import { StorageManagerContext } from '../../api/storageManagerContext';
import { router } from '../../appRouter';
import { backendErrorFrom } from '../../utils/backendError';
import { notifyError } from '../../utils/notify';
export default function KundeListePage() {
return (
<Typography color="text.secondary">Kundenliste — Inhalt folgt.</Typography>
);
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');
});
}
class KundeListePage extends PureComponent {
static contextType = StorageManagerContext;
constructor(props) {
super(props);
this.state = {
status: 'loading',
error: null,
entities: [],
groupsById: {},
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() {
this.setState({ status: 'loading', error: null });
try {
const [entities, groups] = await Promise.all([
this.context.entities ?? this.context.entityPromise,
this.context.customergroups ?? this.context.customergroupPromise,
]);
if (this._cancelled) return;
const groupsById = Object.fromEntries(groups.map((row) => [row.id, row]));
this.setState({
status: 'ready',
entities: sortEntities(entities),
groupsById,
});
} catch (err) {
if (this._cancelled) return;
this.setState({ status: 'failed', error: backendErrorFrom(err) });
}
}
handleRetry() {
void this.load();
}
handleCreate() {
void router.navigate('/kunde/neu');
}
handleEdit(entity) {
void router.navigate(`/kunde/${entity.id}`);
}
groupName(customergroupId) {
return this.state.groupsById[customergroupId]?.name;
}
async handleDelete(entity) {
if (this.state.busyId != null) return;
const label = [entity.firstName, entity.name].filter(Boolean).join(' ');
if (!window.confirm(`Kunde „${label}“ wirklich löschen?`)) return;
this.setState({ busyId: entity.id });
try {
await this.context.entity.delete(entity.id);
const list = await this.context.updateEntity();
if (this._cancelled) return;
this.setState({
entities: sortEntities(list),
busyId: null,
});
enqueueSnackbar('Kunde gelöscht.', { variant: 'success' });
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ busyId: null });
}
}
render() {
const { status, error, entities, busyId } = 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>
<PanelTile wide={3} minHeight={240} color="#bfdbfe">
<Stack spacing={2}>
<Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button variant="contained" size="small" onClick={this.handleCreate}>
Neuer Kunde
</Button>
</Box>
{entities.length === 0 ? (
<Typography variant="body2" color="text.secondary">
Noch keine Kunden.
</Typography>
) : (
<TableContainer>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Vorname</TableCell>
<TableCell>Gruppe</TableCell>
<TableCell padding="checkbox" />
</TableRow>
</TableHead>
<TableBody>
{entities.map((row) => (
<TableRow
key={row.id}
hover
sx={{ cursor: 'pointer' }}
onClick={() => this.handleEdit(row)}
>
<TableCell>{row.name}</TableCell>
<TableCell>{row.firstName}</TableCell>
<TableCell>{this.groupName(row.customergroupId)}</TableCell>
<TableCell padding="checkbox" onClick={(e) => e.stopPropagation()}>
<IconButton
size="small"
aria-label={`„${row.name}“ bearbeiten`}
onClick={() => this.handleEdit(row)}
>
<EditOutlinedIcon fontSize="small" />
</IconButton>
<IconButton
size="small"
aria-label={`„${row.name}“ löschen`}
disabled={busyId != null}
onClick={() => void this.handleDelete(row)}
>
<DeleteOutlinedIcon fontSize="small" />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
</Stack>
</PanelTile>
</PanelTileGrid>
);
}
}
export default KundeListePage;

View File

@@ -1,7 +0,0 @@
import Typography from '@mui/material/Typography';
export default function KundeKontaktePage() {
return (
<Typography color="text.secondary">Kontakte — Inhalt folgt.</Typography>
);
}

203
src/pages/kunde/neu.jsx Normal file
View File

@@ -0,0 +1,203 @@
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 TextField from '@mui/material/TextField';
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 sortGroups(groups) {
return [...groups].sort((a, b) =>
String(a.name).localeCompare(String(b.name), 'de'),
);
}
class KundeNeuPage extends PureComponent {
static contextType = StorageManagerContext;
constructor(props) {
super(props);
this.state = {
status: 'loading',
error: null,
groups: [],
customergroupId: null,
name: '',
firstName: '',
saving: false,
};
this._cancelled = false;
this.handleRetry = this.handleRetry.bind(this);
this.handleGroupChange = this.handleGroupChange.bind(this);
this.handleSave = this.handleSave.bind(this);
}
componentDidMount() {
this._cancelled = false;
void this.loadGroups();
}
componentWillUnmount() {
this._cancelled = true;
}
async loadGroups() {
this.setState({ status: 'loading', error: null });
try {
const list =
this.context.customergroups ??
(await this.context.customergroupPromise);
if (this._cancelled) return;
this.setState({
status: 'ready',
groups: sortGroups(list),
});
} catch (err) {
if (this._cancelled) return;
this.setState({
status: 'failed',
error: backendErrorFrom(err),
});
}
}
handleRetry() {
void this.loadGroups();
}
handleGroupChange(_event, option) {
this.setState({ customergroupId: option?.id ?? null });
}
async handleSave() {
if (this.state.saving) return;
const { customergroupId, name, firstName } = this.state;
const trimmedName = name.trim();
const trimmedFirst = firstName.trim();
if (customergroupId == null) {
notifyError(new Error('Kundengruppe fehlt.'));
return;
}
if (!trimmedName) {
notifyError(new Error('Name fehlt.'));
return;
}
const body = {
customergroupId,
name: trimmedName,
};
if (trimmedFirst) body.firstName = trimmedFirst;
this.setState({ saving: true });
try {
const data = await this.context.entity.create(body);
requireObject(data, 'POST /api/entity');
requireObject(data.entity, 'entity');
requireDefined(data.entity.id, 'entity.id');
await this.context.updateEntity();
if (this._cancelled) return;
enqueueSnackbar('Kunde angelegt.', { variant: 'success' });
void router.navigate(`/kunde/${data.entity.id}`);
} catch (err) {
if (this._cancelled) return;
notifyError(err);
this.setState({ saving: false });
}
}
render() {
const {
status,
error,
groups,
customergroupId,
name,
firstName,
saving,
} = this.state;
if (status === 'failed') {
return <BackendError error={error} onRetry={this.handleRetry} />;
}
const selected =
groups.find((row) => row.id === customergroupId) ?? null;
const canSave =
customergroupId != null && name.trim() !== '' && !saving;
return (
<PanelTileGrid>
<PanelTile wide={2} minHeight={220} color="#bfdbfe" title="Neuer Kunde">
<Stack spacing={2}>
<Autocomplete
size="small"
options={groups}
value={selected}
loading={status === 'loading'}
disabled={saving || status === 'loading'}
getOptionLabel={(option) => String(option.name ?? '')}
isOptionEqualToValue={(option, value) => option.id === value.id}
onChange={this.handleGroupChange}
renderInput={(params) => {
const { InputProps, inputProps, ...other } = params;
return (
<TextField
{...other}
label="Kundengruppe"
required
autoComplete="off"
slotProps={{
input: InputProps,
htmlInput: {
...inputProps,
spellCheck: false,
autoComplete: 'off',
},
}}
/>
);
}}
/>
<SingleLineTextEdit
size="small"
label="Name"
required
value={name}
disabled={saving}
onChange={(next) => this.setState({ name: next })}
/>
<SingleLineTextEdit
size="small"
label="Vorname"
value={firstName}
disabled={saving}
onChange={(next) => this.setState({ firstName: next })}
/>
<Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button
variant="contained"
size="small"
disabled={!canSave}
onClick={() => void this.handleSave()}
>
{saving ? 'Speichern…' : 'Speichern'}
</Button>
</Box>
</Stack>
</PanelTile>
</PanelTileGrid>
);
}
}
export default KundeNeuPage;

View File

@@ -0,0 +1,16 @@
import { useParams } from 'react-router-dom';
/** Injects numeric `entityId` from `/kunde/:entityId`. */
export default function withEntityRoute(Wrapped) {
function EntityRouteWrapper(props) {
const { entityId: raw } = useParams();
const entityId = Number(raw);
return (
<Wrapped
{...props}
entityId={Number.isInteger(entityId) ? entityId : null}
/>
);
}
return EntityRouteWrapper;
}