Skip to content

Commit 0241df4

Browse files
fix(plugin-form): a line-items column over a formula takes the type its returnType declares (#34319)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9Nf3gqWSittou77go2LaJkT)_ Fixes #34286 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:明细(record:line_items / 主从表)里只写字段名的列,如果那个字段是公式(或汇总),列类型改按公式声明的 `returnType` 推导;货币公式现在打印 `$157,780.00` / `157,780` 这样的金额,而不是裸数字 `157780`。 - 为什么改:报价单、发票打印的明细里,货币公式列显示成未格式化的数字,而同一个值在记录详情页和普通货币列里是格式化的,客户看到的单据不一致。 - 风险与回滚:只改一个纯函数(列类型推导);没有 `returnType` 的公式、手写了 `type` 的列、普通货币字段都和以前一样。回滚就是撤销这一个 PR。 - 先看:`ui/packages/plugin-form/src/deriveMasterDetail.ts` 的 `columnValueType`(新)和它在 `hydrateColumns` 里的那一处调用。 - 两分钟验证:在 `ui/` 下跑 `pnpm exec vitest run packages/plugin-form/src/LineItemsPanel.childFieldHydration-12854.test.tsx`,预期 9 个用例全绿,其中 `#34286` 一组 4 个。 - 需要你做的:无,席位落地。 ## What changes `hydrateColumns` (and the internal `deriveColumn`, for symmetry) in `ui/packages/plugin-form/src/deriveMasterDetail.ts` now map a child field through a new private `columnValueType(d)` before `fieldTypeToColumnType`: - a `summary` that declares its currency (`summaryDeclaresCurrency`, already exported by `@object-ui/fields`, the formula cell's own test) → `currency`; - otherwise a `formula` / `summary` field's declared `returnType`, as declared; - with neither, the field's own `type`, so the column hydrates exactly as before (`text`); - every other field type is unchanged. This is the formula cell's reading (`FormulaCellRenderer` in `ui/packages/fields/src/index.tsx`), applied to the declaration alone: a column is typed before any value exists, so the cell's last arm (a JS number drawn as a number) has no counterpart, and nothing is inferred from the expression. No second return-type table: the declared value type is a field type, and the existing `fieldTypeToColumnType` maps it. Mappings: `currency` → `currency`; `number` → `number` (the formula's `scale` still carried by the computed branch); `date` → `date`; `boolean` → `select` with the two session-language option labels a boolean field gets (`optionsFor` now reads the value type); `text` → `text`. The spec `returnType` enum has no `percent`, so none is added. Unchanged: a column with an authored `type` is returned as written; the column stays computed and read-only (`isExpressionComputedField`); a hydrated `currency` column with an authored `scale` is still reported by `reportCurrencyColumnScale`; the column's currency is resolved where every currency column's is (`GridField` `columnCurrencies`, filled from the child field's own `currencyConfig` by `parentCurrencyFieldsOf`, which reads any field type). ## Tests - `LineItemsPanel.childFieldHydration-12854.test.tsx`, new top-level `describe` in the existing harness: a name-only column over a `returnType: 'currency'` formula prints `$157,780.00` (USD tenant); `returnType: 'number'` prints `157,780`; CONTROL no `returnType` prints `157780` as before; CONTROL an authored `type: 'number'` wins. - `deriveMasterDetail.test.ts`, new top-level `describe`: currency / number (+ scale) / date / boolean (select + labels) / text mappings; a summary declaring a currency → `currency`; CONTROL a formula with no `returnType` and a summary with no currency stay `text`; CONTROL authored type wins and a plain currency field stays `currency`. ## Acceptance notes - `deriveColumns` never reaches a `formula` / `summary` field: the spec's `deriveInlineGridColumns` skips both as non-editable (`INLINE_GRID_NON_EDITABLE_TYPES`), so only the hydration path (`record:line_items` and the master-detail block's explicit `columns`, both through `hydrateColumns`) is live. `deriveColumn` takes the same rule so the two cannot drift. - A `number` column's read-only text is `toLocaleString` with no minimum fraction digits (`GridField` `cellDisplayText`), so a declared `scale` rounds the stored computed value but does not pad the display. Pre-existing for every number column; not changed here. - A hydrated `summary` column is not `computed` (a summary has no `expression`), so in an editable panel it renders an input, as it did as `text` before. Pre-existing. - The card's print door (`POST /api/v1/print/records`) renders the console page, whose `record:line_items` is `LineItemsPanel` → `hydrateColumns`; the panel pin reproduces the card's `157780` on main (ablation below). The print door itself was not driven end to end: NOT MEASURED. ## Verification All at head `c922a5f0` (branch merged with `origin/main` f9120b8; main moved no file this diff reads). - Symptom on main, measured: ablation A below is main's rule for a formula (its `type` mapped as is); the panel cell read `157780` where the pin expects `$157,780.00`, the card's text. - `pnpm exec vitest run packages/plugin-form/src/deriveMasterDetail.test.ts packages/plugin-form/src/LineItemsPanel.childFieldHydration-12854.test.tsx` (from `ui/`): `Test Files 2 passed (2)`, `Tests 61 passed (61)`. - Whole package, `pnpm exec vitest run packages/plugin-form/` under the verify lock: `VERDICT command-exit 0`, `Test Files 232 passed (232)`, `Tests 2582 passed | 1 skipped (2583)` (run on `0fbbd921`, before the main merge; the merge touched no `ui/packages/{plugin-form,fields,core,i18n}` file). - `pnpm --filter @object-ui/plugin-form type-check`: `VERDICT command-exit 0`. - `eslint` on the three touched source/test files: 0 errors (21 pre-existing `no-explicit-any` warnings). - Derived gates: `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` → 38 families, each run, all `exit 0`; `--ran` reconciliation: `38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN`. <details><summary>Ablations (node scripts/ablation-replace.mjs, mutation proven on disk, restored to the HEAD blob)</summary> - A: `return typeof d?.returnType === 'string' ? d.returnType : type;` → `return type;` (blob 06c9c5a → 6024bd16): 4 red, the currency and number pins in both files (`Expected $157,780.00, Received 157780`; `Expected /^157,780$/, Received 157780`). Restored: blob == HEAD, `git diff HEAD` empty. - B: delete `if (type === 'summary' && summaryDeclaresCurrency(d)) return 'currency';` (blob 06c9c5a → c9a3bbaa): 1 red, the summary pin. Restored: blob == HEAD, `git diff HEAD` empty. The tests import `./deriveMasterDetail` by relative path (source), so no dist leg applies. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. Dev session `session_01ADHkmPj7KdYMP7i9jmhi3m`, card thread for seat `domain:ui#2`. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmPj7KdYMP7i9jmhi3m)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8559ee1 commit 0241df4

4 files changed

Lines changed: 187 additions & 5 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/plugin-form': patch
3+
---
4+
5+
fix(plugin-form): a `record:line_items` or master-detail column that names only a `formula` field formats the value the way the formula declares it, so a `returnType: 'currency'` formula prints money instead of the bare number
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A line-items column written as `{ name: 'total_price' }` takes its type from the child field. For a `formula` field it used to map `type: 'formula'` itself, which falls through to a plain text column, so a formula declaring `returnType: 'currency'` printed `157780` on screen and on a printed quote, where its record page and a column authored with `type: 'currency'` print `157,780`.
11+
12+
The column now takes the type the formula's VALUE is declared as, read the way the formula's own table cell reads it: `returnType: 'currency'` gives a currency column, `number` a number column, `date` a date column, `boolean` a Yes / No select, `text` a text column. A `summary` field that declares its currency is a currency column. A formula with no `returnType`, and a summary that declares no currency, hydrate as before (text). The column stays computed and read-only, and a column that declares its own `type` keeps it. A currency column resolves its currency the way every currency column in the grid does.
13+
14+
Nothing to migrate: a column that worked around this with `type: 'currency'` keeps working, and the key can now be dropped.

‎ui/packages/plugin-form/src/LineItemsPanel.childFieldHydration-12854.test.tsx‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
import { describe, it, expect, vi, afterEach } from 'vitest';
3030
import * as React from 'react';
3131
import { render, screen, cleanup } from '@testing-library/react';
32-
import { I18nProvider } from '@object-ui/i18n';
32+
import { I18nProvider, LocalizationProvider } from '@object-ui/i18n';
3333
import { registerAllFields } from '@object-ui/fields';
3434
import { SchemaRendererProvider } from '@object-ui/react';
3535
import { LineItemsPanel } from './LineItemsPanel';
@@ -149,3 +149,66 @@ describe('record:line_items hydrates an untyped column from the child field (obj
149149
expect(((await screen.findAllByLabelText('note'))[0] as HTMLInputElement).value).toBe('rush');
150150
});
151151
});
152+
153+
/**
154+
* objectstack-ai/objectstack#34286 — an identity-only column over a `formula`
155+
* child field formats the way that formula reads everywhere else. A formula
156+
* declaring `returnType: 'currency'` used to hydrate as text and print the bare
157+
* number (`157780`) where a plain currency field printed money; the column now
158+
* takes the type the formula's value is declared as (`hydrateColumns`).
159+
*
160+
* The tenant currency is USD here so money and a grouped number read
161+
* differently: `$157,780.00` against `157,780`.
162+
*/
163+
describe('record:line_items types a formula column by its returnType (#34286)', () => {
164+
const QUOTE_LINE = {
165+
name: 'quote_line',
166+
fields: {
167+
quote: { type: 'master_detail', label: 'Quote', reference: 'quote' },
168+
quantity: { type: 'number', label: 'Quantity' },
169+
unit_price: { type: 'currency', label: 'Unit price' },
170+
total_price: { type: 'formula', label: 'Total price', expression: 'quantity * unit_price', returnType: 'currency' },
171+
total_units: { type: 'formula', label: 'Total units', expression: 'quantity * unit_price', returnType: 'number' },
172+
total_raw: { type: 'formula', label: 'Total raw', expression: 'quantity * unit_price' },
173+
},
174+
};
175+
const LINES = [{ id: 'q1', quantity: 20, unit_price: 7889, total_price: 157780, total_units: 157780, total_raw: 157780 }];
176+
177+
function mountQuote(columns: unknown[]) {
178+
const ds = {
179+
getObjectSchema: vi.fn().mockResolvedValue(QUOTE_LINE),
180+
find: vi.fn(async () => ({ data: LINES })),
181+
};
182+
return render(
183+
<LocalizationProvider value={{ locale: 'en', currency: 'USD' }}>
184+
<SchemaRendererProvider dataSource={ds as never}>
185+
<LineItemsPanel
186+
schema={{ childObject: 'quote_line', relationshipField: 'quote', parentObject: 'quote', parentId: 'qt1', columns } as never}
187+
/>
188+
</SchemaRendererProvider>
189+
</LocalizationProvider>,
190+
);
191+
}
192+
const cell = async (name: string) => (await screen.findAllByText((_t, el) => el?.getAttribute('data-computed') === name))[0];
193+
194+
it('a name-only column over a returnType currency formula prints money, not the bare number', async () => {
195+
mountQuote([{ name: 'quantity' }, { name: 'total_price' }]);
196+
expect(await screen.findByRole('columnheader', { name: 'Total price' })).toBeInTheDocument();
197+
expect(await cell('total_price')).toHaveTextContent('$157,780.00');
198+
});
199+
200+
it('a name-only column over a returnType number formula prints a grouped number', async () => {
201+
mountQuote([{ name: 'quantity' }, { name: 'total_units' }]);
202+
expect(await cell('total_units')).toHaveTextContent(/^157,780$/);
203+
});
204+
205+
it('CONTROL — a formula with no returnType prints as before (text)', async () => {
206+
mountQuote([{ name: 'quantity' }, { name: 'total_raw' }]);
207+
expect(await cell('total_raw')).toHaveTextContent(/^157780$/);
208+
});
209+
210+
it('CONTROL — an authored type still wins', async () => {
211+
mountQuote([{ name: 'quantity' }, { name: 'unit_price' }, { name: 'total_price', type: 'number', computed: true, expr: 'quantity * unit_price' }]);
212+
expect(await cell('total_price')).toHaveTextContent(/^157,780$/);
213+
});
214+
});

‎ui/packages/plugin-form/src/deriveMasterDetail.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,3 +500,69 @@ describe('deriveDetail takes the line-position field from the spec (deriveInline
500500
expect(sortFieldOf(child({ position: { type: 'number' }, sequence: { type: 'number' } }))).toBe('position');
501501
});
502502
});
503+
504+
/**
505+
* objectstack-ai/objectstack#34286 — a column over a `formula` / `summary`
506+
* child field takes the type its VALUE is declared as, read the way the
507+
* formula cell reads it (`FormulaCellRenderer`, objectui#11748 /
508+
* objectui#12111): a summary declaring its currency is money, else the
509+
* declared `returnType` decides, else the column hydrates as it always has.
510+
*/
511+
describe('hydrateColumns types a formula / summary column by its declared value type (#34286)', () => {
512+
const lineSchema = {
513+
name: 'quote_line',
514+
fields: {
515+
quote: { type: 'master_detail', reference: 'quote' },
516+
quantity: { type: 'number', label: 'Quantity' },
517+
unit_price: { type: 'currency', label: 'Unit price' },
518+
total_price: { type: 'formula', label: 'Total', expression: 'quantity * unit_price', returnType: 'currency' },
519+
weight: { type: 'formula', label: 'Weight', expression: 'quantity * 2', returnType: 'number', scale: 1 },
520+
ships_on: { type: 'formula', label: 'Ships on', expression: 'x', returnType: 'date' },
521+
is_large: { type: 'formula', label: 'Large', expression: 'x', returnType: 'boolean' },
522+
line_code: { type: 'formula', label: 'Code', expression: 'x', returnType: 'text' },
523+
undeclared: { type: 'formula', label: 'Undeclared', expression: 'quantity * unit_price' },
524+
tax_total: { type: 'summary', label: 'Tax', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } },
525+
line_count: { type: 'summary', label: 'Lines' },
526+
},
527+
};
528+
const hydrate = (names: string[]) =>
529+
Object.fromEntries(hydrateColumns(names.map((name) => ({ name })) as any, lineSchema, { booleanLabel }).map((c) => [c.name, c]));
530+
531+
it('a formula declaring returnType currency hydrates as a computed currency column', () => {
532+
expect(hydrate(['total_price']).total_price).toMatchObject({
533+
type: 'currency',
534+
label: 'Total',
535+
computed: true,
536+
expr: 'quantity * unit_price',
537+
required: false,
538+
});
539+
});
540+
541+
it('returnType number → number (its scale carried); date → date; boolean → select with the boolean labels; text → text', () => {
542+
const byName = hydrate(['weight', 'ships_on', 'is_large', 'line_code']);
543+
expect(byName.weight).toMatchObject({ type: 'number', computed: true, scale: 1 });
544+
expect(byName.ships_on.type).toBe('date');
545+
expect(byName.is_large).toMatchObject({
546+
type: 'select',
547+
options: [{ label: en.common.yes, value: 'true' }, { label: en.common.no, value: 'false' }],
548+
});
549+
expect(byName.line_code.type).toBe('text');
550+
});
551+
552+
it('a summary declaring its currency hydrates as currency', () => {
553+
expect(hydrate(['tax_total']).tax_total.type).toBe('currency');
554+
});
555+
556+
it('CONTROL — a formula with no returnType, and a summary declaring no currency, hydrate as before (text)', () => {
557+
const byName = hydrate(['undeclared', 'line_count']);
558+
expect(byName.undeclared).toMatchObject({ type: 'text', computed: true });
559+
expect(byName.line_count.type).toBe('text');
560+
});
561+
562+
it('CONTROL — an authored type wins over the returnType, and a plain currency field is unchanged', () => {
563+
const cols = hydrateColumns([{ name: 'total_price', type: 'number' }, { name: 'unit_price' }] as any, lineSchema, { booleanLabel });
564+
expect(cols[0].type).toBe('number');
565+
expect(cols[0].computed).toBeUndefined(); // an authored column is returned as written
566+
expect(cols[1].type).toBe('currency');
567+
});
568+
});

‎ui/packages/plugin-form/src/deriveMasterDetail.ts‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
deriveInlineGridSortField,
2222
deriveInlineRowFormFields,
2323
} from '@objectstack/spec/data';
24-
import type { BooleanValueLabel, GridColumn } from '@object-ui/fields';
24+
import { summaryDeclaresCurrency, type BooleanValueLabel, type GridColumn } from '@object-ui/fields';
2525
import { isExpressionComputedField } from '@object-ui/core';
2626

2727
/**
@@ -89,6 +89,42 @@ export function fieldTypeToColumnType(type: string | undefined): GridColumn['typ
8989
}
9090
}
9191

92+
/**
93+
* The type a child field's VALUE is drawn as, for {@link fieldTypeToColumnType}
94+
* (objectstack-ai/objectstack#34286).
95+
*
96+
* For every type but the two computed ones that is the field's own `type`. A
97+
* `formula` or `summary` field holds a value of ANOTHER type, and a column over
98+
* it used to map `type: 'formula'` itself, which no case names, so a formula
99+
* declaring `returnType: 'currency'` hydrated to a `text` column and printed
100+
* `157780` where its form face and its table cell print money.
101+
*
102+
* The reading is the formula cell's (`FormulaCellRenderer` in
103+
* `@object-ui/fields`, objectui#11748 / objectui#12111), applied to the
104+
* declaration alone because a column is typed before any value exists:
105+
* - a `summary` that declares its currency (`summaryDeclaresCurrency`, the
106+
* cell's own test, ADR-0144 D6 as amended) is money;
107+
* - otherwise the declared `returnType` decides, as declared;
108+
* - with neither, the field's own type, so the column hydrates as it always
109+
* has (`text`). The cell's last arm, a JS number drawn as a number, reads
110+
* the value, which a column does not have.
111+
* ⛔ Nothing is inferred from the expression or from its inputs, as in the cell.
112+
*
113+
* The declared value type is then a field type like any other, so
114+
* {@link fieldTypeToColumnType} maps it with no second table: `number` →
115+
* `number`, `currency` → `currency`, `date` → `date`, `boolean` → `select`
116+
* (with the two option labels {@link optionsFor} draws for a boolean field),
117+
* `text` → `text`. A currency column's code is resolved where every currency
118+
* column's is (`GridField`'s `columnCurrencies`, filled from the child field's
119+
* own `currencyConfig` by `parentCurrencyFieldsOf`, whatever the field's type).
120+
*/
121+
function columnValueType(d: any): string | undefined {
122+
const type = d?.type;
123+
if (type !== 'formula' && type !== 'summary') return type;
124+
if (type === 'summary' && summaryDeclaresCurrency(d)) return 'currency';
125+
return typeof d?.returnType === 'string' ? d.returnType : type;
126+
}
127+
92128
/** Image-flavoured field types whose picker should be restricted to images. */
93129
const IMAGE_TYPES = new Set(['image', 'avatar']);
94130

@@ -127,7 +163,8 @@ function applyFileColumnProps(col: GridColumn, d: any): void {
127163
* options in a language the session is not in.
128164
*/
129165
function optionsFor(def: any, booleanLabel: BooleanValueLabel): GridColumn['options'] | undefined {
130-
if (def?.type === 'boolean' || def?.type === 'toggle') {
166+
const valueType = columnValueType(def);
167+
if (valueType === 'boolean' || valueType === 'toggle') {
131168
return [
132169
{ label: booleanLabel(true), value: 'true' },
133170
{ label: booleanLabel(false), value: 'false' },
@@ -211,7 +248,7 @@ function deriveColumn(name: string, d: any, booleanLabel: BooleanValueLabel): Gr
211248
const col: GridColumn = {
212249
name,
213250
label: d?.label || name,
214-
type: fieldTypeToColumnType(d?.type),
251+
type: fieldTypeToColumnType(columnValueType(d)),
215252
required: !!d?.required,
216253
};
217254
const options = optionsFor(d, booleanLabel);
@@ -343,7 +380,9 @@ export function hydrateColumns(
343380
}
344381
const d = (fields as any)[col.name];
345382
if (!d) return col; // unknown field — leave as-is (grid falls back to text)
346-
const type = fieldTypeToColumnType(d?.type);
383+
// A formula / summary column takes the type its VALUE is declared as
384+
// (objectstack-ai/objectstack#34286), see `columnValueType`.
385+
const type = fieldTypeToColumnType(columnValueType(d));
347386
if (type === 'currency') reportCurrencyColumnScale(col, childSchema?.name, true);
348387
const next: GridColumn = { ...col, type };
349388
if (next.label == null) next.label = d?.label || col.name;

0 commit comments

Comments
 (0)