Skip to content

Commit 2d18ba8

Browse files
fix(ui): grouped grid and used-currency read treat a cut grouped answer as partial (#37317)
Fixes #37278 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在设了默认分页大小的部署上,按服务器分组的表格在分组数超过一页时,顶部多一行提示「更多分组未加载」,且不再报出偏少的记录总数;表单里币种字段的「可用」组在币种读取被截断时不再只列出部分已用币种,改为不列已用币种(所有币种仍在「全部」组里可选)。 - 为什么做:分组表头查询在被服务器截断时,上一张卡已把「截断」信号传给前端,但只有看板读了它;这次补上分组表格和币种读取两处,把同一族问题收口。 - 出错会怎样:最坏是分组表格多一行提示、批量栏不显示「全选 N 条」,或币种「可用」组少列已用币种;不会显示错误数字,可直接撤回。 - 要你做什么:无 ## What changes Both readers of `DataSource.queryGroupHeaders` that `#36870` left reading a cut answer as whole now read `hasMore`: - **Server-grouped grid** (`@object-ui/plugin-grid`): `useServerGroupHeaders` reports `partial` when any depth's answer says `hasMore`. The grid then draws one status line above the rows (`grid.grouping.moreGroupsNotLoaded`, "More groups were not loaded: this view has more groups than the server returns in one read, so only some are listed.", translated in all eleven locale packs (zh-Hant regenerated with `gen:zh-hant`) and in the grid's English fallback map), and `serverGroupTotalOf` tells no record total instead of summing the listed groups' counts. Listed groups keep their exact counts. A whole answer draws exactly as before. - **Used-currency read** (`@object-ui/components`): `readUsedCurrencyCodes` reads a partial answer as no codes, so the code field gets what a failed read gives it (home + rated + the record's own code under "available"; every code stays under "all"). This is the kanban lane statistic's shape (a cut answer is read as no answer), not a second marker. - **Nit N2** (`@object-ui/types`): `ListViewGroupHeaderAnswer`'s jsdoc warns that `hasMore` lives on the array and a copy drops it. The type is declared in `ui/packages/types/src/data.ts` (the claim named the import site in `data-objectstack`). - **Nit N1**: `content/docs/frontend/data-objectstack.mdx` says the answer can be partial and how to read the flag. Relation to `objectui#10881` ruling F: that ruling retired the `grid.grouping.partial*` keys, the marker over a grid that grouped one fetched page, whose every count was a page slice; this note is a separate key outside that namespace, because here every listed group's count is the server's exact count and only the group list is cut, so it says more groups were not loaded rather than marking the counts partial. Why a marker / no-answer and not a re-read, for both readers: measured at the public door, a grouped read cannot be completed by the caller. `EngineAggregateOptions` (the header query's contract) carries no `limit`, the grouped branch of `POST /data/:object/query` slices in memory and reads no `offset`, and an explicit `limit` over the maximum page size is refused with `400 MAX_RECORDS_EXCEEDED`. Completing the currency read would need a contract change to the header query; it is not cheap, so it is not done here. ## Tests <details><summary>Reach: both readers' query is cut at the public door (temporary probe, not committed)</summary> A throwaway test beside `packages/rest/src/data-query-read-limits.test.ts` (same harness: real `SqlDriver` on SQLite, the real `POST /api/v1/data/:object/query` route, five rows, five distinct `label` values) sent the header query exactly as `compileListViewGroupQuery` compiles it for both readers, with no `limit`. Tree: objectstack, base 08bf7d2. ``` PROBE query {"groupBy":["label"],"aggregations":[{"function":"count","alias":"count"}]} PROBE cut 200 {"n":2,"hasMore":true,"total":5} OS_DATA_DEFAULT_PAGE_SIZE=2 PROBE maxOnly 200 {"n":3,"hasMore":true} OS_DATA_MAX_PAGE_SIZE=3 alone PROBE whole 200 {"n":5,"hasMore":false} no limits PROBE explicit-limit-3 200 {"n":3,"hasMore":true} default 2, max 3, limit 3 PROBE explicit-limit-4-over-max 400 "MAX_RECORDS_EXCEEDED" default 2, max 3, limit 4 ``` Both readers send that query with no `limit` (`useServerGrouping.ts`, `usedCurrencyCodes.ts`), so both reach users on any deployment whose default page size is below the group count. The grid reaches users on the hosted plane's figure (maximum page size 5,000) for a grouping with more than 5,000 distinct values. The used-currency read groups an ISO 4217 code field (domain-checked on write, so at most one group per code plus the empty group, under 200): it reaches users only where a deployment sets a default page size below the number of codes in use. Both are fixed. </details> <details><summary>Pins, and the ablation that turns each red</summary> New pins, each driven by a double that answers the compiled header query the way the door does under a default page size (every group, sliced to the page, `hasMore` on the answer when the slice dropped one), each beside a control with a whole answer: - `serverGrouping-7189.test.tsx`, new top-level describe: a cut answer (page 3 of 5 groups) draws the partial note and the listed groups' exact counts; the control (page 100) draws five groups and no note; `useServerGroupHeaders` reports `partial` and `serverGroupTotalOf` tells no total over the cut answer, 186 over the whole one. - `form-used-currency-codes-27188.test.tsx`, new top-level describe: a cut answer (page 2 of 4 groups) hands down no used codes; the control (page 10) hands down `EUR, GBP, USD`; `readUsedCurrencyCodes` on a flagged and an unflagged answer. Run, at head `f652fe491`: ``` pnpm --dir ui exec vitest run --maxWorkers=2 packages/i18n/ THE_TWO_PIN_FILES Test Files 113 passed (113) Tests 2052 passed | 13 skipped (2065) ``` That run holds the whole i18n package, including `groupingPartialRetired-10881.test.ts`, `zh-hant-generated.test.ts` and the key-parity tests. The ablation below was measured at `cf697b4f9`; the rename at `f652fe491` changes only the key and test-id names it reads. Ablation (`scripts/ablation-replace.mjs`, anchor hit 1 -> 0 on disk, restored to the HEAD blob with `git diff HEAD` empty; the tests import the sources directly, no `dist/` in the path): ``` useServerGrouping.ts partial = headers.some(... hasMore === true) -> partial = false x says more groups were not loaded, over the groups it did get x folds no record total over a cut answer — and the whole total over a whole one Tests 2 failed | 12 passed (14) (both controls stay green) usedCurrencyCodes.ts the hasMore early return deleted x a cut answer hands down no used codes — never the groups it happened to list (expected [ 'EUR', 'USD' ] to be undefined) x readUsedCurrencyCodes reads a partial answer as no codes, a whole one as its codes Tests 2 failed (control stays green) ``` </details> ## Acceptance notes - The retired `grid.grouping.partial*` namespace stays empty: `groupingPartialRetired-10881.test.ts` is untouched and green. - A partial grid tells the bulk bar no total, so "Select all N" is not offered with a wrong N there; the listed groups and their rows work as before. - Completing either read would need the header query to carry a `limit` (a change to `EngineAggregateOptions`) and the grouped read to page; this PR does not go there. ## Verification Read first, by risk: `ui/packages/plugin-grid/src/useServerGrouping.ts` (the one `hasMore` read for the grid), `ui/packages/plugin-grid/src/objectGridGrouping.ts` (`serverGroupTotalOf`), `ui/packages/components/src/renderers/form/usedCurrencyCodes.ts` (`readUsedCurrencyCodes`). Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-grid/src/__tests__/serverGrouping-7189.test.tsx` — expect the three `objectstack#37278` cases green beside the existing ones. Readings at head `f652fe491`: type-check of `@object-ui/plugin-grid`, `@object-ui/components`, `@object-ui/i18n` all `Done` (`@object-ui/types` at `cf697b4f9`, unchanged since) (lock VERDICT command-exit 0); the run above 2052 passed. Local gate subset green (exit 0 each): `check:test-source-alias`, `check:nul-bytes`, `check:doc-authoring`, `check:doc-anchors`, `check:cross-package-test-inputs`, `check:docs-single-h1`, `check:doc-frontmatter`, `check:docs-redirects`, `check:docs-transcript-drift`, `check:type-check-coverage`, `check:undeclared-dep-imports`, the changeset gates, and `ui/scripts/check-i18n-call-site-keys.mjs`, `check-i18n-en-drift.mjs`, `check-i18n-dead-keys.mjs`. Declared narrowing: the rest of the derived families (48 of 73 by `dispatch-gates --ran`), the full plugin-grid / components suites and lint run in CI. --- _Generated by [Claude Code](https://claude.ai/code/session_012MmDsSBHy5paNUz6zke9Re)_ <!-- signed: repo:objectstack#6 · os-lizheng · session_012MmDsSBHy5paNUz6zke9Re --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent fd06b11 commit 2d18ba8

21 files changed

Lines changed: 250 additions & 15 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@object-ui/plugin-grid': patch
3+
'@object-ui/components': patch
4+
'@object-ui/i18n': patch
5+
'@object-ui/types': patch
6+
---
7+
8+
fix(ui): the grouped grid and the used-currency read treat a cut grouped answer as partial
9+
10+
Clause-②: no
11+
Metadata-protocol: none
12+
13+
On a deployment that sets a default page size (`OS_DATA_DEFAULT_PAGE_SIZE`, or `OS_DATA_MAX_PAGE_SIZE` alone), `POST /data/:object/query` cuts a grouped read that names no `limit` to that page size and answers `hasMore: true`; `queryGroupHeaders` hands it on as the answer's `hasMore`. Two readers read such an answer as every group:
14+
15+
- A grid grouped on the server listed only the groups the answer carried, with nothing saying more exist, and told the bulk bar a record total summed over those groups. It now draws one line above the rows, "More groups were not loaded: this view has more groups than the server returns in one read, so only some are listed." (translated in every locale pack, key `grid.grouping.moreGroupsNotLoaded`; not the `grid.grouping.partial*` page-slice marker retired by objectui#10881 ruling F: those counts were slices of a fetched page, these are the server's exact counts over a cut group list), and tells no total. The groups it lists keep their exact counts. A whole answer draws as before.
16+
- The form's used-currency read (the "available" group of a record-currency code field) took the codes of a cut answer as every code in use, so a code in use could sit under "all". A cut answer now hands down no used codes, as a failed read does: the field offers home + rated + the record's own code under "available", and every code under "all". A whole answer hands every used code down as before.
17+
18+
Neither reader can ask for the rest: the header query carries no `limit`, and the grouped read takes no `offset`.
19+
20+
`ListViewGroupHeaderAnswer`'s doc now warns that `hasMore` lives on the array, so a copy of the answer drops it.

‎content/docs/frontend/data-objectstack.mdx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,14 @@ adapter):
218218
- `onMutation?(listener)` - Subscribe to create/update/delete events
219219
- `queryGroupHeaders?(resource, query)` - Answer a grouped list view's group
220220
header query (`compileListViewGroupQuery`), one row per group with its true
221-
`count` — what a grouped grid groups by on the server (objectui#7189)
221+
`count` — what a grouped grid groups by on the server (objectui#7189). The
222+
answer can be PARTIAL: on a deployment with a default page size
223+
(`OS_DATA_DEFAULT_PAGE_SIZE`, or `OS_DATA_MAX_PAGE_SIZE` alone) the server
224+
cuts the groups to that page, and the answer then carries `hasMore: true`
225+
(`ListViewGroupHeaderAnswer`). A caller that reads the groups as the whole
226+
set — a total folded over them, an absent group read as empty — checks it
227+
first, and reads it off the answer itself: a copy (`[...rows]`, `.slice()`)
228+
drops the flag
222229

223230
`bulk`, `batchTransaction`, `onMutation` and `queryGroupHeaders` are
224231
**optional** members of `DataSource`: not every adapter implements them, so

‎ui/packages/components/src/renderers/form/__tests__/form-used-currency-codes-27188.test.tsx‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ import { render, cleanup, waitFor } from '@testing-library/react';
1818
import { ComponentRegistry } from '@object-ui/core';
1919
import { SchemaRendererContext } from '@object-ui/react';
2020
import '../../../renderers';
21+
// The renderers reach a dynamic `import('@object-ui/react-runtime')`; pay its
22+
// first load at collection, never inside a case's clocked window
23+
// (`check:test-source-alias`).
24+
import '@object-ui/react-runtime';
2125
import {
2226
currencyCodeFieldNames,
2327
readUsedCurrencyCodes,
@@ -148,3 +152,54 @@ describe('form renderer — used currency codes on the code field', () => {
148152
expect(seen.currency_code?.field?.usedCurrencyCodes).toBeUndefined();
149153
});
150154
});
155+
156+
/**
157+
* objectstack#37278 — a grouped read cut to a deployment's default page size.
158+
* The double answers the used-codes header query the way the platform's
159+
* `POST /data/:object/query` does under `OS_DATA_DEFAULT_PAGE_SIZE`: every
160+
* group of the stored rows, sliced to the page, with `hasMore` on the answer
161+
* when the slice dropped a group (as `queryGroupHeaders` hands it on). The
162+
* control is the same store under a page that holds every group.
163+
*/
164+
describe('form renderer — a partial used-codes answer (objectstack#37278)', () => {
165+
const STORED = ['USD', 'EUR', 'GBP', 'USD', null];
166+
167+
function cappedDataSource(defaultPageSize: number) {
168+
const queryGroupHeaders = vi.fn(async (_object: string, query: { groupBy?: string[] }) => {
169+
const field = query.groupBy?.[0] as string;
170+
const counts = new Map<unknown, number>();
171+
for (const code of STORED) counts.set(code, (counts.get(code) ?? 0) + 1);
172+
const groups = [...counts.entries()].map(([code, count]) => ({ [field]: code, count }));
173+
const answer = groups.slice(0, defaultPageSize) as Array<Record<string, unknown>> & { hasMore?: boolean };
174+
if (answer.length < groups.length) answer.hasMore = true;
175+
return answer;
176+
});
177+
return { find: async () => ({ data: [] }), queryGroupHeaders };
178+
}
179+
180+
it('a cut answer hands down no used codes — never the groups it happened to list', async () => {
181+
const ds = cappedDataSource(2);
182+
renderForm(ds, 'deal');
183+
await waitFor(() => expect(ds.queryGroupHeaders).toHaveBeenCalledTimes(1));
184+
const answer = await ds.queryGroupHeaders.mock.results[0].value;
185+
// The cut is real: two of four groups, flagged.
186+
expect(answer).toHaveLength(2);
187+
expect(answer.hasMore).toBe(true);
188+
await new Promise((r) => setTimeout(r, 0));
189+
expect(seen.currency_code?.field?.usedCurrencyCodes).toBeUndefined();
190+
});
191+
192+
it('control: a page that holds every group hands every used code down', async () => {
193+
const ds = cappedDataSource(10);
194+
renderForm(ds, 'deal');
195+
await waitFor(() => expect(seen.currency_code?.field?.usedCurrencyCodes).toEqual(['EUR', 'GBP', 'USD']));
196+
const answer = await ds.queryGroupHeaders.mock.results[0].value;
197+
expect(answer.hasMore).toBeUndefined();
198+
});
199+
200+
it('readUsedCurrencyCodes reads a partial answer as no codes, a whole one as its codes', () => {
201+
const rows = [{ currency_code: 'USD', count: 2 }, { currency_code: 'EUR', count: 1 }];
202+
expect(readUsedCurrencyCodes(rows, 'currency_code')).toEqual(['EUR', 'USD']);
203+
expect(readUsedCurrencyCodes(Object.assign([...rows], { hasMore: true }), 'currency_code')).toEqual([]);
204+
});
205+
});

‎ui/packages/components/src/renderers/form/usedCurrencyCodes.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,17 @@
2121
* query, asks nothing and hands nothing down: the code field then offers home
2222
* + rated + the record's own code. `aggregate` is not asked instead — it may
2323
* degrade to fetching every row, which is no price for a dropdown.
24+
*
25+
* A PARTIAL answer is read as no answer (objectstack#37278). The header query
26+
* names no `limit`, so a deployment with a default page size cuts the group
27+
* rows to that page and answers `hasMore`, which `queryGroupHeaders` hands on
28+
* as the answer's `hasMore` (`ListViewGroupHeaderAnswer`). A cut answer is
29+
* not every stored code, and the "available" group would read it as if it
30+
* were: a code in use would sit in "all" as one nobody used. The header query
31+
* cannot ask for the rest — it carries no `limit`, and the platform's grouped
32+
* read reads no `offset` — so the field gets what a failed read gives it,
33+
* home + rated + the record's own code, as the kanban lane statistic draws no
34+
* figure from a cut answer. Every code stays offered in "all".
2435
*/
2536

2637
import * as React from "react"
@@ -47,8 +58,12 @@ export function usedCurrencyCodesQuery(codeField: string) {
4758
return compileListViewGroupQuery({ grouping: { fields: [{ field: codeField }] } } as never, { depth: 1 })
4859
}
4960

50-
/** The distinct, domain-valid codes of `codeField` in a header answer, sorted. */
61+
/**
62+
* The distinct, domain-valid codes of `codeField` in a header answer, sorted —
63+
* none for a partial answer (`hasMore`), which is not every stored code.
64+
*/
5165
export function readUsedCurrencyCodes(rows: readonly Record<string, unknown>[] | undefined, codeField: string): string[] {
66+
if ((rows as { hasMore?: unknown } | undefined)?.hasMore === true) return []
5267
const codes = new Set<string>()
5368
for (const row of rows ?? []) {
5469
const code = row?.[codeField]
@@ -66,8 +81,8 @@ export function withUsedCurrencyCodes<T>(def: T, codes: readonly string[] | unde
6681
/**
6782
* Code field name → the codes its object's records hold. Asked once per
6883
* (object, code fields) — keyed on content, so a host that rebuilds its field
69-
* list every render does not re-ask. A failed read leaves that field's entry
70-
* out; the picker still works.
84+
* list every render does not re-ask. A failed read, or a partial one, leaves
85+
* that field's entry out; the picker still works.
7186
*/
7287
export function useUsedCurrencyCodes(
7388
dataSource: DataSource | null | undefined,

‎ui/packages/i18n/src/locales/ar.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,7 @@ const ar = {
739739
needsWholeRows:
740740
"يتطلب التجميع جميع السجلات، لكن هذه الشبكة تلقّت صفحة واحدة منها فقط، لذا لا يمكن عدّ المجموعات. مرّر جميع السجلات، أو دع الشبكة تجلبها من مصدر بيانات يطبّق queryGroupHeaders.",
741741
draftOnly: "لم يتم التجميع حسب {{fields}}: هذا الحقل موجود في المسودة فقط حتى تقوم بالنشر.",
742+
moreGroupsNotLoaded: "لم يتم تحميل مجموعات أخرى: يحتوي هذا العرض على مجموعات أكثر مما يعيده الخادم في قراءة واحدة، لذا تُعرض بعضها فقط.",
742743
},
743744
// objectui#4024 — column-footer aggregate prefixes, keyed by the spec's
744745
// `ColumnSummary` vocabulary. `pattern` owns the label/value join so this

‎ui/packages/i18n/src/locales/de.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,7 @@ const de = {
681681
needsWholeRows:
682682
"Die Gruppierung benötigt alle Datensätze, aber dieses Raster hat nur eine Seite davon erhalten, daher können die Gruppen nicht gezählt werden. Übergeben Sie alle Datensätze oder lassen Sie das Raster sie aus einer Datenquelle laden, die queryGroupHeaders implementiert.",
683683
draftOnly: "Nicht nach {{fields}} gruppiert: Das Feld existiert nur im Entwurf, bis Sie veröffentlichen.",
684+
moreGroupsNotLoaded: "Weitere Gruppen wurden nicht geladen: Diese Ansicht hat mehr Gruppen, als der Server in einem Lesevorgang zurückgibt, daher wird nur ein Teil angezeigt.",
684685
},
685686
// objectui#4024 — column-footer aggregate prefixes, keyed by the spec's
686687
// `ColumnSummary` vocabulary. `pattern` owns the label/value join so this

‎ui/packages/i18n/src/locales/en.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,7 @@ const en = {
924924
needsWholeRows:
925925
'Grouping needs every record, but this grid was handed one page of them, so the groups cannot be counted. Hand in every record, or let the grid fetch them from a data source that implements queryGroupHeaders.',
926926
draftOnly: 'Not grouped by {{fields}}: it exists only in the draft until you publish.',
927+
moreGroupsNotLoaded: 'More groups were not loaded: this view has more groups than the server returns in one read, so only some are listed.',
927928
},
928929
// Column-footer aggregate prefixes, keyed by the spec's `ColumnSummary`
929930
// vocabulary (objectui#4024). The footer already formatted its NUMBER

‎ui/packages/i18n/src/locales/es.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,7 @@ const es = {
699699
needsWholeRows:
700700
"La agrupación necesita todos los registros, pero esta cuadrícula recibió solo una página de ellos, por lo que no se pueden contar los grupos. Entregue todos los registros o deje que la cuadrícula los obtenga de un origen de datos que implemente queryGroupHeaders.",
701701
draftOnly: "No agrupado por {{fields}}: solo existe en el borrador hasta que publique.",
702+
moreGroupsNotLoaded: "No se cargaron más grupos: esta vista tiene más grupos de los que el servidor devuelve en una lectura, así que solo se muestran algunos.",
702703
},
703704
// objectui#4024 — column-footer aggregate prefixes, keyed by the spec's
704705
// `ColumnSummary` vocabulary. `pattern` owns the label/value join so this

‎ui/packages/i18n/src/locales/fr.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,7 @@ const fr = {
694694
needsWholeRows:
695695
"Le regroupement a besoin de tous les enregistrements, mais cette grille n'en a reçu qu'une page : les groupes ne peuvent donc pas être comptés. Fournissez tous les enregistrements, ou laissez la grille les charger depuis une source de données qui implémente queryGroupHeaders.",
696696
draftOnly: "Non regroupé par {{fields}} : ce champ n'existe que dans le brouillon jusqu'à la publication.",
697+
moreGroupsNotLoaded: "D'autres groupes n'ont pas été chargés : cette vue compte plus de groupes que le serveur n'en renvoie en une lecture, seuls certains sont donc affichés.",
697698
},
698699
// objectui#4024 — column-footer aggregate prefixes, keyed by the spec's
699700
// `ColumnSummary` vocabulary. `pattern` owns the label/value join so this

‎ui/packages/i18n/src/locales/ja.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,7 @@ const ja = {
681681
needsWholeRows:
682682
"グループ化にはすべてのレコードが必要ですが、このグリッドにはその一部のページしか渡されていないため、グループの件数を数えられません。すべてのレコードを渡すか、queryGroupHeaders を実装したデータソースからグリッドに読み込ませてください。",
683683
draftOnly: "{{fields}} ではグループ化されていません:公開するまで下書きにのみ存在します。",
684+
moreGroupsNotLoaded: "一部のグループは読み込まれていません:このビューのグループ数はサーバーが 1 回の読み取りで返す数を超えているため、一部のみ表示しています。",
684685
},
685686
// objectui#4024 — column-footer aggregate prefixes, keyed by the spec's
686687
// `ColumnSummary` vocabulary. `pattern` owns the label/value join so this

0 commit comments

Comments
 (0)