diff --git a/.changeset/34364-matrix-date-axis-order.md b/.changeset/34364-matrix-date-axis-order.md new file mode 100644 index 00000000000..c6c9b7b6c11 --- /dev/null +++ b/.changeset/34364-matrix-date-axis-order.md @@ -0,0 +1,14 @@ +--- +'@object-ui/plugin-report': patch +--- + +fix(plugin-report): a matrix report lays out each header dimension on its own, so a date axis reads by bucket key and a select axis keeps its option order whatever the report's `order` + +Clause-②: no +Metadata-protocol: none + +A dataset matrix collected its row and column headers in row-arrival order. When the server's empty-bucket fill and its default ascending time order did not run (a selection with limit/offset, an order on a measure, `compareTo`, or a grid over 2,000 cells), a date column axis came out in first-seen order: one ascending run per row bucket, end to end. And any report `order` switched off the select option layout on both axes, so ordering by the date dimension turned a `priority` row axis from Low / Medium / High / Critical into the stored-value order Critical / High / Low / Medium. + +The matrix now decides per header dimension. A dimension the report's `order` names keeps the order the server applied, so an explicit `desc` on a date axis stays descending. A select dimension it does not name takes its declared option order, as before with no `order`. A date dimension it does not name (its answer column is typed `time`, at any `dateGranularity`) takes its bucket keys ascending, compared by the raw key and not the localized label, with the empty bucket last. Any other dimension keeps its arrival order. + +Only the two header lists are permuted. Every cell is still placed by its bucket ids and every drill click still carries its own bucket, so no row is re-sorted and nothing a truncated page holds is reordered. Flat tables and embedded charts are unchanged. diff --git a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx index 3d7e69dbfbe..add203e300c 100644 --- a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx +++ b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx @@ -47,8 +47,9 @@ * keys, most significant first — is lowered onto the dataset selection, so the * SERVER orders the whole grid (after measure-scoped filters merge and derived * measures evaluate) and this renderer only places the rows it is handed. It is - * never a client-side re-sort: sorting here would order the truncated page - * rather than the query, and could not sort by a derived measure at all. + * never a client-side re-sort of the ROWS: sorting them here would order the + * truncated page rather than the query, and could not sort by a derived measure + * at all. * * Declaring NO `order` leaves the grid in the dataset's `GROUP BY` order — the * stored values' alphabetical order — which for a select dimension is not the @@ -61,11 +62,27 @@ * nothing the server ordered on the author's behalf (see * `arrangeByDeclaredOptions`). * - * For a matrix that also decides the ACROSS axis: `colHeaders` are collected in - * row-arrival order, so ordering the rows by the across dimension is what makes - * the columns read left-to-right in that order. Declaring nothing still reads - * correctly — the server defaults a selected time dimension to ascending, which - * is what makes month/quarter columns chronological out of the box. + * A matrix decides its two axes PER DIMENSION, not per report (objectstack#34364). + * Its headers are collected in row-arrival order, and the arrival order of one + * axis's buckets says nothing reliable once the rows are ordered by anything + * else: the server's empty-bucket fill and its default ascending time order do + * not run under limit/offset, a measure order, `compareTo` or a large grid, and + * then a date axis arrives in first-seen order (one ascending run per row + * bucket, end to end). So each header dimension is laid out on its own: + * + * - a dimension the report's scoped `order` NAMES keeps the server's order — an + * author's explicit order on it (`desc` included) is the author's; + * - a select dimension it does not name takes its declared option order (the + * rule above); + * - a date dimension it does not name (its answer column types `time`, at any + * `dateGranularity`) takes its bucket KEYS ascending — the raw values, minted + * sort-stable by the server, never the localized label — the empty bucket + * last; + * - any other dimension keeps its arrival order. + * + * Sorting the HEADERS is not the client-side re-sort ruled out above: the pivot + * places every cell by its bucket ids, so no row moves, no page is re-sorted and + * no measure is re-ordered — only the two header lists are permuted. * * Drill-down (ADR-0021 D2): when the report's `drilldown` flag is not `false` * and the host supplies `onDrill`, every aggregated row / matrix cell is @@ -483,9 +500,11 @@ function declaredOptionPosition(value: unknown, rank: ReadonlyMap( valueOf: (item: T, dim: string) => unknown, ranks: DimensionRanks | null, ): number[] | null { - if (!ranks || !dims.some((d) => ranks[d])) return null; + if (!ranks) return null; + return arrangeGroups(items, dims, valueOf, (dim) => { + const rank = ranks[dim]; + return rank + ? (a, b) => declaredOptionPosition(valueOf(a, dim), rank) - declaredOptionPosition(valueOf(b, dim), rank) + : null; + }); +} + +/** + * Where one date bucket sits on its axis (objectstack#34364): by its KEY — the + * raw value the server minted sort-stable (`2026-03`, `2026-Q1`, `2026-W03`, + * `2026-03-07`, or an ISO instant), compared as a string by code unit, never the + * localized label — ascending, the empty bucket last as in + * {@link declaredOptionPosition}. Two numbers compare as numbers. + */ +function compareDateBucketKeys(a: unknown, b: unknown): number { + const aEmpty = a == null || a === ''; + const bEmpty = b == null || b === ''; + if (aEmpty || bEmpty) return aEmpty === bEmpty ? 0 : aEmpty ? 1 : -1; + if (typeof a === 'number' && typeof b === 'number') return a - b; + const sa = String(a); + const sb = String(b); + return sa < sb ? -1 : sa > sb ? 1 : 0; +} + +/** + * The level-by-level layout {@link arrangeByDeclaredOptions} describes, with + * the ORDER of each level's buckets supplied per dimension: `compareFor(dim)` + * compares two items' buckets at that level, or is `null` to keep the buckets in + * arrival order. Items are bucketed by `valueOf`, the sort is STABLE, and the + * answer is `null` — nothing moves — when no level has a comparator. + */ +function arrangeGroups( + items: readonly T[], + dims: readonly string[], + valueOf: (item: T, dim: string) => unknown, + compareFor: (dim: string) => ((a: T, b: T) => number) | null, +): number[] | null { + const comparators = dims.map((d) => compareFor(d)); + if (!comparators.some(Boolean)) return null; const arrange = (indices: number[], level: number): number[] => { if (level >= dims.length || indices.length < 2) return indices; const dim = dims[level]; @@ -509,14 +568,8 @@ function arrangeByDeclaredOptions( else buckets.set(id, [i]); } const groups = [...buckets.values()]; - const rank = ranks[dim]; - if (rank) { - groups.sort( - (a, b) => - declaredOptionPosition(valueOf(items[a[0]], dim), rank) - - declaredOptionPosition(valueOf(items[b[0]], dim), rank), - ); - } + const compare = comparators[level]; + if (compare) groups.sort((a, b) => compare(items[a[0]], items[b[0]])); return groups.flatMap((group) => arrange(group, level + 1)); }; return arrange(items.map((_, i) => i), 0); @@ -1907,6 +1960,42 @@ function bucketLabel( return dims.map((d) => dimensionText(fields, d, row[d], locale)).join(' / '); } +/** One matrix axis header: the RAW bucket (`key`) and how it reads (`display`). */ +type MatrixHeader = { id: string; label: string; key: Row; display: Row }; + +/** + * How a matrix lays out each header dimension (objectstack#34364), decided per + * DIMENSION rather than per report — the comparator `arrangeGroups` sorts that + * level's buckets by, or `null` to keep the server's arrival order: + * + * - named by the report's scoped `order` → `null`: the author's order, which + * the server applied (an explicit `desc` on a date axis stays descending); + * - a select (it has declared-option `ranks`) → its declared option order, + * read off the DISPLAY value (objectui#12243); + * - a date → its bucket KEY ascending ({@link compareDateBucketKeys}). Date-ness + * is read off the answer's own column descriptor — a date dimension's column + * is typed `time` (`AnalyticsResult.fields[].type`) at every + * `dateGranularity` — never sniffed from the values; + * - anything else → `null`. + */ +function matrixAxisComparators( + fields: readonly DatasetResultField[] | undefined, + ranks: DimensionRanks | null, + ordered: ReadonlySet, +): (dim: string) => ((a: MatrixHeader, b: MatrixHeader) => number) | null { + return (dim) => { + if (ordered.has(dim)) return null; + const rank = ranks?.[dim]; + if (rank) { + return (a, b) => declaredOptionPosition(a.display[dim], rank) - declaredOptionPosition(b.display[dim], rank); + } + if (fields?.find((f) => f.name === dim)?.type === 'time') { + return (a, b) => compareDateBucketKeys(a.key[dim], b.key[dim]); + } + return null; + }; +} + /** * True cross-tab for `type: 'matrix'` — one dataset query over * `[...rows, ...columns]`, pivoted client-side. Cells show every measure @@ -1941,9 +2030,9 @@ function DatasetMatrixTable({ // objectstack-ai/objectstack#3916: the ordering rides on the PRIMARY query only — the server drops it // for the totals sub-queries by design (a total covers the whole selection, // and an order key may name a dimension the totals grouping doesn't have). - // The across-axis header sequence follows from it: `pivot` below collects - // `colHeaders` in row-ARRIVAL order, so ordering the rows by the across - // dimension is what makes the columns read left-to-right in that order. + // `pivot` below collects both header lists in row-ARRIVAL order, so a header + // dimension the order NAMES reads in the order the server applied; every + // other header dimension is laid out per `matrixAxisComparators`. const state = useDatasetRows( dataset, [...rows, ...columnsAcross], @@ -1972,18 +2061,20 @@ function DatasetMatrixTable({ () => deriveDimensionDisplay(dimensionMeta, fieldOptionLabel), [dimensionMeta, fieldOptionLabel], ); - // objectui#12243 — a report that declares its own `order` for this selection - // keeps the server's arrival order on both axes; otherwise each axis is laid - // out in its select dimensions' declared option order. - const hasAuthoredOrder = scopeOrder(order, [...rows, ...columnsAcross], values) !== undefined; + // objectstack#34364 — the keys of the report's `order` this selection + // carries, read PER DIMENSION: a header dimension it names keeps the server's + // order; every other one is laid out by the renderer (see + // `matrixAxisComparators`). Serialized so the pivot memo keys on the names, + // not on an object rebuilt every render. + const orderedDimensionsKey = JSON.stringify(Object.keys(scopeOrder(order, [...rows, ...columnsAcross], values) ?? {})); const pivot = React.useMemo(() => { if (state.status !== 'ok') return null; // `key` is the RAW bucket (drill identity); `display` is the same bucket as // it reads on screen, per dimension — the two are deliberately separate // (objectui#4330). - const rowHeaders: Array<{ id: string; label: string; key: Row; display: Row }> = []; - const colHeaders: Array<{ id: string; label: string; key: Row; display: Row }> = []; + const rowHeaders: MatrixHeader[] = []; + const colHeaders: MatrixHeader[] = []; const seenRow = new Set(); const seenCol = new Set(); const cells = new Map(); @@ -2019,17 +2110,21 @@ function DatasetMatrixTable({ // server's own row. cells.set(pivotCellKey(rid, cid), { row: raw, index }); }); - // objectui#12243 — the headers were collected in row-ARRIVAL order, which - // with no authored `order` is the dataset's `GROUP BY` order (alphabetical - // by stored value). Each axis is laid out by its own dimensions' declared - // option order, read off the DISPLAY values the headers carry, so a - // `priority` column axis reads Low, Medium, High as a `status` row axis - // reads New, In Progress, Closed. A time or text dimension keeps its - // arrival order (the server's chronological default for a time axis). - // Only the header lists move: every cell is still looked up by bucket id. - const ranks = hasAuthoredOrder ? null : dimensionRanks; - const rowLayout = arrangeByDeclaredOptions(rowHeaders, rows, (h, d) => h.display[d], ranks); - const colLayout = arrangeByDeclaredOptions(colHeaders, columnsAcross, (h, d) => h.display[d], ranks); + // The headers were collected in row-ARRIVAL order, which says nothing + // reliable about either axis once the rows are ordered by anything else. + // Each header dimension is laid out on its own (objectstack#34364): one the + // report's `order` names keeps that arrival order, an unnamed select takes + // its declared option order read off the DISPLAY values (objectui#12243), + // an unnamed date takes its bucket KEYS ascending, anything else stays put. + // This permutes only the two header lists, never a row: every cell is still + // looked up by bucket id, and each header carries its own drill `key`. + const comparatorsFor = matrixAxisComparators( + state.fields, + dimensionRanks, + new Set(JSON.parse(orderedDimensionsKey) as string[]), + ); + const rowLayout = arrangeGroups(rowHeaders, rows, (h, d) => h.display[d], comparatorsFor); + const colLayout = arrangeGroups(colHeaders, columnsAcross, (h, d) => h.display[d], comparatorsFor); return { rowHeaders: rowLayout ? rowLayout.map((i) => rowHeaders[i]) : rowHeaders, colHeaders: colLayout ? colLayout.map((i) => colHeaders[i]) : colHeaders, @@ -2041,7 +2136,7 @@ function DatasetMatrixTable({ // that switches locale without refetching keeps the previous locale's // headers, and the pin for that is the "re-labels the across header when // only the locale changes" case in DatasetReportRenderer.measureLocale.test.tsx. - }, [state, rows, columnsAcross, dimensionLabels, dimensionRanks, hasAuthoredOrder, displayLocale]); + }, [state, rows, columnsAcross, dimensionLabels, dimensionRanks, orderedDimensionsKey, displayLocale]); if (values.length === 0) return ; if (state.status === 'loading' || state.status === 'idle') return ; diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.selectOptionOrder-12243.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.selectOptionOrder-12243.test.tsx index 174ffb44f47..d6f6898540d 100644 --- a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.selectOptionOrder-12243.test.tsx +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.selectOptionOrder-12243.test.tsx @@ -538,3 +538,140 @@ describe('CONTROLs — what keeps its order (objectui#12243)', () => { ); }); }); + +// ── Cases Opened by Day and Priority (objectstack#34364) ──────────────────── +// HotCRM's `cases_opened_by_day_priority`: rows `priority` (a select), columns +// `created_at` (a date dimension, `dateGranularity: 'day'`, so its answer +// column types `time`), values `case_count`. The rows below are what a server +// answers when the empty-bucket fill does not run: grouped by the STORED +// priority, so the day columns arrive in first-seen order. The null day is the +// empty bucket, named by its declared `nullLabel`. +// +// DIRECTIONS, written before the ablations were run: +// - no date comparator: RED (a), (b) and the CONTROL (their day headers); +// GREEN (c), (d), whose server order already reads correctly; +// - an order on ANY key re-lays nothing (the old all-or-nothing rule): RED +// (b), (c), (d) (their rows) and the CONTROL (its day headers); GREEN (a); +// - a named dimension re-laid anyway: RED (d) and the CONTROL; GREEN the rest. +const DAY_FIELDS = [ + { name: 'priority', type: 'string', label: 'Priority' }, + { name: 'created_at', type: 'time', label: 'Created', nullLabel: 'No date' }, + { name: 'case_count', type: 'number', label: 'Cases' }, +]; +const DAY_ROWS_BY_PRIORITY = [ + { priority: 'Critical', created_at: '2026-11-12', case_count: 1 }, + { priority: 'Critical', created_at: '2026-11-16', case_count: 2 }, + { priority: 'High', created_at: '2026-11-14', case_count: 3 }, + { priority: 'High', created_at: '2026-11-03', case_count: 4 }, + { priority: 'Low', created_at: '2026-11-03', case_count: 5 }, + { priority: 'Low', created_at: '2026-11-12', case_count: 6 }, + { priority: 'Medium', created_at: null, case_count: 7 }, + { priority: 'Medium', created_at: '2026-11-14', case_count: 8 }, +]; +const STORED_PRIORITY: Record = { Critical: 'critical', High: 'high', Low: 'low', Medium: 'medium' }; +/** One dataset answer carrying `rows` in the order given, with its drill rows aligned to them. */ +const dayAnswer = (rows: typeof DAY_ROWS_BY_PRIORITY) => ({ + rows, + fields: DAY_FIELDS, + object: 'crm_case', + dimensionFields: { priority: 'priority', created_at: 'created_at' }, + drillScopes: { case_count: {} }, + drillRawRows: rows.map((r) => ({ priority: STORED_PRIORITY[r.priority], created_at: r.created_at })), +}); +const byCount = (dir: 1 | -1) => [...DAY_ROWS_BY_PRIORITY].sort((a, b) => dir * (a.case_count - b.case_count)); +// The server's `created_at` order, the stored priority breaking ties; the +// empty day sorts last ascending and first descending, as Postgres does. +const byDay = (dir: 1 | -1) => + [...DAY_ROWS_BY_PRIORITY].sort((a, b) => { + const ka = a.created_at; + const kb = b.created_at; + if (ka !== kb) { + if (ka === null) return dir; + if (kb === null) return -dir; + return dir * (ka < kb ? -1 : 1); + } + return STORED_PRIORITY[a.priority] < STORED_PRIORITY[b.priority] ? -1 : 1; + }); + +const DAY_MATRIX = { + name: 'cases_opened_by_day_priority', + type: 'matrix', + dataset: 'case_metrics', + rows: ['priority'], + columns: ['created_at'], + values: ['case_count'], +}; +const ASCENDING_DAYS = ['2026-11-03', '2026-11-12', '2026-11-14', '2026-11-16', 'No date']; +// Each row in option order, its cells under the ascending day headers. +const OPTION_ORDER_CELLS = [ + ['Low', '5', '6', '—', '—', '—'], + ['Medium', '—', '—', '8', '—', '7'], + ['High', '4', '—', '3', '—', '—'], + ['Critical', '—', '1', '—', '2', '—'], +]; +const headerTexts = (matrix: HTMLElement) => Array.from(matrix.querySelectorAll('thead th')).map((th) => th.textContent); + +async function renderDayMatrix(rows: typeof DAY_ROWS_BY_PRIORITY, order?: Array<{ by: string; direction?: string }>) { + const src = sourceByDimensions({ 'priority,created_at': dayAnswer(rows) }); + const drills: DatasetDrillArgs[] = []; + render( + drills.push(a)} + />, + ); + const matrix = await screen.findByTestId('dataset-matrix'); + return { src, drills, matrix }; +} + +describe('a matrix lays out each header dimension on its own: a date by bucket key, a select by its options (objectstack#34364)', () => { + it('(a) no order: the day columns ascend by bucket key, the empty day last, and the priority rows read in option order', async () => { + const { src, drills, matrix } = await renderDayMatrix(DAY_ROWS_BY_PRIORITY); + await waitFor(() => expect(headerTexts(matrix)).toEqual(['Priority', ...ASCENDING_DAYS])); + await waitFor(() => expect(rowCells(matrix)).toEqual(OPTION_ORDER_CELLS)); + expect('order' in src.calls[0]).toBe(false); + // Only the headers moved: a cell under a moved header drills into its own bucket. + fireEvent.click(within(matrix).getAllByTestId('dataset-drill-cell')[0]); + await waitFor(() => expect(drills.length).toBe(1)); + expect(drills[0].groupKey).toEqual({ priority: 'Low', created_at: '2026-11-03' }); + }); + + it('(b) an order on the measure names neither axis: the same layout', async () => { + const { src, matrix } = await renderDayMatrix(byCount(-1), [{ by: 'case_count', direction: 'desc' }]); + await waitFor(() => expect(headerTexts(matrix)).toEqual(['Priority', ...ASCENDING_DAYS])); + await waitFor(() => expect(rowCells(matrix)).toEqual(OPTION_ORDER_CELLS)); + expect(src.calls[0].order).toEqual({ case_count: 'desc' }); + }); + + it('(c) an order on the date names only the columns: they ascend as the server ordered them, the rows STILL read in option order', async () => { + const { src, matrix } = await renderDayMatrix(byDay(1), [{ by: 'created_at', direction: 'asc' }]); + await waitFor(() => expect(headerTexts(matrix)).toEqual(['Priority', ...ASCENDING_DAYS])); + await waitFor(() => expect(rowCells(matrix)).toEqual(OPTION_ORDER_CELLS)); + expect(src.calls[0].order).toEqual({ created_at: 'asc' }); + }); + + it('(d) a descending order on the date is the author’s: the columns descend, the rows read in option order', async () => { + const { src, matrix } = await renderDayMatrix(byDay(-1), [{ by: 'created_at', direction: 'desc' }]); + await waitFor(() => expect(rowCells(matrix)[0]?.[0]).toBe('Low')); + expect(headerTexts(matrix)).toEqual(['Priority', 'No date', '2026-11-16', '2026-11-14', '2026-11-12', '2026-11-03']); + expect(rowCells(matrix)).toEqual([ + ['Low', '—', '—', '—', '6', '5'], + ['Medium', '7', '—', '8', '—', '—'], + ['High', '—', '—', '3', '—', '4'], + ['Critical', '—', '2', '—', '1', '—'], + ]); + expect(src.calls[0].order).toEqual({ created_at: 'desc' }); + }); + + it('CONTROL: an order on the select names only the rows: they keep the server’s order, the day columns still ascend', async () => { + const { matrix } = await renderDayMatrix(DAY_ROWS_BY_PRIORITY, [{ by: 'priority', direction: 'asc' }]); + await waitFor(() => expect(headerTexts(matrix)).toEqual(['Priority', ...ASCENDING_DAYS])); + // Wait out the metadata read, so an option layout would have landed by now. + await waitFor(() => expect(metaCalls).toContain('/api/v1/meta/object/crm_case')); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 20)); + }); + expect(rowCells(matrix).map((r) => r[0])).toEqual(['Critical', 'High', 'Low', 'Medium']); + }); +});