u
This commit is contained in:
@@ -1,226 +1,270 @@
|
||||
import { PureComponent } from 'react';
|
||||
import { PureComponent, createRef } from 'react';
|
||||
import Alert from '@mui/material/Alert';
|
||||
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 KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
|
||||
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
|
||||
import Sortable from 'sortablejs';
|
||||
import { enqueueSnackbar } from 'notistack';
|
||||
import BackendError from '../../components/BackendError';
|
||||
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
||||
import { PanelTile, PanelTileGrid } from 'dashgui/panels';
|
||||
import { customergroup as customergroupApi } from '../../api';
|
||||
import customergroupAutomat from '../../automats/customergroupAutomat';
|
||||
import { requireArray, requireDefined, requireObject } from '../../utils/apiShape';
|
||||
import withNavigate from '../../components/withNavigate';
|
||||
import { backendErrorFrom } from '../../utils/backendError';
|
||||
import { notifyError } from '../../utils/notify';
|
||||
import {
|
||||
PURPLE_BG,
|
||||
} from '../../colors';
|
||||
import customergroupAutomat from '../../automats/customergroupAutomat';
|
||||
import { KundeGruppe } from '../../components/kunde';
|
||||
import { PURPLE_BG } from '../../colors';
|
||||
|
||||
function sortGroups(groups) {
|
||||
return [...groups].sort((a, b) => {
|
||||
const bySort = a.sort - b.sort;
|
||||
if (bySort !== 0) return bySort;
|
||||
const byName = String(a.name).localeCompare(String(b.name), 'de');
|
||||
if (byName !== 0) return byName;
|
||||
return a.id - b.id;
|
||||
});
|
||||
function getInitialParams(props) {
|
||||
const searchParams =
|
||||
typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
|
||||
const prefill =
|
||||
props.location?.state?.name ??
|
||||
props.location?.state?.newName ??
|
||||
searchParams?.get('name') ??
|
||||
searchParams?.get('newName') ??
|
||||
'';
|
||||
const returnTo =
|
||||
props.location?.state?.returnTo ??
|
||||
searchParams?.get('returnTo') ??
|
||||
null;
|
||||
return { prefill: prefill.trim(), returnTo };
|
||||
}
|
||||
|
||||
function draftsFrom(groups) {
|
||||
return Object.fromEntries(groups.map((row) => [row.id, row.name]));
|
||||
}
|
||||
class KundeGruppenSearchField extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
const initial = customergroupAutomat.state.filter || props.prefill || '';
|
||||
this.state = {
|
||||
input: initial,
|
||||
submitting: false,
|
||||
};
|
||||
if (props.prefill && !customergroupAutomat.state.filter) {
|
||||
customergroupAutomat.actions.filter(props.prefill);
|
||||
}
|
||||
this.handleSubmit = this.handleSubmit.bind(this);
|
||||
}
|
||||
|
||||
function requireGroupListItem(row, path) {
|
||||
requireObject(row, path);
|
||||
requireDefined(row.id, `${path}.id`);
|
||||
requireDefined(row.name, `${path}.name`);
|
||||
requireDefined(row.sort, `${path}.sort`);
|
||||
requireDefined(row.editable, `${path}.editable`);
|
||||
componentDidMount() {
|
||||
this.unsub = customergroupAutomat.subscribe(this, (state) => ({
|
||||
input: state.filter,
|
||||
}));
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.unsub?.();
|
||||
}
|
||||
|
||||
onInputChange(input) {
|
||||
this.setState({ input });
|
||||
customergroupAutomat.actions.filter(input);
|
||||
}
|
||||
|
||||
async handleSubmit() {
|
||||
const name = this.state.input.trim();
|
||||
if (!name || this.state.submitting) return;
|
||||
|
||||
this.setState({ submitting: true });
|
||||
try {
|
||||
const row = await customergroupAutomat.actions.create({ name });
|
||||
enqueueSnackbar(`Kundengruppe „${row.name || name}“ angelegt.`, { variant: 'success' });
|
||||
this.setState({ input: '', submitting: false });
|
||||
customergroupAutomat.actions.filter('');
|
||||
if (this.props.returnTo && this.props.navigate) {
|
||||
this.props.navigate(this.props.returnTo);
|
||||
}
|
||||
} catch (err) {
|
||||
this.setState({ submitting: false });
|
||||
notifyError(err);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { inputRef, returnTo, navigate } = this.props;
|
||||
const { input, submitting } = this.state;
|
||||
const canSubmit = Boolean(input.trim()) && !submitting;
|
||||
|
||||
return (
|
||||
<PanelTileGrid>
|
||||
<Box
|
||||
ref={inputRef}
|
||||
sx={{
|
||||
gridColumn: {
|
||||
xs: '1 / -1',
|
||||
sm: 'span 2',
|
||||
md: 'span 2',
|
||||
},
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 1,
|
||||
pb: 2,
|
||||
}}
|
||||
>
|
||||
{returnTo ? (
|
||||
<Alert
|
||||
severity="info"
|
||||
sx={{ py: 0.5, alignItems: 'center' }}
|
||||
action={
|
||||
<Button
|
||||
color="inherit"
|
||||
size="small"
|
||||
onClick={() => navigate?.(returnTo)}
|
||||
>
|
||||
Zurück
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{input
|
||||
? `Kundengruppenname „${input}“ übernommen.`
|
||||
: 'Neue Kundengruppe anlegen.'}
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
<SingleLineTextEdit
|
||||
sx={{ flex: 1 }}
|
||||
size="small"
|
||||
search
|
||||
clear
|
||||
placeholder="Kundengruppe suchen oder anlegen…"
|
||||
value={input}
|
||||
disabled={submitting}
|
||||
onChange={(next) => this.onInputChange(next)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void this.handleSubmit();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!canSubmit}
|
||||
onClick={() => void this.handleSubmit()}
|
||||
>
|
||||
Hinzufügen
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</PanelTileGrid>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class KundeGruppenPage extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
const initialGroups =
|
||||
customergroupAutomat.state.filteredItems ?? customergroupAutomat.state.items ?? [];
|
||||
this.state = {
|
||||
status: 'loading',
|
||||
error: null,
|
||||
groups: [],
|
||||
drafts: {},
|
||||
newName: '',
|
||||
busyKey: null,
|
||||
status: customergroupAutomat.state.status === 'ready' ? 'ready' : 'loading',
|
||||
error: customergroupAutomat.state.error ? backendErrorFrom(customergroupAutomat.state.error) : null,
|
||||
groups: initialGroups,
|
||||
filter: customergroupAutomat.state.filter ?? '',
|
||||
};
|
||||
this.searchRef = createRef();
|
||||
this.listRef = createRef();
|
||||
this._sortable = null;
|
||||
this._cancelled = false;
|
||||
this.handleCreate = this.handleCreate.bind(this);
|
||||
this.handleRetry = this.handleRetry.bind(this);
|
||||
this._initSortable = this._initSortable.bind(this);
|
||||
this._destroySortable = this._destroySortable.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this._cancelled = false;
|
||||
void this.load();
|
||||
|
||||
this.unsub = customergroupAutomat.subscribe(this, (state) => ({
|
||||
groups: state.filteredItems ?? state.items,
|
||||
filter: state.filter ?? '',
|
||||
status: state.status,
|
||||
error: state.error ? backendErrorFrom(state.error) : null,
|
||||
}));
|
||||
|
||||
if (customergroupAutomat.state.status !== 'ready') {
|
||||
void customergroupAutomat.actions.load().catch((err) => notifyError(err));
|
||||
} else {
|
||||
this._initSortable();
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps, prevState) {
|
||||
if (
|
||||
prevState.status !== this.state.status ||
|
||||
prevState.groups !== this.state.groups ||
|
||||
prevState.filter !== this.state.filter
|
||||
) {
|
||||
if (this.state.status === 'ready') {
|
||||
this._initSortable();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this._cancelled = true;
|
||||
this.unsub?.();
|
||||
this._destroySortable();
|
||||
}
|
||||
|
||||
applyGroups(groups) {
|
||||
groups.forEach((row, index) => {
|
||||
requireGroupListItem(row, `customergroups[${index}]`);
|
||||
});
|
||||
const sorted = sortGroups(groups);
|
||||
this.setState({
|
||||
status: 'ready',
|
||||
error: null,
|
||||
groups: sorted,
|
||||
drafts: draftsFrom(sorted),
|
||||
_initSortable() {
|
||||
this._destroySortable();
|
||||
const el = this.listRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const isFiltered = Boolean(this.state.filter?.trim());
|
||||
|
||||
this._sortable = Sortable.create(el, {
|
||||
handle: '.drag-handle',
|
||||
animation: 150,
|
||||
ghostClass: 'sortable-ghost',
|
||||
chosenClass: 'sortable-chosen',
|
||||
disabled: isFiltered,
|
||||
onEnd: (evt) => {
|
||||
const { oldIndex, newIndex } = evt;
|
||||
if (oldIndex === newIndex) return;
|
||||
|
||||
this.setState(
|
||||
(prev) => {
|
||||
const next = [...prev.groups];
|
||||
const [moved] = next.splice(oldIndex, 1);
|
||||
next.splice(newIndex, 0, moved);
|
||||
return { groups: next };
|
||||
},
|
||||
() => {
|
||||
const ids = this.state.groups.map((g) => g.id);
|
||||
void this._persistOrder(ids);
|
||||
}
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async load() {
|
||||
this.setState({ status: 'loading', error: null });
|
||||
_destroySortable() {
|
||||
this._sortable?.destroy();
|
||||
this._sortable = null;
|
||||
}
|
||||
|
||||
async _persistOrder(customergroupIds) {
|
||||
try {
|
||||
const list = await customergroupAutomat.actions.ensureLoaded();
|
||||
if (this._cancelled) return;
|
||||
this.applyGroups(list);
|
||||
await customergroupAutomat.actions.reorder(customergroupIds);
|
||||
} catch (err) {
|
||||
if (this._cancelled) return;
|
||||
this.setState({ status: 'failed', error: backendErrorFrom(err) });
|
||||
notifyError(err);
|
||||
void customergroupAutomat.actions.reload();
|
||||
}
|
||||
}
|
||||
|
||||
handleRetry() {
|
||||
void this.load();
|
||||
}
|
||||
|
||||
async refreshFromServer() {
|
||||
const list = await customergroupAutomat.actions.reload();
|
||||
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 customergroupApi.create({ name });
|
||||
requireObject(data, 'POST /api/customergroup');
|
||||
requireObject(data.customergroup, 'customergroup');
|
||||
requireDefined(data.customergroup.id, 'customergroup.id');
|
||||
requireDefined(data.customergroup.sort, 'customergroup.sort');
|
||||
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) {
|
||||
if (!group.editable) return;
|
||||
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 customergroupApi.update(group.id, {
|
||||
name: draft,
|
||||
});
|
||||
requireObject(data, 'PATCH /api/customergroup/:id');
|
||||
requireObject(data.customergroup, 'customergroup');
|
||||
requireDefined(data.customergroup.id, 'customergroup.id');
|
||||
requireDefined(data.customergroup.sort, 'customergroup.sort');
|
||||
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 handleMove(group, delta) {
|
||||
const { groups, busyKey } = this.state;
|
||||
if (busyKey != null) return;
|
||||
|
||||
const index = groups.findIndex((row) => row.id === group.id);
|
||||
const targetIndex = index + delta;
|
||||
if (index < 0 || targetIndex < 0 || targetIndex >= groups.length) return;
|
||||
|
||||
const next = [...groups];
|
||||
const [row] = next.splice(index, 1);
|
||||
next.splice(targetIndex, 0, row);
|
||||
const customergroupIds = next.map((item) => item.id);
|
||||
|
||||
this.setState({ busyKey: group.id });
|
||||
try {
|
||||
const data = await customergroupApi.order({ customergroupIds });
|
||||
requireObject(data, 'PUT /api/customergroup/order');
|
||||
requireArray(data.customergroupIds, 'customergroupIds');
|
||||
await this.refreshFromServer();
|
||||
if (this._cancelled) return;
|
||||
this.setState({ busyKey: null });
|
||||
} catch (err) {
|
||||
if (this._cancelled) return;
|
||||
notifyError(err);
|
||||
try {
|
||||
await this.refreshFromServer();
|
||||
} catch (refreshErr) {
|
||||
notifyError(refreshErr);
|
||||
}
|
||||
if (this._cancelled) return;
|
||||
this.setState({ busyKey: null });
|
||||
}
|
||||
}
|
||||
|
||||
async handleDelete(group) {
|
||||
if (!group.editable || this.state.busyKey != null) return;
|
||||
if (!window.confirm(`Kundengruppe „${group.name}“ wirklich löschen?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.setState({ busyKey: group.id });
|
||||
try {
|
||||
await customergroupApi.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 });
|
||||
}
|
||||
void customergroupAutomat.actions.load().catch((err) => notifyError(err));
|
||||
}
|
||||
|
||||
render() {
|
||||
const { status, error, groups, drafts, newName, busyKey } = this.state;
|
||||
const busy = busyKey != null;
|
||||
const { status, error, groups, filter } = this.state;
|
||||
const { prefill, returnTo } = getInitialParams(this.props);
|
||||
|
||||
if (status === 'loading') {
|
||||
if (status === 'loading' || status === 'idle') {
|
||||
return (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
|
||||
<CircularProgress />
|
||||
@@ -232,117 +276,40 @@ class KundeGruppenPage extends PureComponent {
|
||||
return <BackendError error={error} onRetry={this.handleRetry} />;
|
||||
}
|
||||
|
||||
const trimmedFilter = filter?.trim() ?? '';
|
||||
|
||||
return (
|
||||
<PanelTileGrid>
|
||||
<PanelTile wide={2} minHeight={280} color={PURPLE_BG}>
|
||||
<Stack spacing={2}>
|
||||
<List dense disablePadding>
|
||||
<>
|
||||
<KundeGruppenSearchField
|
||||
inputRef={this.searchRef}
|
||||
prefill={prefill}
|
||||
returnTo={returnTo}
|
||||
navigate={this.props.navigate}
|
||||
/>
|
||||
<PanelTileGrid>
|
||||
<PanelTile wide={2} minHeight={0} color={PURPLE_BG}>
|
||||
<List dense disablePadding ref={this.listRef} sx={{ width: '100%' }}>
|
||||
{groups.length === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
||||
Noch keine Kundengruppen.
|
||||
{trimmedFilter
|
||||
? `Keine Treffer für „${trimmedFilter}“.`
|
||||
: 'Noch keine Kundengruppen angelegt.'}
|
||||
</Typography>
|
||||
) : (
|
||||
groups.map((group, index) => {
|
||||
const editable = group.editable === true;
|
||||
return (
|
||||
<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 || !editable}
|
||||
onChange={(next) =>
|
||||
this.setState((prev) => ({
|
||||
drafts: { ...prev.drafts, [group.id]: next },
|
||||
}))
|
||||
}
|
||||
onBlur={() => void this.handleRename(group)}
|
||||
onKeyDown={(event) => {
|
||||
if (!editable) return;
|
||||
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
|
||||
size="small"
|
||||
aria-label={`„${group.name}“ nach oben`}
|
||||
disabled={busy || index === 0}
|
||||
onClick={() => void this.handleMove(group, -1)}
|
||||
>
|
||||
<KeyboardArrowUpIcon fontSize="small" />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={`„${group.name}“ nach unten`}
|
||||
disabled={busy || index >= groups.length - 1}
|
||||
onClick={() => void this.handleMove(group, 1)}
|
||||
>
|
||||
<KeyboardArrowDownIcon fontSize="small" />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
edge="end"
|
||||
size="small"
|
||||
aria-label={`„${group.name}“ löschen`}
|
||||
disabled={busy || !editable}
|
||||
onClick={() => void this.handleDelete(group)}
|
||||
>
|
||||
<DeleteOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</ListItem>
|
||||
);
|
||||
})
|
||||
groups.map((group) => (
|
||||
<KundeGruppe
|
||||
key={group.id}
|
||||
group={group}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</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>
|
||||
</PanelTile>
|
||||
</PanelTileGrid>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default KundeGruppenPage;
|
||||
export { KundeGruppe, KundeGruppenSearchField };
|
||||
export default withNavigate(KundeGruppenPage);
|
||||
|
||||
Reference in New Issue
Block a user