u
This commit is contained in:
@@ -1,16 +1,19 @@
|
|||||||
/**
|
/**
|
||||||
* @file customergroupAutomat.js
|
* @file customergroupAutomat.js
|
||||||
* @description Manages cached customer groups (`GET /api/customergroup`) for
|
* @description Manages cached customer groups (`GET /api/customergroup`) for
|
||||||
* the active company. Built via `createListAutomat`.
|
* the active company. Follows the brand/warehouse automat pattern with
|
||||||
|
* filtering, deduplicated loads, silent reloads, and CRUD actions.
|
||||||
*
|
*
|
||||||
* Upstream Triggers:
|
* Upstream Triggers:
|
||||||
* - `authAutomat`: Via `createListAutomat` — triggers `load()` on `'authed'` with
|
* - `authAutomat`: Triggers `actions.load()` on `'authed'` with a `selectedCompanyId`,
|
||||||
* a `selectedCompanyId`, and `reset()` on `'anon'`.
|
* and `actions.reset()` on `'anon'`.
|
||||||
* - UI / Routes: Manual calls to `load()` or `reload()`.
|
* - UI / Routes: Mutating actions (`create`, `update`, `remove`, `reorder`, `filter`).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { Automat } from 'react-automat';
|
||||||
import { customergroup as customergroupApi } from '../api';
|
import { customergroup as customergroupApi } from '../api';
|
||||||
import { createListAutomat } from './createListAutomat';
|
import { requireArray, requireDefined, requireObject } from '../utils/apiShape';
|
||||||
|
import authAutomat from './authAutomat';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {Object} CustomerGroup
|
* @typedef {Object} CustomerGroup
|
||||||
@@ -20,22 +23,175 @@ import { createListAutomat } from './createListAutomat';
|
|||||||
* @property {boolean} editable False for reserved POS / Lieferanten groups.
|
* @property {boolean} editable False for reserved POS / Lieferanten groups.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} CustomerGroupState
|
||||||
|
* @property {Array<CustomerGroup>} items Loaded records.
|
||||||
|
* @property {Array<CustomerGroup>} filteredItems Records matching active search filter.
|
||||||
|
* @property {string} filter Active search/filter string.
|
||||||
|
* @property {'idle'|'loading'|'ready'|'failed'} status Load lifecycle state.
|
||||||
|
* @property {Error|string|null} error Last load error.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** @type {CustomerGroupState} */
|
||||||
|
const initialState = {
|
||||||
|
items: [],
|
||||||
|
filteredItems: [],
|
||||||
|
filter: '',
|
||||||
|
status: 'idle',
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyFilter = (groups, filter) => {
|
||||||
|
const query = String(filter ?? '').trim().toLowerCase();
|
||||||
|
return query
|
||||||
|
? groups.filter((g) => String(g.name ?? '').toLowerCase().includes(query))
|
||||||
|
: groups;
|
||||||
|
};
|
||||||
|
|
||||||
|
const sortGroups = (items) =>
|
||||||
|
[...items].sort((a, b) => (Number(a.sort) || 0) - (Number(b.sort) || 0));
|
||||||
|
|
||||||
|
let customergroupAutomat;
|
||||||
|
|
||||||
|
const updateStateWithGroups = (groups, extra = {}) => {
|
||||||
|
const list = sortGroups(Array.isArray(groups) ? groups : []);
|
||||||
|
const filteredItems = applyFilter(list, customergroupAutomat.state.filter);
|
||||||
|
customergroupAutomat.setState({ items: list, filteredItems, ...extra });
|
||||||
|
return list;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function fetchGroups() {
|
||||||
|
const data = await customergroupApi.list();
|
||||||
|
requireObject(data, 'GET /api/customergroup');
|
||||||
|
return requireArray(data.customergroups, 'customergroups');
|
||||||
|
}
|
||||||
|
|
||||||
|
let inflightLoad = null;
|
||||||
|
|
||||||
|
function loadGroups() {
|
||||||
|
if (inflightLoad) return inflightLoad;
|
||||||
|
inflightLoad = (async () => {
|
||||||
|
customergroupAutomat.setState({ status: 'loading', error: null });
|
||||||
|
try {
|
||||||
|
const groups = await fetchGroups();
|
||||||
|
updateStateWithGroups(groups, { status: 'ready', error: null });
|
||||||
|
return groups;
|
||||||
|
} catch (error) {
|
||||||
|
customergroupAutomat.setState({ status: 'failed', error });
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
inflightLoad = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return inflightLoad;
|
||||||
|
}
|
||||||
|
|
||||||
|
const actions = {
|
||||||
|
/** Sets the active search filter query and updates filteredItems. */
|
||||||
|
filter(query) {
|
||||||
|
const filter = String(query ?? '');
|
||||||
|
customergroupAutomat.setState({
|
||||||
|
filter,
|
||||||
|
filteredItems: applyFilter(customergroupAutomat.state.items, filter),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Loads the list, deduplicating concurrent callers. */
|
||||||
|
load() {
|
||||||
|
return loadGroups();
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Silently refreshes the customer groups without flashing loading state. */
|
||||||
|
async reload() {
|
||||||
|
try {
|
||||||
|
const groups = await fetchGroups();
|
||||||
|
updateStateWithGroups(groups, { status: 'ready', error: null });
|
||||||
|
return groups;
|
||||||
|
} catch (error) {
|
||||||
|
customergroupAutomat.setState({ error });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Replaces the cached list without an API call. */
|
||||||
|
replace(items) {
|
||||||
|
return updateStateWithGroups(items, { status: 'ready', error: null });
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Returns cached items if ready, otherwise loads. */
|
||||||
|
ensureLoaded() {
|
||||||
|
if (customergroupAutomat.state.status === 'ready') {
|
||||||
|
return Promise.resolve(customergroupAutomat.state.items);
|
||||||
|
}
|
||||||
|
return actions.load();
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Resets state to initial idle values. */
|
||||||
|
reset() {
|
||||||
|
inflightLoad = null;
|
||||||
|
customergroupAutomat.setState(initialState);
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Creates a customer group and refreshes the cache. */
|
||||||
|
async create(body) {
|
||||||
|
const data = await customergroupApi.create(body);
|
||||||
|
requireObject(data, 'POST /api/customergroup');
|
||||||
|
requireObject(data.customergroup, 'customergroup');
|
||||||
|
requireDefined(data.customergroup.id, 'customergroup.id');
|
||||||
|
await customergroupAutomat.actions.reload();
|
||||||
|
return data.customergroup;
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Updates a customer group name and refreshes the cache. */
|
||||||
|
async update(id, body) {
|
||||||
|
const data = await customergroupApi.update(id, body);
|
||||||
|
requireObject(data, 'PATCH /api/customergroup/:id');
|
||||||
|
requireObject(data.customergroup, 'customergroup');
|
||||||
|
requireDefined(data.customergroup.id, 'customergroup.id');
|
||||||
|
await customergroupAutomat.actions.reload();
|
||||||
|
return data.customergroup;
|
||||||
|
},
|
||||||
|
|
||||||
|
rename(id, body) {
|
||||||
|
return actions.update(id, body);
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Deletes a customer group and refreshes the cache. */
|
||||||
|
async remove(id) {
|
||||||
|
await customergroupApi.delete(id);
|
||||||
|
await customergroupAutomat.actions.reload();
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Reorders customer groups and refreshes the cache. */
|
||||||
|
async reorder(customergroupIds) {
|
||||||
|
const data = await customergroupApi.order({ customergroupIds });
|
||||||
|
requireObject(data, 'PUT /api/customergroup/order');
|
||||||
|
await customergroupAutomat.actions.reload();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Company customer groups (`GET /api/customergroup`).
|
* Company customer groups (`GET /api/customergroup`).
|
||||||
*
|
*
|
||||||
* Reserved groups (`POS`, `Lieferanten`) are flagged `editable: false` and must
|
* Reserved groups (`POS`, `Lieferanten`) are flagged `editable: false` and must
|
||||||
* not be renamed or deleted by the UI.
|
* not be renamed or deleted by the UI.
|
||||||
*
|
*
|
||||||
* @type {import('react-automat').Automat<import('./createListAutomat').ListAutomatState>}
|
* @type {Automat<CustomerGroupState>}
|
||||||
*/
|
*/
|
||||||
export const customergroupAutomat = createListAutomat({
|
customergroupAutomat = new Automat(initialState, actions, {
|
||||||
name: 'customergroup',
|
name: 'customergroup',
|
||||||
fetch: async () => {
|
});
|
||||||
const data = await customergroupApi.list();
|
|
||||||
return data.customergroups ?? [];
|
export { customergroupAutomat };
|
||||||
},
|
|
||||||
sort: (items) =>
|
// Load on session/company establishment, reset on logout.
|
||||||
[...items].sort((a, b) => (Number(a.sort) || 0) - (Number(b.sort) || 0)),
|
authAutomat.subscribe((auth) => {
|
||||||
|
const companyId = auth.user?.selectedCompanyId;
|
||||||
|
if (auth.status === 'authed' && companyId) {
|
||||||
|
void actions.load().catch(() => {});
|
||||||
|
} else if (auth.status === 'anon') {
|
||||||
|
actions.reset();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
export default customergroupAutomat;
|
export default customergroupAutomat;
|
||||||
|
|||||||
155
src/components/kunde/KundeGruppe.jsx
Normal file
155
src/components/kunde/KundeGruppe.jsx
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
import { PureComponent } from 'react';
|
||||||
|
import Box from '@mui/material/Box';
|
||||||
|
import IconButton from '@mui/material/IconButton';
|
||||||
|
import ListItem from '@mui/material/ListItem';
|
||||||
|
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
|
||||||
|
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
|
||||||
|
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
||||||
|
import { enqueueSnackbar } from 'notistack';
|
||||||
|
import customergroupAutomat from '../../automats/customergroupAutomat';
|
||||||
|
import { notifyError } from '../../utils/notify';
|
||||||
|
|
||||||
|
class KundeGruppe extends PureComponent {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
const item = props.group ?? props.item;
|
||||||
|
this.state = {
|
||||||
|
draft: item?.name ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevProps) {
|
||||||
|
const prevItem = prevProps.group ?? prevProps.item;
|
||||||
|
const item = this.props.group ?? this.props.item;
|
||||||
|
if (prevItem?.name !== item?.name) {
|
||||||
|
this.setState({ draft: item?.name ?? '' });
|
||||||
|
} else if (prevProps.disabled && !this.props.disabled) {
|
||||||
|
if (this.state.draft !== item?.name) {
|
||||||
|
this.setState({ draft: item?.name ?? '' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleChange = (next) => {
|
||||||
|
this.setState({ draft: next });
|
||||||
|
const item = this.props.group ?? this.props.item;
|
||||||
|
this.props.onChange?.(next, item);
|
||||||
|
};
|
||||||
|
|
||||||
|
handleBlur = () => {
|
||||||
|
const item = this.props.group ?? this.props.item;
|
||||||
|
if (!item) return;
|
||||||
|
const editable = item.editable !== false;
|
||||||
|
if (!editable) return;
|
||||||
|
|
||||||
|
const draft = this.state.draft.trim();
|
||||||
|
if (!draft) {
|
||||||
|
this.setState({ draft: item.name ?? '' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (draft !== item.name) {
|
||||||
|
void this.renameGroup(item, draft);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
async renameGroup(item, name) {
|
||||||
|
try {
|
||||||
|
await customergroupAutomat.actions.update(item.id, { name });
|
||||||
|
enqueueSnackbar('Kundengruppe gespeichert.', { variant: 'success' });
|
||||||
|
} catch (err) {
|
||||||
|
this.setState({ draft: item.name ?? '' });
|
||||||
|
notifyError(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleKeyDown = (event) => {
|
||||||
|
const item = this.props.group ?? this.props.item;
|
||||||
|
const editable = item?.editable !== false;
|
||||||
|
if (!editable) return;
|
||||||
|
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
event.preventDefault();
|
||||||
|
event.target.blur();
|
||||||
|
}
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.preventDefault();
|
||||||
|
this.setState({ draft: item?.name ?? '' });
|
||||||
|
event.target.blur();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleDelete = () => {
|
||||||
|
const item = this.props.group ?? this.props.item;
|
||||||
|
if (!item) return;
|
||||||
|
const editable = item.editable !== false;
|
||||||
|
if (!editable) return;
|
||||||
|
|
||||||
|
if (!window.confirm(`Kundengruppe „${item.name}“ wirklich löschen?`)) return;
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
await customergroupAutomat.actions.remove(item.id);
|
||||||
|
enqueueSnackbar('Kundengruppe gelöscht.', { variant: 'success' });
|
||||||
|
} catch (err) {
|
||||||
|
notifyError(err);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
const { disabled, sx } = this.props;
|
||||||
|
const item = this.props.group ?? this.props.item;
|
||||||
|
const { draft } = this.state;
|
||||||
|
const name = item?.name ?? '';
|
||||||
|
const editable = item?.editable !== false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ListItem
|
||||||
|
disableGutters
|
||||||
|
data-id={item?.id}
|
||||||
|
sx={{ gap: 1, py: 0.75, alignItems: 'center', width: '100%', minWidth: 0, ...sx }}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
className="drag-handle"
|
||||||
|
sx={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
width: 40,
|
||||||
|
height: 40,
|
||||||
|
flexShrink: 0,
|
||||||
|
color: 'text.disabled',
|
||||||
|
cursor: disabled ? 'default' : 'grab',
|
||||||
|
userSelect: 'none',
|
||||||
|
touchAction: 'none',
|
||||||
|
'&:hover': disabled ? undefined : { color: 'text.secondary' },
|
||||||
|
transition: 'color 0.15s',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DragIndicatorIcon sx={{ fontSize: 24, pointerEvents: 'none' }} />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<SingleLineTextEdit
|
||||||
|
size="small"
|
||||||
|
label=""
|
||||||
|
value={draft}
|
||||||
|
disabled={disabled || !item || !editable}
|
||||||
|
onChange={this.handleChange}
|
||||||
|
onBlur={this.handleBlur}
|
||||||
|
onKeyDown={this.handleKeyDown}
|
||||||
|
sx={{ flex: 1, minWidth: 0 }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
aria-label={`„${name}“ löschen`}
|
||||||
|
disabled={disabled || !item || !editable}
|
||||||
|
onClick={this.handleDelete}
|
||||||
|
sx={{ width: 40, height: 40, flexShrink: 0 }}
|
||||||
|
>
|
||||||
|
<DeleteOutlinedIcon sx={{ fontSize: 24 }} />
|
||||||
|
</IconButton>
|
||||||
|
</ListItem>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default KundeGruppe;
|
||||||
2
src/components/kunde/index.js
Normal file
2
src/components/kunde/index.js
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { default as KundeGruppe } from './KundeGruppe';
|
||||||
|
export { default as withEntityRoute } from './withEntityRoute';
|
||||||
@@ -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 Box from '@mui/material/Box';
|
||||||
import Button from '@mui/material/Button';
|
import Button from '@mui/material/Button';
|
||||||
import CircularProgress from '@mui/material/CircularProgress';
|
import CircularProgress from '@mui/material/CircularProgress';
|
||||||
import IconButton from '@mui/material/IconButton';
|
|
||||||
import List from '@mui/material/List';
|
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 Typography from '@mui/material/Typography';
|
||||||
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
|
import Sortable from 'sortablejs';
|
||||||
import GroupsIcon from '@mui/icons-material/Groups';
|
|
||||||
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
|
|
||||||
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
|
|
||||||
import { enqueueSnackbar } from 'notistack';
|
import { enqueueSnackbar } from 'notistack';
|
||||||
import BackendError from '../../components/BackendError';
|
import BackendError from '../../components/BackendError';
|
||||||
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
||||||
import { PanelTile, PanelTileGrid } from 'dashgui/panels';
|
import { PanelTile, PanelTileGrid } from 'dashgui/panels';
|
||||||
import { customergroup as customergroupApi } from '../../api';
|
import withNavigate from '../../components/withNavigate';
|
||||||
import customergroupAutomat from '../../automats/customergroupAutomat';
|
|
||||||
import { requireArray, requireDefined, requireObject } from '../../utils/apiShape';
|
|
||||||
import { backendErrorFrom } from '../../utils/backendError';
|
import { backendErrorFrom } from '../../utils/backendError';
|
||||||
import { notifyError } from '../../utils/notify';
|
import { notifyError } from '../../utils/notify';
|
||||||
import {
|
import customergroupAutomat from '../../automats/customergroupAutomat';
|
||||||
PURPLE_BG,
|
import { KundeGruppe } from '../../components/kunde';
|
||||||
} from '../../colors';
|
import { PURPLE_BG } from '../../colors';
|
||||||
|
|
||||||
function sortGroups(groups) {
|
function getInitialParams(props) {
|
||||||
return [...groups].sort((a, b) => {
|
const searchParams =
|
||||||
const bySort = a.sort - b.sort;
|
typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
|
||||||
if (bySort !== 0) return bySort;
|
const prefill =
|
||||||
const byName = String(a.name).localeCompare(String(b.name), 'de');
|
props.location?.state?.name ??
|
||||||
if (byName !== 0) return byName;
|
props.location?.state?.newName ??
|
||||||
return a.id - b.id;
|
searchParams?.get('name') ??
|
||||||
});
|
searchParams?.get('newName') ??
|
||||||
|
'';
|
||||||
|
const returnTo =
|
||||||
|
props.location?.state?.returnTo ??
|
||||||
|
searchParams?.get('returnTo') ??
|
||||||
|
null;
|
||||||
|
return { prefill: prefill.trim(), returnTo };
|
||||||
}
|
}
|
||||||
|
|
||||||
function draftsFrom(groups) {
|
class KundeGruppenSearchField extends PureComponent {
|
||||||
return Object.fromEntries(groups.map((row) => [row.id, row.name]));
|
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) {
|
componentDidMount() {
|
||||||
requireObject(row, path);
|
this.unsub = customergroupAutomat.subscribe(this, (state) => ({
|
||||||
requireDefined(row.id, `${path}.id`);
|
input: state.filter,
|
||||||
requireDefined(row.name, `${path}.name`);
|
}));
|
||||||
requireDefined(row.sort, `${path}.sort`);
|
}
|
||||||
requireDefined(row.editable, `${path}.editable`);
|
|
||||||
|
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 {
|
class KundeGruppenPage extends PureComponent {
|
||||||
constructor(props) {
|
constructor(props) {
|
||||||
super(props);
|
super(props);
|
||||||
|
const initialGroups =
|
||||||
|
customergroupAutomat.state.filteredItems ?? customergroupAutomat.state.items ?? [];
|
||||||
this.state = {
|
this.state = {
|
||||||
status: 'loading',
|
status: customergroupAutomat.state.status === 'ready' ? 'ready' : 'loading',
|
||||||
error: null,
|
error: customergroupAutomat.state.error ? backendErrorFrom(customergroupAutomat.state.error) : null,
|
||||||
groups: [],
|
groups: initialGroups,
|
||||||
drafts: {},
|
filter: customergroupAutomat.state.filter ?? '',
|
||||||
newName: '',
|
|
||||||
busyKey: null,
|
|
||||||
};
|
};
|
||||||
|
this.searchRef = createRef();
|
||||||
|
this.listRef = createRef();
|
||||||
|
this._sortable = null;
|
||||||
this._cancelled = false;
|
this._cancelled = false;
|
||||||
this.handleCreate = this.handleCreate.bind(this);
|
|
||||||
this.handleRetry = this.handleRetry.bind(this);
|
this.handleRetry = this.handleRetry.bind(this);
|
||||||
|
this._initSortable = this._initSortable.bind(this);
|
||||||
|
this._destroySortable = this._destroySortable.bind(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
this._cancelled = false;
|
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() {
|
componentWillUnmount() {
|
||||||
this._cancelled = true;
|
this._cancelled = true;
|
||||||
|
this.unsub?.();
|
||||||
|
this._destroySortable();
|
||||||
}
|
}
|
||||||
|
|
||||||
applyGroups(groups) {
|
_initSortable() {
|
||||||
groups.forEach((row, index) => {
|
this._destroySortable();
|
||||||
requireGroupListItem(row, `customergroups[${index}]`);
|
const el = this.listRef.current;
|
||||||
});
|
if (!el) return;
|
||||||
const sorted = sortGroups(groups);
|
|
||||||
this.setState({
|
const isFiltered = Boolean(this.state.filter?.trim());
|
||||||
status: 'ready',
|
|
||||||
error: null,
|
this._sortable = Sortable.create(el, {
|
||||||
groups: sorted,
|
handle: '.drag-handle',
|
||||||
drafts: draftsFrom(sorted),
|
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() {
|
_destroySortable() {
|
||||||
this.setState({ status: 'loading', error: null });
|
this._sortable?.destroy();
|
||||||
|
this._sortable = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async _persistOrder(customergroupIds) {
|
||||||
try {
|
try {
|
||||||
const list = await customergroupAutomat.actions.ensureLoaded();
|
await customergroupAutomat.actions.reorder(customergroupIds);
|
||||||
if (this._cancelled) return;
|
|
||||||
this.applyGroups(list);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (this._cancelled) return;
|
if (this._cancelled) return;
|
||||||
this.setState({ status: 'failed', error: backendErrorFrom(err) });
|
notifyError(err);
|
||||||
|
void customergroupAutomat.actions.reload();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
handleRetry() {
|
handleRetry() {
|
||||||
void this.load();
|
void customergroupAutomat.actions.load().catch((err) => notifyError(err));
|
||||||
}
|
|
||||||
|
|
||||||
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 });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { status, error, groups, drafts, newName, busyKey } = this.state;
|
const { status, error, groups, filter } = this.state;
|
||||||
const busy = busyKey != null;
|
const { prefill, returnTo } = getInitialParams(this.props);
|
||||||
|
|
||||||
if (status === 'loading') {
|
if (status === 'loading' || status === 'idle') {
|
||||||
return (
|
return (
|
||||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
|
<Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
|
||||||
<CircularProgress />
|
<CircularProgress />
|
||||||
@@ -232,117 +276,40 @@ class KundeGruppenPage extends PureComponent {
|
|||||||
return <BackendError error={error} onRetry={this.handleRetry} />;
|
return <BackendError error={error} onRetry={this.handleRetry} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const trimmedFilter = filter?.trim() ?? '';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PanelTileGrid>
|
<>
|
||||||
<PanelTile wide={2} minHeight={280} color={PURPLE_BG}>
|
<KundeGruppenSearchField
|
||||||
<Stack spacing={2}>
|
inputRef={this.searchRef}
|
||||||
<List dense disablePadding>
|
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 ? (
|
{groups.length === 0 ? (
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
||||||
Noch keine Kundengruppen.
|
{trimmedFilter
|
||||||
|
? `Keine Treffer für „${trimmedFilter}“.`
|
||||||
|
: 'Noch keine Kundengruppen angelegt.'}
|
||||||
</Typography>
|
</Typography>
|
||||||
) : (
|
) : (
|
||||||
groups.map((group, index) => {
|
groups.map((group) => (
|
||||||
const editable = group.editable === true;
|
<KundeGruppe
|
||||||
return (
|
key={group.id}
|
||||||
<ListItem
|
group={group}
|
||||||
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>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
)}
|
||||||
</List>
|
</List>
|
||||||
|
</PanelTile>
|
||||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
</PanelTileGrid>
|
||||||
<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;
|
export { KundeGruppe, KundeGruppenSearchField };
|
||||||
|
export default withNavigate(KundeGruppenPage);
|
||||||
|
|||||||
Reference in New Issue
Block a user