diff --git a/.changeset/36645-report-compare-previous-period.md b/.changeset/36645-report-compare-previous-period.md new file mode 100644 index 00000000000..27fac3dd2dc --- /dev/null +++ b/.changeset/36645-report-compare-previous-period.md @@ -0,0 +1,13 @@ +--- +'@object-ui/plugin-report': patch +'@object-ui/i18n': patch +--- + +feat(report): 「Compare with previous period」 beside a report's period chip — the chart draws the earlier window beside the current one + +Clause-②: yes (widening) — one new `@object-ui/i18n` key, `report.dateRange.comparePrevious`, in all 11 locales; no export, spec key, schema or server change +Metadata-protocol: none + +- **The switch**: a report that declares `dateRange` now shows 「Compare with previous period」 next to its period chip when its chart can draw a comparison: bar, column, horizontal bar, line or area over a category axis, or a single number. It is not offered on a `seriesBy` split, nor on a chart whose x axis is the window's own date dimension, where the earlier window's date buckets would not line up with the current ones. Like the period pick it is the viewer's and is not saved into the report. It is off, and cannot be turned on, while the period is All time or a custom range missing an end. +- **What it asks for**: the chart's dataset query carries the contract's `compareTo: { kind: 'previousPeriod', dimension }`, on the same dimension and window the period chip already sends. The chart is compared with the same-length window just before the current one (the contract's `previousPeriod`). The table beside the chart is not asked for a comparison. +- **What it draws**: a bar or line chart gets one more series, the measure's earlier window, labelled 「 · vs previous period」 and drawn muted by the chart's existing `comparison` styling; a single number shows the previous period's value and the change in percent under it. A click on an earlier-window mark opens no record list, the dashboard's rule for the same series. A comparison the server refuses is shown where the chart was, instead of the chart disappearing. diff --git a/content/docs/ui/reports.mdx b/content/docs/ui/reports.mdx index 87b5479848c..00ec6043035 100644 --- a/content/docs/ui/reports.mdx +++ b/content/docs/ui/reports.mdx @@ -248,6 +248,16 @@ same custom-range switch, on by default. - **The window is a filter, not a bucket.** It is applied with the report's `runtimeFilter` and the dataset's own filter. How rows are grouped by date stays with the dimension's `dateGranularity` and the report's `rows` / `columns`. +- **Compare with the previous period** is a switch beside the period chip, not a report key. + Like the chip's own pick, it belongs to the viewer and is not saved. While it is on and the + period names a window, the chart is compared with **the same-length window just before it** + (`compareTo: { kind: 'previousPeriod' }` on the window's dimension): a bar or line chart draws + the earlier window as a muted series, and a single number shows the previous value and the + change under it. All time names no window, so nothing is compared. +- **Where it is offered**: a chart that can draw a second series (`bar`, `column`, + `horizontal-bar`, `line`, `area`) over a category axis, or a single number (`metric`, `kpi`). + It is not offered on a `seriesBy` split, nor on a chart whose x axis is the window's own date + dimension: there the earlier window's date buckets would not line up with the current ones. **`exportOptions`** uses the list export's key and member names: `formats`, `includeHeaders`, `fileNamePrefix`. A report table downloads as `csv` or `xlsx`. Export is on @@ -260,12 +270,9 @@ rows are already aggregated. permissions allow **export of the dataset's base object**. That is the permission-set `allowExport` axis the list toolbar uses (see [Permissions and protection](#permissions-and-protection)). - -**Declared, not drawn yet.** The Console report page does not read either key yet: there is -no period chip and no export control on it today. Until the renderer ships, `os validate` -warns on both keys so the gap is visible. The declarations are the contract the renderer -implements. - +On the Console report page, a report that declares `dateRange` draws a period chip above the +report, and every query the report makes runs inside the chosen window. The Export control is +drawn once the table has rows. What is deliberately **not** offered: a `joined` report refuses both keys, because its blocks may bind different datasets and it draws one table per block. A report has no subscription or diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 8c0e5292784..336b3949654 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -4419,6 +4419,7 @@ const ar = { dateRange: { from: "من", to: "إلى", + comparePrevious: "مقارنة بالفترة السابقة", datasetUnreadable: "لا تحدد الفترة الزمنية لهذا التقرير أي بُعد، وتعذّرت قراءة مجموعة البيانات \"{{dataset}}\" للعثور على بُعد التاريخ ({{reason}}).", noSingleDateDimension: "لا تحدد الفترة الزمنية لهذا التقرير أي بُعد، وتعلن مجموعة البيانات \"{{dataset}}\" عن {{total}} من أبعاد التاريخ ({{found}}) بينما يلزم بُعد واحد بالضبط. حدّد بُعد التاريخ في dateRange.dimension الخاص بالتقرير.", }, diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index d677a8df6fe..16a8acfa4e7 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4061,6 +4061,7 @@ const de = { dateRange: { from: "Von", to: "Bis", + comparePrevious: "Mit vorheriger Periode vergleichen", datasetUnreadable: "Der Zeitraum dieses Berichts nennt keine Dimension, und das Dataset {{dataset}} konnte nicht gelesen werden, um seine Datumsdimension zu finden ({{reason}}).", noSingleDateDimension: "Der Zeitraum dieses Berichts nennt keine Dimension, und das Dataset {{dataset}} deklariert {{total}} Datumsdimensionen ({{found}}), benötigt wird genau eine. Nennen Sie die Datumsdimension in dateRange.dimension des Berichts.", }, diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 58771dbbf06..697745cdd79 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2157,6 +2157,7 @@ const en = { dateRange: { from: 'From', to: 'To', + comparePrevious: 'Compare with previous period', datasetUnreadable: 'This report’s date range names no dimension, and the “{{dataset}}” dataset could not be read to find its date dimension ({{reason}}).', noSingleDateDimension: 'This report’s date range names no dimension, and the “{{dataset}}” dataset declares {{total}} date dimensions ({{found}}) where it needs exactly one. Name the date dimension in the report’s dateRange.dimension.', }, diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 2e5084ff5dd..ae222b987dc 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4151,6 +4151,7 @@ const es = { dateRange: { from: "Desde", to: "Hasta", + comparePrevious: "Comparar con el período anterior", datasetUnreadable: "El periodo de este informe no indica ninguna dimensión y no se pudo leer el conjunto de datos «{{dataset}}» para encontrar su dimensión de fecha ({{reason}}).", noSingleDateDimension: "El periodo de este informe no indica ninguna dimensión y el conjunto de datos «{{dataset}}» declara {{total}} dimensiones de fecha ({{found}}) cuando necesita exactamente una. Indique la dimensión de fecha en dateRange.dimension del informe.", }, diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 54085bda3ca..c43e6a7af32 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4147,6 +4147,7 @@ const fr = { dateRange: { from: "Du", to: "Au", + comparePrevious: "Comparer avec la période précédente", datasetUnreadable: "La période de ce rapport ne nomme aucune dimension, et le jeu de données « {{dataset}} » n’a pas pu être lu pour trouver sa dimension de date ({{reason}}).", noSingleDateDimension: "La période de ce rapport ne nomme aucune dimension, et le jeu de données « {{dataset}} » déclare {{total}} dimensions de date ({{found}}) alors qu’il en faut exactement une. Nommez la dimension de date dans dateRange.dimension du rapport.", }, diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 39f47ede31e..a6b39321717 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4063,6 +4063,7 @@ const ja = { dateRange: { from: "開始", to: "終了", + comparePrevious: "前期と比較", datasetUnreadable: "このレポートの期間はディメンションを指定しておらず、データセット「{{dataset}}」を読み込んで日付ディメンションを特定できませんでした({{reason}})。", noSingleDateDimension: "このレポートの期間はディメンションを指定しておらず、データセット「{{dataset}}」は日付ディメンションを {{total}} 個宣言しています({{found}})。ちょうど 1 個である必要があります。レポートの dateRange.dimension で日付ディメンションを指定してください。", }, diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index b564bd532b9..0807b9684ce 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4060,6 +4060,7 @@ const ko = { dateRange: { from: "시작", to: "종료", + comparePrevious: "이전 기간과 비교", datasetUnreadable: "이 보고서의 기간에 차원이 지정되지 않았으며, 날짜 차원을 찾기 위해 “{{dataset}}” 데이터셋을 읽을 수 없습니다({{reason}}).", noSingleDateDimension: "이 보고서의 기간에 차원이 지정되지 않았으며, “{{dataset}}” 데이터셋은 날짜 차원을 {{total}}개 선언합니다({{found}}). 정확히 하나여야 합니다. 보고서의 dateRange.dimension에 날짜 차원을 지정하세요.", }, diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 9ce1fc490fe..b6e1441cdde 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4146,6 +4146,7 @@ const pt = { dateRange: { from: "De", to: "Até", + comparePrevious: "Comparar com o período anterior", datasetUnreadable: "O período deste relatório não indica nenhuma dimensão, e não foi possível ler o conjunto de dados “{{dataset}}” para encontrar sua dimensão de data ({{reason}}).", noSingleDateDimension: "O período deste relatório não indica nenhuma dimensão, e o conjunto de dados “{{dataset}}” declara {{total}} dimensões de data ({{found}}) quando precisa de exatamente uma. Indique a dimensão de data em dateRange.dimension do relatório.", }, diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index a090b1effd5..724ae6cadc4 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4250,6 +4250,7 @@ const ru = { dateRange: { from: "С", to: "По", + comparePrevious: "Сравнить с предыдущим периодом", datasetUnreadable: "Период этого отчёта не указывает измерение, и не удалось прочитать набор данных «{{dataset}}», чтобы найти его измерение даты ({{reason}}).", noSingleDateDimension: "Период этого отчёта не указывает измерение, а набор данных «{{dataset}}» объявляет измерений даты: {{total}} ({{found}}), тогда как нужно ровно одно. Укажите измерение даты в dateRange.dimension отчёта.", }, diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 047925acf79..2589b10aa16 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1809,6 +1809,7 @@ const zh = { dateRange: { from: '开始', to: '结束', + comparePrevious: '和上一期对比', datasetUnreadable: '该报表的时间范围未指定维度,且无法读取数据集“{{dataset}}”以确定其日期维度({{reason}})。', noSingleDateDimension: '该报表的时间范围未指定维度,而数据集“{{dataset}}”声明了 {{total}} 个日期维度({{found}}),这里需要恰好一个。请在报表的 dateRange.dimension 中指定日期维度。', }, diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 8a26b110441..24ba70a4734 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1809,6 +1809,7 @@ const zhHant = { dateRange: { from: '開始', to: '結束', + comparePrevious: '和上一期對比', datasetUnreadable: '該報表的時間範圍未指定維度,且無法讀取資料集“{{dataset}}”以確定其日期維度({{reason}})。', noSingleDateDimension: '該報表的時間範圍未指定維度,而資料集“{{dataset}}”聲明瞭 {{total}} 個日期維度({{found}}),這裡需要恰好一個。請在報表的 dateRange.dimension 中指定日期維度。', }, diff --git a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx index ca0cb12f3bd..8c85588223a 100644 --- a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx +++ b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx @@ -158,11 +158,15 @@ import { type ReportTableSnapshot, } from './ReportExport'; import { + ReportCompareToggle, ReportDateRangeControl, initialReportPeriod, readDateRangeDeclaration, + reportChartComparable, + reportCompareTo, reportTimeWindow, useReportDateDimension, + type ReportCompareTo, type ReportPeriod, type ReportTimeWindow, } from './ReportDateRange'; @@ -706,6 +710,7 @@ function useDatasetRows( totalsGroupings?: string[][], order?: SelectionOrder, timeWindow?: ReportTimeWindow, + compareTo?: ReportCompareTo, ) { const [state, setState] = React.useState<{ status: 'idle' | 'loading' | 'ok' | 'error'; @@ -737,8 +742,10 @@ function useDatasetRows( // The report's period (`dateRange`) is part of the signature too: picking // another window on the chip is another selection, so it re-queries. const windowKey = JSON.stringify(timeWindow ?? null); + // Turning the comparison on or off is another selection too. + const compareKey = JSON.stringify(compareTo ?? null); const packageId = React.useContext(ReportPackageContext); - const signature = `${packageId ?? ''}|${dataset}|${dimensions.join(',')}|${measures.join(',')}|${rfKey}|${totalsKey}|${orderKey}|${windowKey}`; + const signature = `${packageId ?? ''}|${dataset}|${dimensions.join(',')}|${measures.join(',')}|${rfKey}|${totalsKey}|${orderKey}|${windowKey}|${compareKey}`; // objectui#10814 — the data-invalidation bus (`notifyDataChanged` from // `@object-ui/react`), read the objectui#10623 way: the nonce moves when a @@ -803,6 +810,11 @@ function useDatasetRows( // `runtimeFilter`, never a bucket. Absent, the selection is exactly // what a report without a period has always posted. ...(timeWindow ? { timeDimensions: [timeWindow] } : {}), + // "Compare with previous period" (objectstack#36645): the executor + // runs the same selection over the window just before this one and + // answers each measure's earlier value as `__compare`. Only + // ever sent beside the window it shifts. + ...(timeWindow && compareTo ? { compareTo } : {}), }, ...(packageId ? [{ callerPackage: packageId }] : [])) .then((res) => { if (!cancelled) { @@ -1545,6 +1557,22 @@ function useRegistryComponent( * names the measure but carries no usable `label` returns `undefined` and falls * through to the dataset's own measure label, exactly as an absent entry does. */ +/** The column the dataset executor answers a measure's earlier window under (`compareTo`). */ +const COMPARE_SUFFIX = '__compare'; + +/** + * The signed change from the previous period to the current one, as a percent + * of the previous value (`+25%`, `−10%`). `undefined` when either side is not + * a number or the previous value is 0, where a percent says nothing. + */ +export function formatPeriodChange(current: unknown, previous: unknown, locale?: string): string | undefined { + const cur = typeof current === 'number' ? current : typeof current === 'string' && current.trim() !== '' ? Number(current) : NaN; + const prev = typeof previous === 'number' ? previous : typeof previous === 'string' && previous.trim() !== '' ? Number(previous) : NaN; + if (!Number.isFinite(cur) || !Number.isFinite(prev) || prev === 0) return undefined; + const ratio = (cur - prev) / Math.abs(prev); + return new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 1, signDisplay: 'exceptZero' }).format(ratio); +} + function authoredSeriesLabel(series: unknown, measure: string, language: string | undefined): string | undefined { if (!Array.isArray(series) || !measure) return undefined; for (const entry of series as unknown[]) { @@ -1617,6 +1645,7 @@ function DatasetReportChart({ dataSource, order, timeWindow, + compareTo, onDrill, }: { dataset: string; @@ -1625,6 +1654,12 @@ function DatasetReportChart({ dataSource?: unknown; order?: SelectionOrder; timeWindow?: ReportTimeWindow; + /** + * The viewer's 「Compare with previous period」 (objectstack#36645). Set only + * for a chart {@link reportChartComparable} accepts; the chart then draws the + * earlier window beside the current one. + */ + compareTo?: ReportCompareTo; /** The report's drill sink: a clicked mark drills like its table line (objectstack-ai/objectstack#36256). */ onDrill?: (args: DatasetDrillArgs) => void; }) { @@ -1661,6 +1696,7 @@ function DatasetReportChart({ undefined, order, timeWindow, + compareTo, ); const ChartComponent = useRegistryComponent('chart'); const { fieldLabel, fieldOptionLabel } = useSafeFieldLabel(); @@ -1786,6 +1822,13 @@ function DatasetReportChart({ // refusal is an error here too: the table beside this slot reads the same // dataset and draws the one no-access state, so the chart draws no second // one (objectui#12330). + // + // Except a refused COMPARISON (objectstack#36645): the table beside the + // chart never asks for one, so a silent fallback would leave the viewer's + // switch on over a chart that vanished with no reason given. + if (state.status === 'error' && compareTo && !state.forbidden) { + return ; + } if (state.status === 'error' || state.rows.length === 0) return null; // objectui#7534 — resolve a BUILT-IN default measure's caption through the @@ -1815,16 +1858,33 @@ function DatasetReportChart({ // raw `name` to a fully-translated console. const measureLabel = authoredSeriesLabel(chart.series, yAxis, language) ?? headerLabel(yAxis); + // The earlier window's caption: the dashboard's own words for the same + // `previousPeriod` comparison, so a report and a dashboard tile read alike. + const compareLabel = tt('dashboard.trend.vsPreviousPeriod', 'vs previous period'); + const compareKey = `${yAxis}${COMPARE_SUFFIX}`; + if (plan.kind === 'single_value') { const mf = measureField(yAxis); + const current = state.rows[0]?.[yAxis]; + const previous = compareTo ? state.rows[0]?.[compareKey] : undefined; + const change = compareTo ? formatPeriodChange(current, previous, displayLocale) : undefined; return (
{title ?

{title}

: null}
- {formatMeasure(state.rows[0]?.[yAxis], mf?.format, mf?.currency, mf?.percentScale, displayLocale)} + {formatMeasure(current, mf?.format, mf?.currency, mf?.percentScale, displayLocale)} {measureLabel} + {compareTo ? ( + + {compareLabel}{' '} + + {formatMeasure(previous, mf?.format, mf?.currency, mf?.percentScale, displayLocale)} + + {change ? {` (${change})`} : null} + + ) : null}
); @@ -1930,6 +1990,10 @@ function DatasetReportChart({ const markScope: MeasureDrillScope | undefined = state.object ? measureDrillScope(state.drillScopes, yAxis) : {}; const handleMarkClick = onDrill && markScope !== undefined ? (ev: ChartSegmentClickEvent) => { + // A mark of the earlier window stands for records the current query did + // not count, so it opens no list (the dashboard's rule for the same + // `__compare` series). + if (ev?.series === compareKey) return; const at = findChartSeriesRow(plotRows, queryDimensions, [yAxis], ev?.category, ev?.series, { nullCategoryLabel, bucketId: ev?.categoryId, @@ -1973,6 +2037,23 @@ function DatasetReportChart({ ? { ...s, label: authoredSeriesLabel(chart.series, s.dataKey, language) ?? derivedSeries[i].label } : s.dataKey === yAxis ? { ...s, label: measureLabel } : s, ); + // 「Compare with previous period」 (objectstack#36645): the measure's + // earlier window as one more series, drawn muted / dashed by the chart's + // `variant: 'comparison'` styling. The rows already carry it: the executor + // restates the earlier window's buckets in the current window's keys, so a + // month axis pairs each month with the month one period before it. + const comparisonAggregate = measureField(yAxis)?.aggregate; + const drawnSeries = compareTo && !seriesBy + ? [ + ...chartSeries, + { + dataKey: compareKey, + label: `${measureLabel} · ${compareLabel}`, + variant: 'comparison' as const, + ...(typeof comparisonAggregate === 'string' ? { aggregate: comparisonAggregate } : {}), + }, + ] + : chartSeries; // The authored CHROME — `showLegend`, `showDataLabels`, `colors`, `subtitle`, // `description`, `annotations`, `interaction`, `height` — lowered by the same @@ -2008,7 +2089,7 @@ function DatasetReportChart({ // input the legend, the mark's tooltip name and the single-value // caption all read — so legend and tooltip follow this by // construction rather than by a second resolution. - series: chartSeries, + series: drawnSeries, // The default plot height, kept beneath the spread so an authored // `height` wins. A non-positive one never reaches here (the whitelist // drops it), which leaves this default rather than an invisible plot. @@ -2562,6 +2643,10 @@ const DatasetReportRendererBody: React.FC = ({ const dateDimension = useReportDateDimension(String(report.dataset ?? ''), dateRangeDecl, reportPackageId); const timeWindow = period && dateDimension.status === 'ready' ? reportTimeWindow(dateDimension.dimension, period) : undefined; + // 「Compare with previous period」 (objectstack#36645) — the viewer's, like + // the period itself, and keyed on the same declaration. + const [comparePicked, setComparePicked] = React.useState<{ key: string; on: boolean } | null>(null); + const compareOn = !!comparePicked && comparePicked.key === dateRangeKey && comparePicked.on; // Joined → a vertical stack of dataset-bound blocks. if (presentation === 'joined' && Array.isArray(report.blocks)) { @@ -2653,6 +2738,13 @@ const DatasetReportRendererBody: React.FC = ({ report.chart && typeof report.chart === 'object' && (report.chart as { type?: unknown }).type ? (report.chart as Record) : null; + // Offered beside the period chip only when the chart can draw it over the + // window's dimension; sent only while the period names a window to step + // back from. + const compareOffered = + !!dateRangeDecl && + reportChartComparable(chartCfg, dateDimension.status === 'ready' ? dateDimension.dimension : undefined); + const compareTo = compareOffered ? reportCompareTo(compareOn, timeWindow) : undefined; const chart = chartCfg ? ( = ({ dataSource={dataSource} order={reportOrder} timeWindow={timeWindow} + compareTo={compareTo} onDrill={drillSink} /> ) : null; @@ -2723,15 +2816,25 @@ const DatasetReportRendererBody: React.FC = ({ data-report-name={report.name} data-report-presentation={presentation} > - {/* One header row: the period chip on the left, Export on the right; - hidden when neither draws. */} + {/* One header row: the period chip (and 「Compare with previous + period」 beside it) on the left, Export on the right; hidden when + neither draws. */}
{dateRangeDecl && period ? ( - setPicked({ key: dateRangeKey, period: next })} - /> +
+ setPicked({ key: dateRangeKey, period: next })} + /> + {compareOffered ? ( + setComparePicked({ key: dateRangeKey, on })} + /> + ) : null} +
) : null}
diff --git a/ui/packages/plugin-report/src/ReportDateRange.tsx b/ui/packages/plugin-report/src/ReportDateRange.tsx index 8d3664b0209..5a1ef2f02e5 100644 --- a/ui/packages/plugin-report/src/ReportDateRange.tsx +++ b/ui/packages/plugin-report/src/ReportDateRange.tsx @@ -36,11 +36,13 @@ import * as React from 'react'; import { CalendarIcon } from 'lucide-react'; import { Input, + Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, + Switch, } from '@object-ui/components'; import { DATE_RANGE_PRESETS } from '@object-ui/core'; import { useObjectTranslation, useSafeTranslate } from '@object-ui/i18n'; @@ -59,6 +61,16 @@ export interface ReportTimeWindow { dateRange: string | [string, string]; } +/** + * The comparison the viewer turned on beside the chip (objectstack#36645): the + * dataset contract's `DatasetSelection.compareTo`, always the equal-length + * window just before the active one, shifted on the window's own dimension. + */ +export interface ReportCompareTo { + kind: 'previousPeriod'; + dimension: string; +} + /** What the viewer picked on the chip. */ export type ReportPeriod = | { kind: 'all' } @@ -251,3 +263,92 @@ export function ReportDateRangeControl({ ); } + +/** + * The chart types that draw a comparison as a second, muted series beside the + * current one. A pie, donut or funnel has no second series to draw it as, a + * single-series family (treemap, sankey) would read it as another group, and a + * table type draws no chart at all, so none of those is offered the switch. + */ +const COMPARABLE_SERIES_CHART_TYPES: ReadonlySet = new Set([ + 'bar', + 'column', + 'horizontal-bar', + 'line', + 'area', +]); + +/** The single-number chart types: they show the previous period's number under the current one. */ +const COMPARABLE_SINGLE_VALUE_CHART_TYPES: ReadonlySet = new Set(['metric', 'kpi']); + +/** + * Whether a report's embedded `chart` can draw "compare with the previous + * period" (objectstack#36645) over a window on `windowDimension`. + * + * - A `seriesBy` split is excluded: its series are values of the split + * dimension, not the measure, so no one series pairs with the measure's + * earlier window. + * - A series chart whose x axis IS the window's own date dimension is + * excluded. The earlier window is the same number of days just before the + * current one, and its date buckets pair with the current ones by position + * from each window's start; when the two windows split into a different + * number of buckets (a 31-day month against the 31 days before it, by + * month) the bars would pair with the wrong period. A category axis, or a + * single number, compares clean totals and stays offered. + * - The window's dimension must be known: until it is, nothing is offered. + */ +export function reportChartComparable( + chart: Record | null | undefined, + windowDimension: string | undefined, +): boolean { + if (!chart || !windowDimension) return false; + const type = chart.type; + if (typeof type !== 'string') return false; + if (COMPARABLE_SINGLE_VALUE_CHART_TYPES.has(type)) return true; + if (!COMPARABLE_SERIES_CHART_TYPES.has(type)) return false; + if (typeof chart.seriesBy === 'string' && chart.seriesBy) return false; + return chart.xAxis !== windowDimension; +} + +/** + * The comparison a query carries: only while the switch is on AND the period + * names a window. All time, or a custom pick missing an end, has no window to + * step back from, so nothing is compared. + */ +export function reportCompareTo(on: boolean, window: ReportTimeWindow | undefined): ReportCompareTo | undefined { + if (!on || !window) return undefined; + return { kind: 'previousPeriod', dimension: window.dimension }; +} + +/** + * 「Compare with previous period」 beside the period chip. Like the chip's own + * pick it is the viewer's, never saved into the report. It is off, and cannot + * be turned on, while the period names no window. + */ +export function ReportCompareToggle({ + checked, + available, + onChange, +}: { + checked: boolean; + /** Whether the active period names a window to compare with. */ + available: boolean; + onChange: (next: boolean) => void; +}) { + const tt = useSafeTranslate(); + const id = React.useId(); + return ( +
+ onChange(on)} + data-testid="report-compare-previous-switch" + /> + +
+ ); +} diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.comparePrevious-36645.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.comparePrevious-36645.test.tsx new file mode 100644 index 00000000000..81890bc487b --- /dev/null +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.comparePrevious-36645.test.tsx @@ -0,0 +1,289 @@ +/** + * objectstack-ai/objectstack#36645 item 3 — 「Compare with previous period」 + * beside a report's period chip. + * + * The switch is the viewer's, like the period pick. While it is on and the + * period names a window, the embedded chart's dataset query carries the + * contract's `compareTo: { kind: 'previousPeriod', dimension }` and the chart + * draws the earlier window beside the current one: a muted `comparison` + * series on a bar / line chart, the previous number and the change under a + * single number. The table beside the chart is not asked for a comparison. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, waitFor, cleanup, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { ComponentRegistry } from '@object-ui/core'; +import { SchemaRendererProvider } from '@object-ui/react'; +import { I18nProvider } from '@object-ui/i18n'; +import { DatasetReportRenderer } from '../DatasetReportRenderer'; + +// Radix Select opens on pointer events the DOM environment does not implement; +// the shim the dateRange test uses. +beforeAll(() => { + class MockPointerEvent extends Event { + button: number; + ctrlKey: boolean; + pointerType: string; + constructor(type: string, props: PointerEventInit = {}) { + super(type, props); + this.button = props.button ?? 0; + this.ctrlKey = props.ctrlKey ?? false; + this.pointerType = props.pointerType ?? 'mouse'; + } + } + Object.assign(window, { PointerEvent: MockPointerEvent }); + Object.assign(HTMLElement.prototype, { + hasPointerCapture: vi.fn(), + releasePointerCapture: vi.fn(), + scrollIntoView: vi.fn(), + }); +}); + +// The chart's field-metadata read (`/api/v1/meta/object/...`) answers from a +// double for the whole file: it can run after a test body returns. +vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 404 }))); + +let chartProps: Record | null = null; + +beforeEach(() => { + chartProps = null; + ComponentRegistry.register('chart', (props: any) => { + chartProps = props; + return null; + }); +}); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +/** + * A dataset source that answers like the executor: with `compareTo` in the + * selection, every row also carries `__compare`. + */ +function makeSource(opts: { refuseCompare?: boolean } = {}) { + const selections: any[] = []; + return { + selections, + queryDataset: vi.fn(async (_dataset: string, selection: any) => { + selections.push(selection); + if (selection.compareTo && opts.refuseCompare) { + throw new Error('[dataset-executor] compareTo needs a dated window to shift'); + } + const compare = !!selection.compareTo; + const dims: string[] = selection.dimensions ?? []; + const rows = dims.length === 0 + ? [{ amount: 50, ...(compare ? { amount__compare: 40 } : {}) }] + : [ + { stage: 'Won', amount: 30, ...(compare ? { amount__compare: 20 } : {}) }, + { stage: 'Lost', amount: 10, ...(compare ? { amount__compare: 15 } : {}) }, + ]; + return { + rows, + fields: [{ name: 'amount', label: 'Amount', aggregate: 'sum' }], + object: 'opportunity', + dimensionFields: { stage: 'stage' }, + drillRawRows: rows.map((r) => ({ stage: 'stage' in r ? String(r.stage).toLowerCase() : undefined })), + drillScopes: { amount: {} }, + }; + }), + }; +} + +const BASE = { + name: 'pipeline', + type: 'summary', + dataset: 'opportunity_metrics', + rows: ['stage'], + values: ['amount'], + dateRange: { dimension: 'close_date', defaultRange: 'last_30_days' }, +}; + +function renderReport( + report: Record, + src: ReturnType, + opts: { language?: string; onDrill?: (args: unknown) => void } = {}, +) { + return render( + + + + + , + ); +} + +const compareSwitch = () => screen.getByRole('switch'); +const chartSelections = (src: ReturnType) => + src.selections.filter((s) => (s.dimensions ?? []).length <= 1 && !s.totals); + +describe('「Compare with previous period」 on a report (objectstack-ai/objectstack#36645)', () => { + it('is off at first: the switch is offered, and no query carries compareTo', async () => { + const src = makeSource(); + renderReport({ ...BASE, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + expect(screen.getByTestId('report-compare-previous')).toHaveTextContent('Compare with previous period'); + expect(compareSwitch()).not.toBeChecked(); + for (const selection of src.selections) expect(selection).not.toHaveProperty('compareTo'); + expect(chartProps!.schema.series.map((s: any) => s.dataKey)).toEqual(['amount']); + }); + + it('turned on, the chart queries the previous period on the window dimension and draws it as a comparison series', async () => { + const src = makeSource(); + renderReport({ ...BASE, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + const before = src.selections.length; + + fireEvent.click(compareSwitch()); + await waitFor(() => expect(chartProps!.schema.series).toHaveLength(2)); + expect(compareSwitch()).toBeChecked(); + + // Exactly one new query: the chart's. It keeps its window and adds compareTo. + const after = src.selections.slice(before); + expect(after).toHaveLength(1); + expect(after[0].compareTo).toEqual({ kind: 'previousPeriod', dimension: 'close_date' }); + expect(after[0].timeDimensions).toEqual([{ dimension: 'close_date', dateRange: 'last_30_days' }]); + expect(after[0].dimensions).toEqual(['stage']); + + const [current, previous] = chartProps!.schema.series; + expect(current).toMatchObject({ dataKey: 'amount', label: 'Amount' }); + expect(current.variant).toBeUndefined(); + expect(previous).toEqual({ + dataKey: 'amount__compare', + label: 'Amount · vs previous period', + variant: 'comparison', + aggregate: 'sum', + }); + // Both periods reach the chart on the same bucket. + const won = chartProps!.schema.data.find((r: any) => r.stage === 'Won'); + expect(won).toMatchObject({ amount: 30, amount__compare: 20 }); + + // Turned off again: one series, and the query no longer compares. + fireEvent.click(compareSwitch()); + await waitFor(() => expect(chartProps!.schema.series).toHaveLength(1)); + expect(src.selections[src.selections.length - 1]).not.toHaveProperty('compareTo'); + }); + + it.each([['bar'], ['line']])( + 'is not offered on a %s chart whose x axis is the window\'s own date dimension', + async (type) => { + // The earlier window is the same number of days just before; on its own + // date axis its buckets would pair by position and can land on the + // wrong period, so the switch is not drawn and nothing is compared. + const src = makeSource(); + renderReport( + { + ...BASE, + rows: ['close_date'], + chart: { type, xAxis: 'close_date', yAxis: 'amount' }, + }, + src, + ); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + expect(screen.getByTestId('report-date-range')).toBeInTheDocument(); + expect(screen.queryByTestId('report-compare-previous')).toBeNull(); + for (const selection of src.selections) expect(selection).not.toHaveProperty('compareTo'); + }, + ); + + it('a single number over the same date grouping is still offered, and compares the window total', async () => { + const src = makeSource(); + renderReport({ ...BASE, rows: ['close_date'], chart: { type: 'metric', yAxis: 'amount' } }, src); + await screen.findByTestId('dataset-report-metric'); + fireEvent.click(compareSwitch()); + expect(await screen.findByTestId('dataset-report-metric-change')).toHaveTextContent('+25%'); + }); + + it('a line chart draws the comparison series too', async () => { + const src = makeSource(); + renderReport({ ...BASE, chart: { type: 'line', xAxis: 'stage', yAxis: 'amount' } }, src); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + fireEvent.click(compareSwitch()); + await waitFor(() => expect(chartProps!.schema.series).toHaveLength(2)); + expect(chartProps!.schema.series[1].variant).toBe('comparison'); + }); + + it('a mark of the earlier window drills nothing; a current mark still drills', async () => { + const src = makeSource(); + const onDrill = vi.fn(); + renderReport({ ...BASE, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src, { onDrill }); + await waitFor(() => expect(chartProps?.onChartClick).toBeTypeOf('function')); + fireEvent.click(compareSwitch()); + await waitFor(() => expect(chartProps!.schema.series).toHaveLength(2)); + + act(() => chartProps!.onChartClick({ category: 'Won', series: 'amount__compare' })); + expect(onDrill).not.toHaveBeenCalled(); + + act(() => chartProps!.onChartClick({ category: 'Won', series: 'amount' })); + await waitFor(() => expect(onDrill).toHaveBeenCalledTimes(1)); + }); + + it('All time names no window: the switch turns off and cannot be turned on, and nothing is compared', async () => { + const src = makeSource(); + renderReport({ ...BASE, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + fireEvent.click(compareSwitch()); + await waitFor(() => expect(chartProps!.schema.series).toHaveLength(2)); + + fireEvent.pointerDown(screen.getByRole('combobox', { name: 'Date range' }), { button: 0 }); + fireEvent.click(await screen.findByRole('option', { name: 'All time' })); + + await waitFor(() => expect(chartProps!.schema.series).toHaveLength(1)); + expect(compareSwitch()).not.toBeChecked(); + expect(compareSwitch()).toBeDisabled(); + const last = src.selections[src.selections.length - 1]; + expect(last).not.toHaveProperty('timeDimensions'); + expect(last).not.toHaveProperty('compareTo'); + }); + + it('a single number shows the previous period and the change under it', async () => { + const src = makeSource(); + renderReport({ ...BASE, chart: { type: 'metric', yAxis: 'amount' } }, src); + await screen.findByTestId('dataset-report-metric'); + expect(screen.queryByTestId('dataset-report-metric-previous')).toBeNull(); + + fireEvent.click(compareSwitch()); + const previous = await screen.findByTestId('dataset-report-metric-previous'); + expect(previous).toHaveTextContent('vs previous period'); + expect(previous).toHaveTextContent('40'); + // 50 against 40: up a quarter. + expect(screen.getByTestId('dataset-report-metric-change')).toHaveTextContent('+25%'); + const metricQuery = chartSelections(src).find((s) => (s.dimensions ?? []).length === 0 && s.compareTo); + expect(metricQuery?.compareTo).toEqual({ kind: 'previousPeriod', dimension: 'close_date' }); + }); + + it.each([ + ['a donut', { type: 'donut', xAxis: 'stage', yAxis: 'amount' }], + ['a table chart', { type: 'table', xAxis: 'stage', yAxis: 'amount' }], + ['a chart split by a second dimension', { type: 'bar', xAxis: 'stage', yAxis: 'amount', seriesBy: 'owner' }], + ])('is not offered on %s, which has no second series to draw it as', async (_name, chart) => { + const src = makeSource(); + renderReport({ ...BASE, chart }, src); + await screen.findByTestId('report-date-range'); + await waitFor(() => expect(src.selections.length).toBeGreaterThan(0)); + expect(screen.queryByTestId('report-compare-previous')).toBeNull(); + }); + + it('is not offered on a report without a period', async () => { + const src = makeSource(); + const { dateRange: _none, ...noPeriod } = BASE; + renderReport({ ...noPeriod, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + expect(screen.queryByTestId('report-compare-previous')).toBeNull(); + }); + + it('a refused comparison is said where the chart was, not dropped silently', async () => { + const src = makeSource({ refuseCompare: true }); + renderReport({ ...BASE, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + fireEvent.click(compareSwitch()); + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('compareTo needs a dated window to shift'); + }); + + it('reads 「和上一期对比」 on a zh-CN console', async () => { + const src = makeSource(); + renderReport({ ...BASE, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src, { language: 'zh-CN' }); + expect(await screen.findByTestId('report-compare-previous')).toHaveTextContent('和上一期对比'); + }); +});