u
This commit is contained in:
@@ -8,4 +8,11 @@ class componets disconnected from state, in automat.
|
|||||||
|
|
||||||
Reference:
|
Reference:
|
||||||
Component: src/routes/artikel/marken.jsx
|
Component: src/routes/artikel/marken.jsx
|
||||||
it's Automat: src/automats/brandAutomat.js
|
it's Automat: src/automats/brandAutomat.js
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
use vs code region markers in code files
|
||||||
|
use:
|
||||||
|
// MARK: calls startApi from ./api/index.js
|
||||||
|
atop important functions
|
||||||
@@ -1,42 +1,212 @@
|
|||||||
/**
|
/**
|
||||||
* @file entityAutomat.js
|
* @file entityAutomat.js
|
||||||
* @description Manages cached customer and contact entities (`GET /api/entity`)
|
* @description Manages cached customer and contact entities (`GET /api/entity`)
|
||||||
* for the active company. Built via `createListAutomat`.
|
* for the active company. Follows the brand/warehouse/customergroup 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`, `filter`).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { Automat } from 'react-automat';
|
||||||
import { entity as entityApi } from '../api';
|
import { entity as entityApi } from '../api';
|
||||||
import { createListAutomat } from './createListAutomat';
|
import { requireArray, requireDefined, requireObject } from '../utils/apiShape';
|
||||||
|
import authAutomat from './authAutomat';
|
||||||
|
import customergroupAutomat from './customergroupAutomat';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {Object} Entity
|
* @typedef {Object} Entity
|
||||||
* @property {string|number} id Entity id.
|
* @property {string|number} id Entity id.
|
||||||
* @property {string|number} customergroupId Owning customer group id.
|
* @property {string|number} customergroupId Owning customer group id.
|
||||||
* @property {string|null} firstName First name.
|
* @property {string} [number] Customer number.
|
||||||
|
* @property {string|null} [firstName] First name.
|
||||||
* @property {string} name Last / company name.
|
* @property {string} name Last / company name.
|
||||||
|
* @property {string} [createdAt] Created timestamp.
|
||||||
|
* @property {string} [updatedAt] Updated timestamp.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} EntityState
|
||||||
|
* @property {Array<Entity>} items Loaded records.
|
||||||
|
* @property {Array<Entity>} 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 {EntityState} */
|
||||||
|
const initialState = {
|
||||||
|
items: [],
|
||||||
|
filteredItems: [],
|
||||||
|
filter: '',
|
||||||
|
status: 'idle',
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyFilter = (entities, filter) => {
|
||||||
|
const query = String(filter ?? '').trim().toLowerCase();
|
||||||
|
if (!query) return entities;
|
||||||
|
const groups = customergroupAutomat?.state?.items ?? [];
|
||||||
|
const groupsById = Object.fromEntries(groups.map((g) => [g.id, g]));
|
||||||
|
|
||||||
|
return entities.filter((e) => {
|
||||||
|
const name = String(e.name ?? '').toLowerCase();
|
||||||
|
const firstName = String(e.firstName ?? '').toLowerCase();
|
||||||
|
const number = String(e.number ?? '').toLowerCase();
|
||||||
|
const full1 = `${firstName} ${name}`.trim();
|
||||||
|
const full2 = `${name} ${firstName}`.trim();
|
||||||
|
const group = String(groupsById[e.customergroupId]?.name ?? '').toLowerCase();
|
||||||
|
return (
|
||||||
|
name.includes(query) ||
|
||||||
|
firstName.includes(query) ||
|
||||||
|
number.includes(query) ||
|
||||||
|
full1.includes(query) ||
|
||||||
|
full2.includes(query) ||
|
||||||
|
group.includes(query)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const sortEntities = (items) =>
|
||||||
|
[...items].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');
|
||||||
|
});
|
||||||
|
|
||||||
|
let entityAutomat;
|
||||||
|
|
||||||
|
const updateStateWithEntities = (entities, extra = {}) => {
|
||||||
|
const list = sortEntities(Array.isArray(entities) ? entities : []);
|
||||||
|
const filteredItems = applyFilter(list, entityAutomat.state.filter);
|
||||||
|
entityAutomat.setState({ items: list, filteredItems, ...extra });
|
||||||
|
return list;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function fetchEntities() {
|
||||||
|
const data = await entityApi.list();
|
||||||
|
requireObject(data, 'GET /api/entity');
|
||||||
|
return requireArray(data.entities, 'entities');
|
||||||
|
}
|
||||||
|
|
||||||
|
let inflightLoad = null;
|
||||||
|
|
||||||
|
function loadEntities() {
|
||||||
|
if (inflightLoad) return inflightLoad;
|
||||||
|
inflightLoad = (async () => {
|
||||||
|
entityAutomat.setState({ status: 'loading', error: null });
|
||||||
|
try {
|
||||||
|
const entities = await fetchEntities();
|
||||||
|
updateStateWithEntities(entities, { status: 'ready', error: null });
|
||||||
|
return entities;
|
||||||
|
} catch (error) {
|
||||||
|
entityAutomat.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 ?? '');
|
||||||
|
entityAutomat.setState({
|
||||||
|
filter,
|
||||||
|
filteredItems: applyFilter(entityAutomat.state.items, filter),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Loads the list, deduplicating concurrent callers. */
|
||||||
|
load() {
|
||||||
|
return loadEntities();
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Silently refreshes the entities without flashing loading state. */
|
||||||
|
async reload() {
|
||||||
|
try {
|
||||||
|
const entities = await fetchEntities();
|
||||||
|
updateStateWithEntities(entities, { status: 'ready', error: null });
|
||||||
|
return entities;
|
||||||
|
} catch (error) {
|
||||||
|
entityAutomat.setState({ error });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Replaces the cached list without an API call. */
|
||||||
|
replace(items) {
|
||||||
|
return updateStateWithEntities(items, { status: 'ready', error: null });
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Returns cached items if ready, otherwise loads. */
|
||||||
|
ensureLoaded() {
|
||||||
|
if (entityAutomat.state.status === 'ready') {
|
||||||
|
return Promise.resolve(entityAutomat.state.items);
|
||||||
|
}
|
||||||
|
return actions.load();
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Resets state to initial idle values. */
|
||||||
|
reset() {
|
||||||
|
inflightLoad = null;
|
||||||
|
entityAutomat.setState(initialState);
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Creates a customer entity and refreshes the cache. */
|
||||||
|
async create(body) {
|
||||||
|
const data = await entityApi.create(body);
|
||||||
|
requireObject(data, 'POST /api/entity');
|
||||||
|
requireObject(data.entity, 'entity');
|
||||||
|
requireDefined(data.entity.id, 'entity.id');
|
||||||
|
await entityAutomat.actions.reload();
|
||||||
|
return data.entity;
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Updates an entity name/fields and refreshes the cache. */
|
||||||
|
async update(id, body) {
|
||||||
|
const data = await entityApi.update(id, body);
|
||||||
|
requireObject(data, 'PATCH /api/entity/:id');
|
||||||
|
requireObject(data.entity, 'entity');
|
||||||
|
requireDefined(data.entity.id, 'entity.id');
|
||||||
|
await entityAutomat.actions.reload();
|
||||||
|
return data.entity;
|
||||||
|
},
|
||||||
|
|
||||||
|
rename(id, body) {
|
||||||
|
return actions.update(id, body);
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Deletes an entity and refreshes the cache. */
|
||||||
|
async remove(id) {
|
||||||
|
await entityApi.delete(id);
|
||||||
|
await entityAutomat.actions.reload();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Company customers and contacts (`GET /api/entity`).
|
* Company customers and contacts (`GET /api/entity`).
|
||||||
*
|
*
|
||||||
* @type {import('react-automat').Automat<import('./createListAutomat').ListAutomatState>}
|
* @type {Automat<EntityState>}
|
||||||
*/
|
*/
|
||||||
export const entityAutomat = createListAutomat({
|
entityAutomat = new Automat(initialState, actions, {
|
||||||
name: 'entity',
|
name: 'entity',
|
||||||
fetch: async () => {
|
});
|
||||||
const data = await entityApi.list();
|
|
||||||
return data.entities ?? [];
|
export { entityAutomat };
|
||||||
},
|
|
||||||
sort: (items) =>
|
// Load on session/company establishment, reset on logout.
|
||||||
[...items].sort((a, b) => {
|
authAutomat.subscribe((auth) => {
|
||||||
const byName = String(a.name).localeCompare(String(b.name), 'de');
|
const companyId = auth.user?.selectedCompanyId;
|
||||||
if (byName !== 0) return byName;
|
if (auth.status === 'authed' && companyId) {
|
||||||
return String(a.firstName ?? '').localeCompare(String(b.firstName ?? ''), 'de');
|
void actions.load().catch(() => {});
|
||||||
}),
|
} else if (auth.status === 'anon') {
|
||||||
|
actions.reset();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
export default entityAutomat;
|
export default entityAutomat;
|
||||||
|
|||||||
223
src/components/kunde/Kunde.jsx
Normal file
223
src/components/kunde/Kunde.jsx
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
import { PureComponent } from 'react';
|
||||||
|
import Box from '@mui/material/Box';
|
||||||
|
import Chip from '@mui/material/Chip';
|
||||||
|
import IconButton from '@mui/material/IconButton';
|
||||||
|
import ListItem from '@mui/material/ListItem';
|
||||||
|
import Tooltip from '@mui/material/Tooltip';
|
||||||
|
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
|
||||||
|
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
|
||||||
|
import PersonOutlinedIcon from '@mui/icons-material/PersonOutlined';
|
||||||
|
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
||||||
|
import { enqueueSnackbar } from 'notistack';
|
||||||
|
import { router } from '../../appRouter';
|
||||||
|
import entityAutomat from '../../automats/entityAutomat';
|
||||||
|
import { notifyError } from '../../utils/notify';
|
||||||
|
|
||||||
|
function getCustomerDisplayName(item) {
|
||||||
|
if (!item) return '';
|
||||||
|
return [item.firstName, item.name].filter(Boolean).join(' ') || item.name || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
class Kunde extends PureComponent {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
const item = props.customer ?? props.item;
|
||||||
|
this.state = {
|
||||||
|
draft: getCustomerDisplayName(item),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevProps) {
|
||||||
|
const prevItem = prevProps.customer ?? prevProps.item;
|
||||||
|
const item = this.props.customer ?? this.props.item;
|
||||||
|
const prevName = getCustomerDisplayName(prevItem);
|
||||||
|
const nextName = getCustomerDisplayName(item);
|
||||||
|
|
||||||
|
if (prevName !== nextName) {
|
||||||
|
this.setState({ draft: nextName });
|
||||||
|
} else if (prevProps.disabled && !this.props.disabled) {
|
||||||
|
if (this.state.draft !== nextName) {
|
||||||
|
this.setState({ draft: nextName });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleChange = (next) => {
|
||||||
|
this.setState({ draft: next });
|
||||||
|
const item = this.props.customer ?? this.props.item;
|
||||||
|
this.props.onChange?.(next, item);
|
||||||
|
};
|
||||||
|
|
||||||
|
handleBlur = () => {
|
||||||
|
const item = this.props.customer ?? this.props.item;
|
||||||
|
if (!item) return;
|
||||||
|
|
||||||
|
const draft = this.state.draft.trim();
|
||||||
|
const currentDisplay = getCustomerDisplayName(item);
|
||||||
|
if (!draft) {
|
||||||
|
this.setState({ draft: currentDisplay });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (draft !== currentDisplay) {
|
||||||
|
void this.renameCustomer(item, draft);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
async renameCustomer(item, rawText) {
|
||||||
|
const trimmed = rawText.trim();
|
||||||
|
if (!trimmed) return;
|
||||||
|
let name = trimmed;
|
||||||
|
let firstName = null;
|
||||||
|
|
||||||
|
if (trimmed.includes(',')) {
|
||||||
|
const parts = trimmed.split(',').map((p) => p.trim());
|
||||||
|
name = parts[0];
|
||||||
|
firstName = parts.slice(1).join(' ') || null;
|
||||||
|
} else if (trimmed.includes(' ') && !/gmbh|ag|kg|ug|inc|ltd|co\./i.test(trimmed)) {
|
||||||
|
const parts = trimmed.split(' ');
|
||||||
|
firstName = parts[0];
|
||||||
|
name = parts.slice(1).join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await entityAutomat.actions.update(item.id, { name, firstName });
|
||||||
|
enqueueSnackbar('Kunde gespeichert.', { variant: 'success' });
|
||||||
|
} catch (err) {
|
||||||
|
this.setState({ draft: getCustomerDisplayName(item) });
|
||||||
|
notifyError(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleKeyDown = (event) => {
|
||||||
|
const item = this.props.customer ?? this.props.item;
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
event.preventDefault();
|
||||||
|
event.target.blur();
|
||||||
|
}
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.preventDefault();
|
||||||
|
this.setState({ draft: getCustomerDisplayName(item) });
|
||||||
|
event.target.blur();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleDelete = () => {
|
||||||
|
const item = this.props.customer ?? this.props.item;
|
||||||
|
if (!item) return;
|
||||||
|
const displayName = getCustomerDisplayName(item) || String(item.number ?? item.id);
|
||||||
|
|
||||||
|
if (!window.confirm(`Kunde „${displayName}“ wirklich löschen?`)) return;
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
await entityAutomat.actions.remove(item.id);
|
||||||
|
enqueueSnackbar('Kunde gelöscht.', { variant: 'success' });
|
||||||
|
} catch (err) {
|
||||||
|
notifyError(err);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
const { disabled, sx, groupName, onEdit } = this.props;
|
||||||
|
const item = this.props.customer ?? this.props.item;
|
||||||
|
const { draft } = this.state;
|
||||||
|
const displayName = getCustomerDisplayName(item) || String(item?.number ?? '');
|
||||||
|
|
||||||
|
const handleOpenEdit = () => {
|
||||||
|
if (!item) return;
|
||||||
|
if (onEdit) onEdit(item);
|
||||||
|
else void router.navigate(`/kunde/${item.id}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ListItem
|
||||||
|
disableGutters
|
||||||
|
data-id={item?.id}
|
||||||
|
sx={{ gap: 1, py: 0.75, alignItems: 'center', width: '100%', minWidth: 0, ...sx }}
|
||||||
|
>
|
||||||
|
<Tooltip title="Kunde öffnen">
|
||||||
|
<IconButton
|
||||||
|
aria-label={`„${displayName}“ öffnen`}
|
||||||
|
disabled={disabled || !item}
|
||||||
|
onClick={handleOpenEdit}
|
||||||
|
sx={{ width: 40, height: 40, flexShrink: 0 }}
|
||||||
|
>
|
||||||
|
<PersonOutlinedIcon sx={{ fontSize: 24 }} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<SingleLineTextEdit
|
||||||
|
size="small"
|
||||||
|
label=""
|
||||||
|
value={draft}
|
||||||
|
disabled={disabled || !item}
|
||||||
|
onChange={this.handleChange}
|
||||||
|
onBlur={this.handleBlur}
|
||||||
|
onKeyDown={this.handleKeyDown}
|
||||||
|
sx={{ flex: 1, minWidth: 0 }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{item?.number ? (
|
||||||
|
<Chip
|
||||||
|
size="small"
|
||||||
|
label={item.number}
|
||||||
|
sx={{
|
||||||
|
height: 24,
|
||||||
|
fontSize: '0.75rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
fontVariantNumeric: 'tabular-nums',
|
||||||
|
bgcolor: 'action.hover',
|
||||||
|
color: 'text.primary',
|
||||||
|
flexShrink: 0,
|
||||||
|
'& .MuiChip-label': {
|
||||||
|
px: 0.75,
|
||||||
|
textAlign: 'center',
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{groupName ? (
|
||||||
|
<Chip
|
||||||
|
size="small"
|
||||||
|
label={groupName}
|
||||||
|
sx={{
|
||||||
|
height: 24,
|
||||||
|
fontSize: '0.75rem',
|
||||||
|
bgcolor: 'action.hover',
|
||||||
|
color: 'text.secondary',
|
||||||
|
flexShrink: 0,
|
||||||
|
display: { xs: 'none', sm: 'inline-flex' },
|
||||||
|
'& .MuiChip-label': {
|
||||||
|
px: 0.75,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Tooltip title="Details bearbeiten">
|
||||||
|
<IconButton
|
||||||
|
aria-label={`„${displayName}“ bearbeiten`}
|
||||||
|
disabled={disabled || !item}
|
||||||
|
onClick={handleOpenEdit}
|
||||||
|
sx={{ width: 40, height: 40, flexShrink: 0 }}
|
||||||
|
>
|
||||||
|
<EditOutlinedIcon sx={{ fontSize: 22 }} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
aria-label={`„${displayName}“ löschen`}
|
||||||
|
disabled={disabled || !item}
|
||||||
|
onClick={this.handleDelete}
|
||||||
|
sx={{ width: 40, height: 40, flexShrink: 0 }}
|
||||||
|
>
|
||||||
|
<DeleteOutlinedIcon sx={{ fontSize: 24 }} />
|
||||||
|
</IconButton>
|
||||||
|
</ListItem>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { getCustomerDisplayName };
|
||||||
|
export default Kunde;
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
|
export { default as Kunde } from './Kunde';
|
||||||
export { default as KundeGruppe } from './KundeGruppe';
|
export { default as KundeGruppe } from './KundeGruppe';
|
||||||
export { default as withEntityRoute } from './withEntityRoute';
|
export { default as withEntityRoute } from './withEntityRoute';
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import Sortable from 'sortablejs';
|
|||||||
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 FillSpace from 'dashgui/FillSpace';
|
||||||
import { PanelTile, PanelTileGrid } from 'dashgui/panels';
|
import { PanelTile, PanelTileGrid } from 'dashgui/panels';
|
||||||
import withNavigate from '../../components/withNavigate';
|
import withNavigate from '../../components/withNavigate';
|
||||||
import { backendErrorFrom } from '../../utils/backendError';
|
import { backendErrorFrom } from '../../utils/backendError';
|
||||||
@@ -45,14 +46,17 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
attributes: initialAttributes,
|
attributes: initialAttributes,
|
||||||
attrFilter: '',
|
attrFilter: '',
|
||||||
attrSubmitting: false,
|
attrSubmitting: false,
|
||||||
|
attrPage: 1,
|
||||||
selectedAttributeId: initialSelectedAttrId,
|
selectedAttributeId: initialSelectedAttrId,
|
||||||
|
|
||||||
valFilter: '',
|
valFilter: '',
|
||||||
valSubmitting: false,
|
valSubmitting: false,
|
||||||
|
valPage: 1,
|
||||||
|
|
||||||
properties: initialProperties,
|
properties: initialProperties,
|
||||||
propFilter: '',
|
propFilter: '',
|
||||||
propSubmitting: false,
|
propSubmitting: false,
|
||||||
|
propPage: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
this._cancelled = false;
|
this._cancelled = false;
|
||||||
@@ -112,6 +116,7 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
if (
|
if (
|
||||||
(prevState.properties !== this.state.properties ||
|
(prevState.properties !== this.state.properties ||
|
||||||
prevState.propFilter !== this.state.propFilter ||
|
prevState.propFilter !== this.state.propFilter ||
|
||||||
|
prevState.propPage !== this.state.propPage ||
|
||||||
prevState.propStatus !== this.state.propStatus) &&
|
prevState.propStatus !== this.state.propStatus) &&
|
||||||
this.propListRef.current
|
this.propListRef.current
|
||||||
) {
|
) {
|
||||||
@@ -123,6 +128,7 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
if (
|
if (
|
||||||
(prevState.attributes !== this.state.attributes ||
|
(prevState.attributes !== this.state.attributes ||
|
||||||
prevState.attrFilter !== this.state.attrFilter ||
|
prevState.attrFilter !== this.state.attrFilter ||
|
||||||
|
prevState.attrPage !== this.state.attrPage ||
|
||||||
prevState.attrStatus !== this.state.attrStatus) &&
|
prevState.attrStatus !== this.state.attrStatus) &&
|
||||||
this.attrListRef.current
|
this.attrListRef.current
|
||||||
) {
|
) {
|
||||||
@@ -135,6 +141,7 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
(prevState.selectedAttributeId !== this.state.selectedAttributeId ||
|
(prevState.selectedAttributeId !== this.state.selectedAttributeId ||
|
||||||
prevState.attributes !== this.state.attributes ||
|
prevState.attributes !== this.state.attributes ||
|
||||||
prevState.valFilter !== this.state.valFilter ||
|
prevState.valFilter !== this.state.valFilter ||
|
||||||
|
prevState.valPage !== this.state.valPage ||
|
||||||
prevState.attrStatus !== this.state.attrStatus) &&
|
prevState.attrStatus !== this.state.attrStatus) &&
|
||||||
this.valListRef.current
|
this.valListRef.current
|
||||||
) {
|
) {
|
||||||
@@ -170,11 +177,16 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
const { oldIndex, newIndex } = evt;
|
const { oldIndex, newIndex } = evt;
|
||||||
if (oldIndex === newIndex) return;
|
if (oldIndex === newIndex) return;
|
||||||
|
|
||||||
|
const offset = ((this.state.propPage || 1) - 1) * 8;
|
||||||
|
const realOld = offset + oldIndex;
|
||||||
|
const realNew = offset + newIndex;
|
||||||
|
if (realOld === realNew) return;
|
||||||
|
|
||||||
this.setState(
|
this.setState(
|
||||||
(prev) => {
|
(prev) => {
|
||||||
const next = [...prev.properties];
|
const next = [...prev.properties];
|
||||||
const [moved] = next.splice(oldIndex, 1);
|
const [moved] = next.splice(realOld, 1);
|
||||||
next.splice(newIndex, 0, moved);
|
next.splice(realNew, 0, moved);
|
||||||
return { properties: next };
|
return { properties: next };
|
||||||
},
|
},
|
||||||
() => {
|
() => {
|
||||||
@@ -203,11 +215,16 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
const { oldIndex, newIndex } = evt;
|
const { oldIndex, newIndex } = evt;
|
||||||
if (oldIndex === newIndex) return;
|
if (oldIndex === newIndex) return;
|
||||||
|
|
||||||
|
const offset = ((this.state.attrPage || 1) - 1) * 8;
|
||||||
|
const realOld = offset + oldIndex;
|
||||||
|
const realNew = offset + newIndex;
|
||||||
|
if (realOld === realNew) return;
|
||||||
|
|
||||||
this.setState(
|
this.setState(
|
||||||
(prev) => {
|
(prev) => {
|
||||||
const next = [...prev.attributes];
|
const next = [...prev.attributes];
|
||||||
const [moved] = next.splice(oldIndex, 1);
|
const [moved] = next.splice(realOld, 1);
|
||||||
next.splice(newIndex, 0, moved);
|
next.splice(realNew, 0, moved);
|
||||||
return { attributes: next };
|
return { attributes: next };
|
||||||
},
|
},
|
||||||
() => {
|
() => {
|
||||||
@@ -236,6 +253,11 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
const { oldIndex, newIndex } = evt;
|
const { oldIndex, newIndex } = evt;
|
||||||
if (oldIndex === newIndex) return;
|
if (oldIndex === newIndex) return;
|
||||||
|
|
||||||
|
const offset = ((this.state.valPage || 1) - 1) * 8;
|
||||||
|
const realOld = offset + oldIndex;
|
||||||
|
const realNew = offset + newIndex;
|
||||||
|
if (realOld === realNew) return;
|
||||||
|
|
||||||
const currentAttr = this.state.attributes.find(
|
const currentAttr = this.state.attributes.find(
|
||||||
(a) => a.id === this.state.selectedAttributeId
|
(a) => a.id === this.state.selectedAttributeId
|
||||||
);
|
);
|
||||||
@@ -243,8 +265,8 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
|
|
||||||
const values = currentAttr.values || [];
|
const values = currentAttr.values || [];
|
||||||
const next = [...values];
|
const next = [...values];
|
||||||
const [moved] = next.splice(oldIndex, 1);
|
const [moved] = next.splice(realOld, 1);
|
||||||
next.splice(newIndex, 0, moved);
|
next.splice(realNew, 0, moved);
|
||||||
|
|
||||||
const updatedAttributes = this.state.attributes.map((a) =>
|
const updatedAttributes = this.state.attributes.map((a) =>
|
||||||
a.id === currentAttr.id ? { ...a, values: next } : a
|
a.id === currentAttr.id ? { ...a, values: next } : a
|
||||||
@@ -319,7 +341,7 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleSelectAttribute(attrId) {
|
handleSelectAttribute(attrId) {
|
||||||
this.setState({ selectedAttributeId: attrId, valFilter: '' });
|
this.setState({ selectedAttributeId: attrId, valFilter: '', valPage: 1 });
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleCreateAttribute() {
|
async handleCreateAttribute() {
|
||||||
@@ -468,24 +490,29 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<List dense disablePadding ref={this.attrListRef} sx={{ width: '100%' }}>
|
{filteredAttributes.length === 0 ? (
|
||||||
{filteredAttributes.length === 0 ? (
|
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
{attrFilterTrimmed
|
||||||
{attrFilterTrimmed
|
? `Keine Treffer für „${attrFilterTrimmed}“.`
|
||||||
? `Keine Treffer für „${attrFilterTrimmed}“.`
|
: 'Noch keine Auswahl-Merkmale angelegt.'}
|
||||||
: 'Noch keine Auswahl-Merkmale angelegt.'}
|
</Typography>
|
||||||
</Typography>
|
) : (
|
||||||
) : (
|
<FillSpace
|
||||||
filteredAttributes.map((a) => (
|
items={filteredAttributes}
|
||||||
|
minPageSize={8}
|
||||||
|
maxPageSize={8}
|
||||||
|
listRef={this.attrListRef}
|
||||||
|
onPageChange={(page) => this.setState({ attrPage: page })}
|
||||||
|
renderItem={(a) => (
|
||||||
<ArtikelMerkmalAuswahl
|
<ArtikelMerkmalAuswahl
|
||||||
key={a.id}
|
key={a.id}
|
||||||
attribute={a}
|
attribute={a}
|
||||||
isSelected={selectedAttr?.id === a.id}
|
isSelected={selectedAttr?.id === a.id}
|
||||||
onSelect={() => this.handleSelectAttribute(a.id)}
|
onSelect={() => this.handleSelectAttribute(a.id)}
|
||||||
/>
|
/>
|
||||||
))
|
)}
|
||||||
)}
|
/>
|
||||||
</List>
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
</PanelTile>
|
</PanelTile>
|
||||||
|
|
||||||
@@ -531,22 +558,27 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<List dense disablePadding ref={this.valListRef} sx={{ width: '100%' }}>
|
{filteredValues.length === 0 ? (
|
||||||
{filteredValues.length === 0 ? (
|
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
{valFilterTrimmed
|
||||||
{valFilterTrimmed
|
? `Keine Treffer für „${valFilterTrimmed}“.`
|
||||||
? `Keine Treffer für „${valFilterTrimmed}“.`
|
: 'Noch keine Werte angelegt.'}
|
||||||
: 'Noch keine Werte angelegt.'}
|
</Typography>
|
||||||
</Typography>
|
) : (
|
||||||
) : (
|
<FillSpace
|
||||||
filteredValues.map((v) => (
|
items={filteredValues}
|
||||||
|
minPageSize={8}
|
||||||
|
maxPageSize={8}
|
||||||
|
listRef={this.valListRef}
|
||||||
|
onPageChange={(page) => this.setState({ valPage: page })}
|
||||||
|
renderItem={(v) => (
|
||||||
<ArtikelMerkmalWert
|
<ArtikelMerkmalWert
|
||||||
key={v.id}
|
key={v.id}
|
||||||
value={v}
|
value={v}
|
||||||
/>
|
/>
|
||||||
))
|
)}
|
||||||
)}
|
/>
|
||||||
</List>
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
@@ -588,22 +620,27 @@ class ArtikelMerkmalePage extends PureComponent {
|
|||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<List dense disablePadding ref={this.propListRef} sx={{ width: '100%' }}>
|
{filteredProperties.length === 0 ? (
|
||||||
{filteredProperties.length === 0 ? (
|
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
{propFilterTrimmed
|
||||||
{propFilterTrimmed
|
? `Keine Treffer für „${propFilterTrimmed}“.`
|
||||||
? `Keine Treffer für „${propFilterTrimmed}“.`
|
: 'Noch keine Text-Merkmale angelegt.'}
|
||||||
: 'Noch keine Text-Merkmale angelegt.'}
|
</Typography>
|
||||||
</Typography>
|
) : (
|
||||||
) : (
|
<FillSpace
|
||||||
filteredProperties.map((p) => (
|
items={filteredProperties}
|
||||||
|
minPageSize={8}
|
||||||
|
maxPageSize={8}
|
||||||
|
listRef={this.propListRef}
|
||||||
|
onPageChange={(page) => this.setState({ propPage: page })}
|
||||||
|
renderItem={(p) => (
|
||||||
<ArtikelMerkmalText
|
<ArtikelMerkmalText
|
||||||
key={p.id}
|
key={p.id}
|
||||||
property={p}
|
property={p}
|
||||||
/>
|
/>
|
||||||
))
|
)}
|
||||||
)}
|
/>
|
||||||
</List>
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
</PanelTile>
|
</PanelTile>
|
||||||
</PanelTileGrid>
|
</PanelTileGrid>
|
||||||
|
|||||||
@@ -1,156 +1,289 @@
|
|||||||
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 List from '@mui/material/List';
|
||||||
|
import Typography from '@mui/material/Typography';
|
||||||
import { enqueueSnackbar } from 'notistack';
|
import { enqueueSnackbar } from 'notistack';
|
||||||
import BackendError from '../components/BackendError';
|
import BackendError from '../components/BackendError';
|
||||||
import { RecordList } from 'dashgui/lists';
|
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
||||||
import { entity as entityApi } from '../api';
|
import { PanelTile, PanelTileGrid } from 'dashgui/panels';
|
||||||
import entityAutomat from '../automats/entityAutomat';
|
import withNavigate from '../components/withNavigate';
|
||||||
import customergroupAutomat from '../automats/customergroupAutomat';
|
|
||||||
import { router } from '../appRouter';
|
|
||||||
import { backendErrorFrom } from '../utils/backendError';
|
import { backendErrorFrom } from '../utils/backendError';
|
||||||
import { notifyError } from '../utils/notify';
|
import { notifyError } from '../utils/notify';
|
||||||
import {
|
import entityAutomat from '../automats/entityAutomat';
|
||||||
BLUE_PANEL,
|
import customergroupAutomat from '../automats/customergroupAutomat';
|
||||||
} from '../colors';
|
import { Kunde } from '../components/kunde';
|
||||||
|
import { BLUE_PANEL } from '../colors';
|
||||||
|
|
||||||
function sortEntities(entities) {
|
function getInitialParams(props) {
|
||||||
return [...entities].sort((a, b) => {
|
const searchParams =
|
||||||
const byName = String(a.name).localeCompare(String(b.name), 'de');
|
typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
|
||||||
if (byName !== 0) return byName;
|
const prefill =
|
||||||
return String(a.firstName ?? '').localeCompare(String(b.firstName ?? ''), 'de');
|
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 formatDate(value) {
|
class KundeSearchField extends PureComponent {
|
||||||
if (!value) return '';
|
constructor(props) {
|
||||||
return new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium' }).format(new Date(value));
|
super(props);
|
||||||
|
const initial = entityAutomat.state.filter || props.prefill || '';
|
||||||
|
this.state = {
|
||||||
|
input: initial,
|
||||||
|
submitting: false,
|
||||||
|
};
|
||||||
|
if (props.prefill && !entityAutomat.state.filter) {
|
||||||
|
entityAutomat.actions.filter(props.prefill);
|
||||||
|
}
|
||||||
|
this.handleSubmit = this.handleSubmit.bind(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
this.unsub = entityAutomat.subscribe(this, (state) => ({
|
||||||
|
input: state.filter,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
componentWillUnmount() {
|
||||||
|
this.unsub?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
onInputChange(input) {
|
||||||
|
this.setState({ input });
|
||||||
|
entityAutomat.actions.filter(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleSubmit() {
|
||||||
|
const raw = this.state.input.trim();
|
||||||
|
if (!raw || this.state.submitting) return;
|
||||||
|
|
||||||
|
this.setState({ submitting: true });
|
||||||
|
try {
|
||||||
|
await customergroupAutomat.actions.ensureLoaded();
|
||||||
|
const groups = customergroupAutomat.state.items ?? [];
|
||||||
|
const defaultGroup = groups.find((g) => g.editable !== false) ?? groups[0];
|
||||||
|
if (!defaultGroup) {
|
||||||
|
throw new Error('Keine Kundengruppe vorhanden.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let name = raw;
|
||||||
|
let firstName = null;
|
||||||
|
|
||||||
|
if (raw.includes(',')) {
|
||||||
|
const parts = raw.split(',').map((p) => p.trim());
|
||||||
|
name = parts[0];
|
||||||
|
firstName = parts.slice(1).join(' ') || null;
|
||||||
|
} else if (raw.includes(' ') && !/gmbh|ag|kg|ug|inc|ltd|co\./i.test(raw)) {
|
||||||
|
const parts = raw.split(' ');
|
||||||
|
firstName = parts[0];
|
||||||
|
name = parts.slice(1).join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
customergroupId: defaultGroup.id,
|
||||||
|
name,
|
||||||
|
};
|
||||||
|
if (firstName) body.firstName = firstName;
|
||||||
|
|
||||||
|
const row = await entityAutomat.actions.create(body);
|
||||||
|
const displayName = [row.firstName, row.name].filter(Boolean).join(' ') || row.name || raw;
|
||||||
|
enqueueSnackbar(`Kunde „${displayName}“ angelegt.`, { variant: 'success' });
|
||||||
|
this.setState({ input: '', submitting: false });
|
||||||
|
entityAutomat.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
|
||||||
|
? `Kundenname „${input}“ übernommen.`
|
||||||
|
: 'Neuen Kunden anlegen.'}
|
||||||
|
</Alert>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||||
|
<SingleLineTextEdit
|
||||||
|
sx={{ flex: 1 }}
|
||||||
|
size="small"
|
||||||
|
search
|
||||||
|
clear
|
||||||
|
placeholder="Kunde 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 KundeListePage extends PureComponent {
|
class KundeListePage extends PureComponent {
|
||||||
constructor(props) {
|
constructor(props) {
|
||||||
super(props);
|
super(props);
|
||||||
|
const initialEntities =
|
||||||
|
entityAutomat.state.filteredItems ?? entityAutomat.state.items ?? [];
|
||||||
this.state = {
|
this.state = {
|
||||||
status: 'loading',
|
status: entityAutomat.state.status === 'ready' ? 'ready' : 'loading',
|
||||||
error: null,
|
error: entityAutomat.state.error ? backendErrorFrom(entityAutomat.state.error) : null,
|
||||||
entities: [],
|
entities: initialEntities,
|
||||||
groupsById: {},
|
groups: customergroupAutomat.state.items ?? [],
|
||||||
busyId: null,
|
filter: entityAutomat.state.filter ?? '',
|
||||||
};
|
};
|
||||||
this._cancelled = false;
|
this.searchRef = createRef();
|
||||||
this.handleRetry = this.handleRetry.bind(this);
|
this.handleRetry = this.handleRetry.bind(this);
|
||||||
this.handleCreate = this.handleCreate.bind(this);
|
this.handleEdit = this.handleEdit.bind(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
this._cancelled = false;
|
this.unsub = entityAutomat.subscribe(this, (state) => ({
|
||||||
void this.load();
|
entities: state.filteredItems ?? state.items,
|
||||||
|
filter: state.filter ?? '',
|
||||||
|
status: state.status,
|
||||||
|
error: state.error ? backendErrorFrom(state.error) : null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
this.unsubGroups = customergroupAutomat.subscribe(this, (state) => ({
|
||||||
|
groups: state.items,
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (entityAutomat.state.status !== 'ready') {
|
||||||
|
void entityAutomat.actions.load().catch((err) => notifyError(err));
|
||||||
|
}
|
||||||
|
if (customergroupAutomat.state.status !== 'ready') {
|
||||||
|
void customergroupAutomat.actions.load().catch(() => {});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillUnmount() {
|
componentWillUnmount() {
|
||||||
this._cancelled = true;
|
this.unsub?.();
|
||||||
}
|
this.unsubGroups?.();
|
||||||
|
|
||||||
async load() {
|
|
||||||
this.setState({ status: 'loading', error: null });
|
|
||||||
try {
|
|
||||||
const [entities, groups] = await Promise.all([
|
|
||||||
entityAutomat.actions.ensureLoaded(),
|
|
||||||
customergroupAutomat.actions.ensureLoaded(),
|
|
||||||
]);
|
|
||||||
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() {
|
handleRetry() {
|
||||||
void this.load();
|
void entityAutomat.actions.load().catch((err) => notifyError(err));
|
||||||
}
|
|
||||||
|
|
||||||
handleCreate() {
|
|
||||||
void router.navigate('/kunde/neu');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleEdit(entity) {
|
handleEdit(entity) {
|
||||||
void router.navigate(`/kunde/${entity.id}`);
|
if (!entity?.id) return;
|
||||||
}
|
this.props.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 entityApi.delete(entity.id);
|
|
||||||
const list = await entityAutomat.actions.reload();
|
|
||||||
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() {
|
render() {
|
||||||
const { status, error, entities, busyId } = this.state;
|
const { status, error, entities, groups, filter } = this.state;
|
||||||
|
const { prefill, returnTo } = getInitialParams(this.props);
|
||||||
|
|
||||||
|
if (status === 'loading' || status === 'idle') {
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
|
||||||
|
<CircularProgress />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (status === 'failed') {
|
if (status === 'failed') {
|
||||||
return <BackendError error={error} onRetry={this.handleRetry} />;
|
return <BackendError error={error} onRetry={this.handleRetry} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
const columns = [
|
const trimmedFilter = filter?.trim() ?? '';
|
||||||
{ key: 'number', label: 'Kundennummer' },
|
const groupsById = Object.fromEntries(groups.map((g) => [g.id, g]));
|
||||||
{ key: 'name', label: 'Name' },
|
|
||||||
{ key: 'firstName', label: 'Vorname' },
|
|
||||||
{
|
|
||||||
key: 'customergroupId',
|
|
||||||
label: 'Gruppe',
|
|
||||||
render: (row) => this.groupName(row.customergroupId),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'createdAt',
|
|
||||||
label: 'Erstellt am',
|
|
||||||
render: (row) => formatDate(row.createdAt),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const label = (row) =>
|
|
||||||
[row.firstName, row.name].filter(Boolean).join(' ') || String(row.number);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<RecordList
|
<>
|
||||||
status={status}
|
<KundeSearchField
|
||||||
error={<BackendError error={error} onRetry={this.handleRetry} />}
|
inputRef={this.searchRef}
|
||||||
rows={entities}
|
prefill={prefill}
|
||||||
columns={columns}
|
returnTo={returnTo}
|
||||||
createLabel="Neuer Kunde"
|
navigate={this.props.navigate}
|
||||||
onCreate={this.handleCreate}
|
/>
|
||||||
onEdit={this.handleEdit}
|
<PanelTileGrid>
|
||||||
onDelete={this.handleDelete}
|
<PanelTile wide={2} minHeight={0} color={BLUE_PANEL}>
|
||||||
deleteDisabled={busyId != null}
|
<List dense disablePadding sx={{ width: '100%' }}>
|
||||||
emptyMessage="Noch keine Kunden."
|
{entities.length === 0 ? (
|
||||||
color={BLUE_PANEL}
|
<Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
|
||||||
getEditLabel={(row) => `„${label(row)}“ bearbeiten`}
|
{trimmedFilter
|
||||||
getDeleteLabel={(row) => `„${label(row)}“ löschen`}
|
? `Keine Treffer für „${trimmedFilter}“.`
|
||||||
/>
|
: 'Noch keine Kunden angelegt.'}
|
||||||
|
</Typography>
|
||||||
|
) : (
|
||||||
|
entities.map((entity) => (
|
||||||
|
<Kunde
|
||||||
|
key={entity.id}
|
||||||
|
customer={entity}
|
||||||
|
groupName={groupsById[entity.customergroupId]?.name}
|
||||||
|
onEdit={this.handleEdit}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</List>
|
||||||
|
</PanelTile>
|
||||||
|
</PanelTileGrid>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default KundeListePage;
|
export { Kunde, KundeSearchField };
|
||||||
|
export default withNavigate(KundeListePage);
|
||||||
|
|||||||
@@ -17,16 +17,40 @@ import { notifyError } from '../../utils/notify';
|
|||||||
import {
|
import {
|
||||||
BLUE_PANEL,
|
BLUE_PANEL,
|
||||||
} from '../../colors';
|
} from '../../colors';
|
||||||
|
import withNavigate from '../../components/withNavigate';
|
||||||
|
|
||||||
|
function getInitialPrefill(props) {
|
||||||
|
const searchParams =
|
||||||
|
typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
|
||||||
|
const raw =
|
||||||
|
props.location?.state?.name ??
|
||||||
|
props.location?.state?.newName ??
|
||||||
|
searchParams?.get('name') ??
|
||||||
|
searchParams?.get('newName') ??
|
||||||
|
'';
|
||||||
|
const trimmed = raw.trim();
|
||||||
|
if (!trimmed) return { name: '', firstName: '' };
|
||||||
|
if (trimmed.includes(',')) {
|
||||||
|
const parts = trimmed.split(',').map((p) => p.trim());
|
||||||
|
return { name: parts[0] || '', firstName: parts.slice(1).join(' ') || '' };
|
||||||
|
}
|
||||||
|
if (trimmed.includes(' ') && !/gmbh|ag|kg|ug|inc|ltd|co\./i.test(trimmed)) {
|
||||||
|
const parts = trimmed.split(' ');
|
||||||
|
return { firstName: parts[0] || '', name: parts.slice(1).join(' ') || '' };
|
||||||
|
}
|
||||||
|
return { name: trimmed, firstName: '' };
|
||||||
|
}
|
||||||
|
|
||||||
class KundeNeuPage extends PureComponent {
|
class KundeNeuPage extends PureComponent {
|
||||||
constructor(props) {
|
constructor(props) {
|
||||||
super(props);
|
super(props);
|
||||||
const groups = customergroupAutomat.state.items ?? [];
|
const groups = customergroupAutomat.state.items ?? [];
|
||||||
|
const prefill = getInitialPrefill(props);
|
||||||
this.state = {
|
this.state = {
|
||||||
customergroupId: groups.length > 0 ? groups[0].id : null,
|
customergroupId: groups.length > 0 ? groups[0].id : null,
|
||||||
number: '',
|
number: '',
|
||||||
name: '',
|
name: prefill.name,
|
||||||
firstName: '',
|
firstName: prefill.firstName,
|
||||||
saving: false,
|
saving: false,
|
||||||
};
|
};
|
||||||
this.handleGroupChange = this.handleGroupChange.bind(this);
|
this.handleGroupChange = this.handleGroupChange.bind(this);
|
||||||
@@ -157,4 +181,4 @@ class KundeNeuPage extends PureComponent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default KundeNeuPage;
|
export default withNavigate(KundeNeuPage);
|
||||||
|
|||||||
Reference in New Issue
Block a user