diff --git a/.changeset/35702-boolean-yes-no-counts.md b/.changeset/35702-boolean-yes-no-counts.md new file mode 100644 index 00000000000..3fbec222f95 --- /dev/null +++ b/.changeset/35702-boolean-yes-no-counts.md @@ -0,0 +1,19 @@ +--- +'@objectstack/spec': minor +'@objectstack/lint': minor +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +--- + +feat(spec): `count_true` / `count_false` column summaries — a boolean column's Yes and No counts in the list footer and group headers + +Clause-②: yes (widening) +Metadata-protocol: added + +`ListColumn.summary` accepts two more members, `count_true` and `count_false`: the number of rows whose boolean (or toggle) cell is true, and the number whose cell is false. A cell with no value is neither; it stays `count_empty`'s, so `count_true + count_false = count_filled`. + +Both are answered on the server with no new aggregation function: booleans aggregate as numbers on every backend, so `count_true` is `SUM(field)` and `count_false` is `COUNT(field) − SUM(field)`, read off the group header row (or the footer's whole-set row) by `deriveColumnSummary`. `COLUMN_SUMMARY_AGGREGATION`'s derived rows now carry `reads`, every node the member reads (`from` is its first); `columnSummaryNodeFunctions(mapping)` is the one reading of a row's nodes, which the group header compiler, the footer's whole-set query and the lint now share. `COLUMN_SUMMARY_FIELD_TYPES` / `isColumnSummaryCompatibleWithFieldType` say the two members apply to `boolean` and `toggle` only. + +`@objectstack/lint` refuses `count_true` / `count_false` over any other field type under `list-view-summary-field-type-refused` (an error, so `os validate` and the save door fail): over a number the same `SUM(field)` is a total, and the footer would print it as a count. + +`@object-ui/plugin-grid`'s footer menu offers Count of Yes and Count of No first on a boolean or toggle column, and only there; the footer draws them as `Yes 12` / `No 3`, from the whole matched set when the server answers it and from the page, labelled as the page's, when it does not. `@object-ui/i18n` adds the `grid.summary` keys `countTrue`, `countFalse`, `menuCountTrue` and `menuCountFalse` in every pack. diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index 84bad929c6f..391a1487de3 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -130,7 +130,7 @@ Compound-cell prefix configuration ## ColumnSummary -Aggregation function for the column footer summary — and, on a grouped list view, the per-group header summary (server-side): count (COUNT(*), the group count), count_unique (count_distinct), sum, avg, min, max map onto the query AST's AggregationFunction; count_filled, count_empty, percent_filled, percent_empty derive from one COUNT(field) node (the non-null count) and the group count — count_filled = COUNT(field), count_empty = count − COUNT(field), percent_filled = COUNT(field) / count (0 when count is 0), percent_empty = 1 − percent_filled. Server-side "empty" is null on every face; the footer's client-side reading of empty strings and empty arrays as empty is the renderer's to converge +Aggregation function for the column footer summary — and, on a grouped list view, the per-group header summary (server-side): count (COUNT(*), the group count), count_unique (count_distinct), sum, avg, min, max map onto the query AST's AggregationFunction; count_filled, count_empty, percent_filled, percent_empty derive from one COUNT(field) node (the non-null count) and the group count — count_filled = COUNT(field), count_empty = count − COUNT(field), percent_filled = COUNT(field) / count (0 when count is 0), percent_empty = 1 − percent_filled. count_true and count_false are a boolean column's yes and no counts, boolean fields only — count_true = SUM(field), count_false = COUNT(field) − SUM(field); a null cell is neither. Server-side "empty" is null on every face; the footer's client-side reading of empty strings and empty arrays as empty is the renderer's to converge ### Allowed Values @@ -141,6 +141,8 @@ Aggregation function for the column footer summary — and, on a grouped list vi * `count_unique` * `percent_empty` * `percent_filled` +* `count_true` +* `count_false` * `sum` * `avg` * `min` @@ -157,7 +159,7 @@ Column footer summary configuration | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'none' \| 'count' \| 'count_empty' \| 'count_filled' \| 'count_unique' \| 'percent_empty' \| 'percent_filled' \| 'sum' \| 'avg' \| 'min' \| 'max'>` | ✅ | Aggregation function | +| **type** | `Enum<'none' \| 'count' \| 'count_empty' \| 'count_filled' \| 'count_unique' \| 'percent_empty' \| 'percent_filled' \| 'count_true' \| 'count_false' \| 'sum' \| 'avg' \| 'min' \| 'max'>` | ✅ | Aggregation function | | **field** | `string` | optional | Field to aggregate (defaults to the column field) | @@ -725,7 +727,7 @@ List chart view configuration | **wrap** | `boolean` | optional | Allow text wrapping | | **type** | `string` | optional | Renderer type override (e.g., "currency", "date") | | **pinned** | `Enum<'left' \| 'right'>` | optional | Pin/freeze column to left or right side | -| **summary** | `Enum<'none' \| 'count' \| 'count_empty' \| 'count_filled' \| 'count_unique' \| 'percent_empty' \| 'percent_filled' \| 'sum' \| 'avg' \| 'min' \| 'max'> \| { type: Enum<'none' \| 'count' \| 'count_empty' \| 'count_filled' \| 'count_unique' \| …>; field?: string }` | optional | Footer aggregation for this column — the function alone, or `{ type, field }` to aggregate another field | +| **summary** | `Enum<'none' \| 'count' \| 'count_empty' \| 'count_filled' \| 'count_unique' \| 'percent_empty' \| 'percent_filled' \| 'count_true' \| 'count_false' \| 'sum' \| 'avg' \| 'min' \| 'max'> \| { type: Enum<'none' \| 'count' \| 'count_empty' \| 'count_filled' \| 'count_unique' \| …>; field?: string }` | optional | Footer aggregation for this column — the function alone, or `{ type, field }` to aggregate another field | | **prefix** | `{ field: string; type?: Enum<'badge' \| 'text'> }` | optional | Field rendered inline before this cell value | | **link** | `boolean` | optional | Functions as the primary navigation link (triggers View navigation) | | **action** | `string` | optional | Registered Action ID to execute when clicked | diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index 9fb4b78289a..a86a57c8639 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -228,7 +228,7 @@ columns: [ | `sortable` | `boolean` | Allow column sorting | | `resizable` | `boolean` | Allow column resize | | `wrap` | `boolean` | Allow text wrapping | -| `summary` | `enum \| { type, field? }` | Footer aggregation: `none`, `count`, `count_empty`, `count_filled`, `count_unique`, `percent_empty`, `percent_filled`, `sum`, `avg`, `min`, `max`. The object form aggregates a different field than the column's own | +| `summary` | `enum \| { type, field? }` | Footer aggregation: `none`, `count`, `count_empty`, `count_filled`, `count_unique`, `percent_empty`, `percent_filled`, `count_true`, `count_false` (a boolean column's yes / no counts; a cell with no value is neither), `sum`, `avg`, `min`, `max`. The object form aggregates a different field than the column's own | | `prefix` | `{ field, type?: 'badge' \| 'text' }` | Compound cell — render another field's value inline before this cell's value | | `align` | `'left' \| 'center' \| 'right'` | Text alignment | | `link` | `boolean` | Cell functions as the primary navigation link | diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index f27e076b8da..c56f12e9ce2 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -4283,6 +4283,12 @@ const LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED_EXPLANATION: RuleExplanation = { '`dataSource.object`, else `properties.objectName`; its grouped header numbers come from its ' + '`aggregations` (`grid-aggregation-field-type-refused`), not from the column summaries.', AGGREGATE_PAIR_ROWS, + 'The yes / no counts of a boolean column, `count_true` and `count_false`, lower to `SUM(field)` ' + + '(booleans aggregate as numbers, so the sum is the number of true cells) and `COUNT(field)`. The ' + + 'door accepts that sum over a number too, where it is a total rather than a count, so these two ' + + 'members are judged by the spec\'s member × field-type table (`COLUMN_SUMMARY_FIELD_TYPES`) and ' + + 'refused, under this id, over anything but a `boolean` or `toggle` field. A null cell is neither ' + + 'true nor false: it is counted by `count_empty`.', 'The fix is a field of a type the function accepts (`summary: { type, field }` aggregates another ' + 'field), or a summary the field accepts: `count`, or a filled / empty count, takes any field. ' + 'A `formula` field stores no value, whatever its `returnType`, so a total over it has to be ' + diff --git a/packages/lint/src/validate-list-view-field-refs.test.ts b/packages/lint/src/validate-list-view-field-refs.test.ts index d592930810d..d3908c5d1fb 100644 --- a/packages/lint/src/validate-list-view-field-refs.test.ts +++ b/packages/lint/src/validate-list-view-field-refs.test.ts @@ -1593,6 +1593,34 @@ describe('[#32449] a column summary whose function the aggregate door refuses', } }); + it('[#35702] refuses the boolean yes / no counts over anything but a boolean — the door would answer a total', () => { + expect(refused(withColumns( + { field: 'is_locked', summary: 'count_true' }, + { field: 'title', summary: { type: 'count_false', field: 'is_all_day' } }, + ))).toEqual([]); + for (const [column, words] of [ + [{ field: 'estimate', summary: 'count_true' }, '"count_true" over "estimate" (`number`)'], + [{ field: 'is_locked', summary: { type: 'count_false', field: 'title' } }, '"count_false" over "title" (`text`)'], + ] as const) { + const findings = withColumns(column); + expect(findings.map((f) => [f.rule, f.path, f.severity])).toEqual([ + [LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED, 'views[0].list.columns[1].summary', 'error'], + ]); + expect(findings[0].message).toContain(`summary ${words} is a true / false count`); + expect(findings[0].hint).toMatch(/^Point "count_(true|false)" at a boolean or toggle field/); + } + // Every declared `FieldType`: refused exactly where the spec's member table refuses. + for (const member of ['count_true', 'count_false']) { + for (const type of FieldType.options) { + const objects = [{ name: 'duly_task', label: 'Task', fields: [{ name: 'probe', type, label: 'Probe' }] }]; + const findings = refused(validateListViewFieldRefsUnrecorded(stackWith({ data: { provider: 'object', object: 'duly_task' }, columns: [{ field: 'probe', summary: member }] }, objects))); + expect(findings.length, `${member} over ${type}`).toBe(type === 'boolean' || type === 'toggle' ? 0 : 1); + } + } + // Unjudgeable stays unjudged: an unknown field is the existence rule's, a dotted path is skipped. + expect(refused(withColumns({ field: 'title', summary: { type: 'count_true', field: 'owner.name' } }))).toEqual([]); + }); + it('skips what it cannot judge: an unknown field (the existence rule\'s), a dotted path, no declared type, a type outside `FieldType`', () => { expect(withColumns({ field: 'title', summary: { type: 'sum', field: 'nope_field' } }).map((f) => [f.rule, f.path])).toEqual([ [LIST_VIEW_FIELD_UNKNOWN, 'views[0].list.columns[1].summary.field'], diff --git a/packages/lint/src/validate-list-view-field-refs.ts b/packages/lint/src/validate-list-view-field-refs.ts index 0f3b088496c..bf8d370efa9 100644 --- a/packages/lint/src/validate-list-view-field-refs.ts +++ b/packages/lint/src/validate-list-view-field-refs.ts @@ -372,6 +372,14 @@ * door, and judged by this module's {@link columnSummaryRefusal}, under this * rule id. * + * [#35702] The boolean yes / no counts `count_true` / `count_false` ride + * `SUM(field)` (and `COUNT(field)`), which the door ACCEPTS over a number as + * well — where it answers a total, not a count of true cells. So they are + * judged by the spec's member × field-type table instead + * (`COLUMN_SUMMARY_FIELD_TYPES` through `isColumnSummaryCompatibleWithFieldType`, + * the boolean class only), under the same rule id: the footer would print a + * total labelled as a count, with no refusal anywhere to say so. + * * Not judged: `none`; `count` (fieldless, `COUNT(*)`); the four DERIVED * members (`count_filled` / `count_empty` / `percent_filled` / * `percent_empty`), which ride one `COUNT(field)` node and so compare no @@ -466,7 +474,13 @@ import { isAggregateCompatibleWithFieldType, virtualFieldAggregateRemedy, } from '@objectstack/spec/data'; -import { COLUMN_SUMMARY_AGGREGATION, ListViewSchema, type ColumnSummary } from '@objectstack/spec/ui'; +import { + COLUMN_SUMMARY_AGGREGATION, + COLUMN_SUMMARY_FIELD_TYPES, + ListViewSchema, + isColumnSummaryCompatibleWithFieldType, + type ColumnSummary, +} from '@objectstack/spec/ui'; import { aggregateAcceptsDeclaration, @@ -924,9 +938,10 @@ export function columnSummaryRefusal( const member = typeof summary === 'string' ? summary : isRec(summary) ? summary.type : undefined; if (typeof member !== 'string' || !Object.prototype.hasOwnProperty.call(COLUMN_SUMMARY_AGGREGATION, member)) return undefined; const mapping = COLUMN_SUMMARY_AGGREGATION[member as ColumnSummary]; + // A member the spec restricts to some field types (the boolean yes / no counts) is judged by that table. + const restricted = Object.prototype.hasOwnProperty.call(COLUMN_SUMMARY_FIELD_TYPES, member); // `none`, the fieldless `count` and the derived `COUNT(field)` members compare no value. - if (mapping.kind !== 'aggregate' || mapping.fieldless) return undefined; - const fn = mapping.function; + if (!restricted && (mapping.kind !== 'aggregate' || mapping.fieldless)) return undefined; const field = strName(isRec(summary) && summary.field !== undefined ? summary.field : column.field); if (!field || field.includes('.')) return undefined; const verdict = resolveFieldPath(graph, object, field); @@ -934,6 +949,17 @@ export function columnSummaryRefusal( const fieldType = verdict.meta?.type; if (!isJudgeableAggregateType(fieldType)) return undefined; const shape = { type: fieldType, multiple: verdict.meta?.multiple === true }; + if (restricted) { + if (isColumnSummaryCompatibleWithFieldType(member, fieldType)) return undefined; + return { + message: + `summary "${member}" over "${field}" (${declaredAs(shape)}) is a true / false count, for a ` + + 'boolean or toggle field only: here it would print a total as a count', + hint: `Point "${member}" at a boolean or toggle field, or count "${field}" with count_filled or count_empty.`, + }; + } + if (mapping.kind !== 'aggregate') return undefined; + const fn = mapping.function; if (aggregateAcceptsDeclaration(fn, shape)) return undefined; return { message: diff --git a/packages/rest/src/list-view-grouping-query-door.test.ts b/packages/rest/src/list-view-grouping-query-door.test.ts index 6a98de4a007..5df50483c0a 100644 --- a/packages/rest/src/list-view-grouping-query-door.test.ts +++ b/packages/rest/src/list-view-grouping-query-door.test.ts @@ -141,6 +141,8 @@ interface Row { owner: string; /** Nullable on purpose — the field the derived `count_filled` pin reads. */ notes: string | null; + /** A nullable boolean — the field the derived `count_true` / `count_false` pin reads. */ + approved: boolean | null; } function makeRow(unit: string | null, ordinal: number): Row { @@ -154,6 +156,8 @@ function makeRow(unit: string | null, ordinal: number): Row { owner: `owner_${ordinal % 4}`, // Every fifth row has no note — the server's "empty" (null), never ''. notes: ordinal % 5 === 0 ? null : `note ${ordinal}`, + // Every fourth row unset, the rest true / false alternating. + approved: ordinal % 4 === 0 ? null : ordinal % 2 === 0, }; } @@ -283,6 +287,7 @@ function objectSchema(name: string) { amount: { name: 'amount', type: 'number' as const, label: 'Amount' }, owner: { name: 'owner', type: 'text' as const, label: 'Owner' }, notes: { name: 'notes', type: 'text' as const, label: 'Notes' }, + approved: { name: 'approved', type: 'boolean' as const, label: 'Approved' }, seq: { name: 'seq', type: 'number' as const, label: 'Stored Order' }, }, }; @@ -806,6 +811,48 @@ describe('§7 `count_filled` is derived on the header row, and the view filter r }); }); +// ─── §7b The boolean yes / no counts (#35702) ───────────────────────────────── + +describe('§7b `count_true` / `count_false` are SUM(field) and COUNT(field) over a boolean, on both faces', () => { + const FLAG_VIEW: ListViewGroupQuerySource = { + grouping: { fields: [{ field: 'business_unit' }] }, + columns: [ + { field: 'approved', summary: 'count_true' }, + { field: 'id', summary: { type: 'count_false', field: 'approved' } }, + { field: 'business_unit', summary: { type: 'count_empty', field: 'approved' } }, + ], + }; + const tally = (rows: readonly Row[], value: boolean | null) => rows.filter((r) => r.approved === value).length; + + it.each(TIERS)('%s: per group and over the whole set, a null cell counts as neither', async (tier) => { + const query = compileListViewGroupQuery(FLAG_VIEW); + expect(query.aggregations).toEqual([ + { function: 'count', alias: LIST_VIEW_GROUP_COUNT_ALIAS }, + { function: 'sum', field: 'approved', alias: 'sum_approved' }, + { function: 'count', field: 'approved', alias: 'count_approved' }, + ]); + const headers = await onTier(tier, () => records(OBJECT_CONTIGUOUS, query)); + for (const [unit] of UNITS) { + const row = headers.find((h) => h.business_unit === unit) as ListViewGroupHeaderRow; + const rows = CONTIGUOUS.filter((r) => r.business_unit === unit); + expect(deriveColumnSummary(row, 'count_true', 'approved'), `${tier}/${unit} true`).toBe(tally(rows, true)); + expect(deriveColumnSummary(row, { type: 'count_false', field: 'approved' }, 'id'), `${tier}/${unit} false`).toBe(tally(rows, false)); + expect(deriveColumnSummary(row, { type: 'count_empty', field: 'approved' }, 'business_unit')).toBe(tally(rows, null)); + } + // `harbour_office` is one row, ordinal 1: false. Its true count is 0, not blank. + const harbour = headers.find((h) => h.business_unit === 'harbour_office') as ListViewGroupHeaderRow; + expect(deriveColumnSummary(harbour, 'count_true', 'approved')).toBe(0); + + // The footer's whole-set question: the same nodes with no `groupBy`. + const whole = await onTier(tier, () => records(OBJECT_CONTIGUOUS, { aggregations: query.aggregations })); + expect(whole).toHaveLength(1); + const [set] = whole as ListViewGroupHeaderRow[]; + expect(deriveColumnSummary(set, 'count_true', 'approved')).toBe(tally(CONTIGUOUS, true)); + expect(deriveColumnSummary(set, 'count_false', 'approved')).toBe(tally(CONTIGUOUS, false)); + expect(tally(CONTIGUOUS, true) + tally(CONTIGUOUS, false) + tally(CONTIGUOUS, null)).toBe(TOTAL_ROWS); + }); +}); + // ─── §8 Rows inside a group are the existing paged find ────────────────────── describe('§8 `limit` / `offset` slice INSIDE one group', () => { diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index bbe4f7cde88..362baf65595 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -89,6 +89,7 @@ "BulkActionResultSchema (const)", "CHART_AGGREGATE_COMPARISON_SUFFIX (const)", "COLUMN_SUMMARY_AGGREGATION (const)", + "COLUMN_SUMMARY_FIELD_TYPES (const)", "COMPILED_PAGE_KINDS (const)", "CalendarConfig (type)", "CalendarConfigSchema (const)", @@ -125,6 +126,7 @@ "ColumnSummaryAggregation (type)", "ColumnSummaryConfig (type)", "ColumnSummaryConfigSchema (const)", + "ColumnSummaryDerivedSource (type)", "ColumnSummarySchema (const)", "ColumnSummaryValue (type)", "CompileListViewGroupQueryOptions (interface)", @@ -556,6 +558,7 @@ "checkPageRequiresKind (function)", "checkPageSourceCompleteness (function)", "columnSummaryAlias (function)", + "columnSummaryNodeFunctions (function)", "compileListViewGroupQuery (function)", "compileListViewGroupRowsQuery (function)", "dashboardForm (const)", @@ -578,6 +581,7 @@ "hasReservedComponentNamespace (function)", "isActionParamValuePresent (function)", "isAggregatedViewContainer (function)", + "isColumnSummaryCompatibleWithFieldType (function)", "isExpressionBindableTextKey (function)", "isKnownComponentType (function)", "isRecordContextBlockType (function)", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index 2de045b1e01..9e99d1d29e7 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -86,6 +86,7 @@ "BulkActionResultSchema": "src/ui/bulk-action.zod.ts#BulkActionResultSchema (const)", "CHART_AGGREGATE_COMPARISON_SUFFIX": "src/ui/chart-aggregate.ts#CHART_AGGREGATE_COMPARISON_SUFFIX (const)", "COLUMN_SUMMARY_AGGREGATION": "src/ui/view-grouping-query.ts#COLUMN_SUMMARY_AGGREGATION (const)", + "COLUMN_SUMMARY_FIELD_TYPES": "src/ui/view-grouping-query.ts#COLUMN_SUMMARY_FIELD_TYPES (const)", "COMPILED_PAGE_KINDS": "src/ui/page.zod.ts#COMPILED_PAGE_KINDS (const)", "CalendarConfig": "src/ui/view.zod.ts#CalendarConfig (type)", "CalendarConfigSchema": "src/ui/view.zod.ts#CalendarConfigSchema (const)", @@ -122,6 +123,7 @@ "ColumnSummaryAggregation": "src/ui/view-grouping-query.ts#ColumnSummaryAggregation (type)", "ColumnSummaryConfig": "src/ui/view.zod.ts#ColumnSummaryConfig (type)", "ColumnSummaryConfigSchema": "src/ui/view.zod.ts#ColumnSummaryConfigSchema (const)", + "ColumnSummaryDerivedSource": "src/ui/view-grouping-query.ts#ColumnSummaryDerivedSource (type)", "ColumnSummarySchema": "src/ui/view.zod.ts#ColumnSummarySchema (const)", "ColumnSummaryValue": "src/ui/view-grouping-query.ts#ColumnSummaryValue (type)", "CompileListViewGroupQueryOptions": "src/ui/view-grouping-query.ts#CompileListViewGroupQueryOptions (interface)", @@ -539,6 +541,7 @@ "checkPageRequiresKind": "src/ui/page.zod.ts#checkPageRequiresKind (function)", "checkPageSourceCompleteness": "src/ui/page.zod.ts#checkPageSourceCompleteness (function)", "columnSummaryAlias": "src/ui/view-grouping-query.ts#columnSummaryAlias (function)", + "columnSummaryNodeFunctions": "src/ui/view-grouping-query.ts#columnSummaryNodeFunctions (function)", "compileListViewGroupQuery": "src/ui/view-grouping-query.ts#compileListViewGroupQuery (function)", "compileListViewGroupRowsQuery": "src/ui/view-grouping-query.ts#compileListViewGroupRowsQuery (function)", "dashboardForm": "src/ui/dashboard.form.ts#dashboardForm (const)", @@ -561,6 +564,7 @@ "hasReservedComponentNamespace": "src/ui/component-type-vocabulary.ts#hasReservedComponentNamespace (function)", "isActionParamValuePresent": "src/ui/action-params.zod.ts#isActionParamValuePresent (function)", "isAggregatedViewContainer": "src/ui/view.zod.ts#isAggregatedViewContainer (function)", + "isColumnSummaryCompatibleWithFieldType": "src/ui/view-grouping-query.ts#isColumnSummaryCompatibleWithFieldType (function)", "isExpressionBindableTextKey": "src/ui/expression-bindable-text-keys.zod.ts#isExpressionBindableTextKey (function)", "isKnownComponentType": "src/ui/component-type-vocabulary.ts#isKnownComponentType (function)", "isRecordContextBlockType": "src/ui/react-blocks.ts#isRecordContextBlockType (function)", diff --git a/packages/spec/src/ui/view-grouping-query.test.ts b/packages/spec/src/ui/view-grouping-query.test.ts index b888caff051..eac79934fda 100644 --- a/packages/spec/src/ui/view-grouping-query.test.ts +++ b/packages/spec/src/ui/view-grouping-query.test.ts @@ -18,15 +18,19 @@ import { ListViewSchema } from './view.zod'; import type { ColumnSummary } from './view.zod'; import type { FilterCondition } from '../data/filter.zod'; import type { EngineAggregateOptions } from '../data/data-engine.zod'; +import { BOOLEAN_VALUE_TYPES } from '../data/field-value.zod'; import { COLUMN_SUMMARY_AGGREGATION, + COLUMN_SUMMARY_FIELD_TYPES, LIST_VIEW_GROUP_COUNT_ALIAS, ListViewGroupQueryError, UNMAPPED_COLUMN_SUMMARIES, columnSummaryAlias, + columnSummaryNodeFunctions, compileListViewGroupQuery, compileListViewGroupRowsQuery, deriveColumnSummary, + isColumnSummaryCompatibleWithFieldType, listViewGroupKeyPredicate, listViewGroupOrderColumn, } from './view-grouping-query'; @@ -442,10 +446,102 @@ describe('count_filled / count_empty / percent_filled / percent_empty — ONE CO }); }); +// ─── The boolean yes / no counts (#35702) ───────────────────────────────────── + +describe('count_true / count_false — SUM(field) and COUNT(field) over a boolean, derived on the header row', () => { + interface FlagRow { id: string; business_unit: string; approved: boolean | null } + // Per unit: 3 true, 2 false, 1 null in `north`; all null in `south`; 0 true in `east`. + const FLAG_ROWS: FlagRow[] = [ + ...[true, true, true, false, false, null].map((approved, i) => ({ id: `n${i}`, business_unit: 'north', approved })), + ...[null, null].map((approved, i) => ({ id: `s${i}`, business_unit: 'south', approved })), + ...[false, false, false].map((approved, i) => ({ id: `e${i}`, business_unit: 'east', approved })), + ]; + const FLAG_VIEW = { + grouping: { fields: [{ field: 'business_unit' }] }, + columns: [ + { field: 'approved', summary: 'count_true' as const }, + { field: 'id', summary: { type: 'count_false' as const, field: 'approved' } }, + { field: 'approved', summary: 'count_empty' as const }, + ], + }; + + it('compile to one `sum_` node and the shared `count_` node, deduplicated', () => { + expect(compileListViewGroupQuery(FLAG_VIEW).aggregations).toEqual([ + { function: 'count', alias: 'count' }, + { function: 'sum', field: 'approved', alias: 'sum_approved' }, + { function: 'count', field: 'approved', alias: 'count_approved' }, + ]); + }); + + it('a null cell is neither true nor false: true + false = filled, and the empty count holds the nulls', () => { + const headers = reduceHeaderQuery(FLAG_ROWS as unknown as Row[], compileListViewGroupQuery(FLAG_VIEW)); + const byUnit = (unit: string) => headers.find((h) => h.business_unit === unit)!; + const read = (unit: string) => ({ + yes: deriveColumnSummary(byUnit(unit), 'count_true', 'approved'), + no: deriveColumnSummary(byUnit(unit), { type: 'count_false', field: 'approved' }, 'id'), + empty: deriveColumnSummary(byUnit(unit), 'count_empty', 'approved'), + filled: deriveColumnSummary(byUnit(unit), 'count_filled', 'approved'), + }); + expect(read('north')).toEqual({ yes: 3, no: 2, empty: 1, filled: 5 }); + expect(read('south')).toEqual({ yes: 0, no: 0, empty: 2, filled: 0 }); + expect(read('east')).toEqual({ yes: 0, no: 3, empty: 0, filled: 3 }); + }); + + it('a SUM that answered no value reads 0 true; a missing column reads undefined, never a guess', () => { + const noValue: ListViewGroupHeaderRow = { business_unit: 'x', count: 2, sum_approved: null, count_approved: 0 }; + expect(deriveColumnSummary(noValue, 'count_true', 'approved')).toBe(0); + expect(deriveColumnSummary(noValue, 'count_false', 'approved')).toBe(0); + const noSum: ListViewGroupHeaderRow = { business_unit: 'x', count: 2, count_approved: 2 }; + expect(deriveColumnSummary(noSum, 'count_true', 'approved')).toBeUndefined(); + expect(deriveColumnSummary(noSum, 'count_false', 'approved')).toBeUndefined(); + const noCount: ListViewGroupHeaderRow = { business_unit: 'x', count: 2, sum_approved: 1 }; + expect(deriveColumnSummary(noCount, 'count_true', 'approved')).toBe(1); + expect(deriveColumnSummary(noCount, 'count_false', 'approved')).toBeUndefined(); + // A driver may answer a sum as its string spelling. + expect(deriveColumnSummary({ count: 3, sum_approved: '2', count_approved: '3' }, 'count_false', 'approved')).toBe(1); + expectTypeOf(deriveColumnSummary(noValue, 'count_true', 'approved')).toEqualTypeOf(); + }); + + it('applies to the boolean class only — over a number SUM(field) is a total, not a count', () => { + expect(COLUMN_SUMMARY_FIELD_TYPES).toEqual({ count_true: ['boolean', 'toggle'], count_false: ['boolean', 'toggle'] }); + expect([...COLUMN_SUMMARY_FIELD_TYPES.count_true!].sort()).toEqual([...BOOLEAN_VALUE_TYPES].sort()); + for (const member of ['count_true', 'count_false']) { + expect(isColumnSummaryCompatibleWithFieldType(member, 'boolean')).toBe(true); + expect(isColumnSummaryCompatibleWithFieldType(member, 'toggle')).toBe(true); + for (const type of ['number', 'currency', 'text', 'select', 'date', 'lookup']) { + expect(isColumnSummaryCompatibleWithFieldType(member, type), `${member} × ${type}`).toBe(false); + } + } + // A member the table does not restrict is judged by its nodes alone. + expect(isColumnSummaryCompatibleWithFieldType('count_filled', 'text')).toBe(true); + expect(isColumnSummaryCompatibleWithFieldType('sum', 'number')).toBe(true); + // Fail-closed on shape; an inherited key is no member. + expect(isColumnSummaryCompatibleWithFieldType(['count_true'] as unknown as string, 'number')).toBe(false); + expect(isColumnSummaryCompatibleWithFieldType('toString', 'number')).toBe(true); + }); + + it('columnSummaryNodeFunctions reads every row: the aggregate function, the derived nodes, nothing for none', () => { + expect(columnSummaryNodeFunctions(COLUMN_SUMMARY_AGGREGATION.sum)).toEqual(['sum']); + expect(columnSummaryNodeFunctions(COLUMN_SUMMARY_AGGREGATION.count_unique)).toEqual(['count_distinct']); + expect(columnSummaryNodeFunctions(COLUMN_SUMMARY_AGGREGATION.count_empty)).toEqual(['count']); + expect(columnSummaryNodeFunctions(COLUMN_SUMMARY_AGGREGATION.count_false)).toEqual(['sum', 'count']); + expect(columnSummaryNodeFunctions(COLUMN_SUMMARY_AGGREGATION.none)).toEqual([]); + }); + + it('a boolean field named like its sum column collides loudly', () => { + const err = refusal(() => compileListViewGroupQuery({ + grouping: { fields: [{ field: 'sum_approved' }] }, + columns: [{ field: 'approved', summary: 'count_false' }], + })); + expect(err.reason).toBe('alias_collision'); + expect(err.path).toEqual(['columns', 0, 'summary']); + }); +}); + // ─── The mapping table ─────────────────────────────────────────────────────── describe('COLUMN_SUMMARY_AGGREGATION — one vocabulary, not two', () => { - it('maps every member: six onto AggregationFunction, four by derivation from count, none as nothing', () => { + it('maps every member: six onto AggregationFunction, six by derivation, none as nothing', () => { expect(COLUMN_SUMMARY_AGGREGATION).toEqual({ none: { kind: 'none' }, count: { kind: 'aggregate', function: 'count', fieldless: true }, @@ -454,11 +550,17 @@ describe('COLUMN_SUMMARY_AGGREGATION — one vocabulary, not two', () => { avg: { kind: 'aggregate', function: 'avg', fieldless: false }, min: { kind: 'aggregate', function: 'min', fieldless: false }, max: { kind: 'aggregate', function: 'max', fieldless: false }, - count_filled: { kind: 'derived', from: 'count', fieldless: false }, - count_empty: { kind: 'derived', from: 'count', fieldless: false }, - percent_filled: { kind: 'derived', from: 'count', fieldless: false }, - percent_empty: { kind: 'derived', from: 'count', fieldless: false }, + count_filled: { kind: 'derived', from: 'count', reads: ['count'], fieldless: false }, + count_empty: { kind: 'derived', from: 'count', reads: ['count'], fieldless: false }, + percent_filled: { kind: 'derived', from: 'count', reads: ['count'], fieldless: false }, + percent_empty: { kind: 'derived', from: 'count', reads: ['count'], fieldless: false }, + count_true: { kind: 'derived', from: 'sum', reads: ['sum'], fieldless: false }, + count_false: { kind: 'derived', from: 'sum', reads: ['sum', 'count'], fieldless: false }, }); + // `from` is the first node a derived row reads, on every derived row. + for (const mapping of Object.values(COLUMN_SUMMARY_AGGREGATION)) { + if (mapping.kind === 'derived') expect(mapping.reads[0]).toBe(mapping.from); + } expect(UNMAPPED_COLUMN_SUMMARIES).toEqual([]); expect(Object.values(COLUMN_SUMMARY_AGGREGATION).every((m) => m.kind !== 'unmapped')).toBe(true); }); diff --git a/packages/spec/src/ui/view-grouping-query.ts b/packages/spec/src/ui/view-grouping-query.ts index 7e312ac65a2..2570c84ef05 100644 --- a/packages/spec/src/ui/view-grouping-query.ts +++ b/packages/spec/src/ui/view-grouping-query.ts @@ -61,6 +61,10 @@ * ONE column per summarised field, `count_` — `COUNT(field)`, the * non-null count — from which all four are DERIVED on the header row by * {@link deriveColumnSummary} (see the mapping table). + * * for `count_true` ONE column per summarised field, `sum_` — + * `SUM(field)`, the true count of a boolean column — and for + * `count_false` that column and `count_` beside it; both members + * are DERIVED from them by {@link deriveColumnSummary}. * * A summary alias that would land on a grouped field's own column * (`sum_amount` while grouping by a field named `sum_amount`) is refused, not @@ -80,6 +84,21 @@ * | `count_empty` | the same node | derived: `count − count_` | * | `percent_filled` | the same node | derived: `count_ / count` (0 when `count` is 0) | * | `percent_empty` | the same node | derived: `1 − percent_filled` | + * | `count_true` | `{ function: 'sum', field }` | derived: `sum_` — `SUM(field)`, the true count (`0` when it answers no value) | + * | `count_false` | that node and `{ function: 'count', field }` | derived: `count_ − sum_` — the non-null cells that are not true | + * + * `count_true` / `count_false` (#35702) are the boolean column's yes / no + * counts, on the fork-i ground above: no new `AggregationFunction`, two + * nodes the vocabulary already has. Booleans aggregate as NUMBERS on every + * backend (ruling #11152, `aggregation-conformance`'s `sum(flag)` row + * enrolled on six of them), so `SUM(field)` is the count of true cells; a + * null cell is in neither count — it is `count_empty`'s — so + * `count_true + count_false = count_filled`. The pair applies to the boolean + * class only ({@link COLUMN_SUMMARY_FIELD_TYPES}): over a number the same + * `SUM(field)` is a total, not a count, so the authoring leg refuses the + * member on any other field type. This module reads no field types, so the + * refusal is the consumer's that has the catalogue, exactly as for the + * aggregate × field-type pairs. * * The seat ruling on fork (i) (contract review on the card, 2026-09-04): the * four `*_filled` / `*_empty` members map by DERIVATION from two exact @@ -106,7 +125,8 @@ * answers one row per LEAF combination. An outer level's header is derived * from the leaf rows sharing its prefix: `count`, `sum`, `min`, `max` and * the `count_` column (hence `count_filled` / `count_empty`, and the - * two percents recomputed from the folded counts) fold exactly; `avg` and + * two percents recomputed from the folded counts, and `count_true` / + * `count_false` from the folded `sum_`) fold exactly; `avg` and * `count_distinct` do NOT — an average of averages weights the groups, not * the rows, and the same value can be distinct in several leaves at once, so * per-leaf distinct counts over-count the union. When an outer level must @@ -200,6 +220,7 @@ import type { FilterCondition } from '../data/filter.zod'; import type { AggregationFunction, AggregationNode } from '../data/query.zod'; import type { EngineAggregateOptions, EngineQueryOptions } from '../data/data-engine.zod'; +import type { FieldType } from '../data/field.zod'; import type { ColumnSummary, ColumnSummaryConfig, GroupingConfig, ListColumn, ListView } from './view.zod'; /** @@ -214,16 +235,30 @@ export const LIST_VIEW_GROUP_COUNT_ALIAS = 'count'; * * * `aggregate` — a node with this `function`; `fieldless` says whether the * node names the summarised field (`COUNT(*)` does not). - * * `derived` — a `count` node over the summarised field (`COUNT(field)`, - * the non-null count, column `count_`), from which the member is - * computed on the header row by {@link deriveColumnSummary}. + * * `derived` — nodes over the summarised field, from which the member is + * computed on the header row by {@link deriveColumnSummary}. `reads` + * lists every node's function, in order; `from` is its first. The + * `*_filled` / `*_empty` members read one `count` node (`COUNT(field)`, + * the non-null count, column `count_`); `count_true` reads one + * `sum` node (`SUM(field)`, column `sum_`); `count_false` reads + * that `sum` node and the `count` node. * * `none` — the member means "no summary"; no node. * * `unmapped` — no counterpart in the vocabulary; the compiler refuses it * loudly (`NOT_IMPLEMENTED` / 501). No member is in this state today. */ +/** The aggregation functions a derived column summary reads its nodes with. */ +export type ColumnSummaryDerivedSource = Extract; + export type ColumnSummaryAggregation = | { readonly kind: 'aggregate'; readonly function: AggregationFunction; readonly fieldless: boolean } - | { readonly kind: 'derived'; readonly from: 'count'; readonly fieldless: false } + | { + readonly kind: 'derived'; + /** The first of {@link reads}. */ + readonly from: ColumnSummaryDerivedSource; + /** Every node the derivation reads over the summarised field, `from` first. */ + readonly reads: readonly [ColumnSummaryDerivedSource, ...ColumnSummaryDerivedSource[]]; + readonly fieldless: false; + } | { readonly kind: 'none' } | { readonly kind: 'unmapped' }; @@ -240,12 +275,60 @@ export const COLUMN_SUMMARY_AGGREGATION: Readonly>> = Object.freeze({ + count_true: BOOLEAN_SUMMARY_FIELD_TYPES, + count_false: BOOLEAN_SUMMARY_FIELD_TYPES, +}); + +/** + * May the column summary `member` be declared over a field of `fieldType`, + * as far as {@link COLUMN_SUMMARY_FIELD_TYPES} says? `true` for a member the + * table does not restrict (its aggregation nodes are judged on their own + * table). Fail-closed on shape: a non-string answers `false`. + */ +export function isColumnSummaryCompatibleWithFieldType(member: string, fieldType: string): boolean { + if (typeof member !== 'string' || typeof fieldType !== 'string') return false; + if (!Object.prototype.hasOwnProperty.call(COLUMN_SUMMARY_FIELD_TYPES, member)) return true; + const row: readonly string[] | undefined = COLUMN_SUMMARY_FIELD_TYPES[member as ColumnSummary]; + return row === undefined || row.includes(fieldType); +} + /** * The `ColumnSummary` members with no `AggregationFunction` counterpart — the * exact list the compiler refuses (fork i on #14556), derived from the table @@ -506,25 +589,26 @@ function summaryAggregationNodes( const mapping = columnSummaryMapping(member, path, `columns[${index}] (field "${field}")`); if (mapping.kind === 'none') return; - const fn: AggregationFunction = mapping.kind === 'derived' ? mapping.from : mapping.function; const aggregatedField = mapping.fieldless ? undefined : field; - const alias = columnSummaryAlias(fn, aggregatedField); - // The collision check comes FIRST: a grouped field named `count` would - // share its column with the group count, whether or not a summary is - // declared, and `compileListViewGroupQuery` refuses that up front — this - // ordering keeps the two answers identical for a `count` summary too. - if (grouped.has(alias)) { - throw new ListViewGroupQueryError( - 'alias_collision', - path, - `Column summary "${member}" on columns[${index}] would land under "${alias}", which is also a ` - + 'grouped field\'s own column on the header row — one column cannot carry both the group key ' - + 'and the summary. Rename the field or drop one of the two declarations.', - ); - } - if (alias === LIST_VIEW_GROUP_COUNT_ALIAS) return; // the group count column already carries it - if (!nodes.has(alias)) { - nodes.set(alias, { function: fn, field: aggregatedField, alias }); + for (const fn of columnSummaryNodeFunctions(mapping)) { + const alias = columnSummaryAlias(fn, aggregatedField); + // The collision check comes FIRST: a grouped field named `count` would + // share its column with the group count, whether or not a summary is + // declared, and `compileListViewGroupQuery` refuses that up front — this + // ordering keeps the two answers identical for a `count` summary too. + if (grouped.has(alias)) { + throw new ListViewGroupQueryError( + 'alias_collision', + path, + `Column summary "${member}" on columns[${index}] would land under "${alias}", which is also a ` + + 'grouped field\'s own column on the header row — one column cannot carry both the group key ' + + 'and the summary. Rename the field or drop one of the two declarations.', + ); + } + if (alias === LIST_VIEW_GROUP_COUNT_ALIAS) continue; // the group count column already carries it + if (!nodes.has(alias)) { + nodes.set(alias, { function: fn, field: aggregatedField, alias }); + } } }); @@ -549,7 +633,8 @@ type ColumnSummaryMemberValue = M extends 'none' ? never : M extends ColumnSu * `null` (the aggregate answered no value) and `undefined` (no column / `none`): * * * `count`, `count_unique`, `sum`, `avg`, `count_filled`, `count_empty`, - * `percent_filled`, `percent_empty` — a `number`; + * `percent_filled`, `percent_empty`, `count_true`, `count_false` — a + * `number`; * * `min`, `max` — `unknown`: the aggregated field's stored value, as the * header row carries it (text for a date-family field, a number for a * numeric one), never converted; @@ -609,6 +694,10 @@ function columnSummaryMapping( * * `percent_filled` = `count_ / count` — a ratio in `0..1`, and `0` * when `count` is `0` (no division) * * `percent_empty` = `1 − percent_filled` — so an empty group reads `1` + * * `count_true` = `sum_` (`SUM(field)` over a boolean), and `0` + * when the sum answered no value (no non-null cell to add) + * * `count_false` = `count_ − sum_` — the non-null cells + * that are not true; a null cell is neither true nor false * * `undefined` when the row carries no column for the summary (the header * query was compiled without it) and for `none`; `null` is what the @@ -646,6 +735,16 @@ export function deriveColumnSummary( // `max` the field's stored value: either way, the row's own value. return row[columnSummaryAlias(mapping.function, mapping.fieldless ? undefined : aggregatedField)]; } + if (member === 'count_true' || member === 'count_false') { + const sum = row[columnSummaryAlias('sum', aggregatedField)]; + if (sum === undefined) return undefined; + // `SUM` over no non-null cell answers no value: there is no true cell. + const trues = sum === null ? 0 : Number(sum); + if (member === 'count_true') return trues; + const nonNull = row[columnSummaryAlias('count', aggregatedField)]; + if (nonNull === undefined || nonNull === null) return undefined; + return Number(nonNull) - trues; + } const raw = row[columnSummaryAlias(mapping.from, aggregatedField)]; if (raw === undefined || raw === null) return undefined; const filled = Number(raw); diff --git a/packages/spec/src/ui/view.test.ts b/packages/spec/src/ui/view.test.ts index 5c700ab44c6..2691c4101ff 100644 --- a/packages/spec/src/ui/view.test.ts +++ b/packages/spec/src/ui/view.test.ts @@ -2165,7 +2165,7 @@ describe('ColumnSummarySchema', () => { it('should accept all summary functions', () => { const functions = [ 'none', 'count', 'count_empty', 'count_filled', 'count_unique', - 'percent_empty', 'percent_filled', 'sum', 'avg', 'min', 'max', + 'percent_empty', 'percent_filled', 'count_true', 'count_false', 'sum', 'avg', 'min', 'max', ] as const; functions.forEach(fn => { diff --git a/packages/spec/src/ui/view.zod.ts b/packages/spec/src/ui/view.zod.ts index 60651f684ff..a9596f125b1 100644 --- a/packages/spec/src/ui/view.zod.ts +++ b/packages/spec/src/ui/view.zod.ts @@ -1330,6 +1330,15 @@ export type ViewFilterElementParsed = z.infer; * on every face — the stored value is `null` (`aggregation-conformance`); * the footer's client-side reading, which also treats `''` and `[]` as * empty, is objectui's to converge under "one vocabulary". + * * `count_true` / `count_false` — the yes / no counts of a BOOLEAN column + * (`boolean`, `toggle`; `COLUMN_SUMMARY_FIELD_TYPES` in + * `view-grouping-query.ts`) — map by DERIVATION too, on the same fork-i + * ground: booleans aggregate as numbers on every backend (ruling #11152, + * `aggregation-conformance`'s `sum(flag)`), so `count_true` = `SUM(field)` + * and `count_false` = `COUNT(field) − SUM(field)`. A null cell is neither + * — it is `count_empty`'s — so `count_true + count_false = count_filled`. + * They are refused over any other field type: a `SUM(field)` over a + * number is a total, not a count of true values. * * ⛔ Adding a member here without deciding its row in * `COLUMN_SUMMARY_AGGREGATION` is a type error by construction, so the table @@ -1345,6 +1354,8 @@ export const ColumnSummarySchema = lazySchema(() => z.enum([ 'count_unique', 'percent_empty', 'percent_filled', + 'count_true', + 'count_false', 'sum', 'avg', 'min', @@ -1358,6 +1369,8 @@ export const ColumnSummarySchema = lazySchema(() => z.enum([ + 'count_filled, count_empty, percent_filled, percent_empty derive from one COUNT(field) node (the ' + 'non-null count) and the group count — count_filled = COUNT(field), count_empty = count − COUNT(field), ' + 'percent_filled = COUNT(field) / count (0 when count is 0), percent_empty = 1 − percent_filled. ' + + 'count_true and count_false are a boolean column\'s yes and no counts, boolean fields only — ' + + 'count_true = SUM(field), count_false = COUNT(field) − SUM(field); a null cell is neither. ' + 'Server-side "empty" is null on every face; the footer\'s client-side reading of empty strings and ' + 'empty arrays as empty is the renderer\'s to converge', )); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 0e5533d0853..0d2ef86dd91 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -691,6 +691,10 @@ const ar = { none: "لا شيء", menuPercentEmpty: "نسبة الفارغ", menuPercentFilled: "نسبة المعبأ", + countTrue: "نعم", + countFalse: "لا", + menuCountTrue: "عدد «نعم»", + menuCountFalse: "عدد «لا»", }, toolbar: { densityMode: "الكثافة", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 524e145960f..373d97e1a07 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -637,6 +637,10 @@ const de = { none: "Keine", menuPercentEmpty: "Anteil leer", menuPercentFilled: "Anteil gefüllt", + countTrue: "Ja", + countFalse: "Nein", + menuCountTrue: "Anzahl Ja", + menuCountFalse: "Anzahl Nein", }, toolbar: { densityMode: "Dichte", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index d849fe57db8..08ab2c12f5e 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -883,6 +883,10 @@ const en = { none: 'None', menuPercentEmpty: 'Percent empty', menuPercentFilled: 'Percent filled', + countTrue: 'Yes', + countFalse: 'No', + menuCountTrue: 'Count of Yes', + menuCountFalse: 'Count of No', }, toolbar: { densityMode: 'Density', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 0501f14d953..0ea0170ac89 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -654,6 +654,10 @@ const es = { none: "Ninguno", menuPercentEmpty: "Porcentaje vacío", menuPercentFilled: "Porcentaje con valor", + countTrue: "Sí", + countFalse: "No", + menuCountTrue: "Número de Sí", + menuCountFalse: "Número de No", }, toolbar: { densityMode: "Densidad", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d1c21ddfbfc..54581190b43 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -649,6 +649,10 @@ const fr = { none: "Aucun", menuPercentEmpty: "Pourcentage vide", menuPercentFilled: "Pourcentage rempli", + countTrue: "Oui", + countFalse: "Non", + menuCountTrue: "Nombre de Oui", + menuCountFalse: "Nombre de Non", }, toolbar: { densityMode: "Densité", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index afb9452b692..f2b2fbcfaf2 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -637,6 +637,10 @@ const ja = { none: "なし", menuPercentEmpty: "空の割合", menuPercentFilled: "入力済みの割合", + countTrue: "はい", + countFalse: "いいえ", + menuCountTrue: "「はい」の件数", + menuCountFalse: "「いいえ」の件数", }, toolbar: { densityMode: "密度", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 5f81fd6a437..5ae5b13ee07 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -637,6 +637,10 @@ const ko = { none: "없음", menuPercentEmpty: "빈 값 비율", menuPercentFilled: "입력된 값 비율", + countTrue: "예", + countFalse: "아니오", + menuCountTrue: '"예" 개수', + menuCountFalse: '"아니오" 개수', }, toolbar: { densityMode: "밀도", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 3b714b36e82..a562c8c22ff 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -649,6 +649,10 @@ const pt = { none: "Nenhum", menuPercentEmpty: "Percentual vazio", menuPercentFilled: "Percentual preenchido", + countTrue: "Sim", + countFalse: "Não", + menuCountTrue: "Quantidade de Sim", + menuCountFalse: "Quantidade de Não", }, toolbar: { densityMode: "Densidade", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 4affd4f3167..e7aff192f34 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -664,6 +664,10 @@ const ru = { none: "Нет", menuPercentEmpty: "Доля пустых", menuPercentFilled: "Доля заполненных", + countTrue: "Да", + countFalse: "Нет", + menuCountTrue: "Количество «Да»", + menuCountFalse: "Количество «Нет»", }, toolbar: { densityMode: "Плотность", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 20224f7d44e..558d964f293 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -617,6 +617,10 @@ const zh = { none: '无', menuPercentEmpty: '空值占比', menuPercentFilled: '非空占比', + countTrue: '是', + countFalse: '否', + menuCountTrue: '「是」的条数', + menuCountFalse: '「否」的条数', }, toolbar: { densityMode: '密度', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index abd7c3573ae..5239b09d1a6 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -617,6 +617,10 @@ const zhHant = { none: '無', menuPercentEmpty: '空值佔比', menuPercentFilled: '非空佔比', + countTrue: '是', + countFalse: '否', + menuCountTrue: '「是」的條數', + menuCountFalse: '「否」的條數', }, toolbar: { densityMode: '密度', diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index 1c72257fbbb..51eba2388b6 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -351,6 +351,8 @@ The accepted values are `ColumnSummarySchema` from `@objectstack/spec`: | `count_unique` | distinct non-empty values | raw values | | `percent_filled` | share of rows that are non-empty | raw values | | `percent_empty` | share of rows that are empty | raw values | +| `count_true` | rows whose boolean cell is true (Yes) — boolean / toggle only | raw values | +| `count_false` | rows whose boolean cell is false (No); an empty cell is neither — boolean / toggle only | raw values | | `sum` | total | numeric values | | `avg` | mean | numeric values | | `min` | smallest | numeric values | @@ -369,7 +371,8 @@ A host that also passes `onColumnSummaryPick(field, summary)` (wire it only for a reader who may change the view) turns each cell into a menu of the calculations the column's field type allows — `sum`/`avg` on numbers and amounts, `min`/`max` on numbers and dates (named Earliest and -Latest on a date), the count family on any field, the current one ticked and +Latest on a date), Count of Yes / Count of No first on a boolean, the count +family on any field, the current one ticked and None last. `summaryPickFields` limits the menu to the columns the host can save (the console passes the columns the view itself declares); the other cells draw their figure only. The grid draws a pick at once; the host saves it as the diff --git a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx index dd2286c4843..9027b7b646f 100644 --- a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx @@ -53,9 +53,16 @@ describe('offeredColumnSummaries (objectstack#35702)', () => { expect(isTemporalSummaryField({ type: 'date' })).toBe(true); expect(isTemporalSummaryField({ type: 'number' })).toBe(false); }); - it.each(['boolean', 'toggle'])('offers a %s no sum, average or extremes', (type) => { + it.each(['boolean', 'toggle'])('offers a %s its yes / no counts first, and no sum, average or extremes', (type) => { expect(offeredColumnSummaries({ type }).filter((s) => ['sum', 'avg', 'min', 'max'].includes(s))).toEqual([]); - expect(offeredColumnSummaries({ type })).toContain('count_filled'); + expect(offeredColumnSummaries({ type })).toEqual([ + 'count_true', 'count_false', 'count_unique', 'count_filled', 'count_empty', 'percent_filled', 'percent_empty', + ]); + }); + it.each(['number', 'currency', 'text', 'select', 'date', 'lookup'])('never offers the yes / no counts on a %s', (type) => { + const offered = offeredColumnSummaries({ type }); + expect(offered).not.toContain('count_true'); + expect(offered).not.toContain('count_false'); }); it('offers an unknown field the counts it can draw, never count_unique', () => { expect(offeredColumnSummaries(undefined)).toEqual(['count_filled', 'count_empty', 'percent_filled', 'percent_empty']); @@ -64,14 +71,15 @@ describe('offeredColumnSummaries (objectstack#35702)', () => { const OBJECT = 'plan_line'; const ROWS = [ - { id: 'r1', name: 'Line 1', amount: 100, due: '2026-01-05' }, - { id: 'r2', name: 'Line 2', amount: 250, due: '2026-03-09' }, + { id: 'r1', name: 'Line 1', amount: 100, due: '2026-01-05', approved: true }, + { id: 'r2', name: 'Line 2', amount: 250, due: '2026-03-09', approved: false }, ]; const FIELDS = { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' }, amount: { type: 'number', label: 'Amount' }, due: { type: 'date', label: 'Due' }, + approved: { type: 'boolean', label: 'Approved' }, }; const dataSource = () => ({ @@ -148,6 +156,31 @@ describe('the resident footer row (objectstack#35702)', () => { await waitFor(() => expect(screen.getByTestId('summary-picker-amount')).not.toHaveTextContent('Sum')); }); + it('objectstack#35702 — a boolean column offers Count of Yes / Count of No first, and draws each', async () => { + const user = userEvent.setup(); + const onPick = vi.fn(); + renderGrid({ residentSummaryRow: true, onColumnSummaryPick: onPick }, [ + { field: 'name', label: 'Name' }, + { field: 'approved', label: 'Approved' }, + ]); + await screen.findByTestId('data-table-summary-row'); + await user.click(screen.getByTestId('summary-picker-approved')); + const menu = await screen.findByTestId('summary-menu-approved'); + const options = within(menu).getAllByTestId(/^summary-option-/).map((o) => o.getAttribute('data-testid')); + expect(options.slice(0, 2)).toEqual(['summary-option-count_true', 'summary-option-count_false']); + expect(within(menu).getByTestId('summary-option-count_true')).toHaveTextContent('Count of Yes'); + expect(within(menu).getByTestId('summary-option-count_false')).toHaveTextContent('Count of No'); + expect(within(menu).queryByTestId('summary-option-sum')).toBeNull(); + await user.click(within(menu).getByTestId('summary-option-count_true')); + expect(onPick).toHaveBeenLastCalledWith('approved', 'count_true'); + await waitFor(() => expect(screen.getByTestId('summary-picker-approved')).toHaveTextContent('Yes 1')); + + await user.click(screen.getByTestId('summary-picker-approved')); + await user.click(within(await screen.findByTestId('summary-menu-approved')).getByTestId('summary-option-count_false')); + expect(onPick).toHaveBeenLastCalledWith('approved', 'count_false'); + await waitFor(() => expect(screen.getByTestId('summary-picker-approved')).toHaveTextContent('No 1')); + }); + it('names a date column\'s extremes Earliest and Latest', async () => { const user = userEvent.setup(); renderGrid({ residentSummaryRow: true, onColumnSummaryPick: vi.fn() }); diff --git a/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx index e43662de4e7..230038c8eb5 100644 --- a/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx @@ -74,7 +74,7 @@ afterEach(() => { const OBJECT = 'plan_line'; const PAGE = 25; -type Row = { id: string; name: string; stage: string; amount: number; note: string | null; closed_at: string; qty: number; currency_code: string } & Record; +type Row = { id: string; name: string; stage: string; amount: number; note: string | null; closed_at: string; qty: number; currency_code: string; approved: boolean | null } & Record; /** * 300 rows; every fifth `note` is empty, every third row is `won`, and * `closed_at` is one day later per row, so the last row is the latest. @@ -90,6 +90,8 @@ const ROWS: Row[] = Array.from({ length: 300 }, (_, i) => ({ closed_at: new Date(Date.UTC(2025, 0, 1, 9, 30) + i * 86_400_000).toISOString(), qty: (i % 7) + 1, currency_code: i % 2 === 0 ? 'USD' : 'EUR', + // objectstack#35702 — a boolean: every fourth unset, then true / false alternating (75 / 75 / 150). + approved: i % 4 === 0 ? null : i % 2 === 0, })); const OBJECT_FIELDS = { @@ -391,6 +393,44 @@ describe('the footer reads the whole matched set when the grid shows one page of expect(footerText('note')).toBe(`Note: Empty: ${fmt(ROWS.length - notes.length)}`); }); + it('objectstack#35702 — a boolean\'s yes / no counts read the whole set; an unset cell is neither, it is empty', async () => { + const ds = makeDataSource(); + const count = (v: boolean | null) => ROWS.filter((r) => r.approved === v).length; + render(hostGrid(ds, { + rows: ROWS, + columns: [ + { field: 'name', label: 'Name' }, + { field: 'approved', label: 'Approved', summary: 'count_true' }, + { field: 'id', label: 'Id', summary: { type: 'count_false', field: 'approved' } }, + { field: 'stage', label: 'Stage', summary: { type: 'count_empty', field: 'approved' } }, + ], + })); + await waitFor(() => expect(footerText('approved')).toBe(`Approved: Yes: ${fmt(count(true))}`)); + expect(footerText('id')).toBe(`Id: No: ${fmt(count(false))}`); + expect(footerText('stage')).toBe(`Stage: Empty: ${fmt(count(null))}`); + expect(count(true) + count(false) + count(null)).toBe(ROWS.length); + // ONE `SUM(approved)` and ONE `COUNT(approved)` node, shared by the three columns. + expect(ds.queryGroupHeaders.mock.calls[0][1].aggregations).toEqual([ + { function: 'count', alias: 'count' }, + { function: 'sum', field: 'approved', alias: 'sum_approved' }, + { function: 'count', field: 'approved', alias: 'count_approved' }, + ]); + }); + + it('objectstack#35702 — with no whole-set answer, the yes / no counts are the page\'s, and say so', async () => { + const page = ROWS.slice(0, PAGE); + render(hostGrid(makeDataSource({ door: 'absent' }), { + rows: ROWS, + columns: [ + { field: 'name', label: 'Name' }, + { field: 'approved', label: 'Approved', summary: 'count_true' }, + { field: 'id', label: 'Id', summary: { type: 'count_false', field: 'approved' } }, + ], + })); + await waitFor(() => expect(footerText('approved')).toBe(`Approved: Yes (this page): ${page.filter((r) => r.approved === true).length}`)); + expect(footerText('id')).toBe(`Id: No (this page): ${page.filter((r) => r.approved === false).length}`); + }); + it('a currency column — the issue\'s own shape — formats the whole-set figure as its cells', async () => { const ds = makeDataSource(); render(hostGrid(ds, { diff --git a/ui/packages/plugin-grid/src/useColumnSummary.ts b/ui/packages/plugin-grid/src/useColumnSummary.ts index 029ba95ec79..444f8562961 100644 --- a/ui/packages/plugin-grid/src/useColumnSummary.ts +++ b/ui/packages/plugin-grid/src/useColumnSummary.ts @@ -9,7 +9,7 @@ import { useMemo } from 'react'; import type { ListColumn } from '@object-ui/types'; import type { ColumnSummary, ListViewGroupHeaderRow } from '@objectstack/spec/ui'; -import { deriveColumnSummary } from '@objectstack/spec/ui'; +import { deriveColumnSummary, isColumnSummaryCompatibleWithFieldType } from '@objectstack/spec/ui'; import type { CurrencyConfig } from '@objectstack/spec/data'; import { resolveFieldScale, isAggregateCompatibleWithFieldType } from '@objectstack/spec/data'; import { useLocalization, useDisplayLocale, resolveFieldCurrency, recordCurrencyField, createSafeTranslation } from '@object-ui/i18n'; @@ -79,6 +79,8 @@ const NON_NUMERIC_TYPES = new Set([ 'count_unique', 'percent_empty', 'percent_filled', + 'count_true', + 'count_false', ]); /** Aggregations whose result is a percentage (0-100), not a value in the column's unit. */ @@ -110,6 +112,9 @@ const TYPE_LABEL_KEYS: Record = { // which is why the two families deliberately share a word in every pack. percent_empty: 'grid.summary.percentEmpty', percent_filled: 'grid.summary.percentFilled', + // A boolean column's yes / no counts read as the cell's own words. + count_true: 'grid.summary.countTrue', + count_false: 'grid.summary.countFalse', sum: 'grid.summary.sum', avg: 'grid.summary.avg', min: 'grid.summary.min', @@ -145,6 +150,10 @@ const SUMMARY_DEFAULT_TRANSLATIONS: Record = { 'grid.summary.none': 'None', 'grid.summary.menuPercentEmpty': 'Percent empty', 'grid.summary.menuPercentFilled': 'Percent filled', + 'grid.summary.countTrue': 'Yes', + 'grid.summary.countFalse': 'No', + 'grid.summary.menuCountTrue': 'Count of Yes', + 'grid.summary.menuCountFalse': 'Count of No', }; export const useSummaryTranslation = createSafeTranslation( @@ -157,8 +166,11 @@ export const useSummaryTranslation = createSafeTranslation( * Each one the footer can draw for that type: an aggregate the spec allows on * the type (`isAggregateCompatibleWithFieldType`), and the count family on * any. ⛔ No `count`: the row's first cell already carries the record count. - * Booleans get the count family only, and a record-currency amount (whose sum - * the footer withholds) likewise. + * Booleans get their yes / no counts first, then the count family — never + * the arithmetic, which reads a boolean as 0 / 1 — and a record-currency + * amount (whose sum the footer withholds) gets the count family only. The + * yes / no counts are offered exactly where the spec's member table allows + * them (`isColumnSummaryCompatibleWithFieldType`). */ const MENU_AGGREGATES: ReadonlyArray = ['sum', 'avg', 'min', 'max']; /** The spec's boolean class (`BOOLEAN_AGGREGATE_FIELD_TYPES`): `toggle` is a boolean too. */ @@ -166,12 +178,14 @@ const BOOLEAN_FIELD_TYPES: ReadonlySet = new Set(['boolean', 'toggle']); const MENU_COUNTS: ReadonlyArray = [ 'count_unique', 'count_filled', 'count_empty', 'percent_filled', 'percent_empty', ]; +const MENU_BOOLEAN_COUNTS: ReadonlyArray = ['count_true', 'count_false']; export function offeredColumnSummaries( field: ({ type?: string } & NonNullable[0]>) | undefined, ): ColumnSummaryType[] { const type = field?.type; const numeric = !!type && !BOOLEAN_FIELD_TYPES.has(type) && !recordCurrencyField(field); return [ + ...(type ? MENU_BOOLEAN_COUNTS.filter((m) => isColumnSummaryCompatibleWithFieldType(m, type)) : []), ...(numeric ? MENU_AGGREGATES.filter((m) => isAggregateCompatibleWithFieldType(m, type!)) : []), ...MENU_COUNTS.filter((m) => m !== 'count_unique' || (!!type && isAggregateCompatibleWithFieldType('count_distinct', type))), ]; @@ -188,6 +202,8 @@ export function summaryMenuLabel(type: ColumnSummaryType, temporal: boolean, t: if (temporal && type === 'max') return t('grid.summary.latest'); if (type === 'percent_empty') return t('grid.summary.menuPercentEmpty'); if (type === 'percent_filled') return t('grid.summary.menuPercentFilled'); + if (type === 'count_true') return t('grid.summary.menuCountTrue'); + if (type === 'count_false') return t('grid.summary.menuCountFalse'); return type === 'none' ? t('grid.summary.none') : t(TYPE_LABEL_KEYS[type]); } @@ -320,6 +336,13 @@ function computeAggregation(type: string, rows: SummaryRow[], field: string): nu return (rows.filter((r) => !isEmptyValue(r[field])).length / total) * 100; case 'percent_empty': return (rows.filter((r) => isEmptyValue(r[field])).length / total) * 100; + // A boolean column's yes / no counts: only a real boolean is a value of + // the column (the cell's own reading), so a null cell is neither — it is + // `count_empty`'s, as on the server (`deriveColumnSummary`). + case 'count_true': + return rows.filter((r) => r[field] === true).length; + case 'count_false': + return rows.filter((r) => r[field] === false).length; default: return null; } diff --git a/ui/packages/plugin-grid/src/useWholeSetSummary.ts b/ui/packages/plugin-grid/src/useWholeSetSummary.ts index abc0c982ded..d7f83349e83 100644 --- a/ui/packages/plugin-grid/src/useWholeSetSummary.ts +++ b/ui/packages/plugin-grid/src/useWholeSetSummary.ts @@ -95,6 +95,7 @@ import { COLUMN_SUMMARY_AGGREGATION, LIST_VIEW_GROUP_COUNT_ALIAS, columnSummaryAlias, + columnSummaryNodeFunctions, type ColumnSummary, type ListViewGroupHeaderRow, } from '@objectstack/spec/ui'; @@ -140,12 +141,17 @@ export function wholeSetSummaryNodes( if (!mapping || mapping.kind === 'none' || mapping.kind === 'unmapped') continue; const field = typeof summary === 'string' ? column.field : (summary.field ?? column.field); if (typeof field !== 'string' || field === '') continue; - const fn = mapping.kind === 'derived' ? mapping.from : mapping.function; - if (requiredCurrencyGrouping(field, fn, objectFields) !== undefined) continue; + // Every node the member reads (a derived member may read two: the boolean + // `count_false` asks `SUM(field)` and `COUNT(field)`), off the spec's own + // reading of the row, so this question and the group header's agree. + const fns = columnSummaryNodeFunctions(mapping); + if (fns.some((fn) => requiredCurrencyGrouping(field, fn, objectFields) !== undefined)) continue; declared = true; const aggregated = mapping.fieldless ? undefined : field; - const alias = columnSummaryAlias(fn, aggregated); - if (!nodes.has(alias)) nodes.set(alias, { function: fn, ...(aggregated !== undefined ? { field: aggregated } : {}), alias }); + for (const fn of fns) { + const alias = columnSummaryAlias(fn, aggregated); + if (!nodes.has(alias)) nodes.set(alias, { function: fn, ...(aggregated !== undefined ? { field: aggregated } : {}), alias }); + } } return declared ? [...nodes.values()] : null; } diff --git a/ui/packages/types/src/__tests__/spec-subschema-parity.test.ts b/ui/packages/types/src/__tests__/spec-subschema-parity.test.ts index 9733b4ded9a..16769fd436a 100644 --- a/ui/packages/types/src/__tests__/spec-subschema-parity.test.ts +++ b/ui/packages/types/src/__tests__/spec-subschema-parity.test.ts @@ -256,7 +256,7 @@ describe('ListColumnSchema is the spec schema (the extension collapsed)', () => }); it('summary accepts every spec aggregation and the renderer object form', () => { - for (const agg of ['none', 'count', 'count_unique', 'percent_filled', 'sum', 'avg', 'min', 'max']) { + for (const agg of ['none', 'count', 'count_unique', 'percent_filled', 'count_true', 'count_false', 'sum', 'avg', 'min', 'max']) { expect(ListColumnSchema.shape.summary.safeParse(agg).success, `summary "${agg}"`).toBe(true); } expect(ListColumnSchema.shape.summary.safeParse({ type: 'sum', field: 'amount' }).success).toBe(true);