From 7afd1b685f5db43e33b961f6ed591c7b343892f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 04:47:58 +0000 Subject: [PATCH 01/11] fix(app-shell): the formula stamp asks inferFormulaReturn for the currency verdict Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- .../src/views/metadata-admin/celAuthoring.ts | 47 ++++++++++ ...eldInspector.returnTypeHeld-27485.test.tsx | 85 +++++++++++++++++-- .../inspectors/ObjectFieldInspector.tsx | 72 ++++++++++++++-- 3 files changed, 187 insertions(+), 17 deletions(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/celAuthoring.ts b/ui/packages/app-shell/src/views/metadata-admin/celAuthoring.ts index 98f36c19747..634b78aa6c1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/celAuthoring.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/celAuthoring.ts @@ -26,6 +26,7 @@ * 2. {@link introspectCelScope} — the valid field + scope identifiers (autocomplete). * 3. {@link testRunCelPredicate} — dry-run a predicate against a sample record. * 4. {@link inferCelValueType} — the value type a formula computes (objectui#1582 follow-up). + * 5. {@link inferFormulaReturnDeclaration} — whether that value is provably money, and in which currency. * * Progressive enhancement (mirrors `preview/capabilityLint.ts`): the engine is * loaded LAZILY via dynamic `import()` — it carries the CEL parser (cel-js), so @@ -223,6 +224,10 @@ interface FormulaModule { input: unknown, schema?: unknown, ) => 'number' | 'text' | 'boolean' | 'date' | 'unknown'; + inferFormulaReturn?: ( + input: unknown, + fields?: Readonly>, + ) => { returnType?: unknown; currencyConfig?: unknown }; ExpressionEngine?: { evaluate: ( expr: { dialect: string; source: string }, @@ -751,6 +756,48 @@ export async function inferCelValueType( } } +/** + * A formula field's declared result as the engine's `inferFormulaReturn` + * answers it: `returnType: 'currency'` (with the source amounts' currency in + * `currencyConfig`, absent for the tenant default) when the result is provably + * money, otherwise the plain inferred type, absent when none is proven. + */ +export interface FormulaReturnVerdict { + returnType?: string; + currencyConfig?: Record; +} + +/** + * Ask the engine's `inferFormulaReturn` whether `source` computes money, over + * the host object's declared field map (name → field definition, passed + * unchanged). The CEL type alone never says so — `record.amount * 0.1` types + * a plain `double` — so this is the one verdict that can PROVE a `currency` + * result, or withdraw one. + * + * Returns `null` — "no verdict", never "not money" — for empty input, or when + * the engine (or its `inferFormulaReturn` export) is unavailable or throws. + */ +export async function inferFormulaReturnDeclaration( + source: string, + fields: Readonly>, +): Promise { + if (!source || !source.trim()) return null; + try { + const mod = await loadFormula(); + if (!mod?.inferFormulaReturn) return null; + const res = mod.inferFormulaReturn(source, fields); + if (!res || typeof res !== 'object') return null; + const verdict: FormulaReturnVerdict = {}; + if (typeof res.returnType === 'string') verdict.returnType = res.returnType; + if (res.currencyConfig && typeof res.currencyConfig === 'object') { + verdict.currencyConfig = { ...(res.currencyConfig as Record) }; + } + return verdict; + } catch { + return null; + } +} + /* ── 2. Autocomplete scope ───────────────────────────────────────────── */ /** diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx index c4358bf578e..734240f660c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx @@ -19,7 +19,7 @@ import '@testing-library/jest-dom/vitest'; // The source loads these lazily; pay that load at collection, not inside a // case's clocked window. -import '@objectstack/formula'; +import { inferFormulaReturn } from '@objectstack/formula'; import '@objectstack/lint'; import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; @@ -47,9 +47,12 @@ afterEach(() => { /** The card's repro shape: a source left open on a bracket or an operator. */ const BROKEN = /[*+\-/&|=<>(]\s*$/; -function stubEngine() { +function stubEngine({ money = false }: { money?: boolean } = {}) { __setCelFormulaLoader(() => Promise.resolve({ + // objectstack#35631 — the money verdict is the engine's own, unstubbed; + // left out, the engine gives none (an engine without the export). + ...(money ? { inferFormulaReturn } : {}), validateExpression: (_role: string, input: unknown) => { const src = typeof input === 'string' ? input : String((input as { source?: string })?.source ?? ''); return BROKEN.test(src) @@ -73,10 +76,20 @@ function stubEngine() { ); } -function Harness({ onDef, returnType = 'number' }: { onDef: (def: Record) => void; returnType?: string }) { +function Harness({ + onDef, + returnType = 'number', + extra = {}, +}: { + onDef: (def: Record) => void; + returnType?: string; + extra?: Record; +}) { const [fields, setFields] = React.useState>>({ est_hours: { type: 'number' }, - f_total: { type: 'formula', label: 'F Total', expression: 'record.est_hours * 2', returnType }, + budget: { type: 'number' }, + amount: { type: 'currency', currencyConfig: USD }, + f_total: { type: 'formula', label: 'F Total', expression: 'record.est_hours * 2', returnType, ...extra }, }); React.useEffect(() => { onDef(fields.f_total); @@ -97,10 +110,12 @@ function Harness({ onDef, returnType = 'number' }: { onDef: (def: Record } = {}) { + stubEngine({ money }); const defs: Array> = []; - render( defs.push(def)} returnType={returnType} />); + render( defs.push(def)} returnType={returnType} extra={extra} />); const box = screen.getByText('Formula (CEL)').parentElement!.querySelector('[role="combobox"]') as HTMLTextAreaElement; const latest = () => defs.at(-1)!; return { box, latest }; @@ -176,7 +191,7 @@ describe('ObjectFieldInspector — a declared percent or currency survives an un expect(latest().returnType).toBe('currency'); }); - it('a `number` verdict keeps a declared `currency` too', async () => { + it('with no money verdict from the engine, a `number` verdict keeps a declared `currency` too', async () => { const { box, latest } = renderFormula('currency'); fireEvent.change(box, { target: { value: 'record.est_hours / 40' } }); await waitFor(() => expect(latest().expression).toBe('record.est_hours / 40'), { timeout: 3000 }); @@ -196,3 +211,57 @@ describe('ObjectFieldInspector — a declared percent or currency survives an un await waitFor(() => expect(latest().returnType).toBeUndefined(), { timeout: 3000 }); }); }); + +describe('ObjectFieldInspector — the money verdict proves or withdraws a declared currency (objectstack#35631)', () => { + const MONEY = 'record.amount * 0.1'; + const COUNT = 'record.est_hours * 2'; + const asCurrency = (money = true) => renderFormula('currency', { money, extra: { expression: MONEY, currencyConfig: USD } }); + + it("the card's repro: an edit from a money expression to a count drops `currency` and its `currencyConfig`", async () => { + const { box, latest } = asCurrency(); + fireEvent.change(box, { target: { value: COUNT } }); + await waitFor(() => expect(latest().returnType).toBe('number'), { timeout: 3000 }); + expect(latest().expression).toBe(COUNT); + expect('currencyConfig' in latest()).toBe(false); + }); + + it('an edit that still proves money keeps `currency` and the currency it proves', async () => { + const { box, latest } = asCurrency(); + fireEvent.change(box, { target: { value: 'record.amount * 0.2' } }); + await waitFor(() => expect(latest().expression).toBe('record.amount * 0.2'), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('currency'); + expect(latest().currencyConfig).toEqual(USD); + }); + + it('a `number` formula edited into money is stamped `currency`, with the source amount\'s currency', async () => { + const { box, latest } = renderFormula('number', { money: true }); + fireEvent.change(box, { target: { value: MONEY } }); + await waitFor(() => expect(latest().returnType).toBe('currency'), { timeout: 3000 }); + expect(latest().currencyConfig).toEqual(USD); + }); + + it('an unproven verdict (a field-over-field quotient) still keeps a declared `currency`', async () => { + const { box, latest } = asCurrency(); + fireEvent.change(box, { target: { value: 'record.est_hours / record.budget' } }); + await waitFor(() => expect(latest().expression).toBe('record.est_hours / record.budget'), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('currency'); + expect(latest().currencyConfig).toEqual(USD); + }); + + it('CONTROL — a declared `percent` is still kept under a `number` verdict', async () => { + const { box, latest } = renderFormula('percent', { money: true }); + fireEvent.change(box, { target: { value: COUNT } }); + await waitFor(() => expect(latest().expression).toBe(COUNT), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('percent'); + }); + + it('CONTROL — a verdict that proves text, boolean or date still stamps over a declared `currency`', async () => { + const { box, latest } = asCurrency(); + fireEvent.change(box, { target: { value: 'record.amount > 40' } }); + await waitFor(() => expect(latest().returnType).toBe('boolean'), { timeout: 3000 }); + expect('currencyConfig' in latest()).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx index f1651274c71..e57c8280560 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx @@ -146,7 +146,12 @@ import { } from '../previews/external-object.js'; import { CelPredicateField } from '../CelPredicateField.js'; import { useRequiredVisibleWhenFormulaReads, useRequiredVisibleWhenReferenceReads } from './requiredVisibleWhenReference.js'; -import type { CelLintIssue, CelValueType } from '../celAuthoring.js'; +import { + inferFormulaReturnDeclaration, + type CelLintIssue, + type CelValueType, + type FormulaReturnVerdict, +} from '../celAuthoring.js'; import { t, tFormat, type SupportedLocale } from '../i18n.js'; import { FilterConditionField } from './FilterConditionField.js'; import type { FilterCondition } from './datasetFilterCondition.js'; @@ -734,6 +739,15 @@ const FIELD_RULE_ROOTS = ['record', 'previous', 'parent']; */ const FORMULA_ROOTS = ['record']; +/** Do two flat records (a `currencyConfig`) hold the same keys and values? Absent equals absent only. */ +function sameFlatRecord(a: unknown, b: unknown): boolean { + if (a === undefined || b === undefined) return a === b; + if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false; + const ak = Object.keys(a as object); + const bk = Object.keys(b as object); + return ak.length === bk.length && ak.every((k) => (a as Record)[k] === (b as Record)[k]); +} + /** Read a `*When` predicate for editing: a bare string or an Expression envelope's `source`. */ function readPredicate(v: unknown): string { if (typeof v === 'string') return v; @@ -904,6 +918,13 @@ export function ObjectFieldInspector({ typed?: boolean; inferred?: CelValueType | null; }>({ field: '', source: '' }); + // objectstack#35631 — the money verdict (`inferFormulaReturn`) is read from + // the lazily loaded engine, so it lands after the render that settled the + // two editor verdicts; the stamp it completes is the LATEST render's, whose + // draft is the one a write must build on. + const stampFormulaTypeRef = React.useRef< + ((settled: typeof formulaVerdictRef.current, declared: FormulaReturnVerdict | null) => void) | null + >(null); /* ─── Who owns the API name (objectui#7615) ────────────────────────────── * @@ -1098,17 +1119,50 @@ export function ObjectFieldInspector({ const now = { ...(same ? was : { field: entry.name, source }), ...verdict }; formulaVerdictRef.current = now; if (!formulaEdited.current || now.errors === undefined || !now.typed || now.errors > 0) return; + // objectstack#35631 — the third verdict, money, comes from the engine's + // `inferFormulaReturn` over this object's declared fields. A newer verdict + // recorded meanwhile supersedes this one, and settles in its own turn. + void inferFormulaReturnDeclaration(source, siblingDefs).then((declared) => { + if (formulaVerdictRef.current !== now) return; + stampFormulaTypeRef.current?.(now, declared); + }); + }; + + /** objectstack#35631 — writes the settled verdicts as the formula's declared result (`returnType` + `currencyConfig`). */ + const stampFormulaType = (settled: typeof formulaVerdictRef.current, declared: FormulaReturnVerdict | null) => { + // The draft moved to another field or another source since: that one settles itself. + if (settled.field !== entry.name || settled.source !== readPredicate(def.expression ?? def.formula)) return; // Spec: `returnType` carries only a PROVEN concrete type — // an ambiguous (`unknown`) or unavailable verdict clears it. - const next = now.inferred && now.inferred !== 'unknown' ? now.inferred : undefined; - // objectstack#35047 — `percent` and `currency` are DECLARED: no CEL type - // proves a quotient is a percentage or a number is money, so a declared - // one survives every verdict that proves no OTHER type — `number`, and an - // unproven one alike (a field-over-field quotient types `dyn`). A verdict - // that proves text, boolean or date still stamps. - if ((def.returnType === 'percent' || def.returnType === 'currency') && (next === undefined || next === 'number')) return; - if (def.returnType !== next) patchDef({ returnType: next }); + const proven = settled.inferred && settled.inferred !== 'unknown' ? settled.inferred : undefined; + // objectstack#35047 — `percent` is DECLARED: no type proves a quotient is + // a percentage, so a declared one survives every verdict that proves no + // OTHER type — `number`, and an unproven one alike (a field-over-field + // quotient types `dyn`). A verdict that proves text, boolean or date still + // stamps. + if (def.returnType === 'percent' && (proven === undefined || proven === 'number')) return; + let next: string | undefined = proven; + if (declared?.returnType === 'currency') { + // Provably money: the engine names the result and its currency. + next = 'currency'; + } else if (def.returnType === 'currency' && (proven === undefined || proven === 'number')) { + // Only the money verdict's own `number` withdraws a declared `currency` + // (the edit stopped computing money). Unproven — a field-over-field + // quotient, two currencies meeting — or no engine verdict keeps it. + if (declared?.returnType !== 'number') return; + next = 'number'; + } + // The declaration is the PAIR (`inferFormulaReturn`): a `currency` result + // carries the proven currency, absent for the tenant default, and any + // other result carries none, so a withdrawn one loses its stale config. + const nextConfig = next === 'currency' ? declared?.currencyConfig : undefined; + if (def.returnType === next && sameFlatRecord(def.currencyConfig, nextConfig)) return; + const nextDef: Record = { ...def, returnType: next }; + if (nextConfig) nextDef.currencyConfig = nextConfig; + else delete nextDef.currencyConfig; + writeDef(nextDef); }; + stampFormulaTypeRef.current = stampFormulaType; /** * objectui#10202 — "use picklist". Naming a list sets `picklist` and removes From ddc555bd4bd1f2bcdb61f651f9133b86eb5da56e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 04:49:12 +0000 Subject: [PATCH 02/11] docs(spec): returnType prose names the currency stamp and its withdrawal Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- packages/spec/src/data/field.zod.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index bfbba20a35d..9ac60c6e31c 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2385,7 +2385,11 @@ export const FieldSchema = lazySchema(() => { * expression references at read time: "taken from the source field" happens * at AUTHORING, where `@objectstack/formula`'s `inferFormulaReturn` proves the * result is money and answers the source's currency for the stamp to copy. - * The value itself is a bare number, as a currency field's is. + * The value itself is a bare number, as a currency field's is. Authoring + * stamps `currency`, with the currency the source amounts are in, when that + * verdict proves money, and withdraws a declared `currency` — for `number`, + * with no `currencyConfig` — when an edit leaves it answering `number`: the + * expression no longer computes money. * * `percent` (#35047): the result is a ratio, read exactly as a `percent` * field reads its stored value — one convention, never a second one. The @@ -2399,11 +2403,11 @@ export const FieldSchema = lazySchema(() => { * under every verdict that proves no other type — where it would stamp * `number`, and where the type is unproven (a field-over-field quotient such * as `record.spent / record.budget` types `dyn`), which would otherwise - * clear it. A declared `currency` is kept the same way. A verdict that - * proves `text`, `boolean` or `date` still stamps. + * clear it. A declared `currency` is kept under an unproven verdict the + * same way. A verdict that proves `text`, `boolean` or `date` still stamps. */ returnType: z.enum(['number', 'text', 'boolean', 'date', 'currency', 'percent']).optional() - .describe('Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression\'s inferred type and leaves it absent when none is proven; `currency` and `percent` are declared by the author, and a verdict that proves no other type (`number`, or none) keeps them. `currency`: an amount of money, in the currency the formula\'s own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face.'), + .describe('Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression\'s inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula\'s own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face.'), summaryOperations: strictObject({ surface: 'this roll-up summary', history: FIELD_HISTORY, From 4ea7e78cb29c055a5f01d775ad40b468f86bfe95 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 04:57:16 +0000 Subject: [PATCH 03/11] chore(changeset): formula currency verdict Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- .changeset/35631-formula-currency-verdict.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .changeset/35631-formula-currency-verdict.md diff --git a/.changeset/35631-formula-currency-verdict.md b/.changeset/35631-formula-currency-verdict.md new file mode 100644 index 00000000000..6ac9f651a1d --- /dev/null +++ b/.changeset/35631-formula-currency-verdict.md @@ -0,0 +1,20 @@ +--- +'@object-ui/app-shell': patch +'@objectstack/spec': patch +--- + +fix(app-shell): Studio's formula inspector asks whether the formula still computes money before it keeps a `currency` result type + +Clause-②: no +Metadata-protocol: none + +When an author edited a formula field in Studio, the inspector re-stamped `returnType` from the expression's inferred CEL type, and kept a declared `currency` under every `number` or unproven verdict, because that type never says "money". So a formula edited from an amount (`record.amount * 0.1`) into a count (`record.est_hours * 2`) kept `returnType: 'currency'` and its `currencyConfig`, and its value was still shown as an amount. + +The stamp now also asks `@objectstack/formula`'s `inferFormulaReturn`, over the object's declared fields, whether the edited expression computes money: + +- Provably money: `returnType` is stamped `currency`, with the currency the source amounts are in as the formula's `currencyConfig` (absent for the tenant default currency). This holds for a formula that was `number` too. +- An edit it answers `number` for withdraws a declared `currency`: `returnType` becomes `number` and the `currencyConfig` is removed. +- An unproven verdict (a field-over-field quotient, two currencies meeting) keeps a declared `currency`, as before, and so does an engine that does not offer `inferFormulaReturn`. +- A declared `percent` is unchanged: it survives a `number` or unproven verdict. A verdict that proves `text`, `boolean` or `date` still stamps, and now also removes a stale `currencyConfig`. + +The stamp still runs only after the author edits the expression; selecting a field writes nothing. The `returnType` description in `@objectstack/spec` now says the same: `currency` is stamped when the expression provably computes money and withdrawn for `number` when an edit leaves it a plain number. From 23762acd4871821527382244178acdf9ed8f4d74 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:37:33 +0000 Subject: [PATCH 04/11] test(app-shell): type the inferFormulaReturn stub to the loader seam Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- .../ObjectFieldInspector.returnTypeHeld-27485.test.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx index 734240f660c..b07f75926ee 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx @@ -52,7 +52,12 @@ function stubEngine({ money = false }: { money?: boolean } = {}) { Promise.resolve({ // objectstack#35631 — the money verdict is the engine's own, unstubbed; // left out, the engine gives none (an engine without the export). - ...(money ? { inferFormulaReturn } : {}), + ...(money + ? { + inferFormulaReturn: (input: unknown, fields?: Readonly>) => + inferFormulaReturn(input as Parameters[0], fields as Parameters[1]), + } + : {}), validateExpression: (_role: string, input: unknown) => { const src = typeof input === 'string' ? input : String((input as { source?: string })?.source ?? ''); return BROKEN.test(src) From 0f9e503f3f2eee7b004cec0358d30863fb255ff6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:39:26 +0000 Subject: [PATCH 05/11] docs(spec): regenerate references for the returnType prose Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- content/docs/references/data/field.mdx | 2 +- content/docs/references/data/object.mdx | 4 ++-- content/docs/references/system/migration.mdx | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 94f592352d8..1397c16b864 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -98,7 +98,7 @@ const result = CurrencyConfigSchema.parse(data); | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `currency` and `percent` are declared by the author, and a verdict that proves no other type (`number`, or none) keeps them. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index e97ec7fa60c..e3667e1a630 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -277,7 +277,7 @@ const result = ApiMethod.parse(data); | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `currency` and `percent` are declared by the author, and a verdict that proves no other type (`number`, or none) keeps them. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | @@ -657,7 +657,7 @@ const result = ApiMethod.parse(data); | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `currency` and `percent` are declared by the author, and a verdict that proves no other type (`number`, or none) keeps them. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index e9828c9eb34..b6450b31d49 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -101,7 +101,7 @@ Add a new field to an existing object | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `currency` and `percent` are declared by the author, and a verdict that proves no other type (`number`, or none) keeps them. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | @@ -537,7 +537,7 @@ Add a new field to an existing object | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `currency` and `percent` are declared by the author, and a verdict that proves no other type (`number`, or none) keeps them. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | From 4bf77d2d0d5da808092f3de5359dc59e2634a3c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 06:33:29 +0000 Subject: [PATCH 06/11] fix(formula): an amount the proof cannot follow answers unproven, never number Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- packages/formula/src/formula-return.test.ts | 62 +++++++++++++------ packages/formula/src/formula-return.ts | 62 ++++++++++++++++--- ...eldInspector.returnTypeHeld-27485.test.tsx | 17 +++++ 3 files changed, 114 insertions(+), 27 deletions(-) diff --git a/packages/formula/src/formula-return.test.ts b/packages/formula/src/formula-return.test.ts index 9ccf5de24cc..e52285aff03 100644 --- a/packages/formula/src/formula-return.test.ts +++ b/packages/formula/src/formula-return.test.ts @@ -113,27 +113,11 @@ describe('CONTROL — a numeric formula stays `number`', () => { expect(inferFormulaReturn('record.count_formula + 1', FIELDS)).toEqual({ returnType: 'number' }); }); - it('nothing it cannot prove is money: each answer is exactly the plain inference', () => { + it('nothing it cannot prove is money: an expression that reads no amount gets exactly the plain inference', () => { for (const source of [ 'record.quantity * 2', - // Two amounts multiplied, or a quantity divided by one, is not an amount. - 'record.amount * record.tax', - 'record.quantity / record.amount', - // A ratio of two amounts is a plain number. + // A ratio of two amounts in one currency is proven a plain number. 'record.amount / record.tax', - // An amount plus a quantity adds two units. - 'record.amount + record.quantity', - // Two currencies — fixed USD with fixed EUR, fixed USD with dynamic — are not one amount. - 'record.amount + record.fee_eur', - 'record.amount + record.budget', - 'record.flag ? record.amount : record.fee_eur', - // A source whose currency does not parse names no currency. - 'record.broken * 2', - // Nor does a fixed source with no code: it is never read as CNY (#27157). - 'record.fixed_no_code * 2', - // A roll-up's unit is its child field's, not readable here. - 'record.rollup * 2', - 'record.amount % 3', 'record.amount > 100', 'upper(record.name)', 'today()', @@ -146,6 +130,10 @@ describe('CONTROL — a numeric formula stays `number`', () => { } }); + it('CONTROL — a `count` roll-up is a plain number: no amount is read', () => { + const withCount = { ...FIELDS, line_count: { type: 'summary', summaryOperations: { object: 'line', function: 'count' } } }; + expect(inferFormulaReturn('record.line_count * 2', withCount)).toEqual({ returnType: 'number' }); + }); it('without the host\'s fields it never claims money — the plain inference, unchanged', () => { expect(inferFormulaReturn('record.amount * 0.1')).toEqual({ returnType: 'number' }); expect(inferFormulaReturn('record.amount * 0.1').returnType).toBe(inferExpressionType('record.amount * 0.1')); @@ -170,6 +158,44 @@ describe('CONTROL — a numeric formula stays `number`', () => { }); }); +describe('#35631 — an amount the proof cannot follow is unproven, never `number`', () => { + // A `number` answer is read by a stamp as "proved not money", so it may + // withdraw a declared `currency`; each shape below reads an amount (or a + // roll-up that may sum one) and fails the proof, so it answers `{}`. + const UNPROVEN_OVER_MONEY = [ + // Shapes that answered `number` before #35631 — each pinned as `{}` now. + 'record.amount * 1.0 + record.fee_eur * 1.0', // two currencies meeting + '100 / record.amount', // anything divided by an amount + 'record.rollup * 0.9', // a roll-up operand + 'record.amount % 3', // a remainder of an amount + 'record.broken * 2', // a source whose currency does not parse + 'record.fixed_no_code * 2', // a fixed source with no code (#27157) + 'double(record.amount) * double(record.tax)', // an amount times an amount + // Shapes that already answered `{}` (the CEL type is `dyn`): unchanged. + 'record.amount * record.tax', + 'record.quantity / record.amount', + 'record.amount + record.quantity', + 'record.amount + record.fee_eur', + 'record.amount + record.budget', + 'record.flag ? record.amount : record.fee_eur', + 'max(record.amount, record.quantity)', + 'sqrt(record.amount)', // a function the proof does not name + 'record.weighted * record.weighted', + ]; + + it('each answers `{}`', () => { + for (const source of UNPROVEN_OVER_MONEY) { + expect(inferFormulaReturn(source, FIELDS), source).toEqual({}); + } + }); + + it('CONTROL — proven money still stamps `currency` with its config, and quantities still stamp `number`', () => { + expect(inferFormulaReturn('record.amount * 0.1', FIELDS)) + .toEqual({ returnType: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'USD' } }); + expect(inferFormulaReturn('record.quantity * 2', FIELDS)).toEqual({ returnType: 'number' }); + }); +}); + describe('a formula over a record-mode amount carries the record currency (ADR-0144 D2)', () => { const RECORD = { currencyMode: 'record', currencyField: 'currency_code' } as const; const RECORD_FIELDS: Readonly> = { diff --git a/packages/formula/src/formula-return.ts b/packages/formula/src/formula-return.ts index bb298a082b3..7054c046d83 100644 --- a/packages/formula/src/formula-return.ts +++ b/packages/formula/src/formula-return.ts @@ -48,11 +48,17 @@ * name, a field whose type or currency cannot be read, two different * currencies meeting — is unproven. * - * Unproven is never guessed into money: the answer then is exactly what - * {@link inferExpressionType} gives today, so a numeric formula stays `number` - * and the stamp never claims a currency it cannot name. A `summary` field is - * not read as a quantity: a roll-up of a currency field is itself money, and - * its source type is not on this object. + * Unproven is never guessed into money, and it is never answered as a plain + * `number` either when the expression reads a money-typed operand — a + * `currency` field, a formula declared `currency`, or a `summary` other than a + * `count` — on its numeric path: the answer then is `{}`, unproven, so a + * `number` answer always means "proved not money" and a stamp may withdraw a + * declared `currency` on it (#35631). An expression that reads no such operand + * gets exactly what {@link inferExpressionType} gives, so a numeric formula over + * quantities stays `number`, and a ratio of two amounts in one currency is a + * proven plain number. A `summary` field is not read as a quantity: a roll-up + * of a currency field is itself money, and its source type is not on this + * object. */ import { CurrencyConfigSchema, NUMERIC_VALUE_TYPES, type Field } from '@objectstack/spec/data'; @@ -69,6 +75,8 @@ export interface FormulaSourceField { readonly returnType?: string; /** A currency field's (or a currency formula's) `currencyConfig`, as declared. Absent ⇒ dynamic. */ readonly currencyConfig?: unknown; + /** `summary` only — its roll-up, as declared; a `count` is a plain number, any other function may be money. */ + readonly summaryOperations?: unknown; } /** @@ -259,6 +267,34 @@ function dimOf(node: unknown, fields: Readonly>): boolean { + const field = Object.prototype.hasOwnProperty.call(fields, name) ? fields[name] : undefined; + if (!field) return false; + if (field.type === 'currency') return true; + if (field.type === 'formula') return field.returnType === 'currency'; + if (field.type === 'summary') { + const ops = field.summaryOperations; + return !(ops && typeof ops === 'object' && (ops as { function?: unknown }).function === 'count'); + } + return false; +} + +/** Does the expression read a money-typed field of the host anywhere (#35631)? */ +function readsMoneyOperand(node: unknown, fields: Readonly>): boolean { + if (Array.isArray(node)) return node.some((n) => readsMoneyOperand(n, fields)); + if (!isNode(node)) return false; + if (node.op === 'id') return typeof node.args === 'string' && isMoneyTyped(node.args, fields); + if (node.op === '.' && Array.isArray(node.args) && node.args.length === 2) { + const [base, member] = node.args; + if (isNode(base) && base.op === 'id' && base.args === 'record' && typeof member === 'string') { + return isMoneyTyped(member, fields); + } + return readsMoneyOperand(base, fields); + } + return readsMoneyOperand(node.args, fields); +} + function sourceOf(input: ExprInput): string | null { const source = typeof input === 'string' ? input @@ -279,10 +315,13 @@ function sourceOf(input: ExprInput): string | null { * `currencyConfig: { currencyMode: 'record', currencyField }` when they are * record-mode amounts naming one code field (ADR-0144 D2). Sources in two * different currencies are not provably one amount, and fall through. + * - A numeric expression that reads a money-typed operand (a `currency` + * field, a `currency` formula, a non-`count` `summary`) and is neither proven + * money nor proven a plain number ⇒ `{}`, unproven — never `number`, which + * a stamp reads as "not money". * - Otherwise ⇒ the {@link inferExpressionType} answer as `returnType` - * (`number` / `text` / `boolean` / `date`), or `{}` when that is `unknown` — - * unchanged from before this function existed, so a numeric formula stays - * `number`. + * (`number` / `text` / `boolean` / `date`), or `{}` when that is `unknown`, + * so a numeric formula over quantities stays `number`. * * Pure and conservative: it never throws, and an expression that does not * type-check is never money. @@ -300,7 +339,8 @@ export function inferFormulaReturn( // ternary outright — so the guard idiom would never be judged at all. const celType = inferCelType(rewriteNullableTernary(source), names); if (celType !== null && MONEY_CEL_TYPES.has(celType)) { - const dim = dimOf(parseCelToAst(source), fields); + const ast = parseCelToAst(source); + const dim = dimOf(ast, fields); if (dim.kind === 'money') { if (dim.currency.mode === 'fixed') { return { returnType: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: dim.currency.code } }; @@ -310,6 +350,10 @@ export function inferFormulaReturn( } return { returnType: 'currency' }; } + // #35631 — a money operand on the numeric path that the proof could not + // follow (a function it does not name, two currencies, an amount times an + // amount, a divisor that is an amount, a roll-up): unproven, never `number`. + if (dim.kind === 'unproven' && readsMoneyOperand(ast, fields)) return {}; } } const plain = inferExpressionType(input, { fields: names }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx index b07f75926ee..bab432321fd 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx @@ -94,6 +94,7 @@ function Harness({ est_hours: { type: 'number' }, budget: { type: 'number' }, amount: { type: 'currency', currencyConfig: USD }, + total: { type: 'summary', summaryOperations: { object: 'line', field: 'amount', function: 'sum' } }, f_total: { type: 'formula', label: 'F Total', expression: 'record.est_hours * 2', returnType, ...extra }, }); React.useEffect(() => { @@ -255,6 +256,22 @@ describe('ObjectFieldInspector — the money verdict proves or withdraws a decla expect(latest().currencyConfig).toEqual(USD); }); + it('a roll-up the proof cannot read as money is unproven, and keeps a declared `currency`', async () => { + const { box, latest } = asCurrency(); + fireEvent.change(box, { target: { value: 'record.total * 0.9' } }); + await waitFor(() => expect(latest().expression).toBe('record.total * 0.9'), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('currency'); + expect(latest().currencyConfig).toEqual(USD); + }); + + it('a new formula over an amount the proof cannot follow still stamps the proven CEL type', async () => { + const { box, latest } = renderFormula(undefined, { money: true, extra: { returnType: undefined } }); + fireEvent.change(box, { target: { value: '100 / record.amount' } }); + await waitFor(() => expect(latest().returnType).toBe('number'), { timeout: 3000 }); + expect('currencyConfig' in latest()).toBe(false); + }); + it('CONTROL — a declared `percent` is still kept under a `number` verdict', async () => { const { box, latest } = renderFormula('percent', { money: true }); fireEvent.change(box, { target: { value: COUNT } }); From 76bbb5432949854fd7a7efbfe9c5387bf66ab88b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 06:33:44 +0000 Subject: [PATCH 07/11] chore(changeset): formula answer change FROM/TO Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- .changeset/35631-formula-currency-verdict.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.changeset/35631-formula-currency-verdict.md b/.changeset/35631-formula-currency-verdict.md index 6ac9f651a1d..04008b2712c 100644 --- a/.changeset/35631-formula-currency-verdict.md +++ b/.changeset/35631-formula-currency-verdict.md @@ -1,6 +1,7 @@ --- '@object-ui/app-shell': patch '@objectstack/spec': patch +'@objectstack/formula': patch --- fix(app-shell): Studio's formula inspector asks whether the formula still computes money before it keeps a `currency` result type @@ -17,4 +18,6 @@ The stamp now also asks `@objectstack/formula`'s `inferFormulaReturn`, over the - An unproven verdict (a field-over-field quotient, two currencies meeting) keeps a declared `currency`, as before, and so does an engine that does not offer `inferFormulaReturn`. - A declared `percent` is unchanged: it survives a `number` or unproven verdict. A verdict that proves `text`, `boolean` or `date` still stamps, and now also removes a stale `currencyConfig`. +`@objectstack/formula`'s `inferFormulaReturn` now answers `{}` (unproven) where it used to answer `{ returnType: 'number' }` for a numeric expression that reads a money-typed operand the proof cannot follow: a `currency` field, a formula declared `currency`, or a `summary` other than a `count`. FROM `inferFormulaReturn('record.rollup * 0.9', fields)` → `{ returnType: 'number' }` TO → `{}`; likewise `100 / record.amount`, `record.amount % 3`, `record.amount * 1.0 + record.fee_eur * 1.0` (two currencies), `double(record.amount) * double(record.tax)`, and an amount whose `currencyConfig` does not parse. So a `number` answer now always means "proved not money", and only that answer withdraws a declared `currency`. An expression that reads no such operand (a `count` roll-up included) is answered as before, and a ratio of two amounts in one currency is unchanged. A caller that read the old `number` for these shapes should read the expression's CEL type (`inferExpressionType`) instead. In Studio, a new formula over such an amount is still stamped `number` from that CEL type. + The stamp still runs only after the author edits the expression; selecting a field writes nothing. The `returnType` description in `@objectstack/spec` now says the same: `currency` is stamped when the expression provably computes money and withdrawn for `number` when an edit leaves it a plain number. From e5a7e08b934241bb2a835b29c85c1d6bc5e5cc8d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 06:51:09 +0000 Subject: [PATCH 08/11] fix(app-shell): the stamp's field check is not a column-identity dual read Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- .../views/metadata-admin/inspectors/ObjectFieldInspector.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx index e57c8280560..80b3157e849 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx @@ -1131,7 +1131,10 @@ export function ObjectFieldInspector({ /** objectstack#35631 — writes the settled verdicts as the formula's declared result (`returnType` + `currencyConfig`). */ const stampFormulaType = (settled: typeof formulaVerdictRef.current, declared: FormulaReturnVerdict | null) => { // The draft moved to another field or another source since: that one settles itself. - if (settled.field !== entry.name || settled.source !== readPredicate(def.expression ?? def.formula)) return; + // (`settled.field` is the verdict record's field NAME, not a column identity.) + const sameField = settled.field === entry.name; + if (!sameField) return; + if (settled.source !== readPredicate(def.expression ?? def.formula)) return; // Spec: `returnType` carries only a PROVEN concrete type — // an ambiguous (`unknown`) or unavailable verdict clears it. const proven = settled.inferred && settled.inferred !== 'unknown' ? settled.inferred : undefined; From 4e33d26f714760933c706fd3ed72d65e07112e8e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:16:34 +0000 Subject: [PATCH 09/11] =?UTF-8?q?fix(formula):=20a=20number=20answer=20is?= =?UTF-8?q?=20a=20proof=20=E2=80=94=20unproven=20unless=20every=20record?= =?UTF-8?q?=20read=20has=20a=20readable=20non-money=20unit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- packages/formula/src/formula-return.ts | 134 ++++++++++++++++--------- 1 file changed, 88 insertions(+), 46 deletions(-) diff --git a/packages/formula/src/formula-return.ts b/packages/formula/src/formula-return.ts index 7054c046d83..61722a6be43 100644 --- a/packages/formula/src/formula-return.ts +++ b/packages/formula/src/formula-return.ts @@ -48,17 +48,29 @@ * name, a field whose type or currency cannot be read, two different * currencies meeting — is unproven. * - * Unproven is never guessed into money, and it is never answered as a plain - * `number` either when the expression reads a money-typed operand — a - * `currency` field, a formula declared `currency`, or a `summary` other than a - * `count` — on its numeric path: the answer then is `{}`, unproven, so a - * `number` answer always means "proved not money" and a stamp may withdraw a - * declared `currency` on it (#35631). An expression that reads no such operand - * gets exactly what {@link inferExpressionType} gives, so a numeric formula over - * quantities stays `number`, and a ratio of two amounts in one currency is a - * proven plain number. A `summary` field is not read as a quantity: a roll-up - * of a currency field is itself money, and its source type is not on this - * object. + * Unproven is never guessed into money, and on the numeric path it is never + * answered `number` either (#35631): a `number` answer means "proved not + * money", so a stamp may withdraw a declared `currency` on it. A numeric + * expression is answered by {@link inferExpressionType} only when the unit + * proof succeeds (a plain quantity or constant), or when every read of the + * record — `record.x`, `record['x']`, `record.?x`, `record[?'x']`, or a bare + * `x` — is ONE segment naming a field the map declares, whose unit can be read + * and is not money. Anything else answers `{}`, unproven: + * + * - a read of a `currency` field, a formula declared `currency`, or a + * `summary` other than a `count` (a roll-up passed without its + * `summaryOperations` included) that the proof could not follow; + * - a formula that declares no `returnType` — its unit cannot be read; + * - a hop through a reference (`record.account.balance`) — the leaf's type is + * not on this object; + * - a read whose key is computed, or a name the map does not declare. + * + * So a numeric formula over declared quantities stays `number`. The CEL type + * still decides once the proof succeeds: a bare ratio of two amounts in one + * currency (`record.amount / record.tax`) is proven a plain number, but cel-js + * types it `dyn`, so it answers `{}` and a declared `currency` is kept. A + * `summary` field is not read as a quantity: a roll-up of a currency field is + * itself money, and its source type is not on this object. */ import { CurrencyConfigSchema, NUMERIC_VALUE_TYPES, type Field } from '@objectstack/spec/data'; @@ -75,17 +87,24 @@ export interface FormulaSourceField { readonly returnType?: string; /** A currency field's (or a currency formula's) `currencyConfig`, as declared. Absent ⇒ dynamic. */ readonly currencyConfig?: unknown; - /** `summary` only — its roll-up, as declared; a `count` is a plain number, any other function may be money. */ + /** + * `summary` only — its roll-up, as declared. A `count` is a plain number; + * any other function, or a roll-up passed without this member, may be money. + */ readonly summaryOperations?: unknown; } /** - * A formula field's declared result: the pair authoring stamps onto the field. - * BOTH members are the answer — a member that is absent is one the formula does - * not declare, so a stamp writes both and clears an absent one (a formula edited - * from money to a count must lose its stale `currencyConfig`). + * A formula field's declared result, as far as the expression proves it. * - * - `returnType` — absent when no concrete type can be proven. + * - `returnType` — absent means NO verdict, never "declares nothing": the + * expression proves no type (`{}`, unproven), and a stamp keeps what the + * author declared (a `currency`, a `percent`). `number` means proved not + * money. + * - With a `currency` answer the pair is the declaration: the stamp writes + * `currencyConfig` exactly as answered and removes one the answer leaves + * out (a `dynamic` result). A stamp that writes any other type removes a + * stale `currencyConfig` — a formula edited from money to a count loses it. * - `currencyConfig` — present only for a `currency` result whose currency is * `fixed`, or `record` (ADR-0144 D2: each record's own currency, carried as * the same `currencyField` its source amounts name). A `dynamic` result (the @@ -267,32 +286,52 @@ function dimOf(node: unknown, fields: Readonly>): boolean { +/** + * Can the unit of the host field `name` be read, and is it not money? A + * declared non-`currency` field, a formula that declares a non-`currency` + * `returnType`, or a `count` roll-up. Undeclared, untyped, a `currency` + * field, a formula with no `returnType`, or any other roll-up: no (#35631). + */ +function hasPlainUnit(name: string, fields: Readonly>): boolean { const field = Object.prototype.hasOwnProperty.call(fields, name) ? fields[name] : undefined; - if (!field) return false; - if (field.type === 'currency') return true; - if (field.type === 'formula') return field.returnType === 'currency'; + if (!field || typeof field.type !== 'string') return false; + if (field.type === 'currency') return false; + if (field.type === 'formula') return typeof field.returnType === 'string' && field.returnType !== 'currency'; if (field.type === 'summary') { const ops = field.summaryOperations; - return !(ops && typeof ops === 'object' && (ops as { function?: unknown }).function === 'count'); + return !!ops && typeof ops === 'object' && (ops as { function?: unknown }).function === 'count'; } - return false; + return true; } -/** Does the expression read a money-typed field of the host anywhere (#35631)? */ -function readsMoneyOperand(node: unknown, fields: Readonly>): boolean { - if (Array.isArray(node)) return node.some((n) => readsMoneyOperand(n, fields)); - if (!isNode(node)) return false; - if (node.op === 'id') return typeof node.args === 'string' && isMoneyTyped(node.args, fields); - if (node.op === '.' && Array.isArray(node.args) && node.args.length === 2) { - const [base, member] = node.args; - if (isNode(base) && base.op === 'id' && base.args === 'record' && typeof member === 'string') { - return isMoneyTyped(member, fields); - } - return readsMoneyOperand(base, fields); +/** The four spellings of one member read (`relationship-traversal.ts` reads them alike). */ +const MEMBER_READ_OPS: ReadonlySet = new Set(['.', '.?']); +const INDEX_READ_OPS: ReadonlySet = new Set(['[]', '[?]']); + +/** `{ receiver, name }` for `x.name`, `x.?name`, `x['name']`, `x[?'name']`; `null` for a computed key. */ +function memberRead(node: Node): { receiver: unknown; name: string } | null { + if (!Array.isArray(node.args) || node.args.length < 2) return null; + const [receiver, key] = node.args; + if (MEMBER_READ_OPS.has(node.op)) return typeof key === 'string' ? { receiver, name: key } : null; + if (isNode(key) && key.op === 'value' && typeof key.args === 'string') return { receiver, name: key.args }; + return null; +} + +/** + * Is every read of the record one segment naming a declared host field whose + * unit can be read and is not money ({@link hasPlainUnit})? A hop, a + * computed key, a read off anything but `record`, or a bare `record` is not. + */ +function readsOnlyPlainFields(node: unknown, fields: Readonly>): boolean { + if (Array.isArray(node)) return node.every((n) => readsOnlyPlainFields(n, fields)); + if (!isNode(node)) return true; + if (MEMBER_READ_OPS.has(node.op) || INDEX_READ_OPS.has(node.op)) { + const read = memberRead(node); + const onRecord = !!read && isNode(read.receiver) && read.receiver.op === 'id' && read.receiver.args === 'record'; + return onRecord && hasPlainUnit(read!.name, fields); } - return readsMoneyOperand(node.args, fields); + if (node.op === 'id') return typeof node.args === 'string' && node.args !== 'record' && hasPlainUnit(node.args, fields); + return readsOnlyPlainFields(node.args, fields); } function sourceOf(input: ExprInput): string | null { @@ -315,13 +354,16 @@ function sourceOf(input: ExprInput): string | null { * `currencyConfig: { currencyMode: 'record', currencyField }` when they are * record-mode amounts naming one code field (ADR-0144 D2). Sources in two * different currencies are not provably one amount, and fall through. - * - A numeric expression that reads a money-typed operand (a `currency` - * field, a `currency` formula, a non-`count` `summary`) and is neither proven - * money nor proven a plain number ⇒ `{}`, unproven — never `number`, which - * a stamp reads as "not money". + * - A numeric expression the unit proof does not prove a plain number, with a + * record read that is not one segment naming a declared field of a + * readable, non-money unit (a `currency` field, a `currency` formula, a + * formula with no `returnType`, a non-`count` roll-up, a reference hop, a + * computed key, an undeclared name) ⇒ `{}`, unproven. `number` is never + * the answer there: a stamp reads it as "proved not money". * - Otherwise ⇒ the {@link inferExpressionType} answer as `returnType` - * (`number` / `text` / `boolean` / `date`), or `{}` when that is `unknown`, - * so a numeric formula over quantities stays `number`. + * (`number` / `text` / `boolean` / `date`), or `{}` when that is `unknown` + * (a bare same-currency ratio such as `record.amount / record.tax` types + * `dyn`), so a numeric formula over declared quantities stays `number`. * * Pure and conservative: it never throws, and an expression that does not * type-check is never money. @@ -350,10 +392,10 @@ export function inferFormulaReturn( } return { returnType: 'currency' }; } - // #35631 — a money operand on the numeric path that the proof could not - // follow (a function it does not name, two currencies, an amount times an - // amount, a divisor that is an amount, a roll-up): unproven, never `number`. - if (dim.kind === 'unproven' && readsMoneyOperand(ast, fields)) return {}; + // #35631 — `number` means proved not money: unless the unit proof + // succeeded, every record read must name a declared field whose unit + // can be read and is not money, or the answer is unproven. + if (!isPlainNumber(dim) && !readsOnlyPlainFields(ast, fields)) return {}; } } const plain = inferExpressionType(input, { fields: names }); From ae8b9cf9ea3d4a2664f8175723061a22371d3f73 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:17:47 +0000 Subject: [PATCH 10/11] test+docs: M1 route pins, S1/S2 inspector pins, percent precedence in spec prose, widening changeset Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- .changeset/35631-formula-currency-verdict.md | 12 +++-- packages/formula/src/formula-return.test.ts | 26 ++++++++-- packages/spec/src/data/field.zod.ts | 7 +-- ...eldInspector.returnTypeHeld-27485.test.tsx | 52 ++++++++++++++++++- 4 files changed, 85 insertions(+), 12 deletions(-) diff --git a/.changeset/35631-formula-currency-verdict.md b/.changeset/35631-formula-currency-verdict.md index 04008b2712c..7ff1bac8af9 100644 --- a/.changeset/35631-formula-currency-verdict.md +++ b/.changeset/35631-formula-currency-verdict.md @@ -6,7 +6,7 @@ fix(app-shell): Studio's formula inspector asks whether the formula still computes money before it keeps a `currency` result type -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none When an author edited a formula field in Studio, the inspector re-stamped `returnType` from the expression's inferred CEL type, and kept a declared `currency` under every `number` or unproven verdict, because that type never says "money". So a formula edited from an amount (`record.amount * 0.1`) into a count (`record.est_hours * 2`) kept `returnType: 'currency'` and its `currencyConfig`, and its value was still shown as an amount. @@ -16,8 +16,12 @@ The stamp now also asks `@objectstack/formula`'s `inferFormulaReturn`, over the - Provably money: `returnType` is stamped `currency`, with the currency the source amounts are in as the formula's `currencyConfig` (absent for the tenant default currency). This holds for a formula that was `number` too. - An edit it answers `number` for withdraws a declared `currency`: `returnType` becomes `number` and the `currencyConfig` is removed. - An unproven verdict (a field-over-field quotient, two currencies meeting) keeps a declared `currency`, as before, and so does an engine that does not offer `inferFormulaReturn`. -- A declared `percent` is unchanged: it survives a `number` or unproven verdict. A verdict that proves `text`, `boolean` or `date` still stamps, and now also removes a stale `currencyConfig`. +- A declared `percent` is unchanged: it survives a `number`, unproven or money verdict, and is never re-stamped `currency`. A verdict that proves `text`, `boolean` or `date` still stamps, and now also removes a stale `currencyConfig`. -`@objectstack/formula`'s `inferFormulaReturn` now answers `{}` (unproven) where it used to answer `{ returnType: 'number' }` for a numeric expression that reads a money-typed operand the proof cannot follow: a `currency` field, a formula declared `currency`, or a `summary` other than a `count`. FROM `inferFormulaReturn('record.rollup * 0.9', fields)` → `{ returnType: 'number' }` TO → `{}`; likewise `100 / record.amount`, `record.amount % 3`, `record.amount * 1.0 + record.fee_eur * 1.0` (two currencies), `double(record.amount) * double(record.tax)`, and an amount whose `currencyConfig` does not parse. So a `number` answer now always means "proved not money", and only that answer withdraws a declared `currency`. An expression that reads no such operand (a `count` roll-up included) is answered as before, and a ratio of two amounts in one currency is unchanged. A caller that read the old `number` for these shapes should read the expression's CEL type (`inferExpressionType`) instead. In Studio, a new formula over such an amount is still stamped `number` from that CEL type. +`@objectstack/formula`'s `inferFormulaReturn` now answers `{}` (unproven) where it used to answer `{ returnType: 'number' }` on the numeric path, unless the unit proof succeeds or every read of the record (`record.x`, `record['x']`, `record.?x`, `record[?'x']`, or a bare `x`) is one segment naming a declared field whose unit can be read and is not money. FROM `inferFormulaReturn('record.rollup * 0.9', fields)` → `{ returnType: 'number' }` TO → `{}`. The same holds for `100 / record.amount`, `record.amount % 3`, `record.amount * 1.0 + record.fee_eur * 1.0` (two currencies), `double(record.amount) * double(record.tax)`, an amount whose `currencyConfig` does not parse, a hop through a reference (`record.account.balance * 0.9`), a formula operand that declares no `returnType` (`record.subtotal * 0.2`), the indexed and optional spellings of an amount (`record['amount'] * 0.1`), and a name the field map does not declare (`record.unknown_field * 2`). So a `number` answer means "proved not money", and only that answer withdraws a declared `currency`. -The stamp still runs only after the author edits the expression; selecting a field writes nothing. The `returnType` description in `@objectstack/spec` now says the same: `currency` is stamped when the expression provably computes money and withdrawn for `number` when an edit leaves it a plain number. +What still answers `number` is an expression over declared fields of readable non-money units: number, percent and other plain fields, a formula declaring a non-`currency` `returnType`, and a `count` roll-up whose `summaryOperations` is passed. A bare ratio of two amounts in one currency (`record.amount / record.tax`) types `dyn` and answers `{}`, as before. A caller that read the old `number` for these shapes should read the expression's CEL type (`inferExpressionType`) instead. In Studio, a new formula over such an amount is still stamped `number` from that CEL type. + +Widened: the published `FormulaSourceField` type gains one optional member, `summaryOperations` (a `summary` field's roll-up, as declared). A `count` roll-up is read as a plain number only when it is passed. A roll-up passed without `summaryOperations`, a `count` included, is read as possibly money, so an expression over it answers `{}`. + +The stamp still runs only after the author edits the expression; selecting a field writes nothing. The `returnType` description in `@objectstack/spec` now says the same: `currency` is stamped when the expression provably computes money and withdrawn for `number` when an edit leaves it a plain number, and a declared `percent` is kept under a money verdict. diff --git a/packages/formula/src/formula-return.test.ts b/packages/formula/src/formula-return.test.ts index e52285aff03..3b8d6f7fcdb 100644 --- a/packages/formula/src/formula-return.test.ts +++ b/packages/formula/src/formula-return.test.ts @@ -37,6 +37,9 @@ const FIELDS: Readonly> = { rollup: { type: 'summary' }, weighted: { type: 'formula', returnType: 'currency', currencyConfig: USD }, count_formula: { type: 'formula', returnType: 'number' }, + account: { type: 'lookup' }, + // A formula that declares no `returnType`: its unit cannot be read. + subtotal: { type: 'formula' }, broken: { type: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'US' } }, // `fixed` with no code: the spec refuses it rather than filling in CNY (#27157). fixed_no_code: { type: 'currency', currencyConfig: { currencyMode: 'fixed' } }, @@ -113,16 +116,16 @@ describe('CONTROL — a numeric formula stays `number`', () => { expect(inferFormulaReturn('record.count_formula + 1', FIELDS)).toEqual({ returnType: 'number' }); }); - it('nothing it cannot prove is money: an expression that reads no amount gets exactly the plain inference', () => { + it('nothing it cannot prove is money: a numeric expression over declared non-money units, or one that is not numeric, gets exactly the plain inference', () => { for (const source of [ 'record.quantity * 2', - // A ratio of two amounts in one currency is proven a plain number. + // A ratio of two amounts in one currency is proven a plain number, and + // cel-js types it `dyn`: the plain inference answers `{}`. 'record.amount / record.tax', 'record.amount > 100', 'upper(record.name)', 'today()', 'record.amount + record.name', - 'record.unknown_field * 2', 'size(record.name)', ]) { expect(inferFormulaReturn(source, FIELDS), source).toEqual(plainStamp(source)); @@ -181,6 +184,16 @@ describe('#35631 — an amount the proof cannot follow is unproven, never `numbe 'max(record.amount, record.quantity)', 'sqrt(record.amount)', // a function the proof does not name 'record.weighted * record.weighted', + // Reads whose unit cannot be read — each answered `number` before. + 'record.account.balance * 0.9', // a hop through a reference + 'record.subtotal * 0.2', // a formula that declares no returnType + "record['amount'] * 0.1", // the indexed spelling of an amount + 'record.?amount * 0.1', // the optional spelling + "record[?'amount'] * 0.1", // the optional indexed spelling + 'record.unknown_field * 2', // a name the map does not declare + // One shape per leg of the unit check. + '100 / record.weighted', // a formula declared `currency` + '100 / amount', // a bare identifier naming an amount ]; it('each answers `{}`', () => { @@ -194,6 +207,13 @@ describe('#35631 — an amount the proof cannot follow is unproven, never `numbe .toEqual({ returnType: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'USD' } }); expect(inferFormulaReturn('record.quantity * 2', FIELDS)).toEqual({ returnType: 'number' }); }); + + it('CONTROL — every spelling of a quantity read, and a formula declared `number`, still answers `number`', () => { + for (const source of ["record['quantity'] * 2", 'record.count_formula * 2', 'quantity * 2', 'record.probability * 2']) { + expect(inferFormulaReturn(source, FIELDS), source).toEqual(plainStamp(source)); + } + expect(inferFormulaReturn("record['quantity'] * 2", FIELDS)).toEqual({ returnType: 'number' }); + }); }); describe('a formula over a record-mode amount carries the record currency (ADR-0144 D2)', () => { diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 9ac60c6e31c..ad72471fe78 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2403,11 +2403,12 @@ export const FieldSchema = lazySchema(() => { * under every verdict that proves no other type — where it would stamp * `number`, and where the type is unproven (a field-over-field quotient such * as `record.spent / record.budget` types `dyn`), which would otherwise - * clear it. A declared `currency` is kept under an unproven verdict the - * same way. A verdict that proves `text`, `boolean` or `date` still stamps. + * clear it. A declared `percent` is kept under a money verdict too: it is + * never re-stamped `currency`. A declared `currency` is kept under an + * unproven verdict the same way. A verdict that proves `text`, `boolean` or `date` still stamps. */ returnType: z.enum(['number', 'text', 'boolean', 'date', 'currency', 'percent']).optional() - .describe('Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression\'s inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula\'s own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face.'), + .describe('Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression\'s inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula\'s own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face.'), summaryOperations: strictObject({ surface: 'this roll-up summary', history: FIELD_HISTORY, diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx index bab432321fd..04da4d61dc6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.returnTypeHeld-27485.test.tsx @@ -95,6 +95,12 @@ function Harness({ budget: { type: 'number' }, amount: { type: 'currency', currencyConfig: USD }, total: { type: 'summary', summaryOperations: { object: 'line', field: 'amount', function: 'sum' } }, + fee_eur: { type: 'currency', currencyConfig: EUR }, + home_amount: { type: 'currency' }, + currency_code: { type: 'text' }, + local_amount: { type: 'currency', currencyConfig: LOCAL }, + // A formula that declares no `returnType`: its unit cannot be read. + subtotal: { type: 'formula', expression: 'record.est_hours * 3' }, f_total: { type: 'formula', label: 'F Total', expression: 'record.est_hours * 2', returnType, ...extra }, }); React.useEffect(() => { @@ -117,6 +123,8 @@ function Harness({ } const USD = { currencyMode: 'fixed', defaultCurrency: 'USD' } as const; +const EUR = { currencyMode: 'fixed', defaultCurrency: 'EUR' } as const; +const LOCAL = { currencyMode: 'record', currencyField: 'currency_code' } as const; function renderFormula(returnType?: string, { money = false, extra }: { money?: boolean; extra?: Record } = {}) { stubEngine({ money }); @@ -273,13 +281,53 @@ describe('ObjectFieldInspector — the money verdict proves or withdraws a decla }); it('CONTROL — a declared `percent` is still kept under a `number` verdict', async () => { + // An edit to a DIFFERENT quantity expression than the harness default, so + // the stamp really runs and the verdict really is `number`. const { box, latest } = renderFormula('percent', { money: true }); - fireEvent.change(box, { target: { value: COUNT } }); - await waitFor(() => expect(latest().expression).toBe(COUNT), { timeout: 3000 }); + fireEvent.change(box, { target: { value: 'record.est_hours * 3' } }); + await waitFor(() => expect(latest().expression).toBe('record.est_hours * 3'), { timeout: 3000 }); await settle(); expect(latest().returnType).toBe('percent'); }); + it('a declared `percent` is kept under a money verdict too', async () => { + const { box, latest } = renderFormula('percent', { money: true }); + fireEvent.change(box, { target: { value: 'record.amount * 0.2' } }); + await waitFor(() => expect(latest().expression).toBe('record.amount * 0.2'), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('percent'); + expect('currencyConfig' in latest()).toBe(false); + }); + + it('a proven currency that moves updates the config: a USD amount to a EUR amount', async () => { + const { box, latest } = asCurrency(); + fireEvent.change(box, { target: { value: 'record.fee_eur * 0.1' } }); + await waitFor(() => expect(latest().currencyConfig).toEqual(EUR), { timeout: 3000 }); + expect(latest().returnType).toBe('currency'); + }); + + it('a move to a dynamic amount removes the config: absent is the tenant default', async () => { + const { box, latest } = asCurrency(); + fireEvent.change(box, { target: { value: 'record.home_amount * 0.1' } }); + await waitFor(() => expect('currencyConfig' in latest()).toBe(false), { timeout: 3000 }); + expect(latest().returnType).toBe('currency'); + }); + + it('a record-mode source stamps its own code field', async () => { + const { box, latest } = asCurrency(); + fireEvent.change(box, { target: { value: 'record.local_amount * 0.1' } }); + await waitFor(() => expect(latest().currencyConfig).toEqual(LOCAL), { timeout: 3000 }); + expect(latest().returnType).toBe('currency'); + }); + + it('a hand-declared `currency` over a formula with no `returnType` survives an expression edit', async () => { + const { box, latest } = renderFormula('currency', { money: true, extra: { expression: 'record.subtotal * 0.1' } }); + fireEvent.change(box, { target: { value: 'record.subtotal * 0.12' } }); + await waitFor(() => expect(latest().expression).toBe('record.subtotal * 0.12'), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('currency'); + }); + it('CONTROL — a verdict that proves text, boolean or date still stamps over a declared `currency`', async () => { const { box, latest } = asCurrency(); fireEvent.change(box, { target: { value: 'record.amount > 40' } }); From b9ce479e6de7a98539ebcd5cebdb787bc40a471c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:31:23 +0000 Subject: [PATCH 11/11] =?UTF-8?q?fix(formula):=20no=20field=20map,=20no=20?= =?UTF-8?q?declared=20unit=20=E2=80=94=20pin=20the=20empty-map=20answer;?= =?UTF-8?q?=20regenerate=20reference=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01L9qibvVRcFWKrfWeG5jzPb Co-authored-by: Claude --- .changeset/35631-formula-currency-verdict.md | 2 +- content/docs/references/data/field.mdx | 2 +- content/docs/references/data/object.mdx | 4 ++-- content/docs/references/system/migration.mdx | 4 ++-- packages/formula/src/formula-return.test.ts | 12 +++++++++--- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/.changeset/35631-formula-currency-verdict.md b/.changeset/35631-formula-currency-verdict.md index 7ff1bac8af9..749c996a5a0 100644 --- a/.changeset/35631-formula-currency-verdict.md +++ b/.changeset/35631-formula-currency-verdict.md @@ -18,7 +18,7 @@ The stamp now also asks `@objectstack/formula`'s `inferFormulaReturn`, over the - An unproven verdict (a field-over-field quotient, two currencies meeting) keeps a declared `currency`, as before, and so does an engine that does not offer `inferFormulaReturn`. - A declared `percent` is unchanged: it survives a `number`, unproven or money verdict, and is never re-stamped `currency`. A verdict that proves `text`, `boolean` or `date` still stamps, and now also removes a stale `currencyConfig`. -`@objectstack/formula`'s `inferFormulaReturn` now answers `{}` (unproven) where it used to answer `{ returnType: 'number' }` on the numeric path, unless the unit proof succeeds or every read of the record (`record.x`, `record['x']`, `record.?x`, `record[?'x']`, or a bare `x`) is one segment naming a declared field whose unit can be read and is not money. FROM `inferFormulaReturn('record.rollup * 0.9', fields)` → `{ returnType: 'number' }` TO → `{}`. The same holds for `100 / record.amount`, `record.amount % 3`, `record.amount * 1.0 + record.fee_eur * 1.0` (two currencies), `double(record.amount) * double(record.tax)`, an amount whose `currencyConfig` does not parse, a hop through a reference (`record.account.balance * 0.9`), a formula operand that declares no `returnType` (`record.subtotal * 0.2`), the indexed and optional spellings of an amount (`record['amount'] * 0.1`), and a name the field map does not declare (`record.unknown_field * 2`). So a `number` answer means "proved not money", and only that answer withdraws a declared `currency`. +`@objectstack/formula`'s `inferFormulaReturn` now answers `{}` (unproven) where it used to answer `{ returnType: 'number' }` on the numeric path, unless the unit proof succeeds or every read of the record (`record.x`, `record['x']`, `record.?x`, `record[?'x']`, or a bare `x`) is one segment naming a declared field whose unit can be read and is not money. FROM `inferFormulaReturn('record.rollup * 0.9', fields)` → `{ returnType: 'number' }` TO → `{}`. The same holds for `100 / record.amount`, `record.amount % 3`, `record.amount * 1.0 + record.fee_eur * 1.0` (two currencies), `double(record.amount) * double(record.tax)`, an amount whose `currencyConfig` does not parse, a hop through a reference (`record.account.balance * 0.9`), a formula operand that declares no `returnType` (`record.subtotal * 0.2`), the indexed and optional spellings of an amount (`record['amount'] * 0.1`), and a name the field map does not declare (`record.unknown_field * 2`). A call with no field map therefore answers `{}` for any numeric expression that reads the record (`inferFormulaReturn('record.amount * 0.1')` was `number`). So a `number` answer means "proved not money", and only that answer withdraws a declared `currency`. What still answers `number` is an expression over declared fields of readable non-money units: number, percent and other plain fields, a formula declaring a non-`currency` `returnType`, and a `count` roll-up whose `summaryOperations` is passed. A bare ratio of two amounts in one currency (`record.amount / record.tax`) types `dyn` and answers `{}`, as before. A caller that read the old `number` for these shapes should read the expression's CEL type (`inferExpressionType`) instead. In Studio, a new formula over such an amount is still stamped `number` from that CEL type. diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 1397c16b864..bec6dbe6777 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -98,7 +98,7 @@ const result = CurrencyConfigSchema.parse(data); | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index e3667e1a630..35d74e09155 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -277,7 +277,7 @@ const result = ApiMethod.parse(data); | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | @@ -657,7 +657,7 @@ const result = ApiMethod.parse(data); | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index b6450b31d49..188e4709769 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -101,7 +101,7 @@ Add a new field to an existing object | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | @@ -537,7 +537,7 @@ Add a new field to an existing object | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it. `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | | **language** | `string` | optional | Programming language for syntax highlighting (e.g., javascript, python, sql) | | **step** | `number` | optional | Step increment for slider (default: 1) | diff --git a/packages/formula/src/formula-return.test.ts b/packages/formula/src/formula-return.test.ts index 3b8d6f7fcdb..2c7b58aed78 100644 --- a/packages/formula/src/formula-return.test.ts +++ b/packages/formula/src/formula-return.test.ts @@ -137,10 +137,16 @@ describe('CONTROL — a numeric formula stays `number`', () => { const withCount = { ...FIELDS, line_count: { type: 'summary', summaryOperations: { object: 'line', function: 'count' } } }; expect(inferFormulaReturn('record.line_count * 2', withCount)).toEqual({ returnType: 'number' }); }); - it('without the host\'s fields it never claims money — the plain inference, unchanged', () => { - expect(inferFormulaReturn('record.amount * 0.1')).toEqual({ returnType: 'number' }); - expect(inferFormulaReturn('record.amount * 0.1').returnType).toBe(inferExpressionType('record.amount * 0.1')); + it('without the host\'s fields it never claims money, nor proves a plain number: no read has a declared unit', () => { + // #35631 — every read names a field the (empty) map does not declare, so + // the numeric path is unproven; the CEL type alone would say `number`. + expect(inferExpressionType('record.amount * 0.1')).toBe('number'); + expect(inferFormulaReturn('record.amount * 0.1')).toEqual({}); expect(inferFormulaReturn('record.budget - record.spent')).toEqual({}); + // A constant needs no field: the unit proof succeeds. + expect(inferFormulaReturn('2 * 3')).toEqual({ returnType: 'number' }); + // A non-numeric result is not on the numeric path. + expect(inferFormulaReturn('record.amount > 100')).toEqual({ returnType: 'boolean' }); }); it('an empty, missing or non-string source declares nothing', () => {