Skip to content

Commit b53d3a3

Browse files
committed
feat(spec): a formula field can return percent
Round-1 work saved before its commit was refused, committed on the maintainer's word; the changeset, regenerated artifacts and gates follow in the next commit. Claude-Session: https://claude.ai/code/session_01Utp6CajiB6BSQKWowy6YLB Co-authored-by: Claude <noreply@anthropic.com>
1 parent 35c6331 commit b53d3a3

19 files changed

Lines changed: 327 additions & 32 deletions

‎packages/objectql/src/engine-formula-scale.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,24 @@ const CAMPAIGN = {
112112
* nothing on this branch may start rounding it.
113113
*/
114114
plain_rate: { name: 'plain_rate', label: 'Plain Rate', type: 'number' as const, scale: 2 },
115+
/** #35047 — a `percent` formula: a fraction, `scale` counting the displayed percentage's places. */
116+
response_ratio: {
117+
name: 'response_ratio', label: 'Response Ratio', type: 'formula' as const, returnType: 'percent' as const,
118+
expression: { dialect: 'cel', source: 'coalesce(record.num_sent, 0) > 0 ? (coalesce(record.num_responses, 0) * 1.0) / record.num_sent : 0.0' },
119+
scale: 1,
120+
},
121+
/** #35047 — a `percent` formula declaring whole-percent storage (`max` above 1). */
122+
response_points: {
123+
name: 'response_points', label: 'Response Points', type: 'formula' as const, returnType: 'percent' as const,
124+
expression: { dialect: 'cel', source: 'coalesce(record.num_sent, 0) > 0 ? (coalesce(record.num_responses, 0) * 100.0) / record.num_sent : 0.0' },
125+
scale: 1, max: 100,
126+
},
127+
/** #35047 — a STORED `percent` field computed from its expression: the same storage rule. */
128+
stored_ratio: {
129+
name: 'stored_ratio', label: 'Stored Ratio', type: 'percent' as const,
130+
expression: { dialect: 'cel', source: 'coalesce(record.num_sent, 0) > 0 ? (coalesce(record.num_responses, 0) * 1.0) / record.num_sent : 0.0' },
131+
scale: 1,
132+
},
115133
},
116134
};
117135

@@ -313,6 +331,34 @@ describe('#10280 CONTROL 1 (defect) — a formula applies its declared `scale`',
313331
});
314332
});
315333

334+
describe('#35047 — a percentage is rounded at the percent storage scale', () => {
335+
let rig: Rig;
336+
beforeEach(async () => { rig = await makeEngine(); });
337+
338+
it('a `percent` formula keeps `scale + 2` places of its fraction: 5 of 12 at `scale: 1` is 0.417 (41.7%), not 0.4', async () => {
339+
const created = await rig.protocol.createData({ object: 'fs_campaign', data: SEED });
340+
expect((created.record as Rec).response_ratio).toBe(0.417);
341+
const [row] = await rig.engine.find('fs_campaign', {} as never) as Rec[];
342+
expect(row.response_ratio).toBe(0.417);
343+
});
344+
345+
it('a `percent` formula declaring `max` above 1 holds percentage points, rounded to `scale`', async () => {
346+
const created = await rig.protocol.createData({ object: 'fs_campaign', data: SEED });
347+
expect((created.record as Rec).response_points).toBe(41.7);
348+
});
349+
350+
it('a stored `percent` field computed from its expression is rounded the same way', async () => {
351+
const created = await rig.protocol.createData({ object: 'fs_campaign', data: SEED });
352+
expect((created.record as Rec).stored_ratio).toBe(0.417);
353+
});
354+
355+
it('CONTROL — a `number` formula at the same `scale` still rounds to `scale`', async () => {
356+
const created = await rig.protocol.createData({ object: 'fs_campaign', data: SEED });
357+
expect((created.record as Rec).response_rate_whole).toBe(42);
358+
expect((created.record as Rec).response_rate).toBe(41.67);
359+
});
360+
});
361+
316362
describe('#10280 CONTROL 1 — every plan-entry call site rounds, not just `find`', () => {
317363
let rig: Rig;
318364
beforeEach(async () => { rig = await makeEngine(); });

‎packages/objectql/src/engine-top-level.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
// re-exports, by name, every declaration here it exported before, so every
1212
// importer of `./engine.js` reads what it read.
1313

14-
import { AUDIT_PROVENANCE_FIELDS, ENGINE_UPDATE_UPSERT_REMOVED, FILE_REFERENCE_TYPES, FullTextSearchSchema, QUERY_CURSOR_REMOVED, QUERY_DISTINCT_REMOVED, REFERENCE_VALUE_TYPES, RPC_QUERY_ALIAS_SLOTS, VALID_AST_OPERATORS, foldQueryAliasSlots, isFilterAST, isMultiValueField, lowerFilterCondition, normalizeFilterComparandTypes, parseFilterAST, readAutonumberCounter, referenceCarrierOf, referenceTargetOf, resolveInjectedColumnProvenance } from '@objectstack/spec/data';
14+
import { AUDIT_PROVENANCE_FIELDS, ENGINE_UPDATE_UPSERT_REMOVED, FILE_REFERENCE_TYPES, FullTextSearchSchema, QUERY_CURSOR_REMOVED, QUERY_DISTINCT_REMOVED, REFERENCE_VALUE_TYPES, RPC_QUERY_ALIAS_SLOTS, VALID_AST_OPERATORS, foldQueryAliasSlots, isFilterAST, isMultiValueField, lowerFilterCondition, normalizeFilterComparandTypes, parseFilterAST, percentScaleOf, readAutonumberCounter, referenceCarrierOf, referenceTargetOf, resolveInjectedColumnProvenance } from '@objectstack/spec/data';
1515
import type { DroppedFieldsEvent, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryAliasSlot, RecycleBinClearedReference, ServiceObject } from '@objectstack/spec/data';
1616
import type { EngineFilterJudgement, ISecurityService } from '@objectstack/spec/contracts';
1717
import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js';
@@ -1421,10 +1421,25 @@ const MAX_FORMULA_SCALE = 100;
14211421
* carries is a no-op request either way — so the rounding is skipped and the
14221422
* value is returned whole.
14231423
*/
1424-
function formulaRoundingScale(def: { scale?: unknown } | undefined): number | undefined {
1424+
function formulaRoundingScale(
1425+
def: { type?: unknown; scale?: unknown; returnType?: unknown; max?: unknown } | undefined,
1426+
): number | undefined {
14251427
const scale = def?.scale;
14261428
if (typeof scale !== 'number' || !Number.isInteger(scale) || scale < 0) return undefined;
1427-
return scale <= MAX_FORMULA_SCALE ? scale : undefined;
1429+
// [#35047] A percentage — a formula returning `percent`, or a stored
1430+
// `percent` field computed from its `expression` — declares its `scale` as
1431+
// the decimal places of the DISPLAYED percentage. So the value is rounded at
1432+
// the storage the percent field uses (`percentScaleOf`, the rule the write
1433+
// seam's `max_scale` allowance follows): a fraction carries `scale + 2`
1434+
// places (`scale: 1` keeps 0.417, which reads 41.7%), a whole percentage
1435+
// exactly `scale`. Rounding a fraction to `scale` itself turned 41.7% into
1436+
// 40.0%.
1437+
const percentage = def?.type === 'percent' || (def?.type === 'formula' && def.returnType === 'percent');
1438+
const places = percentage
1439+
&& percentScaleOf({ type: 'percent', max: typeof def?.max === 'number' ? def.max : undefined }) === 'fraction'
1440+
? scale + 2
1441+
: scale;
1442+
return places <= MAX_FORMULA_SCALE ? places : undefined;
14281443
}
14291444

14301445
/**

‎packages/services/service-analytics/src/__tests__/formula-return-type-measure.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ describe('A) the formula branch is retired — no declared returnType buys a res
9898
// rule does with `returnType`, not about the key going away. #22727 added
9999
// `currency` — a formula is still VIRTUAL in SQL storage whatever it
100100
// returns, so the walk below holds it to the same `undefined` as the four.
101-
expect([...SPEC_RETURN_TYPES].sort()).toEqual(['boolean', 'currency', 'date', 'number', 'text']);
101+
expect([...SPEC_RETURN_TYPES].sort()).toEqual(['boolean', 'currency', 'date', 'number', 'percent', 'text']);
102102
});
103103

104104
it('⭐ the table REFUSES `min` / `max` over `formula` — the ground the ruling stood on', () => {

‎packages/spec/src/data/display-name.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export interface TitleEligibleFieldDef {
3636
type?: string;
3737
/**
3838
* For `formula` fields: the declared result type. The framework field schema
39-
* carries this as `returnType` (number/text/boolean/date/currency); `valueType` is also
39+
* carries this as `returnType` (number/text/boolean/date/currency/percent); `valueType` is also
4040
* accepted for forward/cross-repo compatibility. A formula is title-eligible
4141
* ONLY when this is `text`.
4242
*/

‎packages/spec/src/data/field.form.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,9 @@ export const fieldForm = defineForm({
9797
// host, so declared = enforced = shown. A select over the schema's two
9898
// members with no default: an untouched row writes nothing and the
9999
// field keeps the renderer's default face, the bar. Gated to `percent`,
100-
// the one type the key describes.
101-
{ field: 'percentDisplay', type: 'select', visibleWhen: "data.type == 'percent'", helpText: 'How the value is shown read-only, in list cells and on the record page. Unset: a progress bar beside the percentage. Bar: always the progress bar, for progress. Plain: the percentage alone, for a rate or a probability.', options: [
100+
// the one type the key describes, and to a formula returning `percent`
101+
// (#35047), which the console draws through the same percent face.
102+
{ field: 'percentDisplay', type: 'select', visibleWhen: "data.type == 'percent' || (data.type == 'formula' && data.returnType == 'percent')", helpText: 'How the value is shown read-only, in list cells and on the record page. Unset: a progress bar beside the percentage. Bar: always the progress bar, for progress. Plain: the percentage alone, for a rate or a probability.', options: [
102103
{ label: 'Bar', value: 'bar' },
103104
{ label: 'Plain', value: 'plain' },
104105
] },
@@ -371,16 +372,18 @@ export const fieldForm = defineForm({
371372
collapsed: true,
372373
fields: [
373374
{ field: 'expression', widget: 'textarea', helpText: 'CEL expression the field\'s value is computed from. On a formula field: computed on read, no stored column. On any other field: computed by the engine from the row each write stores, and stored, so a client-sent value never stands.' },
374-
// The five members are what FieldSchema declares — an explicit list, not
375+
// The six members are what FieldSchema declares — an explicit list, not
375376
// the derived enum, so this row cannot pick up a member the formula
376377
// return type does not have. `currency` joined with #22727; its currency
377378
// is the `currencyConfig` row above, shown for a currency formula too.
378-
{ field: 'returnType', type: 'select', visibleWhen: "data.type == 'formula'", helpText: 'Declared value type of the formula, stamped from the inferred CEL type. Consumers read it instead of re-parsing the expression. Currency: an amount of money, in the currency the Currency Config of this field declares (dynamic when unset).', options: [
379+
// `percent` joined with #35047; its face is the `percentDisplay` row.
380+
{ field: 'returnType', type: 'select', visibleWhen: "data.type == 'formula'", helpText: 'Declared value type of the formula, stamped from the inferred CEL type. Consumers read it instead of re-parsing the expression. Currency: an amount of money, in the currency the Currency Config of this field declares (dynamic when unset). Percent: a ratio, shown as a percent field shows it — a fraction, so 0.25 reads 25%.', options: [
379381
{ label: 'Text', value: 'text' },
380382
{ label: 'Number', value: 'number' },
381383
{ label: 'Boolean', value: 'boolean' },
382384
{ label: 'Date', value: 'date' },
383385
{ label: 'Currency', value: 'currency' },
386+
{ label: 'Percent', value: 'percent' },
384387
] },
385388
{
386389
field: 'summaryOperations',

‎packages/spec/src/data/field.zod.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1677,7 +1677,7 @@ export const FieldSchema = lazySchema(() => {
16771677
// (batch #218 item 2, letter 乙) words. The describe names the type set the
16781678
// key still applies to, for the same reason as above.
16791679
scale: z.number().int().min(0).max(MAX_RENDERABLE_SCALE, { message: SCALE_UPPER_BOUND_MESSAGE }).optional()
1680-
.describe('Decimal places (integer 0-100). Applies to `number`, `percent`, `rating` and `slider` fields, where it is enforced on writes, and to a `formula` field, whose computed result is rounded to it. REFUSED on a `currency` field — delete it there: a currency amount\'s decimal places are its currency\'s, so the currency\'s CLDR fraction digits decide how the amount displays, and a currency write\'s decimal places stay unconstrained. OMITTED on a `percent` field ⇒ 0 decimal places, so a stored 0.25 reads `25%` on every face; omitted on any OTHER numeric type declares NO fixed width — the value keeps its natural precision, and a DECLARED `scale: 0` (a year, a fiscal period, an ordinal) stays distinguishable from having declared nothing, so nothing is defaulted there. Consumers resolve the effective width by calling `resolveFieldScale` from `@objectstack/spec/data`, the single source for an absent `scale`: a renderer that spells its own fallback is a width no other face can see, and that is how one stored 0.25 came to read `25%` on the read-only cell and `25.00%` in the edit widget. On a `percent` field this is the number of decimal places of the PERCENTAGE-POINT value as displayed and entered — `scale: 2` means 12.34% — and the STORED precision derives from the field\'s storage scale rather than being declared again: a fraction-stored percent (no `max`, or a `max` at or below 1) stores 12.34% as 0.1234 and is allowed `scale + 2` decimal places at the write seam, while a whole-percent field (`max` above 1) stores the displayed number itself and is allowed exactly `scale`. `number`, `rating` and `slider` are allowed exactly `scale`. The upper bound is the platform\'s, not a policy: renderers turn `scale` into fraction digits through `toFixed` and `Intl.NumberFormat`\'s `maximumFractionDigits`, both of which throw a RangeError above 100 — so a larger declaration is unrenderable by any conforming consumer.'),
1680+
.describe('Decimal places (integer 0-100). Applies to `number`, `percent`, `rating` and `slider` fields, where it is enforced on writes, and to a `formula` field, whose computed result is rounded to it — a `formula` whose `returnType` is `percent` counts the places of its displayed percentage, as a `percent` field does, so a fraction result is rounded to `scale + 2` places. REFUSED on a `currency` field — delete it there: a currency amount\'s decimal places are its currency\'s, so the currency\'s CLDR fraction digits decide how the amount displays, and a currency write\'s decimal places stay unconstrained. OMITTED on a `percent` field ⇒ 0 decimal places, so a stored 0.25 reads `25%` on every face; omitted on any OTHER numeric type declares NO fixed width — the value keeps its natural precision, and a DECLARED `scale: 0` (a year, a fiscal period, an ordinal) stays distinguishable from having declared nothing, so nothing is defaulted there. Consumers resolve the effective width by calling `resolveFieldScale` from `@objectstack/spec/data`, the single source for an absent `scale`: a renderer that spells its own fallback is a width no other face can see, and that is how one stored 0.25 came to read `25%` on the read-only cell and `25.00%` in the edit widget. On a `percent` field this is the number of decimal places of the PERCENTAGE-POINT value as displayed and entered — `scale: 2` means 12.34% — and the STORED precision derives from the field\'s storage scale rather than being declared again: a fraction-stored percent (no `max`, or a `max` at or below 1) stores 12.34% as 0.1234 and is allowed `scale + 2` decimal places at the write seam, while a whole-percent field (`max` above 1) stores the displayed number itself and is allowed exactly `scale`. `number`, `rating` and `slider` are allowed exactly `scale`. The upper bound is the platform\'s, not a policy: renderers turn `scale` into fraction digits through `toFixed` and `Intl.NumberFormat`\'s `maximumFractionDigits`, both of which throw a RangeError above 100 — so a larger declaration is unrenderable by any conforming consumer.'),
16811681
min: z.number().optional().describe('Minimum value. Checked on the WRITTEN value only — the same transition-gate class as `requiredWhen`: an UPDATE validates just the fields the payload carries, so a stored value below a bound declared later is never re-read and survives unrelated edits; only a write that carries an out-of-bound value is refused, and a repairing write is accepted. For an invariant re-checked on every write, declare a `validations[]` `script` rule instead.'),
16821682
max: z.number().optional().describe('Maximum value. Checked on the WRITTEN value only — the same transition-gate class as `min`: a stored value above a bound declared later is never re-read and survives unrelated edits; only a write that carries an out-of-bound value is refused. For an invariant re-checked on every write, declare a `validations[]` `script` rule instead.'),
16831683
/**
@@ -1744,7 +1744,7 @@ export const FieldSchema = lazySchema(() => {
17441744
* header chips. The liveness row is `live` and names the relay sites that
17451745
* carry the key to that renderer.
17461746
*/
1747-
percentDisplay: z.enum(['bar', 'plain']).optional().describe('How a `percent` field is displayed read-only (list cells, record page). Absent = the renderer default, a progress bar beside the percentage; `bar` = pin the progress bar; `plain` = the percentage as text alone, with no bar, for a rate or a probability rather than progress. Display only: the stored value, its validation and its decimal places (`scale`) are unchanged.'),
1747+
percentDisplay: z.enum(['bar', 'plain']).optional().describe('How a `percent` field, or a `formula` whose `returnType` is `percent`, is displayed read-only (list cells, record page). Absent = the renderer default, a progress bar beside the percentage; `bar` = pin the progress bar; `plain` = the percentage as text alone, with no bar, for a rate or a probability rather than progress. Display only: the stored value, its validation and its decimal places (`scale`) are unchanged.'),
17481748

17491749
/**
17501750
* Media Constraints (ADR-0104 D3 wave 2)
@@ -2380,9 +2380,20 @@ export const FieldSchema = lazySchema(() => {
23802380
* at AUTHORING, where `@objectstack/formula`'s `inferFormulaReturn` proves the
23812381
* result is money and answers the source's currency for the stamp to copy.
23822382
* The value itself is a bare number, as a currency field's is.
2383+
*
2384+
* `percent` (#35047): the result is a ratio, read exactly as a `percent`
2385+
* field reads its stored value — one convention, never a second one. The
2386+
* value is a FRACTION (`0.25` reads `25%`), unless the formula declares a
2387+
* `max` above 1, the percent field's own whole-percent statement
2388+
* (`percentScaleOf`), when it is percentage points. Its `scale` counts the
2389+
* decimal places of the displayed percentage, as on a `percent` field
2390+
* (absent ⇒ 0), so the engine rounds a fraction to `scale + 2` places and a
2391+
* whole percentage to `scale`. It is DECLARED, never inferred: no CEL type
2392+
* proves a quotient is a percentage, so authoring keeps a declared `percent`
2393+
* where it would stamp `number`.
23832394
*/
2384-
returnType: z.enum(['number', 'text', 'boolean', 'date', 'currency']).optional()
2385-
.describe('Inferred value type of a formula field (number/text/boolean/date/currency). `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).'),
2395+
returnType: z.enum(['number', 'text', 'boolean', 'date', 'currency', 'percent']).optional()
2396+
.describe('Inferred value type of a formula field (number/text/boolean/date/currency/percent). `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. Declared by the author, never inferred.'),
23862397
summaryOperations: strictObject({
23872398
surface: 'this roll-up summary',
23882399
history: FIELD_HISTORY,

0 commit comments

Comments
 (0)