From 8f68f7d224de323e769ed2c7ac093e6dc4df35dd Mon Sep 17 00:00:00 2001 From: seb Date: Tue, 13 Oct 2026 01:50:36 +0200 Subject: [PATCH] u --- src/automats/orderAutomat.js | 425 +++++++++++++++----------- src/components/manifest/OrderList.jsx | 7 +- 2 files changed, 241 insertions(+), 191 deletions(-) diff --git a/src/automats/orderAutomat.js b/src/automats/orderAutomat.js index 3291235..4b2992b 100644 --- a/src/automats/orderAutomat.js +++ b/src/automats/orderAutomat.js @@ -10,7 +10,6 @@ import { Automat } from 'react-automat'; import { order as orderApi } from '../api'; import authAutomat from './authAutomat'; -import entityAutomat from './entityAutomat'; /** * @typedef {Object} OrderLine @@ -47,6 +46,7 @@ import entityAutomat from './entityAutomat'; export const CHUNK_SIZE = 50; const PREFETCH_CHUNKS = 2; +const CHUNK_DEBOUNCE_MS = 130; const initialState = { items: null, @@ -62,10 +62,59 @@ const initialState = { }; let automat; -let rawItems = null; +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; const loadedChunks = new Set(); const inflightChunks = new Map(); +// Clears pending debounced chunk requests +function clearChunkDebounce() { + if (chunkDebounceTimer) { + clearTimeout(chunkDebounceTimer); + chunkDebounceTimer = null; + } + pendingTargetChunks.clear(); + pendingChunkPromise = null; + pendingChunkResolve = null; + pendingChunkReject = null; +} + +// Executes chunk loading for the standstill target and prefetches lookahead chunks +function _executeRequiredChunks(chunks, targetEpoch) { + 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)); + } + + // Prefetch lookahead chunks after the highest requested chunk + const maxChunk = chunkList[chunkList.length - 1]; + const 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); + } + + return Promise.all(promises).then(() => automat.state.items); +} + // MARK: pure order helpers export function isOrderPaid(order) { if (!order) return false; @@ -118,123 +167,155 @@ export function formatNegativeSeek(months) { return `-${parts.join(' ')}`; } -// MARK: fetches a single chunk from GET /api/order +// Builds server query parameters from current automat filter state +function buildQueryParams(offset = 0, limit = CHUNK_SIZE) { + const { filter, onlyUnpaid, onlyUndelivered, negativeSeekMonths } = automat.state; + const params = { offset, limit }; + const trimmed = String(filter ?? '').trim(); + if (trimmed) params.search = trimmed; + if (onlyUnpaid) params.onlyUnpaid = true; + if (onlyUndelivered) params.onlyUndelivered = true; + if (negativeSeekMonths != null && Number(negativeSeekMonths) < 0) { + params.seekMonths = Number(negativeSeekMonths); + } + return params; +} + +// MARK: fetches a single chunk from GET /api/order with server-side filters async function fetchOrdersPage(offset = 0, limit = CHUNK_SIZE) { - const res = await orderApi.list({ offset, limit }); + const params = buildQueryParams(offset, limit); + const res = await orderApi.list(params); const orders = Array.isArray(res?.orders) ? res.orders : []; const total = Number(res?.total ?? orders.length); return { orders, total }; } -/** - * Client-side filter helper over loaded orders. - * @param {Order[]} items - * @param {string|object} filterOrOpts String filter query or options object - * @param {(order: Order) => string} [nameOf] Customer name resolver. - */ -export function filterOrders(items, filterOrOpts, nameOf) { - if (!Array.isArray(items)) return []; - const opts = typeof filterOrOpts === 'string' - ? { filter: filterOrOpts } - : (filterOrOpts ?? {}); - - const query = String(opts.filter ?? '').trim().toLowerCase(); - const onlyUnpaid = Boolean(opts.onlyUnpaid); - const onlyUndelivered = Boolean(opts.onlyUndelivered); - const seekMonths = Number(opts.negativeSeekMonths ?? 0); - const cutoff = getNegativeSeekCutoff(seekMonths); - - return items.filter((o) => { - if (!o) return false; - if (onlyUnpaid && isOrderPaid(o)) return false; - if (onlyUndelivered && isOrderDelivered(o)) return false; - if (cutoff) { - const orderDate = getOrderDate(o); - if (!orderDate || orderDate.getTime() > cutoff.getTime()) { - return false; - } - } - if (query) { - const customer = nameOf ? nameOf(o) : getCustomerName(o); - const matches = [o.number, o.externalNumber, customer] - .some((v) => String(v ?? '').toLowerCase().includes(query)); - if (!matches) return false; - } - return true; - }); -} - -function getCustomerName(order) { - if (!order?.entityId) return ''; - const entities = entityAutomat.state?.items; - if (!Array.isArray(entities)) return ''; - const entity = entities.find((e) => e.id === order.entityId); - if (!entity) return ''; - return [entity.firstName, entity.name].filter(Boolean).join(' '); -} - -function hasActiveFilters(state = automat.state) { - return Boolean( - state.filter || - state.onlyUnpaid || - state.onlyUndelivered || - state.negativeSeekMonths < 0 - ); -} - -function updatePublishedItems() { - if (rawItems === null) { - automat.setState({ items: null }); - return; +function onFilterChange(immediate = false) { + if (filterDebounceTimer) { + clearTimeout(filterDebounceTimer); + filterDebounceTimer = null; } - const state = automat.state; - if (!hasActiveFilters(state)) { - automat.setState({ - items: rawItems ? [...rawItems] : null, - total: rawItems ? rawItems.length : 0, - }); - return; + if (immediate) { + applyFilterReload(); + } else { + filterDebounceTimer = setTimeout(() => { + filterDebounceTimer = null; + applyFilterReload(); + }, 200); } - const loadedOrders = rawItems.filter(Boolean); - const filtered = filterOrders(loadedOrders, { - filter: state.filter, - onlyUnpaid: state.onlyUnpaid, - onlyUndelivered: state.onlyUndelivered, - negativeSeekMonths: state.negativeSeekMonths, - }); - automat.setState({ - items: filtered, - total: filtered.length, - }); +} + +function applyFilterReload() { + queryEpoch++; + clearChunkDebounce(); + loadedChunks.clear(); + inflightChunks.clear(); + void actions.loadChunk(0, queryEpoch); } const actions = { // MARK: returns current items and triggers chunk 0 if not loaded getItems() { if (automat.state.items === null) { - void actions.requireChunk(0); + void actions.requireChunk(0, 0, { immediate: true }); return null; } return automat.state.items; }, - // MARK: ensures chunkIndex and lookahead chunks are loaded/loading - requireChunk(chunkIndex) { - const start = Math.max(0, Number(chunkIndex) || 0); - const p = actions.loadChunk(start); - for (let c = start + 1; c <= start + PREFETCH_CHUNKS; c++) { - const total = rawItems ? rawItems.length : (automat.state.total || 0); - if (total > 0 && c * CHUNK_SIZE >= total) { - break; + // MARK: ensures chunkIndex and lookahead chunks are loaded/loading (debounced) + 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; + } } - void actions.loadChunk(c); } - return p; + + start = Math.max(0, Math.floor(start)); + end = Math.max(start, Math.floor(end)); + + // If initial items are null or immediate requested, bypass debounce and load immediately + 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); + } + + // New event tick (drag mousemove / pagination click) replaces previous target position + 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(); + + const resolve = pendingChunkResolve; + const reject = pendingChunkReject; + pendingChunkPromise = null; + pendingChunkResolve = null; + pendingChunkReject = null; + + _executeRequiredChunks(chunksToLoad, captureEpoch) + .then((res) => resolve?.(res)) + .catch((err) => reject?.(err)); + }, CHUNK_DEBOUNCE_MS); + + return pendingChunkPromise; }, // MARK: fetches a single chunk and populates prefilled array - loadChunk(chunkIndex) { + loadChunk(chunkIndex, targetEpoch = queryEpoch) { const index = Math.max(0, Number(chunkIndex) || 0); + if (targetEpoch !== queryEpoch) { + return Promise.resolve(automat.state.items); + } if (loadedChunks.has(index)) { return Promise.resolve(automat.state.items); } @@ -244,57 +325,61 @@ const actions = { const offset = index * CHUNK_SIZE; const limit = CHUNK_SIZE; - if (rawItems === null && automat.state.status === 'idle') { + if (index === 0 && automat.state.items === null) { automat.setState({ status: 'loading', error: null }); } const promise = fetchOrdersPage(offset, limit) .then(({ orders, total }) => { - const currentTotal = total > 0 ? total : (orders.length + offset); - - if (rawItems === null) { - // Pre-fill rawItems array with that many empty (null) items - rawItems = new Array(currentTotal).fill(null); - } else if (rawItems.length !== currentTotal) { - const next = new Array(currentTotal).fill(null); - const copyLen = Math.min(rawItems.length, currentTotal); - for (let i = 0; i < copyLen; i++) { - next[i] = rawItems[i]; - } - rawItems = next; + // Discard if active filter query changed while request was in flight + if (targetEpoch !== queryEpoch) { + return automat.state.items; } - // Fill in real received items + let items = automat.state.items; + const currentTotal = total > 0 ? total : 0; + + if (items === null || items.length !== currentTotal) { + // Pre-fill items array with empty (null) items based on server filtered total + items = new Array(currentTotal).fill(null); + } else { + items = [...items]; + } + + // Fill in real received items for this chunk for (let i = 0; i < orders.length; i++) { const idx = offset + i; - if (idx < rawItems.length) { - rawItems[idx] = orders[i]; + if (idx < items.length) { + items[idx] = orders[i]; } } loadedChunks.add(index); automat.setState({ + items, + total: currentTotal, status: 'ready', error: null, }); - updatePublishedItems(); // Trigger lookahead prefetching if first chunk just arrived if (index === 0) { for (let c = 1; c <= PREFETCH_CHUNKS; c++) { if (c * CHUNK_SIZE < currentTotal) { - void actions.loadChunk(c); + void actions.loadChunk(c, targetEpoch); } } } - return automat.state.items; + return items; }) .catch((err) => { - console.error(`[orderAutomat] loadChunk(${index}) error:`, err); - if (rawItems === null) { - automat.setState({ status: 'failed', error: err }); + if (targetEpoch === queryEpoch) { + console.error(`[orderAutomat] loadChunk(${index}) error:`, err); + if (index === 0 && automat.state.items === null) { + automat.setState({ status: 'failed', error: err }); + } } throw err; }) @@ -306,41 +391,20 @@ const actions = { return promise; }, - // MARK: loads all remaining chunks in the background when filtering - loadAllRemainingChunks() { - if (!rawItems) return; - const total = rawItems.length; - const totalChunks = Math.ceil(total / CHUNK_SIZE); - for (let c = 0; c < totalChunks; c++) { - if (!loadedChunks.has(c) && !inflightChunks.has(c)) { - void actions.loadChunk(c); - } - } - }, - - // MARK: filter actions + // MARK: server-side filter actions filter(query) { automat.setState({ filter: String(query ?? '') }); - updatePublishedItems(); - if (hasActiveFilters()) { - actions.loadAllRemainingChunks(); - } + onFilterChange(false); }, setOnlyUnpaid(onlyUnpaid) { automat.setState({ onlyUnpaid: Boolean(onlyUnpaid) }); - updatePublishedItems(); - if (hasActiveFilters()) { - actions.loadAllRemainingChunks(); - } + onFilterChange(true); }, setOnlyUndelivered(onlyUndelivered) { automat.setState({ onlyUndelivered: Boolean(onlyUndelivered) }); - updatePublishedItems(); - if (hasActiveFilters()) { - actions.loadAllRemainingChunks(); - } + onFilterChange(true); }, addSeekMonth() { @@ -348,10 +412,7 @@ const actions = { const seekYears = automat.state.seekYears ?? 0; const totalMonths = -(seekMonths + seekYears * 12); automat.setState({ seekMonths, negativeSeekMonths: totalMonths }); - updatePublishedItems(); - if (hasActiveFilters()) { - actions.loadAllRemainingChunks(); - } + onFilterChange(true); }, addSeekYear() { @@ -359,10 +420,7 @@ const actions = { const seekYears = (automat.state.seekYears ?? 0) + 1; const totalMonths = -(seekMonths + seekYears * 12); automat.setState({ seekYears, negativeSeekMonths: totalMonths }); - updatePublishedItems(); - if (hasActiveFilters()) { - actions.loadAllRemainingChunks(); - } + onFilterChange(true); }, addNegativeSeek(months) { @@ -374,16 +432,13 @@ const actions = { const current = Math.min(0, Number(automat.state.negativeSeekMonths ?? 0)); const next = current + months; automat.setState({ negativeSeekMonths: Math.min(0, next) }); - updatePublishedItems(); - if (hasActiveFilters()) { - actions.loadAllRemainingChunks(); - } + onFilterChange(true); } }, resetNegativeSeek() { automat.setState({ seekMonths: 0, seekYears: 0, negativeSeekMonths: 0 }); - updatePublishedItems(); + onFilterChange(true); }, resetFilters() { @@ -395,12 +450,12 @@ const actions = { seekYears: 0, negativeSeekMonths: 0, }); - updatePublishedItems(); + onFilterChange(true); }, // MARK: initial load load() { - return actions.loadChunk(0); + return actions.loadChunk(0, queryEpoch); }, // MARK: ensure loaded @@ -408,63 +463,61 @@ const actions = { if (automat.state.items !== null) { return Promise.resolve(automat.state.items); } - return actions.loadChunk(0); + return actions.loadChunk(0, queryEpoch); }, - // MARK: reload all previously loaded chunks + // MARK: reload with current active server filters async reload() { - const chunksToReload = Array.from(loadedChunks); + queryEpoch++; + clearChunkDebounce(); loadedChunks.clear(); inflightChunks.clear(); - rawItems = null; - if (chunksToReload.length === 0) { - return actions.loadChunk(0); - } - await actions.loadChunk(0); - for (const c of chunksToReload) { - if (c !== 0 && rawItems && c * CHUNK_SIZE < rawItems.length) { - void actions.loadChunk(c); - } - } + await actions.loadChunk(0, queryEpoch); return automat.state.items; }, // MARK: replace items directly replace(items) { + clearChunkDebounce(); loadedChunks.clear(); inflightChunks.clear(); - rawItems = Array.isArray(items) ? [...items] : []; - updatePublishedItems(); + const count = Array.isArray(items) ? items.length : 0; automat.setState({ + items, + total: count, status: 'ready', error: null, }); - return automat.state.items; + return items; }, // MARK: patches an order locally in the automat items cache patchOrder(id, patch) { + if (!Array.isArray(automat.state.items)) return automat.state.items; let changed = false; - if (Array.isArray(rawItems)) { - rawItems = rawItems.map((o) => { - if (o && o.id === id) { - changed = true; - return { ...o, ...patch }; - } - return o; - }); - } + const items = automat.state.items.map((o) => { + if (o && o.id === id) { + changed = true; + return { ...o, ...patch }; + } + return o; + }); if (changed) { - updatePublishedItems(); + automat.setState({ items }); } - return automat.state.items; + return items; }, // MARK: resets state reset() { + queryEpoch++; + if (filterDebounceTimer) { + clearTimeout(filterDebounceTimer); + filterDebounceTimer = null; + } + clearChunkDebounce(); loadedChunks.clear(); inflightChunks.clear(); - rawItems = null; automat.setState(initialState); }, }; @@ -477,8 +530,8 @@ export function getItems() { return actions.getItems(); } -export function requireChunk(chunkIndex) { - return actions.requireChunk(chunkIndex); +export function requireChunk(chunkIndex, endOrOptions, maybeOptions) { + return actions.requireChunk(chunkIndex, endOrOptions, maybeOptions); } orderAutomat.getItems = getItems; diff --git a/src/components/manifest/OrderList.jsx b/src/components/manifest/OrderList.jsx index b8ad2af..f6b00ea 100644 --- a/src/components/manifest/OrderList.jsx +++ b/src/components/manifest/OrderList.jsx @@ -487,14 +487,11 @@ export class OrderList extends PureComponent { const startChunk = Math.floor(startIndex / CHUNK_SIZE); const endChunk = Math.floor(endIndex / CHUNK_SIZE); - orderAutomat.requireChunk(startChunk); - if (endChunk !== startChunk) { - orderAutomat.requireChunk(endChunk); - } + orderAutomat.requireChunk(startChunk, endChunk); } handleRetry() { - void orderAutomat.actions.requireChunk(0).catch(() => {}); + void orderAutomat.actions.requireChunk(0, 0, { immediate: true }).catch(() => {}); } handleCreate() {