Compare commits
12 Commits
1833fbd631
...
deb22d8b4f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
deb22d8b4f | ||
|
|
3032299257 | ||
|
|
240a5dd3d7 | ||
|
|
e9d8e79cf1 | ||
|
|
c75521dc25 | ||
|
|
3379a63baf | ||
|
|
ce072a3731 | ||
|
|
78994730d1 | ||
|
|
9d578d37f8 | ||
|
|
d32e790540 | ||
|
|
d5aca2b183 | ||
|
|
0dbc7e2f65 |
11
.agents/skills/coding-style/SKILL.md
Normal file
11
.agents/skills/coding-style/SKILL.md
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
name: coding-style
|
||||
description: >-
|
||||
Coding and project style conventions for the Dashfront repository.
|
||||
---
|
||||
|
||||
class componets disconnected from state, in automat.
|
||||
|
||||
Reference:
|
||||
Component: src/routes/artikel/marken.jsx
|
||||
it's Automat: src/automats/brandAutomat.js
|
||||
1
.agents/skills/project-style
Symbolic link
1
.agents/skills/project-style
Symbolic link
@@ -0,0 +1 @@
|
||||
coding-style
|
||||
@@ -149,7 +149,7 @@ src/
|
||||
In `dashfront`, two state management solutions coexist harmoniously:
|
||||
|
||||
### A. `react-automat` (Recommended for Domain Models & Frequent Updates)
|
||||
- **Skill reference**: Read [.agents/skills/automat/SKILL.md](file:///home/seb/src/dashfront/.agents/skills/automat/SKILL.md).
|
||||
- **Skill references**: Read [.agents/skills/automat/SKILL.md](file:///home/seb/src/dashfront/.agents/skills/automat/SKILL.md) and [.agents/skills/coding-style/SKILL.md](file:///home/seb/src/dashfront/.agents/skills/coding-style/SKILL.md) (names [src/automats/brandAutomat.js](file:///home/seb/src/dashfront/src/automats/brandAutomat.js) as the reference automat).
|
||||
- Lives outside the React lifecycle in module scope (`src/automats/*.js`).
|
||||
- Designed for React `PureComponent` to bypass unnecessary React reconciliations.
|
||||
- **Pattern**:
|
||||
|
||||
@@ -7,10 +7,10 @@
|
||||
* `'authed'` with a `selectedCompanyId`, and `actions.reset()` on `'anon'`.
|
||||
* - `sseAutomat`: Subscribes to the single `'brand'` event carrying
|
||||
* `{ sender, brandId }` — any create/rename/delete/picture change triggers
|
||||
* `actions.reload()`, which silently re-fetches the list. Subscribed views
|
||||
* `actions.load(true)`, which silently re-fetches the list. Subscribed views
|
||||
* (e.g. `ArtikelMarkenPage` via `brandAutomat.subscribe(...)`) then
|
||||
* re-render from the updated state. This is the reload pattern. Events sent
|
||||
* by this tab (matching `sender`) are ignored.
|
||||
* re-render from the updated state. Events sent by this tab (matching `sender`)
|
||||
* are ignored.
|
||||
* - UI / Settings: Mutating actions (`create`, `rename`, `remove`, `addImage`, `deleteImage`).
|
||||
*/
|
||||
|
||||
@@ -22,7 +22,8 @@ import sseAutomat, { getSseClientId } from './sseAutomat';
|
||||
/**
|
||||
* @typedef {Object} BrandState
|
||||
* @property {Array<object>} brands All brands (full list, decoupled from page UI).
|
||||
* @property {number} total Unpaged brand count.
|
||||
* @property {Array<object>} filteredBrands Filtered brands according to active filter query.
|
||||
* @property {string} filter Active search/filter string.
|
||||
* @property {'idle'|'loading'|'succeeded'|'failed'} status
|
||||
* @property {string|null} error
|
||||
*/
|
||||
@@ -30,184 +31,122 @@ import sseAutomat, { getSseClientId } from './sseAutomat';
|
||||
/** @type {BrandState} */
|
||||
const initialState = {
|
||||
brands: [],
|
||||
total: 0,
|
||||
filteredBrands: [],
|
||||
filter: '',
|
||||
status: 'idle',
|
||||
error: null,
|
||||
};
|
||||
|
||||
function sortBrands(brands) {
|
||||
return [...brands].sort((a, b) =>
|
||||
String(a.name ?? '').localeCompare(String(b.name ?? ''), 'de'),
|
||||
);
|
||||
}
|
||||
const sortBrands = (brands) =>
|
||||
[...brands].sort((a, b) => String(a.name ?? '').localeCompare(String(b.name ?? ''), 'de'));
|
||||
|
||||
const applyFilter = (brands, filter) => {
|
||||
const query = String(filter ?? '').trim().toLowerCase();
|
||||
return query ? brands.filter((b) => String(b.name ?? '').toLowerCase().includes(query)) : brands;
|
||||
};
|
||||
|
||||
let brandAutomat;
|
||||
|
||||
/** In-flight `load()`/`reload()` promise so concurrent callers share one request. */
|
||||
let inflightLoad = null;
|
||||
|
||||
/** Max page size the API accepts; full list is fetched by paging through. */
|
||||
const FETCH_PAGE_SIZE = 100;
|
||||
|
||||
// #region fetch
|
||||
async function fetchAllBrands() {
|
||||
let offset = 0;
|
||||
let total = Infinity;
|
||||
let offset = 0, total = Infinity;
|
||||
const collected = [];
|
||||
for (;;) {
|
||||
while (offset === 0 || collected.length < total) {
|
||||
const res = await brandApi.list({ offset, limit: FETCH_PAGE_SIZE });
|
||||
if (offset === 0) total = Number(res.total ?? res.brands?.length ?? 0);
|
||||
const page = Array.isArray(res.brands) ? res.brands : [];
|
||||
collected.push(...page);
|
||||
offset += page.length;
|
||||
if (page.length === 0 || collected.length >= total) break;
|
||||
if (page.length === 0) break;
|
||||
}
|
||||
return { brands: sortBrands(collected), total: Number.isFinite(total) ? total : collected.length };
|
||||
return { brands: sortBrands(collected) };
|
||||
}
|
||||
|
||||
const updateStateWithBrands = (brands, extra = {}) => {
|
||||
const filteredBrands = applyFilter(brands, brandAutomat.state.filter);
|
||||
brandAutomat.setState({ brands, filteredBrands, ...extra });
|
||||
return brands;
|
||||
};
|
||||
|
||||
const actions = {
|
||||
/** Load all brands for the selected company (pages through the API). */
|
||||
async load() {
|
||||
if (inflightLoad) return inflightLoad;
|
||||
brandAutomat.setState({ status: 'loading', error: null });
|
||||
inflightLoad = (async () => {
|
||||
try {
|
||||
const { brands, total } = await fetchAllBrands();
|
||||
brandAutomat.setState({ brands, total, status: 'succeeded' });
|
||||
return brands;
|
||||
} catch (err) {
|
||||
brandAutomat.setState({ status: 'failed', error: err?.message ?? String(err) });
|
||||
throw err;
|
||||
} finally {
|
||||
inflightLoad = null;
|
||||
}
|
||||
})();
|
||||
return inflightLoad;
|
||||
/** Sets the active brand search filter and updates filteredBrands. */
|
||||
filter(query) {
|
||||
const filter = String(query ?? '');
|
||||
brandAutomat.setState({ filter, filteredBrands: applyFilter(brandAutomat.state.brands, filter) });
|
||||
},
|
||||
|
||||
/**
|
||||
* Silently re-fetches all brands while keeping the current state
|
||||
* visible (no loading flash). Subscribed views re-render from the updated
|
||||
* state — this is the reload pattern for SSE-driven refreshes.
|
||||
*
|
||||
* @returns {Promise<Array<object>>} Fresh brands.
|
||||
* Load all brands for the selected company (pages through the API).
|
||||
* @param {boolean} [silent=false] If true, re-fetches without setting status to 'loading'.
|
||||
*/
|
||||
async reload() {
|
||||
async load(silent = false) {
|
||||
if (inflightLoad) return inflightLoad;
|
||||
inflightLoad = (async () => {
|
||||
try {
|
||||
const { brands, total } = await fetchAllBrands();
|
||||
brandAutomat.setState({ brands, total, status: 'succeeded', error: null });
|
||||
return brands;
|
||||
} catch (err) {
|
||||
brandAutomat.setState({ error: err?.message ?? String(err) });
|
||||
if (!silent) {
|
||||
brandAutomat.setState({ status: 'loading', error: null });
|
||||
}
|
||||
return (inflightLoad = fetchAllBrands()
|
||||
.then(({ brands }) => updateStateWithBrands(brands, { status: 'succeeded', error: null }))
|
||||
.catch((err) => {
|
||||
const error = err?.message ?? String(err);
|
||||
brandAutomat.setState(silent ? { error } : { status: 'failed', error });
|
||||
throw err;
|
||||
} finally {
|
||||
inflightLoad = null;
|
||||
}
|
||||
})();
|
||||
return inflightLoad;
|
||||
})
|
||||
.finally(() => { inflightLoad = null; }));
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a brand (insert). 409 Brand already exists on duplicate name.
|
||||
* @param {{ name: string, gsprpinfo?: string }} body
|
||||
*/
|
||||
// #region add
|
||||
async create(body) {
|
||||
const res = await brandApi.create(body);
|
||||
const row = res.brand;
|
||||
const brands = sortBrands([
|
||||
...brandAutomat.state.brands.filter((b) => b.id !== row.id),
|
||||
row,
|
||||
]);
|
||||
brandAutomat.setState({ brands, total: brands.length });
|
||||
updateStateWithBrands(sortBrands([...brandAutomat.state.brands.filter((b) => b.id !== row.id), row]));
|
||||
return row;
|
||||
},
|
||||
|
||||
/**
|
||||
* Rename a brand. Returns `{ id, name, gsprpinfo, touchedArticleCount }`.
|
||||
* @param {number} id
|
||||
* @param {{ name?: string, gsprpinfo?: string }} body
|
||||
*/
|
||||
// #region rename
|
||||
async rename(id, body) {
|
||||
const res = await brandApi.rename(id, body);
|
||||
const updated = res.brand ?? { id: res.id, name: res.name, gsprpinfo: res.gsprpinfo };
|
||||
const brands = sortBrands(
|
||||
brandAutomat.state.brands.map((b) => (b.id === id ? { ...b, ...updated } : b)),
|
||||
);
|
||||
brandAutomat.setState({ brands });
|
||||
updateStateWithBrands(sortBrands(brandAutomat.state.brands.map((b) => (b.id === id ? { ...b, ...updated } : b))));
|
||||
return res;
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete a brand by id.
|
||||
* @param {number} id
|
||||
*/
|
||||
// #region del
|
||||
async remove(id) {
|
||||
await brandApi.delete(id);
|
||||
const brands = brandAutomat.state.brands.filter((b) => b.id !== id);
|
||||
brandAutomat.setState({ brands, total: brands.length });
|
||||
updateStateWithBrands(brandAutomat.state.brands.filter((b) => b.id !== id));
|
||||
},
|
||||
|
||||
/**
|
||||
* Add / update brand image.
|
||||
* @param {number} id
|
||||
* @param {Blob|File} file
|
||||
*/
|
||||
// #region addPic
|
||||
async addImage(id, file) {
|
||||
const res = await brandApi.addImage(id, file);
|
||||
await brandAutomat.actions.load();
|
||||
await brandAutomat.actions.load(true);
|
||||
return res.brand;
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete brand image.
|
||||
* @param {number} id
|
||||
*/
|
||||
// #region delPic
|
||||
async deleteImage(id) {
|
||||
const res = await brandApi.deleteImage(id);
|
||||
await brandAutomat.actions.load();
|
||||
const updated = res.brand ?? { pics: [] };
|
||||
updateStateWithBrands(brandAutomat.state.brands.map((b) => (b.id === id ? { ...b, ...updated, pics: [] } : b)));
|
||||
return res.brand;
|
||||
},
|
||||
|
||||
/** Reset to idle state (called on logout / company switch). */
|
||||
reset() {
|
||||
brandAutomat.setState(initialState);
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Global brand state container.
|
||||
* Loads automatically when authAutomat reaches 'authed' with a selectedCompanyId.
|
||||
*
|
||||
* @type {Automat<BrandState>}
|
||||
*/
|
||||
brandAutomat = new Automat(initialState, actions, { name: 'brand' });
|
||||
|
||||
// Subscribe to auth changes
|
||||
authAutomat.subscribe((auth) => {
|
||||
const companyId = auth.user?.selectedCompanyId;
|
||||
if (auth.status === 'authed' && companyId) {
|
||||
void brandAutomat.actions.load();
|
||||
} else if (auth.status === 'anon') {
|
||||
brandAutomat.actions.reset();
|
||||
}
|
||||
if (auth.status === 'authed' && companyId) void brandAutomat.actions.load();
|
||||
else if (auth.status === 'anon') brandAutomat.setState(initialState);
|
||||
});
|
||||
|
||||
// SSE: single `brand` event with `{ sender, brandId }` payload for every
|
||||
// create/rename/delete/picture change. Silently reloads the list; subscribed
|
||||
// views re-render from state. Own events are skipped.
|
||||
// #region onSse
|
||||
sseAutomat.actions.on('brand', (event) => {
|
||||
try {
|
||||
const payload = JSON.parse(event?.data ?? '{}');
|
||||
if (payload && typeof payload.sender === 'string' && payload.sender) {
|
||||
try {
|
||||
if (payload.sender === getSseClientId()) return;
|
||||
} catch {}
|
||||
}
|
||||
} catch {
|
||||
// Unparseable payload: fall through to reload.
|
||||
}
|
||||
void brandAutomat.actions.reload().catch(() => {});
|
||||
if (payload?.sender && payload.sender === getSseClientId()) return;
|
||||
} catch { }
|
||||
void brandAutomat.actions.load(true).catch(() => { });
|
||||
});
|
||||
|
||||
export default brandAutomat;
|
||||
export default brandAutomat;
|
||||
@@ -116,6 +116,10 @@ class AppDialog extends Component {
|
||||
disableScrollLock={disableScrollLock}
|
||||
disableEnforceFocus
|
||||
{...rest}
|
||||
onWheel={(e) => {
|
||||
e.stopPropagation();
|
||||
rest.onWheel?.(e);
|
||||
}}
|
||||
slots={restSlots}
|
||||
slotProps={slotProps}
|
||||
transitionDuration={0}
|
||||
|
||||
@@ -5,6 +5,7 @@ import ListItem from '@mui/material/ListItem';
|
||||
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
|
||||
import ImageSearchIcon from '@mui/icons-material/ImageSearch';
|
||||
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import { enqueueSnackbar } from 'notistack';
|
||||
import brandAutomat from '../../automats/brandAutomat';
|
||||
import { notifyError } from '../../utils/notify';
|
||||
@@ -128,7 +129,7 @@ class ArtikelMarke extends PureComponent {
|
||||
'&:hover': disabled ? undefined : { opacity: 0.8 },
|
||||
}}
|
||||
>
|
||||
<BrandThumb brand={brand}/>
|
||||
<BrandThumb brand={brand} />
|
||||
</Box>
|
||||
) : (
|
||||
<IconButton
|
||||
@@ -141,7 +142,8 @@ class ArtikelMarke extends PureComponent {
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
<SingleLineTextEdit
|
||||
|
||||
{true ? (<SingleLineTextEdit
|
||||
size="small"
|
||||
label=""
|
||||
value={draft}
|
||||
@@ -151,6 +153,7 @@ class ArtikelMarke extends PureComponent {
|
||||
onKeyDown={this.handleKeyDown}
|
||||
sx={{ flex: 1, minWidth: 0 }}
|
||||
/>
|
||||
) : (<Typography sx={{ flex: 1, px: 1.6, py: 0.9, borderRadius: 1, border: '1px solid rgba(0, 0, 0, 0.23)' }}>{draft}</Typography>)}
|
||||
|
||||
<IconButton
|
||||
aria-label={`„${name}" löschen`}
|
||||
|
||||
@@ -34,7 +34,6 @@ class ArtikelMarkeNew extends PureComponent {
|
||||
<Box ref={rowRef} sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 2, pb: 2 }}>
|
||||
<SingleLineTextEdit
|
||||
size="small"
|
||||
label="Neue Marke"
|
||||
value={newName}
|
||||
onChange={(next) => this.setState({ newName: next })}
|
||||
onKeyDown={(event) => {
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { PureComponent, createRef } from 'react';
|
||||
import Box from '@mui/material/Box';
|
||||
import List from '@mui/material/List';
|
||||
import Button from '@mui/material/Button';
|
||||
import CircularProgress from '@mui/material/CircularProgress';
|
||||
import BackendError from '../../components/BackendError';
|
||||
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
||||
import FillSpace from 'dashgui/FillSpace';
|
||||
import { PanelTile, PanelTileGrid } from 'dashgui/panels';
|
||||
import { backendErrorFrom } from '../../utils/backendError';
|
||||
import { notifyError } from '../../utils/notify';
|
||||
import { setLastArticleSku } from '../../automats';
|
||||
import brandAutomat from '../../automats/brandAutomat';
|
||||
import { enqueueSnackbar } from 'notistack';
|
||||
import {
|
||||
ArtikelMarke,
|
||||
ArtikelMarkeNew,
|
||||
@@ -17,6 +19,89 @@ import {
|
||||
PURPLE_PANEL,
|
||||
} from '../../colors';
|
||||
|
||||
class ArtikelMarkenSearchField extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
input: brandAutomat.state.filter ?? '',
|
||||
submitting: false,
|
||||
};
|
||||
this.handleSubmit = this.handleSubmit.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.unsub = brandAutomat.subscribe(this, (state) => ({
|
||||
input: state.filter,
|
||||
}));
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.unsub?.();
|
||||
}
|
||||
|
||||
onInputChange(input) {
|
||||
this.setState({ input });
|
||||
brandAutomat.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 brandAutomat.actions.create({ name });
|
||||
enqueueSnackbar(`Marke „${row.name || name}“ angelegt.`, { variant: 'success' });
|
||||
this.setState({ input: '', submitting: false });
|
||||
brandAutomat.actions.filter('');
|
||||
} catch (err) {
|
||||
this.setState({ submitting: false });
|
||||
notifyError(err);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { inputRef } = 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',
|
||||
alignItems: 'center',
|
||||
gap: 1,
|
||||
pb: 2,
|
||||
}}
|
||||
>
|
||||
<SingleLineTextEdit
|
||||
sx={{ flex: 1 }}
|
||||
size="small"
|
||||
search
|
||||
clear
|
||||
value={input}
|
||||
disabled={submitting}
|
||||
onChange={(next) => this.onInputChange(next)}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!canSubmit}
|
||||
onClick={() => void this.handleSubmit()}
|
||||
>
|
||||
Hinzufügen
|
||||
</Button>
|
||||
</Box>
|
||||
</PanelTileGrid>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ArtikelMarkenPage extends PureComponent {
|
||||
constructor(props) {
|
||||
@@ -24,9 +109,9 @@ class ArtikelMarkenPage extends PureComponent {
|
||||
this.state = {
|
||||
status: brandAutomat.state.status,
|
||||
error: brandAutomat.state.error ? backendErrorFrom({ message: brandAutomat.state.error }) : null,
|
||||
brands: brandAutomat.state.brands,
|
||||
brands: brandAutomat.state.filteredBrands ?? brandAutomat.state.brands,
|
||||
};
|
||||
this.createRowRef = createRef();
|
||||
this.searchRef = createRef();
|
||||
this.handleRetry = this.handleRetry.bind(this);
|
||||
}
|
||||
|
||||
@@ -34,7 +119,7 @@ class ArtikelMarkenPage extends PureComponent {
|
||||
setLastArticleSku(null);
|
||||
|
||||
this.unsub = brandAutomat.subscribe(this, (state) => ({
|
||||
brands: state.brands,
|
||||
brands: state.filteredBrands,
|
||||
status: state.status,
|
||||
error: state.error ? backendErrorFrom({ message: state.error }) : null,
|
||||
}));
|
||||
@@ -45,7 +130,6 @@ class ArtikelMarkenPage extends PureComponent {
|
||||
}
|
||||
|
||||
handleRetry() {
|
||||
// The automat owns fetching; just ask it to load again.
|
||||
void brandAutomat.actions.load().catch((err) => notifyError(err));
|
||||
}
|
||||
|
||||
@@ -65,24 +149,24 @@ class ArtikelMarkenPage extends PureComponent {
|
||||
}
|
||||
|
||||
return (
|
||||
<PanelTileGrid>
|
||||
<PanelTile wide={2} minHeight={0} color={PURPLE_PANEL} sx={{ pb: 0 }}>
|
||||
<FillSpace
|
||||
aboveRef={[]}
|
||||
belowRef={this.createRowRef}
|
||||
reserveBottom={32}
|
||||
minPageSize={8}
|
||||
minHeight={0}
|
||||
items={brands}
|
||||
renderItem={ArtikelMarke}
|
||||
/>
|
||||
|
||||
<ArtikelMarkeNew rowRef={this.createRowRef} />
|
||||
</PanelTile>
|
||||
</PanelTileGrid>
|
||||
<>
|
||||
<ArtikelMarkenSearchField inputRef={this.searchRef} />
|
||||
<PanelTileGrid>
|
||||
<PanelTile wide={2} minHeight={0} color={PURPLE_PANEL} sx={{ pb: 0 }}>
|
||||
<FillSpace
|
||||
aboveRef={[this.searchRef]}
|
||||
reserveBottom={32}
|
||||
minPageSize={8}
|
||||
minHeight={0}
|
||||
items={brands}
|
||||
renderItem={ArtikelMarke}
|
||||
/>
|
||||
</PanelTile>
|
||||
</PanelTileGrid>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export { ArtikelMarke, ArtikelMarkeNew };
|
||||
export { ArtikelMarke, ArtikelMarkeNew, ArtikelMarkenSearchField };
|
||||
export default ArtikelMarkenPage;
|
||||
|
||||
Reference in New Issue
Block a user