You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by rb...@apache.org on 2026/10/06 14:30:27 UTC

(superset) branch master updated: fix(ag-grid-table): refresh totals when summary aggregation changes (#44612)

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

rebenitez1802 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git


The following commit(s) were added to refs/heads/master by this push:
     new 31e3c9a1944 fix(ag-grid-table): refresh totals when summary aggregation changes (#44612)
31e3c9a1944 is described below

commit 31e3c9a1944e40ff7398a62be43b4d7be6eed40f
Author: Rafael Benitez <re...@gmail.com>
AuthorDate: Tue Oct 6 11:30:19 2026 -0300

    fix(ag-grid-table): refresh totals when summary aggregation changes (#44612)
---
 .../creating-your-first-dashboard.mdx              |   2 +
 .../src/AgGridTableChart.tsx                       |  34 ++++-
 .../src/transformProps.ts                          |   2 +
 .../plugin-chart-ag-grid-table/src/types.ts        |   2 +
 .../src/utils/externalAPIs.ts                      |   2 +
 .../test/AgGridTableChart.test.tsx                 | 153 ++++++++++++++++++++-
 6 files changed, 193 insertions(+), 2 deletions(-)

diff --git a/docs/docs/using-superset/creating-your-first-dashboard.mdx b/docs/docs/using-superset/creating-your-first-dashboard.mdx
index b440cea0995..10ae4c735f7 100644
--- a/docs/docs/using-superset/creating-your-first-dashboard.mdx
+++ b/docs/docs/using-superset/creating-your-first-dashboard.mdx
@@ -406,6 +406,8 @@ The **Show summary** checkbox lives at the top of the **Visual formatting** sect
 - In **Aggregate** mode, the summary row applies each metric's own aggregation (or the **Summary aggregation** override, where available) across the full filtered dataset.
 - In **Raw Records** mode, the summary row defaults to a server-side `SUM` for each numeric column that's backed by a physical or calculated dataset column; the **Summary aggregation** control can override this to `AVG` as well. Non-numeric cells and columns built from free-form SQL expressions stay blank.
 
+Changing **Summary aggregation** refreshes the summary row automatically; you do not need to click **Update chart**.
+
 In both modes, the summary is computed across the full result set, independent of the chart's row limit and pagination, and it reflects dashboard and chart-level filters. It does not reflect AG Grid's own server-side column filters (the per-column filter UI in the grid header), which are excluded from the summary query.
 
 ### Dynamic Currency Formatting
diff --git a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/AgGridTableChart.tsx b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/AgGridTableChart.tsx
index 8e939e5b7b8..37925a7de15 100644
--- a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/AgGridTableChart.tsx
+++ b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/AgGridTableChart.tsx
@@ -27,6 +27,10 @@ import {
   isEmptyDateInput,
 } from '@superset-ui/core';
 import { GenericDataType } from '@apache-superset/core/common';
+import {
+  toTotalsAggregate,
+  hasRenderableHeaderGroups,
+} from '@superset-ui/chart-controls';
 import {
   useCallback,
   useEffect,
@@ -42,7 +46,6 @@ import {
   CellContextMenuEvent,
   SelectionChangedEvent,
 } from '@superset-ui/core/components/ThemedAgGridReact';
-import { hasRenderableHeaderGroups } from '@superset-ui/chart-controls';
 import {
   AgGridTableChartTransformedProps,
   InputColumn,
@@ -92,6 +95,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
     isUsingTimeComparison,
     colorPositiveNegative,
     totals,
+    totalsAggregate,
     showTotals,
     columnColorFormatters,
     basicColorFormatters,
@@ -202,6 +206,20 @@ export default function TableChart<D extends DataRecord = DataRecord>(
     [setDataMask],
   );
 
+  const effectiveTotalsAggregate =
+    isRawRecords && totalsAggregate === 'ORIGINAL' ? 'SUM' : totalsAggregate;
+  const requestedTotalsAggregate =
+    serverPaginationData?.totalsAggregate === undefined
+      ? effectiveTotalsAggregate
+      : toTotalsAggregate(serverPaginationData.totalsAggregate);
+  // Preserve the requested aggregation across query-driven remounts, where
+  // a newer selection can coexist with the previous request's totals.
+  const lastTotalsAggregateRef = useRef(
+    isRawRecords && requestedTotalsAggregate === 'ORIGINAL'
+      ? 'SUM'
+      : requestedTotalsAggregate,
+  );
+
   // A single effect owns every ownState write derived from render state.
   // updateTableOwnState replaces ownState wholesale, so separate effects that
   // each spread serverPaginationData in the same render would clobber one
@@ -236,12 +254,25 @@ export default function TableChart<D extends DataRecord = DataRecord>(
     // carries the totals query for the active mode.
     if (showTotals && totals === undefined && !requested) {
       patch.totalsRequested = true;
+      patch.totalsAggregate = effectiveTotalsAggregate;
       changed = true;
     } else if (!showTotals && requested) {
       patch.totalsRequested = false;
       changed = true;
     }
 
+    // Summary aggregation stays a renderTrigger control in Customize, but
+    // its SQL totals need a refresh even when the previous totals exist.
+    // Retain the last visible aggregation while hidden to refresh on reveal.
+    if (
+      showTotals &&
+      lastTotalsAggregateRef.current !== effectiveTotalsAggregate
+    ) {
+      patch.totalsAggregate = effectiveTotalsAggregate;
+      lastTotalsAggregateRef.current = effectiveTotalsAggregate;
+      changed = true;
+    }
+
     if (changed) {
       writeOwnState(patch);
     }
@@ -252,6 +283,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
     isRawRecords,
     showTotals,
     totals,
+    effectiveTotalsAggregate,
     rawSummaryColumns,
     serverPaginationData,
     writeOwnState,
diff --git a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/transformProps.ts b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/transformProps.ts
index d5e8f569c6b..18d78ab9c73 100644
--- a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/transformProps.ts
@@ -46,6 +46,7 @@ import {
   getColorFormatters,
   ColorSchemeEnum,
   resolveHeaderGroups,
+  toTotalsAggregate,
 } from '@superset-ui/chart-controls';
 import isEqualColumns from './utils/isEqualColumns';
 import { BASIC_COLOR_FORMATTERS_ROW_KEY } from './consts';
@@ -966,6 +967,7 @@ const transformProps = (
     isUsingTimeComparison,
     colorPositiveNegative,
     totals,
+    totalsAggregate: toTotalsAggregate(formData.totals_aggregate),
     showTotals,
     columnColorFormatters,
     basicColorColumnFormatters,
diff --git a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/types.ts b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/types.ts
index cc145b979d5..7d3d09f43a4 100644
--- a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/types.ts
+++ b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/types.ts
@@ -23,6 +23,7 @@ import type {
   DataColumnMeta,
   HeaderGroupConfig,
   TableColumnConfig,
+  TotalsAggregate,
 } from '@superset-ui/chart-controls';
 import {
   NumberFormatter,
@@ -129,6 +130,7 @@ export interface AgGridTableChartTransformedProps<
   isUsingTimeComparison: boolean;
   colorPositiveNegative: boolean;
   totals: DataRecord | undefined;
+  totalsAggregate: TotalsAggregate;
   showTotals: boolean;
   columnColorFormatters: ColorFormatters;
   basicColorFormatters?: { [Key: string]: BasicColorFormatterType }[];
diff --git a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/utils/externalAPIs.ts b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/utils/externalAPIs.ts
index 6a2b62f559d..776c5ea8a18 100644
--- a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/utils/externalAPIs.ts
+++ b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/utils/externalAPIs.ts
@@ -18,6 +18,7 @@
  * under the License.
  */
 import { SetDataMaskHook } from '@superset-ui/core';
+import type { TotalsAggregate } from '@superset-ui/chart-controls';
 import { SortByItem } from '../types';
 
 export interface ClientViewColumn {
@@ -40,6 +41,7 @@ interface TableOwnState {
   sortBy?: SortByItem[];
   rawSummaryColumns?: string[];
   totalsRequested?: boolean;
+  totalsAggregate?: TotalsAggregate;
   clientView?: ClientViewSnapshot;
 }
 
diff --git a/superset-frontend/plugins/plugin-chart-ag-grid-table/test/AgGridTableChart.test.tsx b/superset-frontend/plugins/plugin-chart-ag-grid-table/test/AgGridTableChart.test.tsx
index b0430169ae5..7cfc90f36d4 100644
--- a/superset-frontend/plugins/plugin-chart-ag-grid-table/test/AgGridTableChart.test.tsx
+++ b/superset-frontend/plugins/plugin-chart-ag-grid-table/test/AgGridTableChart.test.tsx
@@ -25,7 +25,12 @@ import {
   within,
   userEvent,
 } from '@superset-ui/core/spec';
-import { QueryMode, TimeGranularity, SMART_DATE_ID } from '@superset-ui/core';
+import {
+  QueryMode,
+  TimeGranularity,
+  SMART_DATE_ID,
+  type JsonObject,
+} from '@superset-ui/core';
 import { GenericDataType } from '@apache-superset/core/common';
 import {
   setupAGGridModules,
@@ -909,6 +914,147 @@ test('AgGridTableChart clears the aggregate totals request when the summary is o
   });
 });
 
+test.each([QueryMode.Aggregate, QueryMode.Raw])(
+  'AgGridTableChart refreshes existing %s totals when summary aggregation changes',
+  async queryMode => {
+    const chartProps = {
+      ...rawSummaryProps,
+      rawFormData: {
+        ...rawSummaryProps.rawFormData,
+        query_mode: queryMode,
+      },
+    };
+    const props = transformProps(chartProps);
+    let ownState: JsonObject = {
+      currentPage: 0,
+      pageSize: 20,
+      rawSummaryColumns: props.rawSummaryColumns,
+      totalsRequested: true,
+    };
+    /** Render each selection against the existing query response. */
+    const getChart = (aggregation?: string, showTotals = true) =>
+      ProviderWrapper({
+        children: (
+          <AgGridTableChart
+            {...transformProps({
+              ...chartProps,
+              rawFormData: {
+                ...chartProps.rawFormData,
+                totals_aggregate: aggregation,
+                show_totals: showTotals,
+              },
+            })}
+            setDataMask={mockSetDataMask}
+            slice_id={1}
+            serverPaginationData={ownState}
+          />
+        ),
+      });
+    const { rerender } = render(getChart());
+    await waitFor(() => {
+      expect(document.querySelector('.ag-container')).toBeInTheDocument();
+    });
+    mockSetDataMask.mockClear();
+
+    // A legacy chart without a saved selection already means ORIGINAL.
+    rerender(getChart('ORIGINAL'));
+    expect(mockSetDataMask).not.toHaveBeenCalled();
+    if (queryMode === QueryMode.Raw) {
+      // Raw records use SUM for ORIGINAL as well.
+      rerender(getChart('SUM'));
+      expect(mockSetDataMask).not.toHaveBeenCalled();
+    }
+
+    for (const aggregation of ['AVG', 'ORIGINAL', 'AVG', 'SUM']) {
+      const effectiveAggregation =
+        queryMode === QueryMode.Raw && aggregation === 'ORIGINAL'
+          ? 'SUM'
+          : aggregation;
+      rerender(getChart(aggregation));
+      await waitFor(() => {
+        expect(mockSetDataMask).toHaveBeenCalledWith({
+          ownState: expect.objectContaining({
+            ...ownState,
+            totalsAggregate: effectiveAggregation,
+          }),
+        });
+      });
+
+      ownState = { ...ownState, totalsAggregate: effectiveAggregation };
+      mockSetDataMask.mockClear();
+      rerender(getChart(aggregation));
+      expect(mockSetDataMask).not.toHaveBeenCalled();
+    }
+
+    rerender(getChart('SUM', false));
+    ownState = { ...ownState, totalsRequested: false };
+    mockSetDataMask.mockClear();
+    rerender(getChart('AVG', false));
+    expect(mockSetDataMask).not.toHaveBeenCalled();
+    rerender(getChart('AVG'));
+    await waitFor(() => {
+      expect(mockSetDataMask).toHaveBeenCalledWith({
+        ownState: expect.objectContaining({
+          ...ownState,
+          totalsAggregate: 'AVG',
+        }),
+      });
+    });
+  },
+);
+
+test('AgGridTableChart refreshes an aggregation changed during a query-driven remount', async () => {
+  const props = transformProps({
+    ...rawSummaryProps,
+    rawFormData: {
+      ...rawSummaryProps.rawFormData,
+      query_mode: QueryMode.Aggregate,
+      totals_aggregate: 'AVG',
+    },
+  });
+  const ownState = {
+    totalsRequested: true,
+    totalsAggregate: 'ORIGINAL',
+    currentPage: 1,
+    pageSize: 20,
+  };
+  const { rerender } = render(
+    ProviderWrapper({
+      children: (
+        <AgGridTableChart
+          {...props}
+          setDataMask={mockSetDataMask}
+          slice_id={1}
+          serverPaginationData={ownState}
+        />
+      ),
+    }),
+  );
+  await waitFor(() => {
+    expect(mockSetDataMask).toHaveBeenCalledWith({
+      ownState: expect.objectContaining({
+        ...ownState,
+        totalsAggregate: 'AVG',
+      }),
+    });
+  });
+
+  mockSetDataMask.mockClear();
+  rerender(
+    ProviderWrapper({
+      children: (
+        <AgGridTableChart
+          {...props}
+          setDataMask={mockSetDataMask}
+          slice_id={1}
+          serverPaginationData={{ ...ownState, totalsAggregate: 'AVG' }}
+        />
+      ),
+    }),
+  );
+  expect(mockSetDataMask).not.toHaveBeenCalled();
+});
+
 test('AgGridTableChart clamps the page to zero when the result set is empty', async () => {
   const props = transformProps({
     ...rawSummaryProps,
@@ -950,6 +1096,10 @@ test('AgGridTableChart clamps the page to zero when the result set is empty', as
 test('AgGridTableChart merges the page clamp and totals request into one own-state write', async () => {
   const props = transformProps({
     ...rawSummaryProps,
+    rawFormData: {
+      ...rawSummaryProps.rawFormData,
+      totals_aggregate: 'AVG',
+    },
     queriesData: [rawSummaryProps.queriesData[0]],
   });
   props.serverPagination = true;
@@ -978,6 +1128,7 @@ test('AgGridTableChart merges the page clamp and totals request into one own-sta
           currentPage: 2,
           rawSummaryColumns: ['sum__num'],
           totalsRequested: true,
+          totalsAggregate: 'AVG',
         }),
       }),
     );