Files
baserow/web-frontend/test/unit/database/components/view/grid/gridViewGroupByAggregation.spec.js
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

256 lines
9.0 KiB
JavaScript

import { TestApp } from '@baserow/test/helpers/testApp'
import GridViewGroupByAggregation from '@baserow/modules/database/components/view/grid/GridViewGroupByAggregation'
import DistributionAggregation from '@baserow/modules/database/components/aggregation/DistributionAggregation'
import Context from '@baserow/modules/core/components/Context'
import flushPromises from 'flush-promises'
describe('GridViewGroupByAggregation', () => {
let testApp = null
let store = null
let mockServer = null
beforeEach(() => {
testApp = new TestApp()
store = testApp.store
mockServer = testApp.mockServer
})
afterEach(async () => {
// Restore spies so a mocked `store.dispatch` from one test can't leak into the
// next and turn its setup dispatches into no-ops.
vi.restoreAllMocks()
await testApp.afterEach()
})
const field = { id: 2, name: 'Amount', type: 'number' }
const mountCell = (props = {}, mocks = {}) =>
testApp.mount(GridViewGroupByAggregation, {
propsData: {
view: { id: 1 },
workspaceId: 1,
field,
storePrefix: 'page/',
rawValue: 30,
rowCount: 2,
...props,
},
global: { mocks },
})
const configureSum = () =>
store.dispatch('page/view/grid/forceUpdateAllFieldOptions', {
2: { aggregation_type: 'sum', aggregation_raw_type: 'sum' },
})
const configureNotEmptyCount = () =>
store.dispatch('page/view/grid/forceUpdateAllFieldOptions', {
2: {
aggregation_type: 'not_empty_count',
aggregation_raw_type: 'empty_count',
},
})
const configureDistribution = () =>
store.dispatch('page/view/grid/forceUpdateAllFieldOptions', {
2: {
aggregation_type: 'distribution',
aggregation_raw_type: 'distribution',
},
})
test('renders the per-group aggregation value for a configured field', async () => {
await configureSum()
const wrapper = await mountCell()
expect(wrapper.find('.grid-view-aggregation').exists()).toBe(true)
expect(wrapper.text()).toContain('30')
})
test('keeps the label but hides the value behind the spinner while loading', async () => {
await configureSum()
const wrapper = await mountCell({ loading: true })
// Label stays; the value gets the modifier that hides it and shows the spinner.
expect(wrapper.find('.grid-view-aggregation__generic-name').exists()).toBe(
true
)
expect(
wrapper.find('.grid-view-aggregation__generic-value--loading').exists()
).toBe(true)
})
test('formats derived counts with the server-confirmed aggregation row count', async () => {
await configureNotEmptyCount()
const wrapper = await mountCell({
rawValue: 1,
rowCount: 3,
aggregationRowCount: 2,
})
expect(wrapper.find('.grid-view-aggregation__generic-value').text()).toBe(
'1'
)
})
test('shows a spinner while loading the first value (none to aggregation)', async () => {
await configureSum()
const wrapper = await mountCell({ rawValue: undefined, loading: true })
expect(
wrapper.find('.grid-view__group-by-banner-aggregation-loading').exists()
).toBe(true)
})
test('starts the spinner as the aggregation changes, before the refresh', async () => {
await configureSum()
const wrapper = await mountCell()
const realDispatch = store.dispatch.bind(store)
vi.spyOn(store, 'dispatch').mockImplementation((action, payload) => {
if (action.endsWith('updateFieldOptionsOfField')) {
return Promise.resolve(undefined)
}
return realDispatch(action, payload)
})
await wrapper.find('.grid-view-aggregation').trigger('click')
const context = wrapper.findComponent(Context)
await context
.find('.select__items > .select__item:nth-child(2)')
.find('.select__item-link')
.trigger('click')
await flushPromises()
// Loading is set as part of the change, so the old value never flashes.
expect(
store.getters['page/view/grid/getGroupByAggregationsLoading'](field.id)
).toBe(true)
})
test('renders a summarize affordance when nothing is configured yet', async () => {
const wrapper = await mountCell({ rawValue: undefined })
// The empty state lets an editable user set an aggregation from the group.
expect(wrapper.find('.grid-view-aggregation__empty').exists()).toBe(true)
})
test('never shows the summarize affordance for a configured field without a per-group value', async () => {
// A non-scalar aggregation (e.g. distribution) is configured but the backend
// returns no per-group value, so the field must not look unconfigured.
await configureSum()
const wrapper = await mountCell({ rawValue: undefined })
expect(wrapper.find('.grid-view-aggregation__empty').exists()).toBe(false)
expect(wrapper.text()).not.toContain('30')
})
test('renders nothing for a read-only user when nothing is configured', async () => {
const wrapper = await mountCell(
{ rawValue: undefined },
{ $hasPermission: () => false }
)
expect(wrapper.find('.grid-view-aggregation').exists()).toBe(false)
})
test('selecting an aggregation updates the shared field option and emits change', async () => {
await configureSum()
const wrapper = await mountCell()
const dispatch = vi.spyOn(store, 'dispatch').mockResolvedValue(undefined)
await wrapper.find('.grid-view-aggregation').trigger('click')
const context = wrapper.findComponent(Context)
// The second item is the first aggregation function after "None".
await context
.find('.select__items > .select__item:nth-child(2)')
.find('.select__item-link')
.trigger('click')
await flushPromises()
expect(dispatch).toHaveBeenCalledWith(
'page/view/grid/updateFieldOptionsOfField',
expect.objectContaining({ field })
)
expect(wrapper.emitted('change')).toBeTruthy()
})
test('switching to a display type that shares the raw type re-renders without a refetch or spinner', async () => {
// not_empty_count and empty_count share the raw type, so switching between them
// only re-renders the existing value — the choice is persisted but no group-by-data
// request goes out and the cell never spins (like the footer). The cell emits
// `change` to trigger the refetch, so "no change emitted" is the no-request proof.
store.commit('page/view/grid/SET_LAST_GRID_ID', 1)
await configureNotEmptyCount()
mockServer.updateFieldOptions(1, {
2: {
aggregation_type: 'empty_count',
aggregation_raw_type: 'empty_count',
},
})
const wrapper = await mountCell()
// 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 wrapper.find('.grid-view-aggregation').trigger('click')
const context = wrapper.findComponent(Context)
const emptyCountItem = context.findAll('.select__item').find((item) => {
const name = item.find('.select__item-name-text')
return name.exists() && name.text() === 'viewAggregationType.emptyCount'
})
await emptyCountItem.find('.select__item-link').trigger('click')
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: 'empty_count',
aggregation_raw_type: 'empty_count',
}),
})
)
expect(mockServer.mock.history.patch).toHaveLength(1)
// ...but it neither triggers the refetch, spins the cell, nor issues a GET.
expect(wrapper.emitted('change')).toBeFalsy()
expect(dispatch).not.toHaveBeenCalledWith(
'page/view/grid/setGroupByAggregationsLoading',
expect.objectContaining({ fieldId: field.id })
)
expect(mockServer.mock.history.get).toHaveLength(0)
})
test('renders nothing instead of crashing on a table-only aggregation', async () => {
// Distribution is footer-only; the field's stale scalar value must not be fed to
// its array-shaped getValue (which would throw and break the group render).
await configureDistribution()
const wrapper = await mountCell({ rawValue: 25 })
expect(wrapper.findComponent(DistributionAggregation).exists()).toBe(false)
expect(wrapper.find('.grid-view-aggregation__empty').exists()).toBe(true)
})
test('omits table-only aggregations from the group context menu', async () => {
await configureSum()
const wrapper = await mountCell()
await wrapper.find('.grid-view-aggregation').trigger('click')
const names = wrapper
.findComponent(Context)
.findAll('.select__item-name-text')
.map((node) => node.text())
expect(names).toContain('viewAggregationType.sum')
expect(names).not.toContain('viewAggregationType.distribution')
})
})