diff --git a/.changeset/36722-report-chart-show-empty-groups-ui.md b/.changeset/36722-report-chart-show-empty-groups-ui.md new file mode 100644 index 00000000000..a9222c36f35 --- /dev/null +++ b/.changeset/36722-report-chart-show-empty-groups-ui.md @@ -0,0 +1,14 @@ +--- +'@object-ui/plugin-report': patch +'@object-ui/i18n': patch +--- + +feat(plugin-report): the report chart honours `chart.showEmptyGroups`, and the report builder offers it as a switch + +Clause-②: yes (widening) +Metadata-protocol: added + +- On a chart with a category axis (bar, column, horizontal-bar, line, area, radar, combo), the dataset report chart adds the `xAxis` field's declared options that the answer left out when `chart.showEmptyGroups` is on: in their declared place, with the option's label and colour, valued `0` for a count or sum and left empty for avg/min/max. With a `seriesBy` split an added option reads the empty value in every series. Whether an option is missing is judged by the stored value the answer's `drillRawRows` carries wherever the answer has it, so a label the server translated differently is not drawn as a second, zero-valued group; a row with no raw value falls back to matching the option's spellings. A value-sized chart (pie, donut, funnel, treemap, sankey) and scatter get nothing added. Nothing is added for a field with no declared options, when the report's `order` reaches the chart's query, or on an answer with no rows. A bar on an added option opens no record list. +- The report builder's chart settings gain a "Show groups with no records" switch on the category-axis charts (bar and line among the builder's choices, and a stored column, area or other category-axis type). It writes `chart.showEmptyGroups: true`; off removes the key. An edit keeps an authored key on every series chart type, the donut included, and only a single-value or table chart drops it. +- `@object-ui/i18n`: `report.builder.chart.showEmptyGroups` in all 11 locales. +- `@object-ui/plugin-report` now lists `@objectstack/spec` under `dependencies` (it was a dev dependency): the chart reads the analytics executor's empty-group values from `@objectstack/spec/data` at runtime. diff --git a/.changeset/36722-report-chart-show-empty-groups.md b/.changeset/36722-report-chart-show-empty-groups.md new file mode 100644 index 00000000000..4185db1e056 --- /dev/null +++ b/.changeset/36722-report-chart-show-empty-groups.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): `chart.showEmptyGroups` on a report chart — show the declared options that have no records + +Clause-②: yes (widening) +Metadata-protocol: added + +- `ReportChartSchema` gains an optional boolean `showEmptyGroups`. A grouped query returns only the values that have rows, so a select option no record carries was missing from a report chart rather than drawn at zero. With `showEmptyGroups: true` the report renderer adds every declared option of the `xAxis` field the answer left out, valued the way the analytics executor values any empty group (`emptyGroupValueFor`: `0` for count and sum, empty for avg/min/max). +- Optional with no default: a report that does not set it parses exactly as before and its chart draws exactly the groups the query returned. A non-boolean value is refused at `chart.showEmptyGroups`. +- Acts on a chart with a category axis (bar, column, horizontal-bar, line, area, radar, combo); a chart that sizes its marks by value (pie, donut, funnel, treemap, sankey) and scatter get nothing added, and on a single-value or table chart the key has no effect. Only a field that declares its options is filled. Nothing is added when the report's `order` reaches the chart, and an answer with no rows at all still draws no chart. A date axis needs no switch: the executor already returns every bucket of the report's period. diff --git a/content/docs/references/ui/report.mdx b/content/docs/references/ui/report.mdx index 268e0047c17..7fe47fc53a4 100644 --- a/content/docs/references/ui/report.mdx +++ b/content/docs/references/ui/report.mdx @@ -106,6 +106,7 @@ const result = JoinedReportBlockSchema.parse(data); | **interaction** | `{ tooltips?: boolean; brush?: boolean }` | optional | Interaction toggles: `{ tooltips?, brush? }` | | **aria** | `never` | optional | [REMOVED] `ChartConfig.aria` — authored as `dashboard.widgets[].chartConfig.aria`, `report.chart.aria` and `report.blocks[].chart.aria` — was removed in @objectstack/spec 17 (ADR-0049 D2). No chart renderer ever applied it: the chart implementation declares no `aria` prop, the presentation lowering names it nowhere, and the react `` block never published it, so ARIA attributes declared here parsed and then silently did not reach the DOM. Delete the key. The accessible name that IS applied on this same chart config is its sibling `description`, which the chart renderer lowers onto the chart graphic as `role="img"` plus `aria-label`. The shared `AriaProps` shape is NOT gone — `ariaLabel` / `ariaDescribedBy` / `role` stay live in the `aria` block on `page.aria`, `page.components[].aria` and the list view `aria`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **seriesBy** | `string` | optional | Dataset dimension name that splits the yAxis measure into one series per value of it (bound-dataset dimension, not a raw field); with it set, `series[].name` names a value of this dimension. Refused on a single-series type (pie/donut/funnel/treemap/sankey) and when it names the xAxis dimension | +| **showEmptyGroups** | `boolean` | optional | Show the declared options of the xAxis dimension field that have no records, valued 0 for a count or sum (left empty for avg/min/max), on a chart with a category axis (bar, column, horizontal-bar, line, area, radar, combo); nothing is added on any other chart type. Only a field that declares its options is filled; nothing is added when the report's order reaches the chart, and an answer with no rows still draws no chart; omitted = off | ### Nested Shape: `Report.dateRange` @@ -177,6 +178,7 @@ const result = JoinedReportBlockSchema.parse(data); | **interaction** | `{ tooltips?: boolean; brush?: boolean }` | optional | Interaction toggles: `{ tooltips?, brush? }` | | **aria** | `never` | optional | [REMOVED] `ChartConfig.aria` — authored as `dashboard.widgets[].chartConfig.aria`, `report.chart.aria` and `report.blocks[].chart.aria` — was removed in @objectstack/spec 17 (ADR-0049 D2). No chart renderer ever applied it: the chart implementation declares no `aria` prop, the presentation lowering names it nowhere, and the react `` block never published it, so ARIA attributes declared here parsed and then silently did not reach the DOM. Delete the key. The accessible name that IS applied on this same chart config is its sibling `description`, which the chart renderer lowers onto the chart graphic as `role="img"` plus `aria-label`. The shared `AriaProps` shape is NOT gone — `ariaLabel` / `ariaDescribedBy` / `role` stay live in the `aria` block on `page.aria`, `page.components[].aria` and the list view `aria`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **seriesBy** | `string` | optional | Dataset dimension name that splits the yAxis measure into one series per value of it (bound-dataset dimension, not a raw field); with it set, `series[].name` names a value of this dimension. Refused on a single-series type (pie/donut/funnel/treemap/sankey) and when it names the xAxis dimension | +| **showEmptyGroups** | `boolean` | optional | Show the declared options of the xAxis dimension field that have no records, valued 0 for a count or sum (left empty for avg/min/max), on a chart with a category axis (bar, column, horizontal-bar, line, area, radar, combo); nothing is added on any other chart type. Only a field that declares its options is filled; nothing is added when the report's order reaches the chart, and an answer with no rows still draws no chart; omitted = off | ### Allowed Values: `ReportChart.type` diff --git a/content/docs/ui/reports.mdx b/content/docs/ui/reports.mdx index 00ec6043035..4f9d0cbb98f 100644 --- a/content/docs/ui/reports.mdx +++ b/content/docs/ui/reports.mdx @@ -210,6 +210,21 @@ export const HoursByStatusChartReport = defineReport({ }); ``` +**`showEmptyGroups: true`** shows the groups that hold no records. A grouped query returns only +the values that have rows, so a status no task carries is missing from the chart rather than +drawn at zero. With the switch on, every declared option of the `xAxis` field that the answer +left out appears; an empty one reads `0` for a count or sum and stays empty for an average, +minimum or maximum. An option the report's own filter excludes reads as empty too. Only a field +that declares its options (a select) is filled. Nothing is added when the report's `order` +reaches the chart, and an answer with no rows at all still draws no chart. A date axis needs no +switch: every bucket of the report's period already appears. The switch acts on the charts with +a category axis (bar, column, horizontal bar, line, area, radar, combo), where an empty group is +a category at zero. A pie, donut, funnel, treemap or sankey sizes its marks by value and would +draw a zero group as nothing, and a scatter takes no select axis, so nothing is added there; on a +number or a table the key has no effect. The report builder shows the switch on the category-axis +charts grouped by something other than a date, and keeps an authored one when the chart type +changes to another series chart. + ## Period and export A non-`joined` report can declare the period it covers and how its table is downloaded. diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index e8e047df488..693b1270fad 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -1345,6 +1345,7 @@ "ui/ReportChart:series", "ui/ReportChart:seriesBy", "ui/ReportChart:showDataLabels", + "ui/ReportChart:showEmptyGroups", "ui/ReportChart:showLegend", "ui/ReportChart:subtitle", "ui/ReportChart:title", diff --git a/packages/spec/liveness/report.json b/packages/spec/liveness/report.json index e654fb4e9a7..cc9d1964b5a 100644 --- a/packages/spec/liveness/report.json +++ b/packages/spec/liveness/report.json @@ -65,6 +65,13 @@ "evidenceScope": "in-repo", "evidence": "ui/packages/plugin-report/src/DatasetReportRenderer.tsx#DatasetReportChart (reads `chart.seriesBy`, queries `[xAxis, seriesBy]` × `[yAxis]` and pivots the rows through `buildChartSeries` into one series per value); ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.chartSeriesBy-28206.test.tsx; packages/lint/src/validate-chart-bindings.ts#validateChartBindings (resolves it against the report's bound dataset dimensions exactly as `xAxis`, `chart-dimension-unknown` at error, at os validate / os build and the report publish door)", "note": "The report chart series split (#27974 spec half, #28206 renderer half): a second dataset dimension that splits the one `yAxis` measure into a series per value, the report's spelling of a dashboard widget's two-entry `dimensions` selection. LIVE: DatasetReportChart widens its own query to `[xAxis, seriesBy]` × `[yAxis]` and hands both dimensions to `buildChartSeries` (ui/packages/core/src/utils/chart-series.ts), whose pivot branch draws one row per x bucket and one series per `seriesBy` value, the null group included; the series follow the split dimension's declared option order, and a `series[]` entry whose `name` is a split value lands its presentation on that series. Without `seriesBy` the chart queries and draws exactly what it did before. The other children of `chart` inherit the row's `live` verdict through `childrenDefault`; this row stays to carry the reader as evidence." + }, + "showEmptyGroups": { + "status": "live", + "verifiedAt": "2026-11-28", + "evidenceScope": "in-repo", + "evidence": "ui/packages/plugin-report/src/emptyOptionGroups.ts#fillEmptyOptionGroups (adds the declared options of the `xAxis` field the answer left out, valued by `emptyGroupValueFor`); ui/packages/plugin-report/src/DatasetReportRenderer.tsx#DatasetReportChart (calls it when `chart.showEmptyGroups === true`, no `order` reaches the chart and `chartDrawsEmptyGroups(chart.type)`); ui/packages/plugin-report/src/__tests__/emptyOptionGroups.test.ts; ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.test.tsx (describe `chart.showEmptyGroups`)", + "note": "The report chart's show-the-groups-with-no-records switch (#36722). LIVE: with it on, DatasetReportChart adds every declared option of the x-axis dimension's field that no answer row carries, judged by the stored value `drillRawRows` states (spellings only for a row without one), appended after the answer's rows so the drill still addresses them by index; count and sum read 0, avg/min/max and a derived measure stay empty. Filled only on a chart type with a category axis (bar, column, horizontal-bar, line, area, radar, combo; `chartDrawsEmptyGroups`), never on a value-sized chart (pie, donut, funnel, treemap, sankey) or scatter. Not filled when the field declares no options, when the report's `order` reaches the chart, or on an answer with no rows. The report builder offers it on the category-axis types and keeps an authored key on every series type. Off or absent, the chart draws exactly the groups the query returned. The other children of `chart` inherit `live` through `childrenDefault`; this row stays to carry the reader as evidence." } } }, diff --git a/packages/spec/liveness/state-counts/report.md b/packages/spec/liveness/state-counts/report.md index c4b052c5696..64bb0385abe 100644 --- a/packages/spec/liveness/state-counts/report.md +++ b/packages/spec/liveness/state-counts/report.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `report` | 40 | 0 | 0 | 1 | 2 | 43 | +| `report` | 41 | 0 | 0 | 1 | 2 | 44 | diff --git a/packages/spec/src/ui/report.test.ts b/packages/spec/src/ui/report.test.ts index 3c0d98a76f2..cf704891ba1 100644 --- a/packages/spec/src/ui/report.test.ts +++ b/packages/spec/src/ui/report.test.ts @@ -581,6 +581,29 @@ describe('ReportChartSchema', () => { expect(r.success).toBe(false); expect(r.error?.issues.map((i) => i.path.join('.'))).toContain('seriesBy'); }); + + // objectstack#36722 — "show groups with no records". Optional with NO + // default: an existing report parses to exactly the bytes it parsed to + // before, so the switch is off by being absent. + it('`showEmptyGroups` is optional and off by default — absent stays absent', () => { + const parsed = ReportChartSchema.parse({ type: 'bar', xAxis: 'stage', yAxis: 'count' }); + expect('showEmptyGroups' in parsed).toBe(false); + const on = ReportChartSchema.safeParse({ type: 'bar', xAxis: 'stage', yAxis: 'count', showEmptyGroups: true }); + expect(on.success).toBe(true); + expect(on.data?.showEmptyGroups).toBe(true); + const report = ReportSchema.parse({ + name: 'deals_by_stage', label: 'Deals by stage', type: 'summary', + dataset: 'deals', rows: ['stage'], values: ['count'], + chart: { type: 'bar', xAxis: 'stage', yAxis: 'count', showEmptyGroups: true }, + }); + expect(report.chart?.showEmptyGroups).toBe(true); + }); + + it('refuses a non-boolean `showEmptyGroups`', () => { + const r = ReportChartSchema.safeParse({ type: 'bar', xAxis: 'stage', yAxis: 'count', showEmptyGroups: 'yes' }); + expect(r.success).toBe(false); + expect(r.error?.issues.map((i) => i.path.join('.'))).toContain('showEmptyGroups'); + }); }); /** diff --git a/packages/spec/src/ui/report.zod.ts b/packages/spec/src/ui/report.zod.ts index 907535ac7b8..3010f4d1766 100644 --- a/packages/spec/src/ui/report.zod.ts +++ b/packages/spec/src/ui/report.zod.ts @@ -56,6 +56,42 @@ export const ReportChartSchema = lazySchema(() => ChartConfigSchema.extend({ + '(bound-dataset dimension, not a raw field); with it set, `series[].name` names a value of this dimension. ' + 'Refused on a single-series type (' + SINGLE_SERIES_CHART_TYPES.join('/') + ') and when it names the xAxis dimension', ), + /** + * Show the groups that hold no records. A grouped query answers one row per + * value that HOLDS rows, so a stage with no deals is absent from a + * "deals by stage" chart rather than reading as zero. With this on, the + * report renderer adds every DECLARED option of the `xAxis` dimension's + * field that the answer left out, valued the way the analytics + * executor values any empty group (`emptyGroupValueFor`: `0` for count and + * sum, empty for avg/min/max). A derived measure states no aggregate, so an + * added group carries no value for it. + * + * Acts only on a chart type that lays its groups out on a category axis + * (`bar`, `column`, `horizontal-bar`, `line`, `area`, `radar`, `combo`), where + * an added group is a category at zero. A chart that sizes its marks by value + * (`pie`, `donut`, `funnel`, `treemap`, `sankey`) would draw a zero group as + * nothing, and `scatter` takes no select axis, so nothing is added there; on a + * single-value or table type the key is accepted and has no effect, as + * `showLegend` is. + * + * Only a dimension whose field declares its options is filled (a select or + * similar); a free-text or lookup dimension has no known set of values. Not + * filled when the report's `order` reaches the chart: an added group has no + * place in an authored order, and under a measure order it would compete for + * a place it did not earn. An answer with no rows at all still draws no + * chart: the options are filled around the groups an answer holds. An option + * the report's own filter excludes reads as empty like any other. A date axis + * needs no switch: the executor already fills every bucket of the report's + * period. Omitted = off, and the chart draws exactly the groups the query + * returned. + */ + showEmptyGroups: z.boolean().optional().describe( + 'Show the declared options of the xAxis dimension field that have no records, valued 0 for a count or sum ' + + '(left empty for avg/min/max), on a chart with a category axis (bar, column, horizontal-bar, line, area, ' + + 'radar, combo); nothing is added on any other chart type. Only a field that declares its options is filled; ' + + "nothing is added when the report's order reaches the chart, and an answer with no rows still draws no chart; " + + 'omitted = off', + ), })); /** diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e5b7ea3de1f..6fe6c182f34 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6078,6 +6078,9 @@ importers: '@object-ui/types': specifier: workspace:* version: link:../types + '@objectstack/spec': + specifier: workspace:^ + version: link:../../../packages/spec exceljs: specifier: ^4.4.0 version: 4.4.0 @@ -6094,9 +6097,6 @@ importers: '@object-ui/test-support': specifier: workspace:* version: link:../test-support - '@objectstack/spec': - specifier: workspace:^ - version: link:../../../packages/spec '@types/node': specifier: ^26.6.5 version: 26.6.5 diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 87d96a73ecc..b01755aedd5 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -4469,6 +4469,7 @@ const ar = { metric: "رقم", table: "جدول", showValues: "إظهار القيم", + showEmptyGroups: "إظهار المجموعات التي لا تحتوي على سجلات", targetLine: "خط الهدف", targetLabel: "الهدف", secondLayerTableOnly: "يرسم هذا المخطط التجميع الأول؛ أما الثاني ففي القيم المحسوبة.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 206431f4c31..117a9b4ff5e 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4119,6 +4119,7 @@ const de = { metric: "Zahl", table: "Tabelle", showValues: "Werte anzeigen", + showEmptyGroups: "Gruppen ohne Datensätze anzeigen", targetLine: "Ziellinie", targetLabel: "Ziel", secondLayerTableOnly: "Dieses Diagramm zeigt die erste Gruppierung; die zweite steht in den berechneten Werten.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index c74f15dd6ee..05d3bb620bc 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2290,6 +2290,7 @@ const en = { metric: 'Number', table: 'Table', showValues: 'Show values', + showEmptyGroups: 'Show groups with no records', targetLine: 'Target line', targetLabel: 'Target', secondLayerTableOnly: 'This chart draws the first grouping; the second is in the computed values.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f0d03c893dd..c8f1e2a7746 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4207,6 +4207,7 @@ const es = { metric: "Número", table: "Tabla", showValues: "Mostrar valores", + showEmptyGroups: "Mostrar grupos sin registros", targetLine: "Línea objetivo", targetLabel: "Objetivo", secondLayerTableOnly: "Este gráfico dibuja la primera agrupación; la segunda está en los valores calculados.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index f5a28722d08..423254cca15 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4203,6 +4203,7 @@ const fr = { metric: "Nombre", table: "Tableau", showValues: "Afficher les valeurs", + showEmptyGroups: "Afficher les groupes sans enregistrements", targetLine: "Ligne d’objectif", targetLabel: "Objectif", secondLayerTableOnly: "Ce graphique trace le premier regroupement ; le second figure dans les valeurs calculées.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 52ccf63a4c3..7502236a8f1 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4121,6 +4121,7 @@ const ja = { metric: "数値", table: "表", showValues: "値を表示", + showEmptyGroups: "レコードのないグループを表示", targetLine: "目標線", targetLabel: "目標", secondLayerTableOnly: "このグラフは最初のグループ化のみを描画します。2 つ目は計算値にあります。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index eb69abda7e1..ffc6e3734ed 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4118,6 +4118,7 @@ const ko = { metric: "숫자", table: "표", showValues: "값 표시", + showEmptyGroups: "레코드가 없는 그룹 표시", targetLine: "목표선", targetLabel: "목표", secondLayerTableOnly: "이 차트는 첫 번째 그룹화만 그립니다. 두 번째는 계산 값에 있습니다.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 83346ee342f..0883b0312a2 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4202,6 +4202,7 @@ const pt = { metric: "Número", table: "Tabela", showValues: "Mostrar valores", + showEmptyGroups: "Mostrar grupos sem registros", targetLine: "Linha de meta", targetLabel: "Meta", secondLayerTableOnly: "Este gráfico desenha o primeiro agrupamento; o segundo está nos valores calculados.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 2ff2cecf2d7..f7a47fd5d76 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4304,6 +4304,7 @@ const ru = { metric: "Число", table: "Таблица", showValues: "Показывать значения", + showEmptyGroups: "Показывать группы без записей", targetLine: "Целевая линия", targetLabel: "Цель", secondLayerTableOnly: "Эта диаграмма показывает первую группировку; вторая — в вычисленных значениях.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index ac9f5e1d946..ef789c02c95 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1924,6 +1924,7 @@ const zh = { metric: '数字', table: '表格', showValues: '显示数值', + showEmptyGroups: '显示数量为 0 的分组', targetLine: '目标线', targetLabel: '目标', secondLayerTableOnly: '这种图只画第一层分组,第二层在计算值里。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 7750c385c1f..abaa7ab0dd6 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1924,6 +1924,7 @@ const zhHant = { metric: '數字', table: '表格', showValues: '顯示數值', + showEmptyGroups: '顯示數量為 0 的分組', targetLine: '目標線', targetLabel: '目標', secondLayerTableOnly: '這種圖只畫第一層分組,第二層在計算值裡。', diff --git a/ui/packages/plugin-report/README.md b/ui/packages/plugin-report/README.md index fab5dd78caa..197def4a3e8 100644 --- a/ui/packages/plugin-report/README.md +++ b/ui/packages/plugin-report/README.md @@ -263,6 +263,12 @@ defineReport({ `series`, `colors`, `height`, `showDataLabels`, `annotations` and `interaction` are passed through to the chart as authored. +`showEmptyGroups: true` adds the declared options of the `xAxis` field that the +answer left out, valued `0` for a count or sum and left empty for avg/min/max +(the analytics executor's own empty-group values), on a chart with a category +axis (bar, column, horizontal-bar, line, area, radar, combo) only. Nothing is +added on a value-sized chart (pie, donut, funnel, treemap, sankey), when the +report's `order` reaches the chart, or on an answer with no rows (no chart). The chart runs its own `xAxis` × `yAxis` dataset query, so it binds the same way on every non-`joined` type. It draws above a `tabular` or `summary` table, and diff --git a/ui/packages/plugin-report/package.json b/ui/packages/plugin-report/package.json index 13173f61718..f47322e560b 100644 --- a/ui/packages/plugin-report/package.json +++ b/ui/packages/plugin-report/package.json @@ -38,6 +38,7 @@ "@object-ui/permissions": "workspace:*", "@object-ui/react": "workspace:*", "@object-ui/types": "workspace:*", + "@objectstack/spec": "workspace:^", "exceljs": "^4.4.0", "lucide-react": "^1.43.0" }, @@ -47,7 +48,6 @@ }, "devDependencies": { "@object-ui/test-support": "workspace:*", - "@objectstack/spec": "workspace:^", "@types/node": "^26.6.5", "@types/react": "19.3.0", "@types/react-dom": "19.3.0", diff --git a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx index a9457d15563..127e59e852f 100644 --- a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx +++ b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx @@ -147,6 +147,7 @@ import { import { builtinAggregateLabels, useSafeFieldLabel, useSafeTranslate, useDisplayLocale, useObjectTranslation, pickLocalized } from '@object-ui/i18n'; import { useDataInvalidation, classifyLoadError } from '@object-ui/react'; import { mergeFilters } from './mergeFilters'; +import { chartDrawsEmptyGroups, fillEmptyOptionGroups } from './emptyOptionGroups'; import { measureDrillScope, sharedMeasureDrillScope, scopeDrillFilter, type MeasureDrillScope } from './measureDrillScope'; import { useDatasetDimensionMeta, type DatasetDimensionMeta } from './useDatasetDimensionLabels'; import { @@ -1757,8 +1758,17 @@ function DatasetReportChart({ // component). Mirrors `DatasetWidget`'s own call exactly. (Since // objectui#12243 the tables above read the same hook, for the declared order.) const dimensionMeta = useDatasetDimensionMeta(state.object, state.dimensionFields, chartDimensions); - const { categoryColors, dimensionLabels, categoryOrder, seriesOrder } = React.useMemo(() => { - if (!dimensionMeta) return { categoryColors: null, dimensionLabels: null, categoryOrder: null, seriesOrder: null }; + const { categoryColors, dimensionLabels, categoryOrder, seriesOrder, xOptions, xLocalizedOptions } = React.useMemo(() => { + if (!dimensionMeta) { + return { + categoryColors: null, + dimensionLabels: null, + categoryOrder: null, + seriesOrder: null, + xOptions: undefined, + xLocalizedOptions: undefined, + }; + } const { metaByPath, relabel } = dimensionMeta; // Colours and declared order read `option.label`, so they are fed the // LOCALIZED options — the same "translate the options, then render them" @@ -1784,6 +1794,10 @@ function DatasetReportChart({ dimensionLabels: deriveDimensionLabelMaps(metaByPath, relabel, fieldOptionLabel), categoryOrder: buildCategoryOrder(firstDimOptions), seriesOrder: buildCategoryOrder(secondDimOptions), + // The x-axis field's declared options, authored and translated, for the + // `showEmptyGroups` fill (objectstack#36722). + xOptions: firstDimMeta?.options as unknown, + xLocalizedOptions: firstDimOptions, }; }, [dimensionMeta, fieldOptionLabel]); @@ -1954,8 +1968,34 @@ function DatasetReportChart({ // undeclared values next in the dataset's order, the empty bucket last. A // report whose `order` reaches this chart's selection keeps the server's // order. No drill reads these rows by index, so the reordered copy is safe. - const displayRows = relabelDimensions(state.rows, dimensionLabels); - const categoryRank = scopeOrder(order, queryDimensions, queryMeasures) ? null : buildCategoryRank(categoryOrder); + // + // objectstack#36722 — `chart.showEmptyGroups`: the declared options of the + // x-axis field that no row carries are added BEFORE the relabelling, carrying + // their stored value as an unresolved server row would, so they take the + // label, the declared position and the option colour every real group takes. + // Their measure cells read the executor's empty-group value for the column's + // aggregate (`fillEmptyOptionGroups`). Not filled under an order that reaches + // this selection: the server placed every row, and an added group has no + // position in an order it was never part of. A field with no declared options + // has no known set of values and is never filled; a date axis needs no fill + // here, the executor already answers every bucket of the report's period. + // Only a chart type with a category axis is filled (`chartDrawsEmptyGroups`): + // a value-sized chart (pie, donut, funnel, treemap, sankey) draws a zero + // group as nothing, or worse, and scatter refuses a select axis outright. + const chartOrder = scopeOrder(order, queryDimensions, queryMeasures); + const chartRows = chart.showEmptyGroups === true && !chartOrder && chartDrawsEmptyGroups(chart.type) + ? fillEmptyOptionGroups(state.rows, { + xAxis, + ...(seriesBy ? { seriesBy } : {}), + measures: compareTo && !seriesBy ? [yAxis, compareKey] : [yAxis], + aggregate: measureField(yAxis)?.aggregate, + options: xOptions, + localizedOptions: xLocalizedOptions, + ...(state.drillRawRows ? { rawRows: state.drillRawRows } : {}), + }) + : state.rows; + const displayRows = relabelDimensions(chartRows, dimensionLabels); + const categoryRank = chartOrder ? null : buildCategoryRank(categoryOrder); const plotLayout = arrangeByDeclaredOptions( displayRows, [xAxis], @@ -2025,6 +2065,8 @@ function DatasetReportChart({ }); if (at < 0) return; const index = plotLayout ? plotLayout[at] : at; + // A group `showEmptyGroups` added counted no record: it opens no list. + if (index >= state.rows.length) return; const groupKey: Record = {}; for (const dim of queryDimensions) groupKey[dim] = displayRows[index]?.[dim]; emitBucketDrill({ diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.dateRange-25873.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.dateRange-25873.test.tsx index 85e8bbcecff..a05ba3c0e09 100644 --- a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.dateRange-25873.test.tsx +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.dateRange-25873.test.tsx @@ -14,6 +14,7 @@ import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/re import '@testing-library/jest-dom'; import { SchemaRendererProvider } from '@object-ui/react'; import { I18nProvider } from '@object-ui/i18n'; +import { ComponentRegistry } from '@object-ui/core'; import { DatasetReportRenderer } from '../DatasetReportRenderer'; // Radix Select opens on pointer events the DOM environment does not implement; @@ -294,3 +295,62 @@ describe('DatasetReportRenderer reads the date dimension as the report\'s reader expect(src.selections[0].timeDimensions).toEqual([{ dimension: 'bare_date', dateRange: 'last_90_days' }]); }); }); + +/** + * objectstack#36722 — `chart.showEmptyGroups` and a date axis. The executor + * already answers every bucket of the report's period, the empty ones at 0 + * (`fillEmptyTimeBuckets`, pinned in service-analytics + * `dataset-time-bucket-zero-fill.test.ts`), so the switch adds nothing there: + * with it on or off the report posts the same window and plots the same + * buckets. A date dimension declares no options, so the chart's fill never + * runs on it. + */ +describe('a date axis over the report period is the same with chart.showEmptyGroups on or off (objectstack#36722)', () => { + // The answer as the executor gives it for a three-month window with an + // empty middle month: the bucket is there, at 0. + const MONTHS = [ + { close_date: '2026-09', amount: 4 }, + { close_date: '2026-10', amount: 0 }, + { close_date: '2026-11', amount: 7 }, + ]; + + it('posts the same selection and plots the same buckets', async () => { + const runs: Array<{ selections: unknown[]; data: unknown }> = []; + for (const showEmptyGroups of [false, true]) { + let data: unknown; + ComponentRegistry.register('chart', (props: { schema: { data?: unknown } }) => { + data = props.schema.data; + return null; + }); + const selections: unknown[] = []; + const src = { + selections, + queryDataset: vi.fn(async (_dataset: string, selection: unknown) => { + selections.push(selection); + return { + rows: MONTHS, + fields: [{ name: 'close_date', type: 'date' }, { name: 'amount', type: 'number', aggregate: 'sum' }], + }; + }), + }; + const { apiFetch } = makeApiFetch([{ name: 'close_date', type: 'date' }]); + const { unmount } = renderReport( + { + ...BASE, + rows: ['close_date'], + chart: { type: 'line', xAxis: 'close_date', yAxis: 'amount', ...(showEmptyGroups ? { showEmptyGroups } : {}) }, + dateRange: { dimension: 'close_date', defaultRange: 'last_90_days' }, + }, + src as unknown as ReturnType, + apiFetch, + ); + await waitFor(() => expect(Array.isArray(data) && (data as unknown[]).length).toBe(3)); + runs.push({ selections: [...selections], data }); + unmount(); + } + expect(runs[1].selections).toEqual(runs[0].selections); + expect(runs[0].selections.every((s) => JSON.stringify((s as { timeDimensions?: unknown }).timeDimensions) === JSON.stringify([{ dimension: 'close_date', dateRange: 'last_90_days' }]))).toBe(true); + expect(runs[1].data).toEqual(runs[0].data); + expect(runs[1].data).toEqual(MONTHS); + }); +}); diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.test.tsx index 5574d2d0565..58533c41be3 100644 --- a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.test.tsx +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.test.tsx @@ -19,10 +19,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'; import '@testing-library/jest-dom'; import { I18nProvider } from '@object-ui/i18n'; +import { ComponentRegistry } from '@object-ui/core'; import { DatasetReportRenderer, isDatasetReport } from '../DatasetReportRenderer'; type MockRows = Array>; -type MockField = { name: string; type?: string; label?: string; format?: string; currency?: string }; +type MockField = { name: string; type?: string; label?: string; format?: string; currency?: string; aggregate?: string }; type MockResult = { rows: MockRows; fields?: MockField[]; @@ -1466,3 +1467,195 @@ describe('DatasetReportRenderer — drilling a relationship-path dimension (obje warn.mockRestore(); }); }); + +/** + * objectstack#36722 — `chart.showEmptyGroups`: the report chart adds the x-axis + * field's DECLARED options the dataset answer left out, valued by the + * executor's empty-group table (`emptyGroupValueFor`): `0` for count and sum, + * empty for avg. The answer below is server-resolved to the authored label + * (ADR-0021) and holds two of the four declared stages. + * + * DIRECTIONS, written before the ablation: with the call site's fill removed + * (the chart plots `state.rows` as before), every "adds" case goes RED and the + * three controls stay GREEN on both sides, on purpose. + */ +describe('DatasetReportRenderer — chart.showEmptyGroups (objectstack#36722)', () => { + const STAGES = [ + { value: 'prospecting', label: 'Prospecting' }, + { value: 'qualification', label: 'Qualification' }, + { value: 'proposal', label: 'Proposal' }, + { value: 'closed_won', label: 'Closed Won' }, + ]; + let chartSchema: { data?: Array> } | null = null; + let chartClick: ((ev: Record) => void) | undefined; + + beforeEach(() => { + chartSchema = null; + chartClick = undefined; + metaDocs.deal = { + name: 'deal', + fields: { stage: { type: 'select', options: STAGES }, region: { type: 'text' }, owner: { type: 'select', options: [{ value: 'amy', label: 'Amy' }, { value: 'bo', label: 'Bo' }] } }, + }; + ComponentRegistry.register('chart', (props: { schema: { data?: Array> }; onChartClick?: (ev: Record) => void }) => { + chartSchema = props.schema; + chartClick = props.onChartClick; + return null; + }); + }); + + const answer = (aggregate: string | undefined, extra: Partial = {}): MockResult => ({ + rows: [ + { stage: 'Closed Won', deals: 3 }, + { stage: 'Qualification', deals: 5 }, + ], + fields: [ + { name: 'stage', type: 'string', label: 'Stage' }, + { name: 'deals', type: 'number', label: 'Deals', ...(aggregate ? { aggregate } : {}) }, + ], + object: 'deal', + dimensionFields: { stage: 'stage' }, + drillRawRows: [{ stage: 'closed_won' }, { stage: 'qualification' }], + drillScopes: { deals: {} }, + ...extra, + }); + const report = (chart: Record, extra: Record = {}) => ({ + name: 'deals_by_stage', + type: 'summary', + dataset: 'deal_metrics', + rows: ['stage'], + values: ['deals'], + chart: { type: 'bar', xAxis: 'stage', yAxis: 'deals', ...chart }, + ...extra, + }); + /** The plotted categories once the option metadata has landed (the declared order moves them). */ + const plotted = async (key = 'stage') => { + await waitFor(() => expect(chartSchema?.data?.[0]?.[key]).toBe('Qualification')); + return chartSchema!.data!; + }; + + it('adds the empty declared options in their declared place, at 0 for a count', async () => { + render(); + await waitFor(() => expect(chartSchema?.data?.map((r) => r.stage)).toEqual(['Prospecting', 'Qualification', 'Proposal', 'Closed Won'])); + expect(chartSchema!.data).toEqual([ + { stage: 'Prospecting', deals: 0 }, + { stage: 'Qualification', deals: 5 }, + { stage: 'Proposal', deals: 0 }, + { stage: 'Closed Won', deals: 3 }, + ]); + }); + + it('a group the server labelled in its own words is matched by the stored value its raw twin carries: no false zero', async () => { + // The server translated `closed_won` at the request locale as "Gewonnen"; + // the client knows the option only as "Closed Won". `drillRawRows` states + // `closed_won`, so the real group is recognised and only the two empty + // stages are added. + const translated = answer('count', { rows: [{ stage: 'Gewonnen', deals: 3 }, { stage: 'Qualification', deals: 5 }] }); + render(); + await waitFor(() => expect(chartSchema?.data).toHaveLength(4)); + expect(chartSchema!.data!.map((r) => r.stage).sort()).toEqual(['Gewonnen', 'Proposal', 'Prospecting', 'Qualification']); + expect(chartSchema!.data!.find((r) => r.stage === 'Closed Won')).toBeUndefined(); + expect(chartSchema!.data!.find((r) => r.stage === 'Gewonnen')).toEqual({ stage: 'Gewonnen', deals: 3 }); + }); + + it('a sum reads 0 too; an avg is left empty (nothing to average)', async () => { + const { unmount } = render(); + await waitFor(() => expect(chartSchema?.data).toHaveLength(4)); + expect(chartSchema!.data!.find((r) => r.stage === 'Proposal')).toEqual({ stage: 'Proposal', deals: 0 }); + unmount(); + chartSchema = null; + render(); + await waitFor(() => expect(chartSchema?.data).toHaveLength(4)); + const proposal = chartSchema!.data!.find((r) => r.stage === 'Proposal')!; + expect(proposal).toEqual({ stage: 'Proposal' }); + expect('deals' in proposal).toBe(false); + }); + + it('with a seriesBy split, an added stage reads 0 in every series', async () => { + const src = makeSource({ + deal_metrics: answer('count', { + rows: [ + { stage: 'Closed Won', owner: 'Amy', deals: 3 }, + { stage: 'Qualification', owner: 'Bo', deals: 5 }, + ], + dimensionFields: { stage: 'stage', owner: 'owner' }, + }), + }); + render(); + await waitFor(() => expect(chartSchema?.data).toHaveLength(4)); + const prospecting = chartSchema!.data!.find((r) => r.stage === 'Prospecting')!; + expect(Object.values(prospecting).filter((v) => typeof v === 'number')).toEqual([0, 0]); + }); + + it('a mark on an added stage opens no list; a real one still drills', async () => { + const onDrill = vi.fn(); + render(); + await waitFor(() => expect(chartSchema?.data).toHaveLength(4)); + await waitFor(() => expect(chartClick).toBeTypeOf('function')); + chartClick!({ category: 'Proposal', series: 'deals' }); + expect(onDrill).not.toHaveBeenCalled(); + chartClick!({ category: 'Qualification', series: 'deals' }); + await waitFor(() => expect(onDrill).toHaveBeenCalledTimes(1)); + }); + + it('CONTROL — switch off (absent): only the groups the answer holds', async () => { + render(); + expect((await plotted()).map((r) => r.stage)).toEqual(['Qualification', 'Closed Won']); + }); + + it('CONTROL — an order reaching the chart (a measure): not filled, the server placed every row', async () => { + const src = makeSource({ deal_metrics: answer('count') }); + render(); + await waitFor(() => expect(chartSchema?.data).toBeDefined()); + // The option read lands, and still nothing is added. + await waitFor(() => expect(probedObjects()).toContain('deal')); + await new Promise((r) => setTimeout(r, 20)); + expect(chartSchema!.data!.map((r) => r.stage)).toEqual(['Closed Won', 'Qualification']); + const chartCall = src.calls.find((c) => c.selection.dimensions?.length === 1); + expect(chartCall?.selection.order).toEqual({ deals: 'desc' }); + }); + + it('CONTROL — a field with no declared options (text): nothing to fill', async () => { + const src = makeSource({ + deal_metrics: answer('count', { + rows: [{ region: 'North', deals: 2 }], + fields: [{ name: 'region', type: 'string' }, { name: 'deals', type: 'number', aggregate: 'count' }], + dimensionFields: { region: 'region' }, + }), + }); + render(); + await waitFor(() => expect(probedObjects()).toContain('deal')); + await new Promise((r) => setTimeout(r, 20)); + expect(chartSchema!.data).toEqual([{ region: 'North', deals: 2 }]); + }); + + it('CONTROL — a chart that sizes its marks by value (pie, donut, funnel, treemap, sankey): nothing is added', async () => { + for (const type of ['pie', 'donut', 'funnel', 'treemap', 'sankey']) { + chartSchema = null; + const { unmount } = render(); + // The option read has landed (the declared order moved Qualification first), and still nothing is added. + expect([type, (await plotted()).map((r) => r.stage)]).toEqual([type, ['Qualification', 'Closed Won']]); + unmount(); + } + }); + + it('a category-axis type the builder does not draw (area, column) is filled like a bar', async () => { + for (const type of ['area', 'column']) { + chartSchema = null; + const { unmount } = render(); + await waitFor(() => expect(chartSchema?.data).toHaveLength(4)); + expect([type, chartSchema!.data!.map((r) => r.stage)]).toEqual([type, ['Prospecting', 'Qualification', 'Proposal', 'Closed Won']]); + unmount(); + } + }); + + it('the switch is presentation only: the dataset selection posted is the same with it on or off', async () => { + const off = makeSource({ deal_metrics: answer('count') }); + const { unmount } = render(); + await waitFor(() => expect(off.calls.length).toBeGreaterThan(0)); + unmount(); + const on = makeSource({ deal_metrics: answer('count') }); + render(); + await waitFor(() => expect(on.calls.length).toBe(off.calls.length)); + expect(on.calls).toEqual(off.calls); + }); +}); diff --git a/ui/packages/plugin-report/src/__tests__/emptyOptionGroups.test.ts b/ui/packages/plugin-report/src/__tests__/emptyOptionGroups.test.ts new file mode 100644 index 00000000000..c57192f69df --- /dev/null +++ b/ui/packages/plugin-report/src/__tests__/emptyOptionGroups.test.ts @@ -0,0 +1,98 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36722 — `fillEmptyOptionGroups`, the rows `chart.showEmptyGroups` + * adds. The renderer-level cases live in `DatasetReportRenderer.test.tsx` + * (describe "chart.showEmptyGroups"); these pin the walk itself. + */ +import { describe, it, expect } from 'vitest'; +import { fillEmptyOptionGroups } from '../emptyOptionGroups'; + +const OPTIONS = [ + { value: 'open', label: 'Open' }, + { value: 'won', label: 'Won' }, + { value: 'lost', label: 'Lost' }, +]; + +describe('fillEmptyOptionGroups (objectstack#36722)', () => { + it('a row may carry the stored value, the authored label or the translated label: all three count as present', () => { + const rows = [{ s: 'open', n: 1 }, { s: 'Won', n: 2 }, { s: '输', n: 3 }]; + const localized = [ + { value: 'open', label: '进行中' }, + { value: 'won', label: '赢' }, + { value: 'lost', label: '输' }, + ]; + const out = fillEmptyOptionGroups(rows, { xAxis: 's', measures: ['n'], aggregate: 'count', options: OPTIONS, localizedOptions: localized }); + expect(out).toBe(rows); + }); + + it('a row with a raw twin is matched by its STORED value, not by a label the two sides spell differently', () => { + // The server relabelled `won` as "Gewonnen" (its own translation at the + // request locale); the client knows only "Won" and "赢". The raw twin + // states `won`, so Won is present and only the two empty options are added. + const rows = [{ s: 'Gewonnen', n: 2 }]; + const rawRows = [{ s: 'won' }]; + const localized = [ + { value: 'open', label: '进行中' }, + { value: 'won', label: '赢' }, + { value: 'lost', label: '输' }, + ]; + const out = fillEmptyOptionGroups(rows, { xAxis: 's', measures: ['n'], aggregate: 'count', options: OPTIONS, localizedOptions: localized, rawRows }); + expect(out.slice(1)).toEqual([{ s: 'open', n: 0 }, { s: 'lost', n: 0 }]); + // CONTROL: without the raw twin the label matches nothing, and Won is added + // as a false zero beside its own real group, the case the raw value prevents. + const blind = fillEmptyOptionGroups(rows, { xAxis: 's', measures: ['n'], aggregate: 'count', options: OPTIONS, localizedOptions: localized }); + expect(blind.slice(1).map((r) => r.s)).toEqual(['open', 'won', 'lost']); + }); + + it('a raw twin that states the stored value overrules a display spelling another option carries', () => { + // The row reads "Lost" on screen but its stored value is `open`: only + // `open` is present, so `won` and `lost` are added. + const out = fillEmptyOptionGroups([{ s: 'Lost', n: 1 }], { xAxis: 's', measures: ['n'], aggregate: 'count', options: OPTIONS, rawRows: [{ s: 'open' }] }); + expect(out.slice(1).map((r) => r.s)).toEqual(['won', 'lost']); + }); + + it('a row with no raw twin (or one without the x-axis key) falls back to spellings', () => { + const rows = [{ s: 'Won', n: 2 }, { s: 'open', n: 1 }]; + const out = fillEmptyOptionGroups(rows, { xAxis: 's', measures: ['n'], aggregate: 'count', options: OPTIONS, rawRows: [{ other: 1 }] }); + expect(out.slice(2)).toEqual([{ s: 'lost', n: 0 }]); + }); + + it('appends after the answer, so every index below rows.length still addresses the answer', () => { + const rows = [{ s: 'Won', n: 2 }]; + const out = fillEmptyOptionGroups(rows, { xAxis: 's', measures: ['n'], aggregate: 'count_distinct', options: OPTIONS }); + expect(out[0]).toBe(rows[0]); + expect(out.slice(1)).toEqual([{ s: 'open', n: 0 }, { s: 'lost', n: 0 }]); + }); + + it('an aggregate the answer does not state gets no value (never a guessed 0)', () => { + const out = fillEmptyOptionGroups([{ s: 'Won', n: 2 }], { xAxis: 's', measures: ['n'], aggregate: undefined, options: OPTIONS }); + expect(out.slice(1)).toEqual([{ s: 'open' }, { s: 'lost' }]); + }); + + it('min and max are left empty, like avg', () => { + for (const aggregate of ['min', 'max', 'avg']) { + const out = fillEmptyOptionGroups([{ s: 'Won', n: 2 }], { xAxis: 's', measures: ['n'], aggregate, options: OPTIONS }); + expect(out.slice(1).every((r) => !('n' in r))).toBe(true); + } + }); + + it('with a split: one row per series value the answer holds, the null series included', () => { + const rows = [{ s: 'Won', o: 'amy', n: 1 }, { s: 'Won', o: null, n: 1 }]; + const out = fillEmptyOptionGroups(rows, { xAxis: 's', seriesBy: 'o', measures: ['n'], aggregate: 'sum', options: [OPTIONS[0], OPTIONS[1]] }); + expect(out.slice(2)).toEqual([{ s: 'open', o: 'amy', n: 0 }, { s: 'open', o: null, n: 0 }]); + }); + + it('a compared measure fills its __compare column with the same value', () => { + const out = fillEmptyOptionGroups([{ s: 'Won', n: 2, n__compare: 1 }], { xAxis: 's', measures: ['n', 'n__compare'], aggregate: 'count', options: [OPTIONS[0], OPTIONS[1]] }); + expect(out.slice(1)).toEqual([{ s: 'open', n: 0, n__compare: 0 }]); + }); + + it('bare-string options, a duplicate declaration, and no options at all', () => { + expect(fillEmptyOptionGroups([{ s: 'a' }], { xAxis: 's', measures: ['n'], aggregate: 'count', options: ['a', 'b', 'b'] }).slice(1)) + .toEqual([{ s: 'b', n: 0 }]); + const rows = [{ s: 'a' }]; + expect(fillEmptyOptionGroups(rows, { xAxis: 's', measures: ['n'], aggregate: 'count', options: undefined })).toBe(rows); + expect(fillEmptyOptionGroups(rows, { xAxis: 's', measures: ['n'], aggregate: 'count', options: [] })).toBe(rows); + }); +}); diff --git a/ui/packages/plugin-report/src/__tests__/reportBuilder-36374.test.tsx b/ui/packages/plugin-report/src/__tests__/reportBuilder-36374.test.tsx index df2c4a10c5a..191aaef1e52 100644 --- a/ui/packages/plugin-report/src/__tests__/reportBuilder-36374.test.tsx +++ b/ui/packages/plugin-report/src/__tests__/reportBuilder-36374.test.tsx @@ -11,22 +11,29 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; import { ComponentRegistry } from '@object-ui/core'; -import { ReportSchema } from '@objectstack/spec/ui'; +import { ChartTypeSchema, ReportSchema } from '@objectstack/spec/ui'; +import { enumOptions } from '@object-ui/test-support'; import { ReportBuilder } from '../builder/ReportBuilder'; import { + chartKeepsEmptyGroups, + chartShowsEmptyGroups, fillDefaults, missingPiece, + offersShowEmptyGroups, pickChartType, pickDataset, pickGrouping, pickMeasure, + setShowEmptyGroups, setShowValues, setTargetLine, + showsEmptyGroups, targetLine, type ReportBuilderMembers, type ReportDraft, } from '../builder/reportBuilderModel'; -import { DatasetReportRenderer } from '../DatasetReportRenderer'; +import { DatasetReportRenderer, planReportChart } from '../DatasetReportRenderer'; +import { chartDrawsEmptyGroups } from '../emptyOptionGroups'; const MEMBERS: ReportBuilderMembers = { measures: [ @@ -400,3 +407,129 @@ describe('the report filter under the data source (objectstack#36645)', () => { expect(same.runtimeFilter).toEqual({ stage: { $eq: 'won' } }); }); }); + +/** + * objectstack#36722 — "Show groups with no records" (`chart.showEmptyGroups`): a switch + * in the chart settings, offered on the chart types that draw a category per + * group, written into the report the host saves and read back when it opens. + */ +describe('the show-groups-with-no-records switch (objectstack#36722)', () => { + beforeEach(() => { + ComponentRegistry.register('chart', () =>
); + }); + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + const box = (value = '') => ({ value, onChange: () => {} }); + const dataSource = { queryDataset: vi.fn(async () => ({ rows: [{ stage: 'Won', total_amount: 10 }], fields: [] })) }; + + /** The console host's shape: it saves the draft it holds when Save is pressed. */ + function SaveHarness({ initial, saved }: { initial: ReportDraft; saved: ReportDraft[] }) { + const [report, setReport] = React.useState(initial); + return ( + { saved.push(report); }} + onDiscard={() => setReport(initial)} + onClose={() => {}} + dirty={report !== initial} + dataSource={dataSource} + /> + ); + } + + it('turned on, it is in the report Save hands over; reopened, the switch reads on; off removes the key', () => { + const saved: ReportDraft[] = []; + const { unmount } = render(); + const toggle = screen.getByTestId('report-builder-show-empty-groups'); + expect(toggle).toHaveAttribute('aria-checked', 'false'); + fireEvent.click(toggle); + fireEvent.click(screen.getByTestId('report-builder-save')); + expect(saved).toHaveLength(1); + expect(saved[0].chart).toEqual({ ...(EXISTING.chart as object), showEmptyGroups: true }); + expectSpecValid(saved[0]); + unmount(); + + render(); + const reopened = screen.getByTestId('report-builder-show-empty-groups'); + expect(reopened).toHaveAttribute('aria-checked', 'true'); + fireEvent.click(reopened); + fireEvent.click(screen.getByTestId('report-builder-save')); + expect(saved[1].chart).toEqual(EXISTING.chart); + expect(saved[1].chart).not.toHaveProperty('showEmptyGroups'); + }); + + it('offered on bar and line; hidden on a donut, which keeps the key; a number or a table drops it', () => { + render(); + fireEvent.click(screen.getByTestId('report-builder-chart-line')); + expect(screen.getByTestId('report-builder-show-empty-groups')).toHaveAttribute('aria-checked', 'true'); + // A donut sizes its slices by value, so an empty group has nowhere to be + // drawn: no switch, but the key survives the trip back to a bar. + fireEvent.click(screen.getByTestId('report-builder-chart-donut')); + expect(screen.queryByTestId('report-builder-show-empty-groups')).toBeNull(); + fireEvent.click(screen.getByTestId('report-builder-chart-bar')); + expect(screen.getByTestId('report-builder-show-empty-groups')).toHaveAttribute('aria-checked', 'true'); + fireEvent.click(screen.getByTestId('report-builder-chart-metric')); + expect(screen.queryByTestId('report-builder-show-empty-groups')).toBeNull(); + }); + + it('the model: every chart edit keeps it where it draws, and drops it where it cannot', () => { + const on = setShowEmptyGroups(EXISTING, true); + expect(showsEmptyGroups(on)).toBe(true); + expect(showsEmptyGroups(pickGrouping(on, 'owner', '', MEMBERS))).toBe(true); + expect(showsEmptyGroups(pickMeasure(on, 'deal_count', MEMBERS))).toBe(true); + expect(showsEmptyGroups(pickChartType(on, 'line', MEMBERS))).toBe(true); + expect(pickChartType(on, 'metric', MEMBERS).chart).not.toHaveProperty('showEmptyGroups'); + expect(pickChartType(on, 'table', MEMBERS)).not.toHaveProperty('chart'); + expect(setShowEmptyGroups(on, false).chart).toEqual(EXISTING.chart); + // No chart to set it on: the report is returned as it is. + const noChart = { ...EXISTING, chart: undefined }; + expect(setShowEmptyGroups(noChart, true)).toBe(noChart); + }); + + it('a stored value-sized type (a funnel) keeps an authored key across unrelated edits, and offers no switch', () => { + const funnel = setShowEmptyGroups({ ...EXISTING, chart: { type: 'funnel', xAxis: 'stage', yAxis: 'total_amount' } }, true); + expect(showsEmptyGroups(pickMeasure(funnel, 'deal_count', MEMBERS))).toBe(true); + expect(showsEmptyGroups(pickGrouping(funnel, 'owner', '', MEMBERS))).toBe(true); + expect(pickMeasure(funnel, 'deal_count', MEMBERS).chart).toMatchObject({ type: 'funnel' }); + // A stored single-value type draws no category: an edit drops the key there. + const gauge = { ...EXISTING, chart: { type: 'gauge', xAxis: 'stage', yAxis: 'total_amount', showEmptyGroups: true } }; + expect(pickMeasure(gauge, 'deal_count', MEMBERS).chart).not.toHaveProperty('showEmptyGroups'); + + render(); + expect(screen.queryByTestId('report-builder-show-empty-groups')).toBeNull(); + // A stored category-axis type the builder does not draw (an area) shows it. + cleanup(); + const area = setShowEmptyGroups({ ...EXISTING, chart: { type: 'area', xAxis: 'stage', yAxis: 'total_amount' } }, true); + render(); + expect(screen.getByTestId('report-builder-show-empty-groups')).toHaveAttribute('aria-checked', 'true'); + }); + + it('a date axis shows no switch (every bucket already appears); the model keeps an authored key there', () => { + const byDate: ReportDraft = { ...EXISTING, rows: ['close_month'], chart: { type: 'bar', xAxis: 'close_month', yAxis: 'total_amount', showEmptyGroups: true } }; + expect(offersShowEmptyGroups(byDate, MEMBERS)).toBe(false); + expect(offersShowEmptyGroups(EXISTING, MEMBERS)).toBe(true); + render(); + expect(screen.queryByTestId('report-builder-show-empty-groups')).toBeNull(); + expect(showsEmptyGroups(pickMeasure(byDate, 'deal_count', MEMBERS))).toBe(true); + }); + + it('over the whole spec vocabulary: kept on every series type (planReportChart), offered only where the renderer fills', () => { + const types = enumOptions(ChartTypeSchema); + expect(types.length).toBeGreaterThan(0); + for (const t of types) { + expect([t, chartKeepsEmptyGroups(t)]).toEqual([t, planReportChart(t).kind === 'series']); + expect([t, chartShowsEmptyGroups(t)]).toEqual([t, chartDrawsEmptyGroups(t)]); + } + // The filled set is the category-axis series types, and none of the value-sized ones. + expect(types.filter((t) => chartDrawsEmptyGroups(t)).sort()) + .toEqual(['area', 'bar', 'column', 'combo', 'horizontal-bar', 'line', 'radar']); + }); +}); diff --git a/ui/packages/plugin-report/src/builder/ReportBuilder.tsx b/ui/packages/plugin-report/src/builder/ReportBuilder.tsx index a7ebdaaee46..46f2aa645b3 100644 --- a/ui/packages/plugin-report/src/builder/ReportBuilder.tsx +++ b/ui/packages/plugin-report/src/builder/ReportBuilder.tsx @@ -46,6 +46,7 @@ import { REPORT_BUILDER_CHART_TYPES, boundDataset, chartSplits, + offersShowEmptyGroups, chartTakesTargetLine, fillDefaults, missingPiece, @@ -57,7 +58,9 @@ import { selectedGrouping, selectedMeasure, setShowValues, + setShowEmptyGroups, setTargetLine, + showsEmptyGroups, targetLine, type ReportBuilderDataset, type ReportBuilderMembers, @@ -505,6 +508,19 @@ export function ReportBuilder({ />
) : null} + {offersShowEmptyGroups(report, members) ? ( +
+ + onChange(setShowEmptyGroups(report, on))} + data-testid="report-builder-show-empty-groups" + /> +
+ ) : null} {chartTakesTargetLine(chartType) ? (