You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/08/04 20:58:49 UTC

(superset) branch feat/pivot-table-fraction-of created (now cdb52e562b0)

This is an automated email from the ASF dual-hosted git repository.

rusackas pushed a change to branch feat/pivot-table-fraction-of
in repository https://gitbox.apache.org/repos/asf/superset.git


      at cdb52e562b0 feat(pivot-table): reintroduce show-values-as-fraction display option

This branch includes the following new commits:

     new cdb52e562b0 feat(pivot-table): reintroduce show-values-as-fraction display option

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(superset) 01/01: feat(pivot-table): reintroduce show-values-as-fraction display option

Posted by ru...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rusackas pushed a commit to branch feat/pivot-table-fraction-of
in repository https://gitbox.apache.org/repos/asf/superset.git

commit cdb52e562b02c3c9c4d3dfeffa1ee1701d4ba782
Author: Evan Rusackas <ev...@rusackas.com>
AuthorDate: Tue Aug 4 13:57:06 2026 -0700

    feat(pivot-table): reintroduce show-values-as-fraction display option
    
    Issue #41463 (SIP-216, merged via #41184) correctly moved pivot table
    totals/subtotals to DB-computed rollup queries, fixing non-additive
    metrics (ratios, COUNT_DISTINCT, AVG, etc.). As part of that, the
    Pivot Table's old "Aggregation function" control was removed
    entirely, taking its "Sum as Fraction of Total/Rows/Columns" options
    down with it -- collateral damage, not something the SIP identified
    as broken. Those variants only ever wrapped Sum/Count (both
    additive), so they were already correct before #41184 and remain a
    distinct, wanted feature independent of the non-additive-totals fix.
    
    This reintroduces it as a standalone "Show values as" control rather
    than resurrecting the old per-metric aggregator-override mechanism.
    Now that every cell already holds a DB-correct rollup value at every
    scope (row total, column total, grand total), showing a cell as a
    fraction of one of those scopes is a pure presentational transform at
    render time: reuse react-pivottable's existing fractionOf template,
    wrapping the passthrough `cellValue` aggregator instead of `sum()`/
    `count()`, and reuse the same row/column/grand-total lookup
    (`getAggregator`) the removed feature relied on. No new query, no
    touching grouping_sets, no per-metric control.
    
    Percentage display always uses a fixed percent format; per-metric
    custom formatters (currency, decimals, etc.) don't apply to a ratio,
    so formattedAggregators is skipped while a fraction mode is active.
---
 .../src/PivotTableChart.tsx                        |  2 +
 .../src/plugin/controlPanel.tsx                    | 25 +++++-
 .../src/plugin/transformProps.ts                   |  2 +
 .../src/react-pivottable/utilities.ts              | 75 ++++++++++++-----
 .../plugins/plugin-chart-pivot-table/src/types.ts  | 15 ++++
 .../test/plugin/transformProps.test.ts             | 22 +++++
 .../test/react-pivottable/tableRenders.test.tsx    | 94 ++++++++++++++++++++++
 7 files changed, 212 insertions(+), 23 deletions(-)

diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx b/superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx
index 4f3b5255130..f4b91259a42 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx
@@ -249,6 +249,7 @@ export default function PivotTableChart(props: PivotTableProps) {
     columnFormats,
     currencyFormats,
     metricsLayout,
+    showValuesAs,
     metricColorFormatters,
     dateFormatters,
     onContextMenu,
@@ -754,6 +755,7 @@ export default function PivotTableChart(props: PivotTableProps) {
           namesMapping={verboseMap}
           onContextMenu={handleContextMenu}
           allowRenderHtml={allowRenderHtml}
+          showValuesAs={showValuesAs}
         />
       </PivotTableWrapper>
     </Styles>
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.tsx b/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.tsx
index 6cf9b17dd8c..70107099bb7 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.tsx
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.tsx
@@ -33,7 +33,7 @@ import {
   validateNonEmpty,
   QueryFormColumn,
 } from '@superset-ui/core';
-import { MetricsLayoutEnum } from '../types';
+import { MetricsLayoutEnum, ShowValuesAsEnum } from '../types';
 
 const config: ControlPanelConfig = {
   controlPanelSections: [
@@ -243,6 +243,29 @@ const config: ControlPanelConfig = {
             },
           },
         ],
+        [
+          {
+            name: 'showValuesAs',
+            config: {
+              type: 'SelectControl',
+              label: t('Show values as'),
+              default: ShowValuesAsEnum.ACTUAL,
+              renderTrigger: true,
+              choices: [
+                [ShowValuesAsEnum.ACTUAL, t('Actual values')],
+                [ShowValuesAsEnum.PERCENT_OF_ROW, t('% of row total')],
+                [ShowValuesAsEnum.PERCENT_OF_COLUMN, t('% of column total')],
+                [ShowValuesAsEnum.PERCENT_OF_TOTAL, t('% of grand total')],
+              ],
+              description: t(
+                'Display each cell as a percentage of its row, column, or ' +
+                  'grand total, instead of its actual value. Totals and ' +
+                  'subtotals are still computed correctly first; this only ' +
+                  'changes how they are displayed.',
+              ),
+            },
+          },
+        ],
       ],
     },
     {
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts b/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts
index b354396f2b2..ab94f125e89 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts
@@ -166,6 +166,7 @@ export default function transformProps(chartProps: ChartProps<QueryFormData>) {
     valueFormat,
     dateFormat,
     metricsLayout,
+    showValuesAs,
     conditionalFormatting,
     timeGrainSqla,
     currencyFormat,
@@ -242,6 +243,7 @@ export default function transformProps(chartProps: ChartProps<QueryFormData>) {
     columnFormats,
     currencyFormats,
     metricsLayout,
+    showValuesAs,
     metricColorFormatters,
     dateFormatters,
     onContextMenu,
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.ts b/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.ts
index 8db8940e9fa..b057927b9c5 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.ts
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.ts
@@ -814,6 +814,16 @@ const aggregatorTemplates = {
   ...extendedAggregatorTemplates,
 };
 
+// Maps the pivot's "Show values as" control (see ../types.ts's
+// ShowValuesAsEnum) to fractionOf's `type` parameter. `undefined`/'actual'
+// means "no wrapping" and isn't listed here.
+const FRACTION_TYPE_BY_SHOW_VALUES_AS: Record<string, 'total' | 'row' | 'col'> =
+  {
+    percent_total: 'total',
+    percent_row: 'row',
+    percent_col: 'col',
+  };
+
 // default aggregators & renderers use US naming and number formatting
 const aggregators = (tpl => ({
   Count: tpl.count(usFmtInt),
@@ -970,32 +980,53 @@ class PivotData {
     );
 
     const vals = this.props.vals as string[];
+    const fractionType =
+      FRACTION_TYPE_BY_SHOW_VALUES_AS[this.props.showValuesAs as string];
     // Values come pre-aggregated from the database (one query per rollup level),
     // so the pivot stores them verbatim via `cellValue` instead of aggregating.
-    this.aggregator = cellValue(this.props.defaultFormatter as Formatter)(vals);
-    this.formattedAggregators = this.props.customFormatters
-      ? Object.entries(
-          this.props.customFormatters as Record<
-            string,
-            Record<string, unknown>
-          >,
-        ).reduce(
-          (
-            acc: Record<
+    // When "Show values as" a fraction is active, wrap that passthrough with
+    // the same fractionOf template the pre-SIP-216 "Sum as Fraction of ..."
+    // aggregators used: it divides a cell's own value by the value at the
+    // requested scope (row/column/grand total), each of which is itself one
+    // of these uniformly-wrapped aggregators, so `fractionOf`'s cross-lookup
+    // (`data.getAggregator(...).inner.value()`) resolves correctly no matter
+    // which scope it's called for -- including the totals dividing by
+    // themselves to read 100%. This needs no new query and no per-metric
+    // aggregator-override control (that control is gone, see SIP.md); it's a
+    // pure display transform over values that are already DB-correct.
+    this.aggregator = fractionType
+      ? aggregatorTemplates.fractionOf(
+          cellValue(),
+          fractionType,
+          usFmtPct,
+        )(vals)
+      : cellValue(this.props.defaultFormatter as Formatter)(vals);
+    // Percentage display always uses a fixed percent format -- a per-metric
+    // custom formatter (currency, decimals, etc.) doesn't apply to a ratio.
+    this.formattedAggregators =
+      !fractionType && this.props.customFormatters
+        ? Object.entries(
+            this.props.customFormatters as Record<
               string,
-              Record<string, (...args: unknown[]) => Aggregator>
+              Record<string, unknown>
             >,
-            [key, columnFormatter],
-          ) => {
-            acc[key] = {};
-            Object.entries(columnFormatter).forEach(([column, formatter]) => {
-              acc[key][column] = cellValue(formatter as Formatter)(vals);
-            });
-            return acc;
-          },
-          {},
-        )
-      : false;
+          ).reduce(
+            (
+              acc: Record<
+                string,
+                Record<string, (...args: unknown[]) => Aggregator>
+              >,
+              [key, columnFormatter],
+            ) => {
+              acc[key] = {};
+              Object.entries(columnFormatter).forEach(([column, formatter]) => {
+                acc[key][column] = cellValue(formatter as Formatter)(vals);
+              });
+              return acc;
+            },
+            {},
+          )
+        : false;
     this.tree = {};
     this.rowKeys = [];
     this.colKeys = [];
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts b/superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts
index 3e3d4c145eb..a19d49acd3c 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts
@@ -50,6 +50,20 @@ export enum MetricsLayoutEnum {
   COLUMNS = 'COLUMNS',
 }
 
+/**
+ * Display mode for pivot cell values: raw values, or each value expressed as
+ * a fraction of its row/column/grand total. Purely a presentational transform
+ * applied at render time against the already DB-correct rollup totals (see
+ * `PivotData` in `react-pivottable/utilities.ts`); it does not change what
+ * gets queried.
+ */
+export enum ShowValuesAsEnum {
+  ACTUAL = 'actual',
+  PERCENT_OF_ROW = 'percent_row',
+  PERCENT_OF_COLUMN = 'percent_col',
+  PERCENT_OF_TOTAL = 'percent_total',
+}
+
 /**
  * One rollup level for non-additive totals: a prefix of the row dimensions and
  * a prefix of the column dimensions. See `plugin/utilities.ts`.
@@ -95,6 +109,7 @@ interface PivotTableCustomizeProps {
   columnFormats: JsonObject;
   currencyFormats: Record<string, Currency>;
   metricsLayout?: MetricsLayoutEnum;
+  showValuesAs?: ShowValuesAsEnum;
   metricColorFormatters: ColorFormatters;
   dateFormatters: Record<string, DateFormatter | undefined>;
   legacy_order_by: QueryFormMetric[] | QueryFormMetric | null;
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts b/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts
index a3c09d7bfc3..cfcbde32c2e 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts
@@ -85,6 +85,28 @@ test('should pass through formData props for viz', () => {
   });
 });
 
+test('should pass through showValuesAs', () => {
+  const cp = new ChartProps<QueryFormData>({
+    formData: { ...formData, showValuesAs: 'percent_total' },
+    width: 800,
+    height: 600,
+    queriesData: [
+      {
+        data: [{ name: 'Hulk', sum__num: 1, __timestamp: 599616000000 }],
+        colnames: ['name', 'sum__num', '__timestamp'],
+        coltypes: [1, 0, 2],
+      },
+    ],
+    hooks: { setDataMask },
+    filterState: { selectedFilters: {} },
+    datasource: { verboseMap: {}, columnFormats: {} },
+    theme: supersetTheme,
+  });
+
+  const result = transformProps(cp) as ReturnType<typeof transformProps>;
+  expect(result.showValuesAs).toBe('percent_total');
+});
+
 test('non-additive: transformProps splits the GROUPING SETS result by level', () => {
   const gm = (col: string) => `${col}__superset_grouping`;
   const localFormData = {
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/test/react-pivottable/tableRenders.test.tsx b/superset-frontend/plugins/plugin-chart-pivot-table/test/react-pivottable/tableRenders.test.tsx
index 971753f751f..55efea66432 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/test/react-pivottable/tableRenders.test.tsx
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/test/react-pivottable/tableRenders.test.tsx
@@ -760,3 +760,97 @@ test('TableRenderer renders correct number of thead and tbody sections', () => {
   expect(theadEl).toBeInTheDocument();
   expect(tbodyEl).toBeInTheDocument();
 });
+
+/**
+ * "Show values as" a fraction (percent_row/percent_col/percent_total): a pure
+ * display transform over the already DB-correct rollup values in
+ * TAGGED_COUNT_DATA (leaf cells = 1, row/col totals = 2, grand total = 4).
+ * Reintroduces the pre-SIP-216 "Sum as Fraction of ..." display, but as a
+ * standalone control rather than resurrecting the removed per-metric
+ * "Aggregation function" selector -- see PivotData's constructor in
+ * ../../src/react-pivottable/utilities.ts.
+ */
+function getCellTexts(className: string) {
+  return screen
+    .getAllByRole('gridcell')
+    .filter(cell => cell.classList.contains(className))
+    .map(cell => cell.textContent);
+}
+
+test('TableRenderer shows values as a percentage of the grand total', () => {
+  const props = buildDefaultProps({
+    data: TAGGED_COUNT_DATA,
+    vals: ['value'],
+    tableOptions: { rowTotals: true, colTotals: true },
+    showValuesAs: 'percent_total',
+  });
+  renderWithTheme(<TableRenderer {...props} />);
+
+  // Each leaf cell is 1 out of a grand total of 4.
+  expect(getCellTexts('pvtVal')).toEqual(
+    expect.arrayContaining(['25.0%', '25.0%', '25.0%', '25.0%']),
+  );
+  // Row and column totals are 2 out of 4.
+  const rowTotalCells = getCellTexts('pvtTotal').filter(
+    text => text === '50.0%',
+  );
+  expect(rowTotalCells.length).toBeGreaterThan(0);
+  // The grand total is always 100% of itself.
+  const grandTotalCells = screen
+    .getAllByRole('gridcell')
+    .filter(cell => cell.classList.contains('pvtGrandTotal'));
+  expect(grandTotalCells).toHaveLength(1);
+  expect(grandTotalCells[0]).toHaveTextContent('100.0%');
+});
+
+test('TableRenderer shows values as a percentage of the row total', () => {
+  const props = buildDefaultProps({
+    data: TAGGED_COUNT_DATA,
+    vals: ['value'],
+    tableOptions: { rowTotals: true, colTotals: true },
+    showValuesAs: 'percent_row',
+  });
+  renderWithTheme(<TableRenderer {...props} />);
+
+  // Each leaf cell (1) is half of its row's total (2).
+  expect(getCellTexts('pvtVal')).toEqual(
+    expect.arrayContaining(['50.0%', '50.0%', '50.0%', '50.0%']),
+  );
+  // A row total is 100% of itself.
+  expect(getCellTexts('pvtTotal')).toEqual(expect.arrayContaining(['100.0%']));
+});
+
+test('TableRenderer shows values as a percentage of the column total', () => {
+  const props = buildDefaultProps({
+    data: TAGGED_COUNT_DATA,
+    vals: ['value'],
+    tableOptions: { rowTotals: true, colTotals: true },
+    showValuesAs: 'percent_col',
+  });
+  renderWithTheme(<TableRenderer {...props} />);
+
+  // Each leaf cell (1) is half of its column's total (2).
+  expect(getCellTexts('pvtVal')).toEqual(
+    expect.arrayContaining(['50.0%', '50.0%', '50.0%', '50.0%']),
+  );
+  // A column total is 100% of itself.
+  expect(getCellTexts('pvtTotal')).toEqual(expect.arrayContaining(['100.0%']));
+});
+
+test('TableRenderer shows actual values when showValuesAs is unset (default)', () => {
+  const props = buildDefaultProps({
+    data: TAGGED_COUNT_DATA,
+    vals: ['value'],
+    tableOptions: { rowTotals: true, colTotals: true },
+  });
+  renderWithTheme(<TableRenderer {...props} />);
+
+  // No percent signs anywhere -- the DB-computed values render as-is.
+  const allCellTexts = screen
+    .getAllByRole('gridcell')
+    .map(cell => cell.textContent);
+  expect(allCellTexts.some(text => text?.includes('%'))).toBe(false);
+  expect(getCellTexts('pvtVal')).toEqual(
+    expect.arrayContaining(['1.00', '1.00', '1.00', '1.00']),
+  );
+});