Files
Davide Silvestri ad08d4be1d feat: Group-by aggregations (#5602)
* feat: show per-group aggregations in grouped grid views

Each group header shows the column's configured Summarize value computed
over that group's rows, column-aligned at every depth, visible whether
the group is collapsed or expanded. Reuses the footer aggregation config
and display components, and an interactive per-group picker that sets the
shared column aggregation. Gated behind the group_by_aggregations frontend
flag; backend returns values via the existing group-by-data response.

Not included (follow-up): realtime/live updates, performance and caching,
and consolidating the group-by-data and aggregations endpoints into one
request for grouped views.

* refactor: de-duplicate Decimal NaN handling in grid aggregations

Extract the repeated Decimal("NaN") -> "NaN" JSON-safety hack into a single
json_safe_aggregation_value helper, reused by the group-by per-group and totals
aggregations and the authed/public footer aggregation endpoints.

* fix: address copilot feedback on group-by aggregations

- Only show the "+ Summarize" picker for unconfigured columns; a configured
  column with no per-group value (e.g. distribution) now renders nothing
  instead of looking unconfigured.
- Document the aggregations_only and include_totals query params and the
  optional top-level aggregations field in the group-by-data OpenAPI schema.
- Mark row_count, sibling_index and row_offset optional (omitted in the lean
  aggregations_only mode).

* fix: de-flake replay-events last-seen-expired test

The test assumed RealtimeEvent id 1 never exists, but the id sequence isn't
reset between transactional tests, so the recorded event got id 1 when the
test ran first on an xdist worker and replay succeeded. Capture the real id,
delete it to simulate retention, and replay from it.

* feat: live, consolidated group aggregation updates

Group-header aggregation values and the footer total now update live and in
place on any change (cell edit, row create/delete, realtime), with no spinner.
In grouped mode they come from a single group-by-data request (aggregations_only
+ include_totals); the standalone /aggregations/ endpoint is no longer called
while grouped. Sort changes need no refresh (order-independent). Gated behind the
group_by_aggregations flag; flag-off behaviour is unchanged.

Deferred: per-group targeting (refreshes the loaded window), the optimistic +
realtime double request, and the 7.3.2 picker e2e.

* fix: dedupe and harden per-group aggregation refresh

Selecting an aggregation in a grouped view fired the group-by-data request
two or three times and could leave the footer total hidden behind a stuck
spinner until the page was refreshed.

- Clear the footer loading flag from refreshGroupByAggregations so the total
  shows on first select.
- Make refreshGroupByAggregations the single owner and supersede in-flight
  requests so a stale response can't overwrite newer values.
- Skip the duplicate fetch from updateFieldOptionsOfField and the footer
  watcher while a picker already owns the refresh.
- Right-align and shrink the banner aggregation value, and let the label slide
  behind the previous field instead of hiding it.

* chore: remove the group_by_aggregations feature flag

The per-group aggregations feature is finished, so enable it unconditionally
and drop the flag gating from the grid footer, group banners, and the
aggregation refresh action.

* test: drop obsolete group-by aggregation feature-flag specs

The group_by_aggregations flag is gone, so the two specs that asserted the
flag-disabled behaviour no longer apply.

* fix: stop the row context menu's Select row from clearing its own selection

The global click handler that clears a multi-select when clicking outside the
grid also fired for the row context menu's "Select row" click, wiping the
selection it had just made (most visible in group-by). Skip the clear when the
click lands inside a context menu; cell clicks, which should still clear, are
unaffected.

* fix: flaky test

* fix: show the spinner for updates as well

* fix: address copilot aggregation comment

* fix: avoid optimistic group aggregation values

* fix: address feedback

* fix: hide vert divider before primary field

* fix: only re-fetch when raw_aggregation_type changes
2026-07-06 08:20:54 +00:00

283 lines
8.0 KiB
JavaScript

import { TestApp } from '@baserow/test/helpers/testApp'
import GridViewFieldFooter from '@baserow/modules/database/components/view/grid/GridViewFieldFooter'
import Context from '@baserow/modules/core/components/Context'
import { clone } from '@baserow/modules/core/utils/object'
import flushPromises from 'flush-promises'
describe('Field footer component', () => {
let testApp = null
let mockServer = null
let store = null
beforeEach(() => {
testApp = new TestApp()
store = testApp.store
mockServer = testApp.mockServer
})
afterEach(async () => {
vi.restoreAllMocks()
await testApp.afterEach()
})
const mountComponent = (props, slots = {}) => {
return testApp.mount(GridViewFieldFooter, { propsData: props, slots })
}
const selectValue = async (wrapper, child) => {
await wrapper.find(`.grid-view-aggregation`).trigger('click')
const context = wrapper.findComponent(Context)
await context
.find(`.select__items > .select__item:nth-child(${child})`)
.find('.select__item-link')
.trigger('click')
}
const selectAggregationByName = async (wrapper, name) => {
await wrapper.find(`.grid-view-aggregation`).trigger('click')
const context = wrapper.findComponent(Context)
const link = context
.findAll('.select__item-link')
.find((l) => l.find('.select__item-name-text').text() === name)
await link.trigger('click')
}
test('Default component', async () => {
await store.dispatch('page/view/grid/forceUpdateAllFieldOptions', {
2: {
aggregation_type: 'not_empty_percentage',
aggregation_raw_type: 'not_empty_count',
},
})
store.commit('page/view/grid/SET_COUNT', 1024)
const view = {
id: 1,
}
const database = {
id: 1,
workspace: { id: 1 },
}
// field with no aggregation
const wrapper1 = await mountComponent({
view,
database,
field: { id: 1, type: 'text' },
storePrefix: 'page/',
})
expect(wrapper1.element).toMatchSnapshot()
// Field with aggregation
const wrapper2 = await mountComponent({
view,
database,
field: { id: 2, type: 'text' },
storePrefix: 'page/',
})
expect(wrapper2.element).toMatchSnapshot()
mockServer.getAllFieldAggregationData(view.id, {
field_2: 256,
})
// let's fetch the data for this field
await store.dispatch('page/view/grid/fetchAllFieldAggregationData', {
view,
})
expect(wrapper2.element).toMatchSnapshot()
})
test('Change type', async () => {
await store.dispatch('page/view/grid/forceUpdateAllFieldOptions', {
3: {
aggregation_type: 'not_empty_count',
aggregation_raw_type: 'not_empty_count',
},
})
store.commit('page/view/grid/SET_LAST_GRID_ID', 2)
const view = {
id: 2,
}
const database = {
id: 1,
workspace: { id: 1 },
}
mockServer.getAllFieldAggregationData(view.id, {
field_3: 256,
})
mockServer.updateFieldOptions(view.id, {
3: {
aggregation_type: '',
aggregation_raw_type: '',
},
})
// Field with aggregation
const wrapper = await mountComponent({
view,
database,
field: { id: 3, type: 'text' },
storePrefix: 'page/',
})
// let's fetch the data for this field
await store.dispatch('page/view/grid/fetchAllFieldAggregationData', {
view,
})
// Open menu manually first to have the opportunity to make snapshots
await wrapper.find(`.grid-view-aggregation`).trigger('click')
const context = wrapper.findComponent(Context)
expect(context.element).toMatchSnapshot()
// Click on aggregation type empty_count
await context
.find('.select__items > .select__item:nth-child(1)')
.find('.select__item-link')
.trigger('click')
await flushPromises()
expect(wrapper.element).toMatchSnapshot()
mockServer.getAllFieldAggregationData(view.id, {
field_3: 10,
})
mockServer.updateFieldOptions(view.id, {
3: {
aggregation_type: 'empty_count',
aggregation_raw_type: 'empty_count',
},
})
await store.dispatch('page/view/grid/forceUpdateAllFieldOptions', {
3: {
aggregation_type: 'empty_count',
aggregation_raw_type: 'empty_count',
},
})
// Select empty count aggregation now
await selectValue(wrapper, 2)
await flushPromises()
expect(
clone(store.getters['page/view/grid/getAllFieldAggregationData'])
).toEqual({ 3: { loading: false, value: 10 } })
expect(wrapper.element).toMatchSnapshot()
})
test('ignores an unknown stored aggregation type instead of crashing', async () => {
// A stale/invalid aggregation_type must not crash the grid; the footer treats
// it as unconfigured.
await store.dispatch('page/view/grid/forceUpdateAllFieldOptions', {
2: {
aggregation_type: 'not_empty_count1',
aggregation_raw_type: 'not_empty_count',
},
})
store.commit('page/view/grid/SET_COUNT', 10)
store.commit('page/view/grid/SET_FIELD_AGGREGATION_DATA', {
fieldId: 2,
value: 5,
})
const wrapper = await mountComponent({
view: { id: 1 },
database: { id: 1, workspace: { id: 1 } },
field: { id: 2, type: 'text' },
storePrefix: 'page/',
})
expect(wrapper.find('.grid-view-aggregation__empty').exists()).toBe(true)
})
const mountGroupedFooter = () => {
store.commit('page/view/grid/SET_LAST_GRID_ID', 2)
store.commit('page/view/grid/SET_ACTIVE_GROUP_BYS', [{ field: 1 }])
return testApp.mount(GridViewFieldFooter, {
propsData: {
view: { id: 2 },
database: { id: 1, workspace: { id: 1 } },
field: { id: 3, type: 'text' },
storePrefix: 'page/',
},
})
}
test('changing the aggregation refreshes the group headers in grouped mode', async () => {
const wrapper = await mountGroupedFooter()
const dispatch = vi.spyOn(store, 'dispatch').mockResolvedValue(undefined)
await selectValue(wrapper, 2)
await flushPromises()
expect(dispatch).toHaveBeenCalledWith(
'page/view/grid/refreshGroupByAggregations',
expect.objectContaining({ fieldId: 3 })
)
})
test('a display-only aggregation change in grouped mode persists without refetching the group tree', async () => {
// "Empty" and "Filled" are display variants of the same raw type
// (`empty_count`), so switching between them persists the new label but must NOT
// spin or issue a group-by-data request — the value re-renders client-side.
await store.dispatch('page/view/grid/forceUpdateAllFieldOptions', {
3: {
aggregation_type: 'empty_count',
aggregation_raw_type: 'empty_count',
},
})
mockServer.updateFieldOptions(2, {
3: {
aggregation_type: 'not_empty_count',
aggregation_raw_type: 'empty_count',
},
})
const wrapper = await mountGroupedFooter()
// Run the real dispatch chain so the HTTP layer sees exactly what goes out.
const realDispatch = store.dispatch.bind(store)
const dispatch = vi
.spyOn(store, 'dispatch')
.mockImplementation((action, payload) => realDispatch(action, payload))
await selectAggregationByName(wrapper, 'viewAggregationType.notEmptyCount')
await flushPromises()
// The new display type is still persisted (one PATCH to field-options)...
expect(dispatch).toHaveBeenCalledWith(
'page/view/grid/updateFieldOptionsOfField',
expect.objectContaining({
values: expect.objectContaining({
aggregation_type: 'not_empty_count',
}),
})
)
expect(mockServer.mock.history.patch).toHaveLength(1)
// ...but nothing spins and no group-by-data request goes out.
expect(dispatch).not.toHaveBeenCalledWith(
'page/view/grid/setGroupByAggregationsLoading',
expect.anything()
)
expect(dispatch).not.toHaveBeenCalledWith(
'page/view/grid/refreshGroupByAggregations',
expect.anything()
)
expect(mockServer.mock.history.get).toHaveLength(0)
})
})