u
This commit is contained in:
@@ -22,6 +22,8 @@ import sseAutomat, { getSseClientId } from './sseAutomat';
|
||||
/**
|
||||
* @typedef {Object} BrandState
|
||||
* @property {Array<object>} brands All brands (full list, decoupled from page UI).
|
||||
* @property {Array<object>} filteredBrands Filtered brands according to active filter query.
|
||||
* @property {string} filter Active search/filter string.
|
||||
* @property {number} total Unpaged brand count.
|
||||
* @property {'idle'|'loading'|'succeeded'|'failed'} status
|
||||
* @property {string|null} error
|
||||
@@ -30,139 +32,119 @@ import sseAutomat, { getSseClientId } from './sseAutomat';
|
||||
/** @type {BrandState} */
|
||||
const initialState = {
|
||||
brands: [],
|
||||
filteredBrands: [],
|
||||
filter: '',
|
||||
total: 0,
|
||||
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;
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
const updateStateWithBrands = (brands, extra = {}) => {
|
||||
const filteredBrands = applyFilter(brands, brandAutomat.state.filter);
|
||||
brandAutomat.setState({ brands, filteredBrands, total: brands.length, ...extra });
|
||||
return brands;
|
||||
};
|
||||
|
||||
const actions = {
|
||||
/** Sets the active brand search filter and updates filteredBrands. */
|
||||
filter(query) {
|
||||
const filter = String(query ?? '');
|
||||
brandAutomat.setState({ filter, filteredBrands: applyFilter(brandAutomat.state.brands, filter) });
|
||||
},
|
||||
|
||||
/** 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) {
|
||||
return (inflightLoad = fetchAllBrands()
|
||||
.then(({ brands }) => updateStateWithBrands(brands, { status: 'succeeded' }))
|
||||
.catch((err) => {
|
||||
brandAutomat.setState({ status: 'failed', error: err?.message ?? String(err) });
|
||||
throw err;
|
||||
} finally {
|
||||
inflightLoad = null;
|
||||
}
|
||||
})();
|
||||
return inflightLoad;
|
||||
})
|
||||
.finally(() => { inflightLoad = null; }));
|
||||
},
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** Silently re-fetches all brands while keeping current state visible. */
|
||||
async reload() {
|
||||
if (inflightLoad) return inflightLoad;
|
||||
inflightLoad = (async () => {
|
||||
try {
|
||||
const { brands, total } = await fetchAllBrands();
|
||||
brandAutomat.setState({ brands, total, status: 'succeeded', error: null });
|
||||
return brands;
|
||||
} catch (err) {
|
||||
return (inflightLoad = fetchAllBrands()
|
||||
.then(({ brands }) => updateStateWithBrands(brands, { status: 'succeeded', error: null }))
|
||||
.catch((err) => {
|
||||
brandAutomat.setState({ error: err?.message ?? String(err) });
|
||||
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
|
||||
* Returns the brand state, loading brands first if uninitialized.
|
||||
*
|
||||
* @returns {Promise<BrandState>} Current brand state.
|
||||
*/
|
||||
async getOrLoad() {
|
||||
if (brandAutomat.state.status !== 'succeeded') {
|
||||
await brandAutomat.actions.reload();
|
||||
}
|
||||
return brandAutomat.state;
|
||||
},
|
||||
|
||||
/** Create a brand (insert). */
|
||||
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
|
||||
*/
|
||||
/** Rename a brand. */
|
||||
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
|
||||
*/
|
||||
/** Delete a brand by id. */
|
||||
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
|
||||
*/
|
||||
/** Add / update brand image. */
|
||||
async addImage(id, file) {
|
||||
const res = await brandApi.addImage(id, file);
|
||||
await brandAutomat.actions.reload();
|
||||
return res.brand;
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete brand image.
|
||||
* @param {number} id
|
||||
*/
|
||||
/** Delete brand image. */
|
||||
async deleteImage(id) {
|
||||
const res = await brandApi.deleteImage(id);
|
||||
await brandAutomat.actions.reload();
|
||||
@@ -177,37 +159,22 @@ const actions = {
|
||||
|
||||
/**
|
||||
* 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.actions.reset();
|
||||
});
|
||||
|
||||
// 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.
|
||||
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.
|
||||
}
|
||||
if (payload?.sender && payload.sender === getSseClientId()) return;
|
||||
} catch { }
|
||||
void brandAutomat.actions.reload().catch(() => { });
|
||||
});
|
||||
|
||||
export default brandAutomat;
|
||||
export default brandAutomat;
|
||||
@@ -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`}
|
||||
|
||||
@@ -23,21 +23,25 @@ class ArtikelMarkenSearchField extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
input: props.value ?? '',
|
||||
input: brandAutomat.state.filter ?? '',
|
||||
submitting: false,
|
||||
};
|
||||
this.handleSubmit = this.handleSubmit.bind(this);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (prevProps.value !== this.props.value && this.props.value !== this.state.input) {
|
||||
this.setState({ input: this.props.value ?? '' });
|
||||
}
|
||||
componentDidMount() {
|
||||
this.unsub = brandAutomat.subscribe(this, (state) => ({
|
||||
input: state.filter,
|
||||
}));
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.unsub?.();
|
||||
}
|
||||
|
||||
onInputChange(input) {
|
||||
this.setState({ input });
|
||||
this.props.onChange?.(input);
|
||||
brandAutomat.actions.filter(input);
|
||||
}
|
||||
|
||||
async handleSubmit() {
|
||||
@@ -49,7 +53,7 @@ class ArtikelMarkenSearchField extends PureComponent {
|
||||
const row = await brandAutomat.actions.create({ name });
|
||||
enqueueSnackbar(`Marke „${row.name || name}“ angelegt.`, { variant: 'success' });
|
||||
this.setState({ input: '', submitting: false });
|
||||
this.props.onChange?.('');
|
||||
brandAutomat.actions.filter('');
|
||||
} catch (err) {
|
||||
this.setState({ submitting: false });
|
||||
notifyError(err);
|
||||
@@ -105,7 +109,7 @@ 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.searchRef = createRef();
|
||||
this.handleRetry = this.handleRetry.bind(this);
|
||||
@@ -115,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,
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user