diff --git a/.changeset/37844-kanban-swimlane-whole-counts.md b/.changeset/37844-kanban-swimlane-whole-counts.md new file mode 100644 index 00000000000..cc75923669e --- /dev/null +++ b/.changeset/37844-kanban-swimlane-whole-counts.md @@ -0,0 +1,10 @@ +--- +'@object-ui/plugin-kanban': patch +--- + +fix(kanban): a windowed swimlane board counts each whole swimlane, and each whole column when it queries itself + +Clause-②: no +Metadata-protocol: none + +A kanban drawn in swimlanes that holds only a window of its query (a page a list view hands it, or its own fetch that filled its `limit`) wrote each swimlane row's count from the cards it held, marked `+`, and a board that queried itself wrote its column counts the same way. Such a board now asks one grouped read on the lane field and the swimlane field together, each group's record count under the board's filter and search, and writes every swimlane row's whole count from it; a board that queries itself also writes every column's whole count from the same read. A board that holds every record of its query asks nothing more. A source with no grouped door, or a read that is refused or cut, keeps the counts marked `+`, as before. Nothing to migrate. diff --git a/ui/packages/plugin-kanban/src/KanbanBoardCore.tsx b/ui/packages/plugin-kanban/src/KanbanBoardCore.tsx index 1b322f8f1bf..c41a5a2d663 100644 --- a/ui/packages/plugin-kanban/src/KanbanBoardCore.tsx +++ b/ui/packages/plugin-kanban/src/KanbanBoardCore.tsx @@ -83,6 +83,12 @@ export interface KanbanBoardCoreProps { * reason: only `ObjectKanban`, which asks the grouped lane read, supplies it. */ laneCounts?: KanbanBoardProps['laneCounts']; + /** + * Each swimlane row's whole record count on a windowed board — see + * `KanbanBoardProps.swimlaneCounts` (objectstack#37844). A PROP for the + * reason `laneCounts` is. + */ + swimlaneCounts?: KanbanBoardProps['swimlaneCounts']; /** * Draw the trailing "Uncategorized" lane even when no loaded card lands in * it: its records sit past the page (objectstack#37516). A PROP for the @@ -144,6 +150,7 @@ export const KanbanBoardCore: React.FC = ({ dropBlockedReason, onLaneRowsChange, laneCounts, + swimlaneCounts, keepUncolumned, quickAdd, onQuickAdd, @@ -184,6 +191,7 @@ export const KanbanBoardCore: React.FC = ({ swimlaneField={schema.swimlaneField} countsAreWindowed={schema.countsAreWindowed} laneCounts={laneCounts} + swimlaneCounts={swimlaneCounts} /> ); diff --git a/ui/packages/plugin-kanban/src/KanbanImpl.tsx b/ui/packages/plugin-kanban/src/KanbanImpl.tsx index 19e29a2b1b3..b765e5b372e 100644 --- a/ui/packages/plugin-kanban/src/KanbanImpl.tsx +++ b/ui/packages/plugin-kanban/src/KanbanImpl.tsx @@ -290,6 +290,18 @@ export interface KanbanBoardProps { * (`swimlaneCountIsWhole`). A PROP, never a schema key. */ laneCounts?: Readonly> | null + /** + * objectstack#37844 — each swimlane row's whole record count, by the key + * `laneKeyOf` gives the swimlane value (the no-value swimlane under `''`), + * on a board drawn in swimlanes that holds a window of its query. + * `ObjectKanban` reads it off one grouped read on the lane field and the + * swimlane field (`readLaneCounts` folded by the swimlane key). Absent: the + * row counts its cards, marked `+` where `swimlaneCountIsWhole` says the + * board holds part of its query. `null`: the read has not answered or cannot + * (no door, a refusal, a cut answer), so the row stays marked. A PROP, never + * a schema key. + */ + swimlaneCounts?: Readonly> | null /** * Whether the cards may be dragged at all (default `true`). `ObjectKanban` * passes `false` when the caller may not make the move its `onCardMove` @@ -887,6 +899,26 @@ function swimlaneCountIsWhole( return true } +/** + * objectstack#37844 — a swimlane row's whole count from the swimlane read + * (`KanbanBoardProps.swimlaneCounts`), or `null` where it gives none and the + * row falls back to its cards (`swimlaneCountIsWhole`). The no-value row + * (`UNCATEGORIZED_LANE`) reads the read's no-value group (`''`); a row keyed + * `''` (a stored empty text) shares that group with it, so it reads none. A + * row the whole answer names no group for holds no record of the query when it + * draws no card, and is a floor when it draws some (a write landed between the + * two reads). + */ +function swimlaneRowCount( + swimlaneCounts: Readonly> | null | undefined, + lane: string, + cards: number, +): { count: number; atLeast: boolean } | null { + if (!swimlaneCounts) return null + if (lane === '') return null + return wholeLaneCount(swimlaneCounts, lane === UNCATEGORIZED_LANE ? '' : lane, cards) +} + /** * What a lane header shows IN PLACE OF its count while the board's records * have not settled (objectstack#30431). @@ -1408,7 +1440,7 @@ function moveOutcomeSentence(outcome: unknown, movedSentence: string): string | return movedSentence } -export default function KanbanBoard({ columns, onCardMove, onCardClick, className, quickAdd, onQuickAdd, coverImageField, conditionalFormatting, objectFields, swimlaneTargetDef, swimlaneField, countsAreWindowed, laneCounts, cardsMovable = true, rowOpensRecord = true, canDropCard, dropBlockedReason, onLaneRowsChange }: KanbanBoardProps) { +export default function KanbanBoard({ columns, onCardMove, onCardClick, className, quickAdd, onQuickAdd, coverImageField, conditionalFormatting, objectFields, swimlaneTargetDef, swimlaneField, countsAreWindowed, laneCounts, swimlaneCounts, cardsMovable = true, rowOpensRecord = true, canDropCard, dropBlockedReason, onLaneRowsChange }: KanbanBoardProps) { const hasDnd = useHasDndProvider() if (hasDnd) { @@ -1416,7 +1448,7 @@ export default function KanbanBoard({ columns, onCardMove, onCardClick, classNam - {(dnd) => } + {(dnd) => } @@ -1426,13 +1458,13 @@ export default function KanbanBoard({ columns, onCardMove, onCardClick, classNam return ( - + ) } -function KanbanBoardInner({ columns, onCardMove, onCardClick, className, dnd, quickAdd, onQuickAdd, coverImageField: _coverImageField, conditionalFormatting, objectFields, swimlaneTargetDef, swimlaneField, countsAreWindowed, laneCounts, canDropCard, dropBlockedReason, onLaneRowsChange }: KanbanBoardProps & { dnd: ReturnType | null }) { +function KanbanBoardInner({ columns, onCardMove, onCardClick, className, dnd, quickAdd, onQuickAdd, coverImageField: _coverImageField, conditionalFormatting, objectFields, swimlaneTargetDef, swimlaneField, countsAreWindowed, laneCounts, swimlaneCounts, canDropCard, dropBlockedReason, onLaneRowsChange }: KanbanBoardProps & { dnd: ReturnType | null }) { const { t } = useKanbanT() // The prefix of each swimlane cell's drop-reason element id (#27099). const dropReasonIdBase = React.useId() @@ -2246,7 +2278,10 @@ function KanbanBoardInner({ columns, onCardMove, onCardClick, className, dnd, qu ▶ {laneLabel} - {recordsSettled ? `(${laneCountLabel(laneCardCount, !swimlaneCountIsWhole(laneCounts, boardColumns, countsAreWindowed))})` : } + {recordsSettled + ? `(${countText(swimlaneRowCount(swimlaneCounts, lane, laneCardCount) + ?? { count: laneCardCount, atLeast: !swimlaneCountIsWhole(laneCounts, boardColumns, countsAreWindowed) })})` + : } diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.swimlaneStatistic-37326.test.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.swimlaneStatistic-37326.test.tsx index e94ecded550..8d6c3cd040d 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.swimlaneStatistic-37326.test.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.swimlaneStatistic-37326.test.tsx @@ -89,21 +89,29 @@ const deals = (stage: string, n: number): Row[] => // 20 open deals (amounts 0 … 19, sum 190), 4 won (sum 6). const ROWS = [...deals('open', 20), ...deals('won', 4)]; -/** A grouped aggregate over `rows` as the platform's door answers it. */ -function groupHeadersOver(rows: Row[]) { +/** + * A grouped aggregate over `rows` as the platform's door answers it: one group + * per distinct value of every `groupBy` key (objectstack#37844 asks two). + * `cut` answers the first two groups and `hasMore`, as the door cuts a grouped + * read to its default page size. + */ +function groupHeadersOver(rows: Row[], cut = false) { const store = new ValueDataSource({ items: rows }); return vi.fn(async (_object: string, query: any) => { const kept = extractRecords( await store.find(OBJECT, { ...(query.where ? { $filter: query.where } : {}), $top: 100000 } as any), ) as Row[]; - const key = query.groupBy[0]; - const groups = new Map(); + const keys: string[] = query.groupBy; + const groups = new Map(); for (const row of kept) { - const k = row[key] ?? null; - groups.set(k, [...(groups.get(k) ?? []), row]); + const values = keys.map((key) => row[key] ?? null); + const id = JSON.stringify(values); + const group = groups.get(id) ?? { values, members: [] }; + group.members.push(row); + groups.set(id, group); } - return [...groups].map(([k, members]) => { - const out: Row = { [key]: k }; + const answer: Row[] & { hasMore?: boolean } = [...groups.values()].map(({ values: k, members }) => { + const out: Row = Object.fromEntries(keys.map((key, i) => [key, k[i]])); for (const agg of query.aggregations) { const values = members.map((m) => m[agg.field]) as number[]; out[agg.alias] = agg.function === 'count' @@ -118,10 +126,14 @@ function groupHeadersOver(rows: Row[]) { } return out; }); + if (!cut) return answer; + const partial: Row[] & { hasMore?: boolean } = answer.slice(0, 2); + partial.hasMore = true; + return partial; }); } -function adapter(rows: Row[], door: 'answers' | 'refuses' = 'answers') { +function adapter(rows: Row[], door: 'answers' | 'refuses' | 'cuts' | 'none' = 'answers') { const store = new ValueDataSource({ items: rows }); return { find: vi.fn(async (object: string, params: any) => store.find(object, params)), @@ -130,19 +142,23 @@ function adapter(rows: Row[], door: 'answers' | 'refuses' = 'answers') { update: vi.fn(), delete: vi.fn(), getObjectSchema: vi.fn(async () => DEF), - queryGroupHeaders: door === 'answers' - ? groupHeadersOver(rows) - : vi.fn(async () => { throw Object.assign(new Error('forbidden'), { status: 403 }); }), + ...(door === 'none' + ? {} + : { + queryGroupHeaders: door === 'refuses' + ? vi.fn(async () => { throw Object.assign(new Error('forbidden'), { status: 403 }); }) + : groupHeadersOver(rows, door === 'cuts'), + }), } as any; } const SWIMLANES = { swimlaneField: 'region' }; -function mount(source: any, summary: unknown, handed?: { rows: Row[] }) { +function mount(source: any, summary: unknown, handed?: { rows: Row[] }, extra: Record = {}) { return render( @@ -189,22 +205,30 @@ describe('a swimlane board draws the view\'s lane statistic (objectstack#37326)' expect(footRow(container)!.textContent).toContain('Count'); }); - it('(c) on a page handed in with its query, a column counts the whole lane and a swimlane row is marked a floor', async () => { + it('(c) on a page handed in with its query, a column counts the whole lane and a swimlane row its whole swimlane (objectstack#37844)', async () => { const source = adapter(ROWS); - // The page: 3 open deals, 1 won; the query holds 20 and 4. + // The page: 3 open deals, 1 won; the query holds 20 and 4, 12 north and 12 south. const { container } = mount(source, { type: 'sum', field: 'amount' }, { rows: [...deals('open', 3), ...deals('won', 1)] }); await waitFor(() => expect(columnCounts(container)).toEqual(['20', '4'])); expect(footFigures(container)).toEqual(['190', '6']); - // north holds open-000, open-002, won-000 on the page; south open-001. - expect(swimlaneCounts(container)).toEqual(['3+', '1+']); - expect(source.queryGroupHeaders).toHaveBeenCalledTimes(1); + // The page holds 3 north and 1 south; the swimlane read counts 12 and 12. + await waitFor(() => expect(swimlaneCounts(container)).toEqual(['12', '12'])); + // The lane read, then ONE read on both keys, counting each group. + expect(source.queryGroupHeaders).toHaveBeenCalledTimes(2); + expect(source.queryGroupHeaders.mock.calls[1][1]).toEqual({ + groupBy: ['stage', 'region'], + aggregations: [{ function: 'count', alias: 'count' }], + }); expect(source.find).not.toHaveBeenCalled(); }); - it('(d) CONTROL: handed every record of its query, every count is bare', async () => { - const { container } = mount(adapter(ROWS), undefined, { rows: ROWS }); + it('(d) CONTROL: handed every record of its query, every count is bare, and no swimlane read is asked', async () => { + const source = adapter(ROWS); + const { container } = mount(source, undefined, { rows: ROWS }); await waitFor(() => expect(columnCounts(container)).toEqual(['20', '4'])); expect(swimlaneCounts(container)).toEqual(['12', '12']); + expect(source.queryGroupHeaders).toHaveBeenCalledTimes(1); + expect(source.queryGroupHeaders.mock.calls[0][1].groupBy).toEqual(['stage']); }); it('(e) a refused read marks the page\'s column counts `+`, and draws no figure', async () => { @@ -216,10 +240,13 @@ describe('a swimlane board draws the view\'s lane statistic (objectstack#37326)' expect(footFigures(container)).toEqual([null, null]); }); - it('(f) CONTROL: with no statistic the board draws no foot row', async () => { - const { container } = mount(adapter(ROWS), undefined); + it('(f) CONTROL: with no statistic the board draws no foot row, and a board holding every record asks no read', async () => { + const source = adapter(ROWS); + const { container } = mount(source, undefined); await waitFor(() => expect(swimlaneCounts(container)).toEqual(['12', '12'])); expect(footRow(container)).toBeNull(); + expect(columnCounts(container)).toEqual(['20', '4']); + expect(source.queryGroupHeaders).not.toHaveBeenCalled(); }); // 20 open deals (amounts 0 … 19), 4 won (0 … 3). @@ -237,6 +264,68 @@ describe('a swimlane board draws the view\'s lane statistic (objectstack#37326)' }); }); +/** + * objectstack#37844 — a board drawn in swimlanes that queries its own cards + * through a window (`limit` 10 over the query's 24 records: 10 open, all + * north and south alternating, 5 + 5) reads every swimlane row's count and + * every column's count whole from ONE grouped read on both keys. + */ +describe('a windowed swimlane board counts each whole swimlane and column from one two-key read (objectstack#37844)', () => { + const WINDOW = { limit: 10 }; + + it('a board that queries itself through a full window counts 12 and 12 swimlanes, 20 and 4 columns', async () => { + const source = adapter(ROWS); + const { container } = mount(source, undefined, undefined, WINDOW); + await waitFor(() => expect(swimlaneCounts(container)).toEqual(['12', '12'])); + expect(columnCounts(container)).toEqual(['20', '4']); + // The window: 10 cards, all open. + expect(container.querySelectorAll('[role="listitem"]')).toHaveLength(10); + expect(source.find).toHaveBeenCalledTimes(1); + expect(source.queryGroupHeaders).toHaveBeenCalledTimes(1); + expect(source.queryGroupHeaders.mock.calls[0][1]).toEqual({ + groupBy: ['stage', 'region'], + aggregations: [{ function: 'count', alias: 'count' }], + }); + }); + + it('reads under the board\'s own filter', async () => { + const source = adapter(ROWS); + // amount >= 2: open 2 … 19 (18: 9 north, 9 south), won 2, 3 (north, south). + const { container } = mount(source, undefined, undefined, { ...WINDOW, filter: [['amount', '>=', 2]] }); + await waitFor(() => expect(swimlaneCounts(container)).toEqual(['10', '10'])); + expect(columnCounts(container)).toEqual(['18', '2']); + expect(source.queryGroupHeaders.mock.calls[0][1].where).toBeDefined(); + }); + + it.each([ + ['has no grouped door', 'none'], + ['refuses the read', 'refuses'], + ['cuts the read (hasMore)', 'cuts'], + ] as const)('CONTROL: when the source %s, the window\'s counts stay marked `+`', async (_, door) => { + const source = adapter(ROWS, door); + const { container } = mount(source, undefined, undefined, WINDOW); + if (door !== 'none') await waitFor(() => expect(source.queryGroupHeaders).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(swimlaneCounts(container)).toEqual(['5+', '5+'])); + expect(columnCounts(container)).toEqual(['10+', '0+']); + }); + + it('CONTROL: a window the query does not fill asks no read and writes bare counts', async () => { + const source = adapter(ROWS); + const { container } = mount(source, undefined, undefined, { limit: 50 }); + await waitFor(() => expect(swimlaneCounts(container)).toEqual(['12', '12'])); + expect(columnCounts(container)).toEqual(['20', '4']); + expect(source.queryGroupHeaders).not.toHaveBeenCalled(); + }); + + it('CONTROL: a page handed in whose lane read is cut asks no swimlane read; its rows stay marked `+`', async () => { + const source = adapter(ROWS, 'cuts'); + const { container } = mount(source, undefined, { rows: [...deals('open', 3), ...deals('won', 1)] }); + await waitFor(() => expect(source.queryGroupHeaders).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(swimlaneCounts(container)).toEqual(['3+', '1+'])); + expect(source.queryGroupHeaders).toHaveBeenCalledTimes(1); + }); +}); + describe('a swimlane board handed one page draws no column past the page (objectstack#37718)', () => { const ACCOUNT_DEF = { ...DEF, diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.tsx index 9e83facbef9..731da9325ce 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.tsx @@ -89,6 +89,7 @@ import { resolveCardOwner, type KanbanCardOwner } from './KanbanCardOwner'; import { lanesFromOptions, type LaneLifecycleKind } from './kanbanLaneLifecycle'; import { laneKeyOf, lanesFromRecords, laneValueOf } from './kanbanReferenceLanes'; import { + LANE_COUNT_ALIAS, compileLaneReadQuery, isLaneAggregate, readLaneCounts, @@ -1885,6 +1886,92 @@ export const ObjectKanban: React.FC = ({ const headerTotals: Readonly> | null | undefined = headerTotalField ? laneReadHeld?.totals ?? null : undefined; + /** + * objectstack#37844 — the swimlane read. A board drawn in swimlanes that + * holds a WINDOW of its query (a page its host hands in, or its own fetch + * that saturated its window) asks ONE grouped read on both keys, the lane + * field and the swimlane field, each group's `COUNT(*)`, under the same + * filter and search as the lane read. A swimlane row's count is the sum of + * its groups, and on the board that queries itself, a column's count is the + * sum of its groups too (the board handed a page reads its columns off the + * lane read above). A board that holds every record of its query asks + * nothing: its cards are the whole count. The board that queries itself + * knows it from its own fetch (`countsAreWindowed`); the board handed a page + * knows it once the lane read answers, when its counts add up to more + * records than the board holds. No door, a refusal or a cut answer + * (`hasMore`) answers no counts, and the rows stay marked `+`. + */ + const selfWindowed = boardQueriesItself && countsAreWindowed; + const hostWindowed = + hostLaneRead && !!hostLaneCounts + && Object.values(hostLaneCounts).reduce((sum, count) => sum + count, 0) > (Array.isArray(boardData) ? boardData.length : 0); + const swimlaneReadField = + !!schema.groupBy && !!effectiveSwimlaneField && effectiveSwimlaneField !== schema.groupBy + ? effectiveSwimlaneField + : undefined; + const swimlaneReadAsked = !!swimlaneReadField && (hostWindowed || selfWindowed); + const swimlaneQuestion = useMemo((): string => { + if (!swimlaneReadAsked || !swimlaneReadField || !schema.groupBy) return ''; + if (!objectDefReady || typeof dataSource?.queryGroupHeaders !== 'function') return ''; + const hostSearch = JSON.parse(hostSearchKey) as { $search?: string; $searchFields?: string[] }; + const query = compileLaneReadQuery({ + laneField: schema.groupBy, + laneCount: true, + filter: queryFilter, + search: hostSearch.$search, + searchFields: hostSearch.$searchFields, + }); + if (!query || swimlaneReadField === LANE_COUNT_ALIAS) return ''; + return JSON.stringify([schema.objectName, { ...query, groupBy: [schema.groupBy, swimlaneReadField] }]); + }, [swimlaneReadAsked, swimlaneReadField, schema.groupBy, schema.objectName, objectDefReady, dataSource, hostSearchKey, queryFilter]); + type SwimlaneReadAnswer = { + question: string; + lanes: Record | null; + swimlanes: Record | null; + }; + const [swimlaneRead, setSwimlaneRead] = useState(null); + useEffect(() => { + if (!swimlaneQuestion || !dataSource?.queryGroupHeaders || !schema.groupBy || !swimlaneReadField) return; + let cancelled = false; + const [objectName, query] = JSON.parse(swimlaneQuestion) as [string, Parameters>[1]]; + const lanes = JSON.parse(statisticLanesKey) as { ids: string[] | null; foldCase: boolean }; + const laneField = schema.groupBy; + const swimlaneField = swimlaneReadField; + const question = swimlaneQuestion + statisticLanesKey; + Promise.resolve().then(() => dataSource.queryGroupHeaders!(objectName, query)).then( + (rows) => { + if (cancelled) return; + setSwimlaneRead({ + question, + // Folded by the lane key alone: each column's groups across every swimlane. + lanes: readLaneCounts(rows, { laneField, laneIds: lanes.ids, foldCase: lanes.foldCase, uncolumnedId: KANBAN_UNCOLUMNED_ID }), + // Folded by the swimlane key alone, keyed as `laneKeyOf` keys a + // value: the no-value swimlane under `''`. + swimlanes: readLaneCounts(rows, { laneField: swimlaneField, laneIds: null, foldCase: false, uncolumnedId: '' }), + }); + }, + () => { + if (!cancelled) setSwimlaneRead({ question, lanes: null, swimlanes: null }); + }, + ); + return () => { cancelled = true; }; + }, [swimlaneQuestion, statisticLanesKey, dataSource, schema.groupBy, swimlaneReadField, refreshKey, invalidationNonce, hostReloadKey]); + const swimlaneReadHeld = + swimlaneRead && swimlaneQuestion !== '' && swimlaneRead.question === swimlaneQuestion + statisticLanesKey + ? swimlaneRead + : null; + // Each swimlane row's whole count; `null` (not answered, or no answer to + // give) keeps the rows' page counts marked `+`. Absent where nothing is asked. + const swimlaneCounts: Readonly> | null | undefined = swimlaneReadAsked + ? swimlaneReadHeld?.swimlanes ?? null + : undefined; + // The columns' counts the board draws: the lane read's on the board handed a + // page, the swimlane read's on a windowed board that queries itself. + const boardLaneCounts: Readonly> | null | undefined = hostLaneRead + ? hostLaneCounts + : swimlaneReadAsked + ? swimlaneReadHeld?.lanes ?? null + : undefined; /** * objectstack#37327 — the lanes past the page. A board whose lanes come from * the data draws one lane per value the page holds; the lane read's group @@ -2760,7 +2847,10 @@ export const ObjectKanban: React.FC = ({ onLaneRowsChange={onRowGroupsChange} // objectstack#37327 — each lane's whole count on the board handed one // page (see `hostLaneCounts`). A PROP for the reason `objectFields` is. - laneCounts={hostLaneCounts} + laneCounts={boardLaneCounts} + // objectstack#37844 — each swimlane row's whole count on a windowed + // board (see `swimlaneCounts`). A PROP for the reason `laneCounts` is. + swimlaneCounts={swimlaneCounts} // objectstack#37516 — the "Uncategorized" lane whose records all sit // past the page (see `keepUncolumned`). keepUncolumned={keepUncolumned}