u
This commit is contained in:
@@ -3,9 +3,8 @@
|
||||
* @description Manages cached and paginated company sales orders (`GET /api/order`).
|
||||
*
|
||||
* Upstream Triggers:
|
||||
* - `authAutomat`: Triggers `actions.load()` on `'authed'` with a `selectedCompanyId`,
|
||||
* and `actions.reset()` on `'anon'`.
|
||||
* - UI / Routes: Calls to `load({ offset, limit })`, `setPage(page)`, or `reload()`.
|
||||
* - `authAutomat`: Triggers `actions.reset()` on `'anon'` or when `selectedCompanyId` changes.
|
||||
* - UI / Routes: On-demand calls to `ensureLoaded()`, `load()`, or `reload()`.
|
||||
*/
|
||||
|
||||
import { Automat } from 'react-automat';
|
||||
@@ -53,39 +52,25 @@ const initialState = {
|
||||
total: 0,
|
||||
offset: 0,
|
||||
limit: 20,
|
||||
hasMore: false,
|
||||
loadingMore: false,
|
||||
status: 'idle',
|
||||
error: null,
|
||||
};
|
||||
|
||||
let automat;
|
||||
let inflightLoad = null;
|
||||
let inflightMore = null;
|
||||
const FETCH_PAGE_SIZE = 100;
|
||||
|
||||
// MARK: pages through GET /api/order until every order is collected
|
||||
async function fetchAllOrders() {
|
||||
let offset = 0;
|
||||
let total = Infinity;
|
||||
const collected = [];
|
||||
while (offset === 0 || collected.length < total) {
|
||||
const res = await orderApi.list({ offset, limit: FETCH_PAGE_SIZE });
|
||||
if (offset === 0) total = Number(res?.total ?? res?.orders?.length ?? 0);
|
||||
const page = Array.isArray(res?.orders) ? res.orders : [];
|
||||
collected.push(...page);
|
||||
offset += page.length;
|
||||
if (page.length === 0) break;
|
||||
}
|
||||
return collected;
|
||||
// MARK: fetches a single page from GET /api/order
|
||||
async function fetchOrdersPage(offset = 0, limit = FETCH_PAGE_SIZE) {
|
||||
const res = await orderApi.list({ offset, limit });
|
||||
const orders = Array.isArray(res?.orders) ? res.orders : [];
|
||||
const total = Number(res?.total ?? orders.length);
|
||||
return { orders, total };
|
||||
}
|
||||
|
||||
const applyAll = (orders) => ({
|
||||
items: orders,
|
||||
total: orders.length,
|
||||
offset: 0,
|
||||
limit: Math.max(orders.length, 1),
|
||||
status: 'ready',
|
||||
error: null,
|
||||
});
|
||||
|
||||
/**
|
||||
* Client-side filter over number, external reference and (resolved) customer name.
|
||||
* @param {Order[]} items
|
||||
@@ -107,16 +92,43 @@ const actions = {
|
||||
},
|
||||
|
||||
/**
|
||||
* Loads all orders, deduplicating concurrent callers.
|
||||
* Synchronously returns current items and triggers loading if idle.
|
||||
* On remounts, directly returns cached items from the automat.
|
||||
*
|
||||
* @param {(order: Order) => string} [nameOf] Optional customer name resolver.
|
||||
* @returns {Order[]}
|
||||
*/
|
||||
getOrLoad(nameOf) {
|
||||
if (automat.state.status === 'idle') {
|
||||
void actions.load().catch(() => {});
|
||||
}
|
||||
const { items, filter } = automat.state;
|
||||
if (filter) {
|
||||
return filterOrders(items, filter, nameOf);
|
||||
}
|
||||
return items;
|
||||
},
|
||||
|
||||
/**
|
||||
* Loads the initial 100 orders, deduplicating concurrent callers.
|
||||
*
|
||||
* @returns {Promise<Order[]>}
|
||||
*/
|
||||
load() {
|
||||
if (inflightLoad) return inflightLoad;
|
||||
automat.setState({ status: 'loading', error: null });
|
||||
inflightLoad = fetchAllOrders()
|
||||
.then((orders) => {
|
||||
automat.setState(applyAll(orders));
|
||||
inflightLoad = fetchOrdersPage(0, FETCH_PAGE_SIZE)
|
||||
.then(({ orders, total }) => {
|
||||
automat.setState({
|
||||
items: orders,
|
||||
total,
|
||||
offset: 0,
|
||||
limit: FETCH_PAGE_SIZE,
|
||||
hasMore: orders.length < total && orders.length >= FETCH_PAGE_SIZE,
|
||||
loadingMore: false,
|
||||
status: 'ready',
|
||||
error: null,
|
||||
});
|
||||
return orders;
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -128,14 +140,61 @@ const actions = {
|
||||
},
|
||||
|
||||
/**
|
||||
* Silently re-fetches all orders without flashing loading state.
|
||||
* Loads the next batch of 100 orders when pagination approaches the end.
|
||||
*
|
||||
* @returns {Promise<Order[]>}
|
||||
*/
|
||||
loadMore() {
|
||||
const { items, total, status, loadingMore } = automat.state;
|
||||
if (status !== 'ready' || loadingMore) return Promise.resolve(items);
|
||||
if (total > 0 && items.length >= total) return Promise.resolve(items);
|
||||
if (inflightMore) return inflightMore;
|
||||
|
||||
automat.setState({ loadingMore: true });
|
||||
const offset = items.length;
|
||||
inflightMore = fetchOrdersPage(offset, FETCH_PAGE_SIZE)
|
||||
.then(({ orders: nextBatch, total: newTotal }) => {
|
||||
const existingIds = new Set(automat.state.items.map((o) => o.id));
|
||||
const uniqueNext = nextBatch.filter((o) => !existingIds.has(o.id));
|
||||
const merged = [...automat.state.items, ...uniqueNext];
|
||||
const finalTotal = Math.max(newTotal, merged.length);
|
||||
automat.setState({
|
||||
items: merged,
|
||||
total: finalTotal,
|
||||
hasMore: nextBatch.length > 0 && merged.length < finalTotal,
|
||||
loadingMore: false,
|
||||
});
|
||||
return merged;
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[orderAutomat] loadMore error:', err);
|
||||
automat.setState({ loadingMore: false });
|
||||
return automat.state.items;
|
||||
})
|
||||
.finally(() => {
|
||||
inflightMore = null;
|
||||
});
|
||||
|
||||
return inflightMore;
|
||||
},
|
||||
|
||||
/**
|
||||
* Silently re-fetches loaded orders without flashing loading state.
|
||||
*
|
||||
* @returns {Promise<Order[]>}
|
||||
*/
|
||||
async reload() {
|
||||
try {
|
||||
const orders = await fetchAllOrders();
|
||||
automat.setState(applyAll(orders));
|
||||
const currentCount = Math.max(FETCH_PAGE_SIZE, automat.state.items.length);
|
||||
const { orders, total } = await fetchOrdersPage(0, currentCount);
|
||||
automat.setState({
|
||||
items: orders,
|
||||
total,
|
||||
hasMore: orders.length < total,
|
||||
loadingMore: false,
|
||||
status: 'ready',
|
||||
error: null,
|
||||
});
|
||||
return orders;
|
||||
} catch (error) {
|
||||
automat.setState({ error });
|
||||
@@ -143,7 +202,6 @@ const actions = {
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Ensures orders are loaded once the selected company is known.
|
||||
*
|
||||
@@ -166,17 +224,35 @@ const actions = {
|
||||
automat.setState({
|
||||
items,
|
||||
total: items.length,
|
||||
hasMore: false,
|
||||
loadingMore: false,
|
||||
status: 'ready',
|
||||
error: null,
|
||||
});
|
||||
return items;
|
||||
},
|
||||
|
||||
/**
|
||||
* Patches an order locally in the automat items cache.
|
||||
*
|
||||
* @param {number|string} id Order ID.
|
||||
* @param {Partial<Order>} patch Partial properties to update.
|
||||
* @returns {Order[]}
|
||||
*/
|
||||
patchOrder(id, patch) {
|
||||
const items = automat.state.items.map((o) =>
|
||||
o.id === id ? { ...o, ...patch } : o,
|
||||
);
|
||||
automat.setState({ items });
|
||||
return items;
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets to idle state (called on logout).
|
||||
*/
|
||||
reset() {
|
||||
inflightLoad = null;
|
||||
inflightMore = null;
|
||||
automat.setState(initialState);
|
||||
},
|
||||
};
|
||||
@@ -184,13 +260,20 @@ const actions = {
|
||||
export const orderAutomat = new Automat(initialState, actions, { name: 'order' });
|
||||
automat = orderAutomat;
|
||||
|
||||
// Load on session/company establishment, reset on logout.
|
||||
// Reset on logout or company change (lazy-loaded on demand by views via ensureLoaded).
|
||||
let lastCompanyId = null;
|
||||
authAutomat.subscribe((auth) => {
|
||||
const companyId = auth.user?.selectedCompanyId;
|
||||
if (auth.status === 'authed' && companyId) {
|
||||
void actions.load().catch(() => {});
|
||||
} else if (auth.status === 'anon') {
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -204,6 +287,16 @@ export function selectOrderTotal(state = automat.state) {
|
||||
return state.total;
|
||||
}
|
||||
|
||||
/** Selects whether more orders can be fetched from backend */
|
||||
export function selectHasMoreOrders(state = automat.state) {
|
||||
return state.hasMore;
|
||||
}
|
||||
|
||||
/** Selects whether an incremental fetch is currently in flight */
|
||||
export function selectIsLoadingMoreOrders(state = automat.state) {
|
||||
return state.loadingMore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates client pagination metadata.
|
||||
* Current Page: Math.floor(offset / limit) + 1
|
||||
|
||||
@@ -6,6 +6,8 @@ import CircularProgress from '@mui/material/CircularProgress';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import ListItemButton from '@mui/material/ListItemButton';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import Checkbox from '@mui/material/Checkbox';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
|
||||
import { enqueueSnackbar } from 'notistack';
|
||||
import SingleLineTextEdit from 'dashgui/SingleLineTextEdit';
|
||||
@@ -35,6 +37,14 @@ function orderGrossTotal(lines) {
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function isOrderPaid(order) {
|
||||
return Boolean(order.paid ?? order.payed ?? order.isPaid ?? order.is_paid ?? order.paidAt);
|
||||
}
|
||||
|
||||
function isOrderDelivered(order) {
|
||||
return Boolean(order.delivered ?? order.isDelivered ?? order.is_delivered ?? order.deliveredAt);
|
||||
}
|
||||
|
||||
const cfg = manifestConfig('order');
|
||||
|
||||
const rowSx = {
|
||||
@@ -54,9 +64,16 @@ const ellipsisSx = { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: '
|
||||
* (`<Row item index />`), so the list publishes callbacks and the party map
|
||||
* here on every render.
|
||||
*/
|
||||
const rowContext = { partiesById: {}, busyId: null, onOpen: null, onDelete: null };
|
||||
const rowContext = {
|
||||
partiesById: {},
|
||||
busyId: null,
|
||||
onOpen: null,
|
||||
onDelete: null,
|
||||
onTogglePaid: null,
|
||||
onToggleDelivered: null,
|
||||
};
|
||||
|
||||
// MARK: one row rendered by FillSpace
|
||||
// MARK: <OrderRow/>
|
||||
class OrderRow extends PureComponent {
|
||||
partyName(partyId) {
|
||||
if (partyId == null) return '–';
|
||||
@@ -76,9 +93,11 @@ class OrderRow extends PureComponent {
|
||||
);
|
||||
}
|
||||
|
||||
const { busyId, onOpen, onDelete } = rowContext;
|
||||
const { busyId, onOpen, onDelete, onTogglePaid, onToggleDelivered } = rowContext;
|
||||
const lines = order.lines ?? [];
|
||||
const gross = orderGrossTotal(lines);
|
||||
const paid = isOrderPaid(order);
|
||||
const delivered = isOrderDelivered(order);
|
||||
|
||||
return (
|
||||
<ListItemButton divider sx={rowSx} onClick={() => onOpen?.(order)}>
|
||||
@@ -91,13 +110,48 @@ class OrderRow extends PureComponent {
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ width: 100, flexShrink: 0, minWidth: 0 }}>
|
||||
<Typography variant="body2" color="text.secondary" sx={ellipsisSx}>
|
||||
{order.date ? formatDate(order.date) : '–'}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography variant="body1" sx={{ fontWeight: 500, ...ellipsisSx }}>
|
||||
{this.partyName(order.entityId)}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary" sx={ellipsisSx}>
|
||||
{cfg.dateLabel} {formatDate(order.date)}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ width: 72, flexShrink: 0, display: 'flex', justifyContent: 'center' }}>
|
||||
<Tooltip title={paid ? 'Bezahlt' : 'Offen (nicht bezahlt)'}>
|
||||
<span>
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={paid}
|
||||
color="success"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onChange={(e) => onTogglePaid?.(order, e.target.checked)}
|
||||
inputProps={{ 'aria-label': `Auftrag ${order.number} bezahlt` }}
|
||||
sx={{ p: 0.5 }}
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ width: 72, flexShrink: 0, display: 'flex', justifyContent: 'center' }}>
|
||||
<Tooltip title={delivered ? 'Geliefert' : 'Ausstehend (nicht geliefert)'}>
|
||||
<span>
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={delivered}
|
||||
color="primary"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onChange={(e) => onToggleDelivered?.(order, e.target.checked)}
|
||||
inputProps={{ 'aria-label': `Auftrag ${order.number} geliefert` }}
|
||||
sx={{ p: 0.5 }}
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
|
||||
<Chip
|
||||
@@ -139,7 +193,7 @@ class OrderRow extends PureComponent {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: search + create bar
|
||||
// MARK: <OrderSearchField(>)
|
||||
class OrderSearchField extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
@@ -185,7 +239,7 @@ class OrderSearchField extends PureComponent {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: list page
|
||||
// MARK: <OrderList/>
|
||||
export class OrderList extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
@@ -193,6 +247,7 @@ export class OrderList extends PureComponent {
|
||||
this.state = {
|
||||
status: s.status === 'ready' ? 'ready' : 'loading',
|
||||
error: s.error ? backendErrorFrom(s.error) : null,
|
||||
filteredItems: orderAutomat.actions.getOrLoad(),
|
||||
items: s.items ?? [],
|
||||
filter: s.filter ?? '',
|
||||
partiesById: {},
|
||||
@@ -204,14 +259,56 @@ export class OrderList extends PureComponent {
|
||||
this.handleCreate = this.handleCreate.bind(this);
|
||||
this.handleOpen = this.handleOpen.bind(this);
|
||||
this.handleDelete = this.handleDelete.bind(this);
|
||||
this.handleTogglePaid = this.handleTogglePaid.bind(this);
|
||||
this.handleToggleDelivered = this.handleToggleDelivered.bind(this);
|
||||
this.handlePageChange = this.handlePageChange.bind(this);
|
||||
this.nameOf = this.nameOf.bind(this);
|
||||
}
|
||||
|
||||
async handleTogglePaid(order, checked) {
|
||||
if (this.state.busyId != null) return;
|
||||
const patch = { paid: checked, payed: checked, isPaid: checked };
|
||||
orderAutomat.actions.patchOrder(order.id, patch);
|
||||
try {
|
||||
await orderApi.update(order.id, { paid: checked });
|
||||
enqueueSnackbar(checked ? 'Auftrag als bezahlt markiert' : 'Auftrag als unbezahlt markiert', {
|
||||
variant: 'info',
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[OrderList] update paid on backend failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
async handleToggleDelivered(order, checked) {
|
||||
if (this.state.busyId != null) return;
|
||||
const patch = { delivered: checked, isDelivered: checked };
|
||||
orderAutomat.actions.patchOrder(order.id, patch);
|
||||
try {
|
||||
await orderApi.update(order.id, { delivered: checked });
|
||||
enqueueSnackbar(checked ? 'Auftrag als geliefert markiert' : 'Auftrag als ungeliefert markiert', {
|
||||
variant: 'info',
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[OrderList] update delivered on backend failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
handlePageChange(page, meta) {
|
||||
const pageCount = meta?.pageCount ?? 1;
|
||||
// Load next batch when the pagination comes close to the end (within 2 pages).
|
||||
if (pageCount - page <= 2) {
|
||||
void orderAutomat.actions.loadMore();
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this._cancelled = false;
|
||||
this.unsub = orderAutomat.subscribe(this, (state) => ({
|
||||
items: state.items ?? [],
|
||||
filter: state.filter ?? '',
|
||||
filteredItems: state.filter
|
||||
? filterOrders(state.items ?? [], state.filter, this.nameOf)
|
||||
: (state.items ?? []),
|
||||
status: state.status,
|
||||
error: state.error ? backendErrorFrom(state.error) : null,
|
||||
}));
|
||||
@@ -226,15 +323,18 @@ export class OrderList extends PureComponent {
|
||||
async loadAll() {
|
||||
try {
|
||||
const parties = await loadParties('order');
|
||||
if (!this._cancelled) this.setState({ partiesById: cfg.partiesByIdFromList(parties) });
|
||||
if (!this._cancelled) {
|
||||
const partiesById = cfg.partiesByIdFromList(parties);
|
||||
this.setState((prev) => ({
|
||||
partiesById,
|
||||
filteredItems: prev.filter
|
||||
? filterOrders(prev.items, prev.filter, (o) => partyDisplayName('order', partiesById[o.entityId]))
|
||||
: prev.filteredItems,
|
||||
}));
|
||||
}
|
||||
} catch {
|
||||
// Non-fatal: names fall back to ids.
|
||||
}
|
||||
try {
|
||||
await orderAutomat.actions.ensureLoaded();
|
||||
} catch {
|
||||
// Surfaced through automat state.
|
||||
}
|
||||
}
|
||||
|
||||
nameOf(order) {
|
||||
@@ -243,7 +343,7 @@ export class OrderList extends PureComponent {
|
||||
}
|
||||
|
||||
handleRetry() {
|
||||
void orderAutomat.actions.load().catch(() => {});
|
||||
void orderAutomat.actions.load().catch(() => { });
|
||||
}
|
||||
|
||||
handleCreate() {
|
||||
@@ -270,7 +370,7 @@ export class OrderList extends PureComponent {
|
||||
}
|
||||
|
||||
render() {
|
||||
const { status, error, items, filter, partiesById, busyId } = this.state;
|
||||
const { status, error, items, filteredItems, partiesById, busyId } = this.state;
|
||||
|
||||
if (status === 'loading' || status === 'idle') {
|
||||
return (
|
||||
@@ -287,8 +387,10 @@ export class OrderList extends PureComponent {
|
||||
rowContext.busyId = busyId;
|
||||
rowContext.onOpen = this.handleOpen;
|
||||
rowContext.onDelete = this.handleDelete;
|
||||
rowContext.onTogglePaid = this.handleTogglePaid;
|
||||
rowContext.onToggleDelivered = this.handleToggleDelivered;
|
||||
|
||||
const rows = filterOrders(items, filter, this.nameOf);
|
||||
const rows = filteredItems ?? [];
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -308,6 +410,36 @@ export class OrderList extends PureComponent {
|
||||
items={rows}
|
||||
totalCount={items.length}
|
||||
renderItem={OrderRow}
|
||||
header={
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
height: 36,
|
||||
minHeight: 36,
|
||||
px: 2,
|
||||
gap: 1.5,
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
color: 'text.secondary',
|
||||
typography: 'caption',
|
||||
fontWeight: 600,
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.04em',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
>
|
||||
<Box sx={{ width: 120, flexShrink: 0 }}>Nr. / Ref.</Box>
|
||||
<Box sx={{ width: 100, flexShrink: 0 }}>Datum</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>Kunde</Box>
|
||||
<Box sx={{ width: 72, flexShrink: 0, textAlign: 'center' }}>Bezahlt</Box>
|
||||
<Box sx={{ width: 72, flexShrink: 0, textAlign: 'center' }}>Geliefert</Box>
|
||||
<Box sx={{ width: 64, flexShrink: 0, textAlign: 'center' }}>Pos.</Box>
|
||||
<Box sx={{ width: 96, flexShrink: 0, textAlign: 'right' }}>Gesamt</Box>
|
||||
<Box sx={{ width: 40, flexShrink: 0 }} />
|
||||
</Box>
|
||||
}
|
||||
onPageChange={this.handlePageChange}
|
||||
/>
|
||||
)}
|
||||
</PanelTile>
|
||||
|
||||
Reference in New Issue
Block a user