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;
|
||||
Reference in New Issue
Block a user