1006 lines
30 KiB
JavaScript
1006 lines
30 KiB
JavaScript
/**
|
|
* @file retoureAutomat.js
|
|
* @description Manages cached and chunk-paginated customer returns / Retouren (`GET /api/retoure`).
|
|
*
|
|
* Implements a multi-filter chunk cache:
|
|
* - Each filter combination has its own isolated cache entry (total, items array, loadedChunks).
|
|
* - Total chunk capacity across all filter combinations is bounded by a global LRU (Least Recently Used) limit of 50 chunks.
|
|
* - When filter settings change, previously loaded chunks remain cached in memory up to the 50-chunk limit.
|
|
* - Switching back to a previously used filter is instant with zero network requests if its chunks are in RAM.
|
|
*
|
|
* Upstream Triggers:
|
|
* - `authAutomat`: Triggers `actions.reset()` on `'anon'` or when `selectedCompanyId` changes.
|
|
* - `sseAutomat`: Dispatches `'retoure'` events to `reload()`.
|
|
* - UI / Routes: Calls `getItems()`, `requireChunk(chunkIndex)`, `loadChunk(chunkIndex)`, or `reload()`.
|
|
*/
|
|
|
|
import { Automat } from 'react-automat';
|
|
import { retoure as retoureApi, normalizeRetoureSummary } from '../api/retoure';
|
|
import authAutomat from './authAutomat';
|
|
|
|
/**
|
|
* @typedef {Object} RetoureLine
|
|
* @property {number} id
|
|
* @property {string|null} sku
|
|
* @property {string|null} name
|
|
* @property {number} pu
|
|
* @property {number} amount
|
|
* @property {number} net
|
|
* @property {number} rebate
|
|
* @property {number} taxrate
|
|
* @property {string|null} comment
|
|
*/
|
|
|
|
/**
|
|
* @typedef {Object} Retoure
|
|
* @property {number} id Retoure/manifest id.
|
|
* @property {string} number Retoure number (e.g. RET-00001).
|
|
* @property {string} date Retoure date (ISO).
|
|
* @property {number|null} entityId Customer id.
|
|
* @property {string|null} customerName Customer display name.
|
|
* @property {number} positions Positions count.
|
|
* @property {number} grossTotal Gross sum.
|
|
* @property {number} paidTotal Paid sum (refunded).
|
|
* @property {number} orderedQuantity Ordered/returned quantity.
|
|
* @property {number} shippedQuantity Shipped/received quantity.
|
|
* @property {boolean} isPaid Paid / refunded status.
|
|
* @property {boolean} isShipped Shipped / received status.
|
|
* @property {string|null} createdAt Creation timestamp.
|
|
* @property {RetoureLine[]} lines Line items.
|
|
*/
|
|
|
|
export const CHUNK_SIZE = 50;
|
|
export const MAX_LRU_CHUNKS = 50;
|
|
const PREFETCH_CHUNKS = 1;
|
|
const CHUNK_DEBOUNCE_MS = 130;
|
|
|
|
const initialState = {
|
|
items: null,
|
|
total: 0,
|
|
unfilteredTotal: 0,
|
|
filter: '',
|
|
onlyUnpaid: false,
|
|
onlyUndelivered: false,
|
|
entityId: null,
|
|
seekMonths: 0,
|
|
seekYears: 0,
|
|
negativeSeekMonths: 0,
|
|
status: 'idle',
|
|
error: null,
|
|
};
|
|
|
|
let automat;
|
|
let queryEpoch = 0;
|
|
let filterDebounceTimer = null;
|
|
let chunkDebounceTimer = null;
|
|
let currentEventTick = 0;
|
|
let lastRequireChunkTick = -1;
|
|
|
|
const pendingTargetChunks = new Set();
|
|
let pendingChunkPromise = null;
|
|
let pendingChunkResolve = null;
|
|
let pendingChunkReject = null;
|
|
|
|
// Multi-Filter Cache & Global LRU Management
|
|
const filterCaches = new Map();
|
|
const lruChunks = new Map();
|
|
const inflightChunks = new Map();
|
|
|
|
// Dev / Observability: Chunk event history and subscriber registry
|
|
const MAX_CHUNK_EVENTS = 150;
|
|
let nextEventId = 0;
|
|
const chunkEvents = [];
|
|
const chunkStatsListeners = new Set();
|
|
|
|
export function makeLruKey(filterKey, chunkIndex) {
|
|
return `${filterKey}:::${chunkIndex}`;
|
|
}
|
|
|
|
export function parseLruKey(key) {
|
|
const [filterKey, chunkStr] = key.split(':::');
|
|
return { filterKey, chunkIndex: Number(chunkStr) };
|
|
}
|
|
|
|
// MARK: pure filter helpers
|
|
export function getFilterParams(state = automat?.state || initialState) {
|
|
const filter = String(state.filter ?? '').trim();
|
|
const onlyUnpaid = Boolean(state.onlyUnpaid);
|
|
const onlyUndelivered = Boolean(state.onlyUndelivered);
|
|
const entityId = state.entityId != null && state.entityId !== '' ? Number(state.entityId) : null;
|
|
const negativeSeekMonths = (state.negativeSeekMonths != null && Number(state.negativeSeekMonths) < 0)
|
|
? Number(state.negativeSeekMonths)
|
|
: 0;
|
|
return { filter, onlyUnpaid, onlyUndelivered, entityId, negativeSeekMonths };
|
|
}
|
|
|
|
export function getFilterKey(state = automat?.state || initialState) {
|
|
const { filter, onlyUnpaid, onlyUndelivered, entityId, negativeSeekMonths } = getFilterParams(state);
|
|
return JSON.stringify({ f: filter, u: onlyUnpaid, d: onlyUndelivered, e: entityId, s: negativeSeekMonths });
|
|
}
|
|
|
|
export function formatFilterLabel(filterKeyOrState) {
|
|
let f, u, d, e, s;
|
|
if (typeof filterKeyOrState === 'string') {
|
|
try {
|
|
const parsed = JSON.parse(filterKeyOrState);
|
|
f = parsed.f;
|
|
u = parsed.u;
|
|
d = parsed.d;
|
|
e = parsed.e;
|
|
s = parsed.s;
|
|
} catch {
|
|
return filterKeyOrState;
|
|
}
|
|
} else if (filterKeyOrState && typeof filterKeyOrState === 'object') {
|
|
if ('f' in filterKeyOrState) {
|
|
f = filterKeyOrState.f;
|
|
u = filterKeyOrState.u;
|
|
d = filterKeyOrState.d;
|
|
e = filterKeyOrState.e;
|
|
s = filterKeyOrState.s;
|
|
} else {
|
|
const params = getFilterParams(filterKeyOrState);
|
|
f = params.filter;
|
|
u = params.onlyUnpaid;
|
|
d = params.onlyUndelivered;
|
|
e = params.entityId;
|
|
s = params.negativeSeekMonths;
|
|
}
|
|
}
|
|
|
|
const parts = [];
|
|
if (f) parts.push(`Suche: „${f}“`);
|
|
if (e != null) parts.push(`Kunde: #${e}`);
|
|
if (u) parts.push('Nur unerstattete');
|
|
if (d) parts.push('Nur offene');
|
|
if (s < 0) parts.push(`Seek: ${s}M`);
|
|
if (parts.length === 0) return 'Standard (Alle Retouren)';
|
|
return parts.join(' · ');
|
|
}
|
|
|
|
function countNonNullItems(items) {
|
|
if (!Array.isArray(items)) return 0;
|
|
let count = 0;
|
|
for (let i = 0; i < items.length; i++) {
|
|
if (items[i] != null) count++;
|
|
}
|
|
return count;
|
|
}
|
|
|
|
function getOrCreateFilterCache(filterKey, filterState = automat?.state || initialState) {
|
|
let entry = filterCaches.get(filterKey);
|
|
if (!entry) {
|
|
const params = getFilterParams(filterState);
|
|
entry = {
|
|
key: filterKey,
|
|
label: formatFilterLabel(params),
|
|
params,
|
|
total: 0,
|
|
unfilteredTotal: automat?.state?.unfilteredTotal || 0,
|
|
items: null,
|
|
loadedChunks: new Set(),
|
|
status: 'idle',
|
|
error: null,
|
|
lastAccessed: Date.now(),
|
|
epoch: queryEpoch,
|
|
};
|
|
filterCaches.set(filterKey, entry);
|
|
}
|
|
return entry;
|
|
}
|
|
|
|
function touchChunkLRU(filterKey, chunkIndex) {
|
|
const key = makeLruKey(filterKey, chunkIndex);
|
|
const existing = lruChunks.get(key);
|
|
if (existing) {
|
|
lruChunks.delete(key);
|
|
lruChunks.set(key, { ...existing, accessedAt: Date.now() });
|
|
}
|
|
}
|
|
|
|
function registerChunkLRU(filterKey, chunkIndex, itemCount = 0) {
|
|
const key = makeLruKey(filterKey, chunkIndex);
|
|
if (lruChunks.has(key)) {
|
|
lruChunks.delete(key);
|
|
}
|
|
const now = Date.now();
|
|
lruChunks.set(key, {
|
|
filterKey,
|
|
chunkIndex,
|
|
loadedAt: now,
|
|
accessedAt: now,
|
|
itemCount,
|
|
});
|
|
|
|
while (lruChunks.size > MAX_LRU_CHUNKS) {
|
|
const oldestKey = lruChunks.keys().next().value;
|
|
const oldestInfo = lruChunks.get(oldestKey);
|
|
lruChunks.delete(oldestKey);
|
|
if (oldestInfo) {
|
|
evictChunkFromMemory(oldestInfo.filterKey, oldestInfo.chunkIndex, 'lru');
|
|
}
|
|
}
|
|
}
|
|
|
|
function evictChunkFromMemory(filterKey, chunkIndex, reason = 'manual') {
|
|
const entry = filterCaches.get(filterKey);
|
|
if (!entry) return;
|
|
|
|
if (entry.loadedChunks.has(chunkIndex)) {
|
|
entry.loadedChunks.delete(chunkIndex);
|
|
if (Array.isArray(entry.items)) {
|
|
const offset = chunkIndex * CHUNK_SIZE;
|
|
for (let i = offset; i < offset + CHUNK_SIZE && i < entry.items.length; i++) {
|
|
entry.items[i] = null;
|
|
}
|
|
}
|
|
|
|
const currentKey = getFilterKey(automat.state);
|
|
if (filterKey === currentKey) {
|
|
automat.setState({ items: [...entry.items] });
|
|
}
|
|
|
|
recordChunkEvent({
|
|
type: reason === 'lru' ? 'lru_evict' : 'evict',
|
|
chunkIndex,
|
|
filterKey,
|
|
message: `Chunk #${chunkIndex} von Filter "${entry.label}" verworfen`,
|
|
});
|
|
notifyChunkStats();
|
|
}
|
|
}
|
|
|
|
function recordChunkEvent(entry) {
|
|
const event = {
|
|
id: ++nextEventId,
|
|
time: Date.now(),
|
|
epoch: queryEpoch,
|
|
filterKey: entry.filterKey ?? getFilterKey(automat?.state),
|
|
...entry,
|
|
};
|
|
chunkEvents.push(event);
|
|
if (chunkEvents.length > MAX_CHUNK_EVENTS) {
|
|
chunkEvents.shift();
|
|
}
|
|
notifyChunkStats();
|
|
}
|
|
|
|
function notifyChunkStats() {
|
|
if (chunkStatsListeners.size === 0) return;
|
|
const stats = getChunkStats();
|
|
for (const listener of chunkStatsListeners) {
|
|
try {
|
|
listener(stats);
|
|
} catch (e) {
|
|
console.error('[retoureAutomat] chunkStatsListener error', e);
|
|
}
|
|
}
|
|
}
|
|
|
|
export function getChunkStats() {
|
|
const currentKey = getFilterKey(automat?.state);
|
|
const activeEntry = filterCaches.get(currentKey);
|
|
|
|
const total = activeEntry?.total ?? automat?.state?.total ?? 0;
|
|
const activeLoaded = activeEntry?.loadedChunks ?? new Set();
|
|
const chunkCount = total > 0 ? Math.ceil(total / CHUNK_SIZE) : (activeLoaded.size > 0 ? Math.max(...activeLoaded) + 1 : 0);
|
|
const items = activeEntry?.items ?? automat?.state?.items;
|
|
const loadedItemsCount = countNonNullItems(items);
|
|
|
|
// Summarize all cached filter combinations
|
|
const cachedFiltersSummary = Array.from(filterCaches.values()).map((entry) => ({
|
|
key: entry.key,
|
|
label: entry.label,
|
|
params: entry.params,
|
|
total: entry.total,
|
|
loadedChunksCount: entry.loadedChunks.size,
|
|
loadedChunks: Array.from(entry.loadedChunks).sort((a, b) => a - b),
|
|
chunkCount: entry.total > 0 ? Math.ceil(entry.total / CHUNK_SIZE) : (entry.loadedChunks.size > 0 ? Math.max(...entry.loadedChunks) + 1 : 0),
|
|
loadedItemsCount: countNonNullItems(entry.items),
|
|
lastAccessed: entry.lastAccessed,
|
|
isActive: entry.key === currentKey,
|
|
status: entry.status,
|
|
items: entry.items,
|
|
}));
|
|
|
|
// LRU queue list from oldest (1) to newest (50)
|
|
const lruEntries = Array.from(lruChunks.entries()).map(([key, info], idx) => ({
|
|
lruKey: key,
|
|
filterKey: info.filterKey,
|
|
filterLabel: filterCaches.get(info.filterKey)?.label || info.filterKey,
|
|
chunkIndex: info.chunkIndex,
|
|
loadedAt: info.loadedAt,
|
|
accessedAt: info.accessedAt,
|
|
itemCount: info.itemCount,
|
|
lruRank: idx + 1,
|
|
}));
|
|
|
|
// Active filter's inflight chunks
|
|
const activeInflight = [];
|
|
for (const key of inflightChunks.keys()) {
|
|
if (key.startsWith(`${currentKey}:::`)) {
|
|
const parsed = parseLruKey(key);
|
|
activeInflight.push(parsed.chunkIndex);
|
|
}
|
|
}
|
|
|
|
return {
|
|
automatName: 'retoure',
|
|
chunkSize: CHUNK_SIZE,
|
|
maxLruChunks: MAX_LRU_CHUNKS,
|
|
lruChunksCount: lruChunks.size,
|
|
total,
|
|
chunkCount,
|
|
loadedChunks: Array.from(activeLoaded).sort((a, b) => a - b),
|
|
inflightChunks: activeInflight.sort((a, b) => a - b),
|
|
pendingChunks: Array.from(pendingTargetChunks).sort((a, b) => a - b),
|
|
loadedItemsCount,
|
|
status: automat?.state?.status ?? 'idle',
|
|
queryEpoch,
|
|
filter: automat?.state?.filter ?? '',
|
|
onlyUnpaid: automat?.state?.onlyUnpaid ?? false,
|
|
onlyUndelivered: automat?.state?.onlyUndelivered ?? false,
|
|
items,
|
|
activeFilterKey: currentKey,
|
|
activeFilterLabel: formatFilterLabel(currentKey),
|
|
filterCaches: cachedFiltersSummary,
|
|
lruEntries,
|
|
events: [...chunkEvents],
|
|
};
|
|
}
|
|
|
|
export function subscribeChunkStats(listener) {
|
|
chunkStatsListeners.add(listener);
|
|
try {
|
|
listener(getChunkStats());
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
return () => {
|
|
chunkStatsListeners.delete(listener);
|
|
};
|
|
}
|
|
|
|
function clearChunkDebounce() {
|
|
if (chunkDebounceTimer) {
|
|
clearTimeout(chunkDebounceTimer);
|
|
chunkDebounceTimer = null;
|
|
}
|
|
if (pendingTargetChunks.size > 0) {
|
|
pendingTargetChunks.clear();
|
|
notifyChunkStats();
|
|
}
|
|
pendingChunkPromise = null;
|
|
pendingChunkResolve = null;
|
|
pendingChunkReject = null;
|
|
}
|
|
|
|
function _executeRequiredChunks(chunks, targetEpoch, prefetch = true, targetFilterKey = getFilterKey(automat.state)) {
|
|
if (targetEpoch !== queryEpoch) {
|
|
return Promise.resolve(automat.state.items);
|
|
}
|
|
|
|
const chunkList = Array.from(chunks).sort((a, b) => a - b);
|
|
if (chunkList.length === 0) {
|
|
return Promise.resolve(automat.state.items);
|
|
}
|
|
|
|
const promises = [];
|
|
for (const c of chunkList) {
|
|
promises.push(actions.loadChunk(c, targetEpoch, targetFilterKey));
|
|
}
|
|
|
|
return Promise.all(promises).then(() => {
|
|
if (targetEpoch !== queryEpoch) return automat.state.items;
|
|
if (prefetch) {
|
|
const maxChunk = chunkList[chunkList.length - 1];
|
|
const entry = filterCaches.get(targetFilterKey);
|
|
const total = entry?.total || automat.state.total || 0;
|
|
for (let c = maxChunk + 1; c <= maxChunk + PREFETCH_CHUNKS; c++) {
|
|
if (total > 0 && c * CHUNK_SIZE >= total) {
|
|
break;
|
|
}
|
|
void actions.loadChunk(c, targetEpoch, targetFilterKey);
|
|
}
|
|
}
|
|
return automat.state.items;
|
|
});
|
|
}
|
|
|
|
// MARK: pure retoure helpers
|
|
export function isRetourePaid(retoure) {
|
|
if (!retoure) return false;
|
|
return Boolean(retoure.isPaid ?? retoure.is_paid ?? retoure.paid);
|
|
}
|
|
|
|
export function isRetoureShipped(retoure) {
|
|
if (!retoure) return false;
|
|
return Boolean(retoure.isShipped ?? retoure.is_shipped ?? retoure.delivered);
|
|
}
|
|
|
|
export function isRetoureDelivered(retoure) {
|
|
return isRetoureShipped(retoure);
|
|
}
|
|
|
|
export function getRetoureDate(retoure) {
|
|
if (!retoure) return null;
|
|
const raw = retoure.retoureDate ?? retoure.retoure_date ?? retoure.date ?? retoure.createdAt ?? retoure.created_at;
|
|
if (!raw) return null;
|
|
const d = new Date(raw);
|
|
return Number.isNaN(d.getTime()) ? null : d;
|
|
}
|
|
|
|
function buildQueryParamsFor(filterParams, offset = 0, limit = CHUNK_SIZE) {
|
|
const page = Math.floor(offset / limit) + 1;
|
|
const params = {
|
|
offset,
|
|
limit,
|
|
page,
|
|
pageSize: limit,
|
|
};
|
|
const trimmed = String(filterParams.filter ?? '').trim();
|
|
if (trimmed) {
|
|
params.q = trimmed;
|
|
params.search = trimmed;
|
|
}
|
|
if (filterParams.onlyUnpaid) {
|
|
params.isPaid = false;
|
|
}
|
|
if (filterParams.onlyUndelivered) {
|
|
params.isShipped = false;
|
|
}
|
|
if (filterParams.entityId != null) {
|
|
params.entityId = filterParams.entityId;
|
|
}
|
|
if (filterParams.negativeSeekMonths != null && Number(filterParams.negativeSeekMonths) < 0) {
|
|
params.seekMonths = Number(filterParams.negativeSeekMonths);
|
|
}
|
|
return params;
|
|
}
|
|
|
|
async function fetchRetouresPageFor(filterParams, offset = 0, limit = CHUNK_SIZE) {
|
|
const params = buildQueryParamsFor(filterParams, offset, limit);
|
|
const res = await retoureApi.list(params);
|
|
const rawList = res?.retoures ?? res?.summaries ?? res?.items ?? (Array.isArray(res) ? res : []);
|
|
const items = rawList.map(normalizeRetoureSummary);
|
|
const total = Number(res?.total ?? items.length);
|
|
const unfilteredTotal = res?.unfilteredTotal != null ? Number(res.unfilteredTotal) : total;
|
|
return { items, total, unfilteredTotal };
|
|
}
|
|
|
|
function onFilterChange(immediate = false) {
|
|
if (filterDebounceTimer) {
|
|
clearTimeout(filterDebounceTimer);
|
|
filterDebounceTimer = null;
|
|
}
|
|
if (immediate) {
|
|
applyFilterReload();
|
|
} else {
|
|
filterDebounceTimer = setTimeout(() => {
|
|
filterDebounceTimer = null;
|
|
applyFilterReload();
|
|
}, 200);
|
|
}
|
|
}
|
|
|
|
function applyFilterReload() {
|
|
queryEpoch++;
|
|
clearChunkDebounce();
|
|
|
|
const currentKey = getFilterKey(automat.state);
|
|
const cached = filterCaches.get(currentKey);
|
|
|
|
if (cached && cached.items !== null) {
|
|
cached.lastAccessed = Date.now();
|
|
for (const c of cached.loadedChunks) {
|
|
touchChunkLRU(currentKey, c);
|
|
}
|
|
|
|
automat.setState({
|
|
items: cached.items,
|
|
total: cached.total,
|
|
unfilteredTotal: cached.unfilteredTotal ?? automat.state.unfilteredTotal ?? 0,
|
|
status: cached.status || 'ready',
|
|
error: cached.error || null,
|
|
});
|
|
|
|
if (!cached.loadedChunks.has(0)) {
|
|
void actions.loadChunk(0, queryEpoch, currentKey);
|
|
}
|
|
} else {
|
|
const entry = getOrCreateFilterCache(currentKey, automat.state);
|
|
entry.lastAccessed = Date.now();
|
|
|
|
automat.setState({
|
|
items: null,
|
|
total: 0,
|
|
unfilteredTotal: automat.state.unfilteredTotal ?? 0,
|
|
status: 'loading',
|
|
error: null,
|
|
});
|
|
|
|
void actions.loadChunk(0, queryEpoch, currentKey);
|
|
}
|
|
}
|
|
|
|
const actions = {
|
|
getItems() {
|
|
if (automat.state.items === null) {
|
|
void actions.requireChunk(0, 0, { prefetch: false, immediate: true });
|
|
return null;
|
|
}
|
|
return automat.state.items;
|
|
},
|
|
|
|
requireChunk(chunkIndex, endOrOptions = chunkIndex, maybeOptions = {}) {
|
|
let start;
|
|
let end;
|
|
let options = {};
|
|
|
|
if (Array.isArray(chunkIndex)) {
|
|
start = chunkIndex[0] ?? 0;
|
|
end = chunkIndex[chunkIndex.length - 1] ?? start;
|
|
if (typeof endOrOptions === 'object' && endOrOptions !== null) {
|
|
options = endOrOptions;
|
|
}
|
|
} else {
|
|
start = Number(chunkIndex) || 0;
|
|
if (typeof endOrOptions === 'object' && endOrOptions !== null) {
|
|
end = start;
|
|
options = endOrOptions;
|
|
} else {
|
|
end = Number(endOrOptions ?? start) || start;
|
|
if (typeof maybeOptions === 'object' && maybeOptions !== null) {
|
|
options = maybeOptions;
|
|
}
|
|
}
|
|
}
|
|
|
|
start = Math.max(0, Math.floor(start));
|
|
end = Math.max(start, Math.floor(end));
|
|
const prefetch = options.prefetch !== false;
|
|
const currentKey = getFilterKey(automat.state);
|
|
|
|
if (options.immediate || automat.state.items === null) {
|
|
clearChunkDebounce();
|
|
const chunks = new Set();
|
|
for (let c = start; c <= end; c++) chunks.add(c);
|
|
return _executeRequiredChunks(chunks, queryEpoch, prefetch, currentKey);
|
|
}
|
|
|
|
if (lastRequireChunkTick !== currentEventTick) {
|
|
pendingTargetChunks.clear();
|
|
lastRequireChunkTick = currentEventTick;
|
|
if (typeof queueMicrotask === 'function') {
|
|
queueMicrotask(() => { currentEventTick++; });
|
|
} else {
|
|
Promise.resolve().then(() => { currentEventTick++; });
|
|
}
|
|
}
|
|
|
|
for (let c = start; c <= end; c++) {
|
|
pendingTargetChunks.add(c);
|
|
}
|
|
|
|
if (chunkDebounceTimer) {
|
|
clearTimeout(chunkDebounceTimer);
|
|
chunkDebounceTimer = null;
|
|
}
|
|
|
|
if (!pendingChunkPromise) {
|
|
pendingChunkPromise = new Promise((resolve, reject) => {
|
|
pendingChunkResolve = resolve;
|
|
pendingChunkReject = reject;
|
|
});
|
|
}
|
|
|
|
const captureEpoch = queryEpoch;
|
|
chunkDebounceTimer = setTimeout(() => {
|
|
chunkDebounceTimer = null;
|
|
const chunksToLoad = new Set(pendingTargetChunks);
|
|
pendingTargetChunks.clear();
|
|
notifyChunkStats();
|
|
|
|
const resolve = pendingChunkResolve;
|
|
const reject = pendingChunkReject;
|
|
pendingChunkPromise = null;
|
|
pendingChunkResolve = null;
|
|
pendingChunkReject = null;
|
|
|
|
_executeRequiredChunks(chunksToLoad, captureEpoch, true, currentKey)
|
|
.then((res) => resolve?.(res))
|
|
.catch((err) => reject?.(err));
|
|
}, CHUNK_DEBOUNCE_MS);
|
|
|
|
return pendingChunkPromise;
|
|
},
|
|
|
|
loadChunk(chunkIndex, targetEpoch = queryEpoch, targetFilterKey = getFilterKey(automat.state)) {
|
|
const index = Math.max(0, Number(chunkIndex) || 0);
|
|
const entry = getOrCreateFilterCache(targetFilterKey, automat.state);
|
|
|
|
if (targetEpoch !== queryEpoch && targetFilterKey !== getFilterKey(automat.state)) {
|
|
return Promise.resolve(entry.items);
|
|
}
|
|
|
|
if (entry.loadedChunks.has(index)) {
|
|
touchChunkLRU(targetFilterKey, index);
|
|
return Promise.resolve(targetFilterKey === getFilterKey(automat.state) ? automat.state.items : entry.items);
|
|
}
|
|
|
|
const inflightKey = makeLruKey(targetFilterKey, index);
|
|
if (inflightChunks.has(inflightKey)) {
|
|
return inflightChunks.get(inflightKey);
|
|
}
|
|
|
|
const offset = index * CHUNK_SIZE;
|
|
const limit = CHUNK_SIZE;
|
|
const isActiveFilter = targetFilterKey === getFilterKey(automat.state);
|
|
|
|
if (index === 0 && (entry.items === null || (isActiveFilter && automat.state.items === null))) {
|
|
entry.status = 'loading';
|
|
entry.error = null;
|
|
if (isActiveFilter) {
|
|
automat.setState({ status: 'loading', error: null });
|
|
}
|
|
}
|
|
|
|
const filterParams = entry.params || getFilterParams(automat.state);
|
|
const promise = fetchRetouresPageFor(filterParams, offset, limit)
|
|
.then(({ items, total, unfilteredTotal }) => {
|
|
const currentTotal = total > 0 ? total : 0;
|
|
entry.total = currentTotal;
|
|
entry.unfilteredTotal = unfilteredTotal;
|
|
|
|
if (entry.items === null || entry.items.length !== currentTotal) {
|
|
entry.items = new Array(currentTotal).fill(null);
|
|
} else {
|
|
entry.items = [...entry.items];
|
|
}
|
|
|
|
for (let i = 0; i < items.length; i++) {
|
|
const idx = offset + i;
|
|
if (idx < entry.items.length) {
|
|
entry.items[idx] = items[i];
|
|
}
|
|
}
|
|
|
|
entry.loadedChunks.add(index);
|
|
entry.status = 'ready';
|
|
entry.error = null;
|
|
entry.lastAccessed = Date.now();
|
|
|
|
registerChunkLRU(targetFilterKey, index, items.length);
|
|
|
|
const currentActive = targetFilterKey === getFilterKey(automat.state);
|
|
if (currentActive) {
|
|
automat.setState({
|
|
items: entry.items,
|
|
total: currentTotal,
|
|
unfilteredTotal,
|
|
status: 'ready',
|
|
error: null,
|
|
});
|
|
}
|
|
|
|
notifyChunkStats();
|
|
return entry.items;
|
|
})
|
|
.catch((err) => {
|
|
entry.status = 'failed';
|
|
entry.error = err;
|
|
if (targetFilterKey === getFilterKey(automat.state)) {
|
|
automat.setState({ status: 'failed', error: err });
|
|
}
|
|
notifyChunkStats();
|
|
throw err;
|
|
})
|
|
.finally(() => {
|
|
inflightChunks.delete(inflightKey);
|
|
});
|
|
|
|
inflightChunks.set(inflightKey, promise);
|
|
return promise;
|
|
},
|
|
|
|
async reload() {
|
|
filterCaches.clear();
|
|
lruChunks.clear();
|
|
inflightChunks.clear();
|
|
clearChunkDebounce();
|
|
queryEpoch++;
|
|
|
|
const currentKey = getFilterKey(automat.state);
|
|
const entry = getOrCreateFilterCache(currentKey, automat.state);
|
|
entry.lastAccessed = Date.now();
|
|
|
|
try {
|
|
await actions.loadChunk(0, queryEpoch, currentKey);
|
|
return automat.state.items;
|
|
} catch (err) {
|
|
return automat.state.items;
|
|
}
|
|
},
|
|
|
|
async ensureLoaded() {
|
|
if (automat.state.status === 'ready' && automat.state.items !== null) {
|
|
return automat.state.items;
|
|
}
|
|
return actions.load();
|
|
},
|
|
|
|
async load() {
|
|
return actions.requireChunk(0, 0, { immediate: true });
|
|
},
|
|
|
|
filter(query) {
|
|
actions.setFilter(query);
|
|
},
|
|
|
|
setFilter(value) {
|
|
const next = String(value ?? '');
|
|
if (automat.state.filter === next) return;
|
|
automat.setState({ filter: next });
|
|
onFilterChange(false);
|
|
},
|
|
|
|
setOnlyUnpaid(value) {
|
|
const next = Boolean(value);
|
|
if (automat.state.onlyUnpaid === next) return;
|
|
automat.setState({ onlyUnpaid: next });
|
|
onFilterChange(true);
|
|
},
|
|
|
|
setOnlyUndelivered(value) {
|
|
const next = Boolean(value);
|
|
if (automat.state.onlyUndelivered === next) return;
|
|
automat.setState({ onlyUndelivered: next });
|
|
onFilterChange(true);
|
|
},
|
|
|
|
setEntityId(entityId) {
|
|
const next = entityId != null && entityId !== '' ? Number(entityId) : null;
|
|
if (automat.state.entityId === next) return;
|
|
automat.setState({ entityId: next });
|
|
onFilterChange(true);
|
|
},
|
|
|
|
addSeekMonth() {
|
|
const seekMonths = (automat.state.seekMonths ?? 0) + 1;
|
|
const seekYears = automat.state.seekYears ?? 0;
|
|
const totalMonths = -(seekMonths + seekYears * 12);
|
|
automat.setState({ seekMonths, negativeSeekMonths: totalMonths });
|
|
onFilterChange(true);
|
|
},
|
|
|
|
addSeekYear() {
|
|
const seekMonths = automat.state.seekMonths ?? 0;
|
|
const seekYears = (automat.state.seekYears ?? 0) + 1;
|
|
const totalMonths = -(seekMonths + seekYears * 12);
|
|
automat.setState({ seekYears, negativeSeekMonths: totalMonths });
|
|
onFilterChange(true);
|
|
},
|
|
|
|
addNegativeSeek(months) {
|
|
if (months === -12) {
|
|
actions.addSeekYear();
|
|
} else if (months === -1) {
|
|
actions.addSeekMonth();
|
|
} else {
|
|
const current = Math.min(0, Number(automat.state.negativeSeekMonths ?? 0));
|
|
const next = current + months;
|
|
automat.setState({ negativeSeekMonths: Math.min(0, next) });
|
|
onFilterChange(true);
|
|
}
|
|
},
|
|
|
|
resetNegativeSeek() {
|
|
automat.setState({ seekMonths: 0, seekYears: 0, negativeSeekMonths: 0 });
|
|
onFilterChange(true);
|
|
},
|
|
|
|
resetFilters() {
|
|
automat.setState({
|
|
filter: '',
|
|
onlyUnpaid: false,
|
|
onlyUndelivered: false,
|
|
seekMonths: 0,
|
|
seekYears: 0,
|
|
negativeSeekMonths: 0,
|
|
});
|
|
onFilterChange(true);
|
|
},
|
|
|
|
patchRetoure(retoureId, patch) {
|
|
if (!retoureId || !patch) return;
|
|
for (const entry of filterCaches.values()) {
|
|
if (Array.isArray(entry.items)) {
|
|
let changed = false;
|
|
for (let i = 0; i < entry.items.length; i++) {
|
|
const it = entry.items[i];
|
|
if (it && (it.id === retoureId || it.manifest_id === retoureId)) {
|
|
entry.items[i] = { ...it, ...patch };
|
|
changed = true;
|
|
}
|
|
}
|
|
if (changed && entry.key === getFilterKey(automat.state)) {
|
|
automat.setState({ items: [...entry.items] });
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
// MARK: evicts a specific chunk from cache (optional filterKey, defaults to active)
|
|
evictChunk(chunkIndex, filterKey = getFilterKey(automat.state)) {
|
|
const index = Math.max(0, Number(chunkIndex) || 0);
|
|
const key = makeLruKey(filterKey, index);
|
|
if (lruChunks.has(key)) {
|
|
lruChunks.delete(key);
|
|
}
|
|
evictChunkFromMemory(filterKey, index, 'manual');
|
|
return automat.state.items;
|
|
},
|
|
|
|
// MARK: clears a specific filter cache and removes its chunks from LRU
|
|
clearFilterCache(filterKey = getFilterKey(automat.state)) {
|
|
for (const [lruKey, info] of Array.from(lruChunks.entries())) {
|
|
if (info.filterKey === filterKey) {
|
|
lruChunks.delete(lruKey);
|
|
}
|
|
}
|
|
|
|
const entry = filterCaches.get(filterKey);
|
|
if (entry) {
|
|
entry.loadedChunks.clear();
|
|
entry.items = null;
|
|
entry.total = 0;
|
|
entry.status = 'idle';
|
|
entry.error = null;
|
|
}
|
|
|
|
if (filterKey === getFilterKey(automat.state)) {
|
|
automat.setState({
|
|
items: null,
|
|
total: 0,
|
|
status: 'idle',
|
|
error: null,
|
|
});
|
|
}
|
|
|
|
recordChunkEvent({
|
|
type: 'clear_filter',
|
|
filterKey,
|
|
message: `Filter-Cache für "${formatFilterLabel(filterKey)}" geleert`,
|
|
});
|
|
notifyChunkStats();
|
|
return automat.state.items;
|
|
},
|
|
|
|
// MARK: clears all loaded chunks and filter caches from RAM
|
|
clearCache() {
|
|
clearChunkDebounce();
|
|
lruChunks.clear();
|
|
inflightChunks.clear();
|
|
|
|
for (const entry of filterCaches.values()) {
|
|
entry.loadedChunks.clear();
|
|
entry.items = null;
|
|
entry.total = 0;
|
|
entry.status = 'idle';
|
|
entry.error = null;
|
|
}
|
|
|
|
automat.setState({
|
|
items: null,
|
|
total: 0,
|
|
status: 'idle',
|
|
error: null,
|
|
});
|
|
|
|
recordChunkEvent({
|
|
type: 'clear',
|
|
message: 'Gesamter LRU-Cache und alle Filter-Caches geleert',
|
|
});
|
|
notifyChunkStats();
|
|
return automat.state.items;
|
|
},
|
|
|
|
// MARK: prefetches all remaining chunks for a filter (bounded by MAX_LRU_CHUNKS)
|
|
prefetchAllChunks(filterKey = getFilterKey(automat.state)) {
|
|
const entry = getOrCreateFilterCache(filterKey, automat.state);
|
|
const total = entry.total || automat.state.total || 0;
|
|
const chunkCount = Math.ceil(total / CHUNK_SIZE);
|
|
|
|
recordChunkEvent({
|
|
type: 'prefetch_all',
|
|
filterKey,
|
|
message: `Starte Prefetch aller ${chunkCount} Chunks für "${entry.label}"`,
|
|
});
|
|
|
|
for (let c = 0; c < chunkCount; c++) {
|
|
const inflightKey = makeLruKey(filterKey, c);
|
|
if (!entry.loadedChunks.has(c) && !inflightChunks.has(inflightKey)) {
|
|
void actions.loadChunk(c, queryEpoch, filterKey);
|
|
}
|
|
}
|
|
notifyChunkStats();
|
|
},
|
|
|
|
reset() {
|
|
queryEpoch++;
|
|
if (filterDebounceTimer) {
|
|
clearTimeout(filterDebounceTimer);
|
|
filterDebounceTimer = null;
|
|
}
|
|
clearChunkDebounce();
|
|
filterCaches.clear();
|
|
lruChunks.clear();
|
|
inflightChunks.clear();
|
|
|
|
recordChunkEvent({
|
|
type: 'reset',
|
|
message: 'Retoure-Automat und sämtliche Caches zurückgesetzt',
|
|
});
|
|
notifyChunkStats();
|
|
automat.setState(initialState);
|
|
},
|
|
};
|
|
|
|
export const retoureAutomat = new Automat(initialState, actions, { name: 'retoure' });
|
|
automat = retoureAutomat;
|
|
|
|
// MARK: exported methods for direct invocation
|
|
export function getItems() {
|
|
return actions.getItems();
|
|
}
|
|
|
|
export function requireChunk(chunkIndex, endOrOptions, maybeOptions) {
|
|
return actions.requireChunk(chunkIndex, endOrOptions, maybeOptions);
|
|
}
|
|
|
|
retoureAutomat.getItems = getItems;
|
|
retoureAutomat.requireChunk = requireChunk;
|
|
retoureAutomat.CHUNK_SIZE = CHUNK_SIZE;
|
|
retoureAutomat.MAX_LRU_CHUNKS = MAX_LRU_CHUNKS;
|
|
retoureAutomat.getChunkStats = getChunkStats;
|
|
retoureAutomat.subscribeChunkStats = subscribeChunkStats;
|
|
retoureAutomat.evictChunk = actions.evictChunk;
|
|
retoureAutomat.clearFilterCache = actions.clearFilterCache;
|
|
retoureAutomat.clearCache = actions.clearCache;
|
|
retoureAutomat.prefetchAllChunks = actions.prefetchAllChunks;
|
|
retoureAutomat.getFilterKey = getFilterKey;
|
|
retoureAutomat.formatFilterLabel = formatFilterLabel;
|
|
|
|
// Reset on logout or company change
|
|
let lastCompanyId = null;
|
|
authAutomat.subscribe((auth) => {
|
|
const companyId = auth.user?.selectedCompanyId ?? null;
|
|
if (auth.status === 'anon') {
|
|
actions.reset();
|
|
lastCompanyId = null;
|
|
return;
|
|
}
|
|
if (lastCompanyId !== null && companyId !== lastCompanyId) {
|
|
actions.reset();
|
|
}
|
|
if (auth.status === 'authed' && companyId != null) {
|
|
lastCompanyId = companyId;
|
|
void actions.requireChunk(0, 0, { immediate: true }).catch(() => {});
|
|
}
|
|
});
|
|
|
|
export default retoureAutomat;
|
|
|
|
export function selectRetoures(state = automat.state) {
|
|
return state.items;
|
|
}
|
|
|
|
export function selectRetoureTotal(state = automat.state) {
|
|
return state.total;
|
|
}
|
|
|
|
export function selectRetoureUnfilteredTotal(state = automat.state) {
|
|
return state.unfilteredTotal;
|
|
}
|
|
|